1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BlockFrequencyInfo.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/Analysis/TargetLibraryInfo.h" 38 #include "llvm/Analysis/ValueTracking.h" 39 #include "llvm/Analysis/VectorUtils.h" 40 #include "llvm/CodeGen/Analysis.h" 41 #include "llvm/CodeGen/FunctionLoweringInfo.h" 42 #include "llvm/CodeGen/GCMetadata.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/MachineBasicBlock.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineJumpTableInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineOperand.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/CodeGen/RuntimeLibcalls.h" 55 #include "llvm/CodeGen/SelectionDAG.h" 56 #include "llvm/CodeGen/SelectionDAGNodes.h" 57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 58 #include "llvm/CodeGen/StackMaps.h" 59 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 60 #include "llvm/CodeGen/TargetFrameLowering.h" 61 #include "llvm/CodeGen/TargetInstrInfo.h" 62 #include "llvm/CodeGen/TargetLowering.h" 63 #include "llvm/CodeGen/TargetOpcodes.h" 64 #include "llvm/CodeGen/TargetRegisterInfo.h" 65 #include "llvm/CodeGen/TargetSubtargetInfo.h" 66 #include "llvm/CodeGen/ValueTypes.h" 67 #include "llvm/CodeGen/WinEHFuncInfo.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CFG.h" 72 #include "llvm/IR/CallingConv.h" 73 #include "llvm/IR/Constant.h" 74 #include "llvm/IR/ConstantRange.h" 75 #include "llvm/IR/Constants.h" 76 #include "llvm/IR/DataLayout.h" 77 #include "llvm/IR/DebugInfoMetadata.h" 78 #include "llvm/IR/DebugLoc.h" 79 #include "llvm/IR/DerivedTypes.h" 80 #include "llvm/IR/Function.h" 81 #include "llvm/IR/GetElementPtrTypeIterator.h" 82 #include "llvm/IR/InlineAsm.h" 83 #include "llvm/IR/InstrTypes.h" 84 #include "llvm/IR/Instruction.h" 85 #include "llvm/IR/Instructions.h" 86 #include "llvm/IR/IntrinsicInst.h" 87 #include "llvm/IR/Intrinsics.h" 88 #include "llvm/IR/IntrinsicsAArch64.h" 89 #include "llvm/IR/IntrinsicsWebAssembly.h" 90 #include "llvm/IR/LLVMContext.h" 91 #include "llvm/IR/Metadata.h" 92 #include "llvm/IR/Module.h" 93 #include "llvm/IR/Operator.h" 94 #include "llvm/IR/PatternMatch.h" 95 #include "llvm/IR/Statepoint.h" 96 #include "llvm/IR/Type.h" 97 #include "llvm/IR/User.h" 98 #include "llvm/IR/Value.h" 99 #include "llvm/MC/MCContext.h" 100 #include "llvm/MC/MCSymbol.h" 101 #include "llvm/Support/AtomicOrdering.h" 102 #include "llvm/Support/BranchProbability.h" 103 #include "llvm/Support/Casting.h" 104 #include "llvm/Support/CodeGen.h" 105 #include "llvm/Support/CommandLine.h" 106 #include "llvm/Support/Compiler.h" 107 #include "llvm/Support/Debug.h" 108 #include "llvm/Support/ErrorHandling.h" 109 #include "llvm/Support/MachineValueType.h" 110 #include "llvm/Support/MathExtras.h" 111 #include "llvm/Support/raw_ostream.h" 112 #include "llvm/Target/TargetIntrinsicInfo.h" 113 #include "llvm/Target/TargetMachine.h" 114 #include "llvm/Target/TargetOptions.h" 115 #include "llvm/Transforms/Utils/Local.h" 116 #include <algorithm> 117 #include <cassert> 118 #include <cstddef> 119 #include <cstdint> 120 #include <cstring> 121 #include <iterator> 122 #include <limits> 123 #include <numeric> 124 #include <tuple> 125 #include <utility> 126 #include <vector> 127 128 using namespace llvm; 129 using namespace PatternMatch; 130 using namespace SwitchCG; 131 132 #define DEBUG_TYPE "isel" 133 134 /// LimitFloatPrecision - Generate low-precision inline sequences for 135 /// some float libcalls (6, 8 or 12 bits). 136 static unsigned LimitFloatPrecision; 137 138 static cl::opt<unsigned, true> 139 LimitFPPrecision("limit-float-precision", 140 cl::desc("Generate low-precision inline sequences " 141 "for some float libcalls"), 142 cl::location(LimitFloatPrecision), cl::Hidden, 143 cl::init(0)); 144 145 static cl::opt<unsigned> SwitchPeelThreshold( 146 "switch-peel-threshold", cl::Hidden, cl::init(66), 147 cl::desc("Set the case probability threshold for peeling the case from a " 148 "switch statement. A value greater than 100 will void this " 149 "optimization")); 150 151 // Limit the width of DAG chains. This is important in general to prevent 152 // DAG-based analysis from blowing up. For example, alias analysis and 153 // load clustering may not complete in reasonable time. It is difficult to 154 // recognize and avoid this situation within each individual analysis, and 155 // future analyses are likely to have the same behavior. Limiting DAG width is 156 // the safe approach and will be especially important with global DAGs. 157 // 158 // MaxParallelChains default is arbitrarily high to avoid affecting 159 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 160 // sequence over this should have been converted to llvm.memcpy by the 161 // frontend. It is easy to induce this behavior with .ll code such as: 162 // %buffer = alloca [4096 x i8] 163 // %data = load [4096 x i8]* %argPtr 164 // store [4096 x i8] %data, [4096 x i8]* %buffer 165 static const unsigned MaxParallelChains = 64; 166 167 // Return the calling convention if the Value passed requires ABI mangling as it 168 // is a parameter to a function or a return value from a function which is not 169 // an intrinsic. 170 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 171 if (auto *R = dyn_cast<ReturnInst>(V)) 172 return R->getParent()->getParent()->getCallingConv(); 173 174 if (auto *CI = dyn_cast<CallInst>(V)) { 175 const bool IsInlineAsm = CI->isInlineAsm(); 176 const bool IsIndirectFunctionCall = 177 !IsInlineAsm && !CI->getCalledFunction(); 178 179 // It is possible that the call instruction is an inline asm statement or an 180 // indirect function call in which case the return value of 181 // getCalledFunction() would be nullptr. 182 const bool IsInstrinsicCall = 183 !IsInlineAsm && !IsIndirectFunctionCall && 184 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 185 186 if (!IsInlineAsm && !IsInstrinsicCall) 187 return CI->getCallingConv(); 188 } 189 190 return None; 191 } 192 193 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 194 const SDValue *Parts, unsigned NumParts, 195 MVT PartVT, EVT ValueVT, const Value *V, 196 Optional<CallingConv::ID> CC); 197 198 /// getCopyFromParts - Create a value that contains the specified legal parts 199 /// combined into the value they represent. If the parts combine to a type 200 /// larger than ValueVT then AssertOp can be used to specify whether the extra 201 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 202 /// (ISD::AssertSext). 203 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 204 const SDValue *Parts, unsigned NumParts, 205 MVT PartVT, EVT ValueVT, const Value *V, 206 Optional<CallingConv::ID> CC = None, 207 Optional<ISD::NodeType> AssertOp = None) { 208 if (ValueVT.isVector()) 209 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 210 CC); 211 212 assert(NumParts > 0 && "No parts to assemble!"); 213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 214 SDValue Val = Parts[0]; 215 216 if (NumParts > 1) { 217 // Assemble the value from multiple parts. 218 if (ValueVT.isInteger()) { 219 unsigned PartBits = PartVT.getSizeInBits(); 220 unsigned ValueBits = ValueVT.getSizeInBits(); 221 222 // Assemble the power of 2 part. 223 unsigned RoundParts = 224 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 225 unsigned RoundBits = PartBits * RoundParts; 226 EVT RoundVT = RoundBits == ValueBits ? 227 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 228 SDValue Lo, Hi; 229 230 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 231 232 if (RoundParts > 2) { 233 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 234 PartVT, HalfVT, V); 235 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 236 RoundParts / 2, PartVT, HalfVT, V); 237 } else { 238 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 240 } 241 242 if (DAG.getDataLayout().isBigEndian()) 243 std::swap(Lo, Hi); 244 245 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 246 247 if (RoundParts < NumParts) { 248 // Assemble the trailing non-power-of-2 part. 249 unsigned OddParts = NumParts - RoundParts; 250 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 251 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 252 OddVT, V, CC); 253 254 // Combine the round and odd parts. 255 Lo = Val; 256 if (DAG.getDataLayout().isBigEndian()) 257 std::swap(Lo, Hi); 258 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 259 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 260 Hi = 261 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 262 DAG.getConstant(Lo.getValueSizeInBits(), DL, 263 TLI.getPointerTy(DAG.getDataLayout()))); 264 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 265 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 266 } 267 } else if (PartVT.isFloatingPoint()) { 268 // FP split into multiple FP parts (for ppcf128) 269 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 270 "Unexpected split"); 271 SDValue Lo, Hi; 272 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 273 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 274 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 275 std::swap(Lo, Hi); 276 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 277 } else { 278 // FP split into integer parts (soft fp) 279 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 280 !PartVT.isVector() && "Unexpected split"); 281 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 282 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 283 } 284 } 285 286 // There is now one part, held in Val. Correct it to match ValueVT. 287 // PartEVT is the type of the register class that holds the value. 288 // ValueVT is the type of the inline asm operation. 289 EVT PartEVT = Val.getValueType(); 290 291 if (PartEVT == ValueVT) 292 return Val; 293 294 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 295 ValueVT.bitsLT(PartEVT)) { 296 // For an FP value in an integer part, we need to truncate to the right 297 // width first. 298 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 299 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 300 } 301 302 // Handle types that have the same size. 303 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 304 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 305 306 // Handle types with different sizes. 307 if (PartEVT.isInteger() && ValueVT.isInteger()) { 308 if (ValueVT.bitsLT(PartEVT)) { 309 // For a truncate, see if we have any information to 310 // indicate whether the truncated bits will always be 311 // zero or sign-extension. 312 if (AssertOp.hasValue()) 313 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 314 DAG.getValueType(ValueVT)); 315 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 316 } 317 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 318 } 319 320 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 321 // FP_ROUND's are always exact here. 322 if (ValueVT.bitsLT(Val.getValueType())) 323 return DAG.getNode( 324 ISD::FP_ROUND, DL, ValueVT, Val, 325 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 326 327 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 328 } 329 330 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 331 // then truncating. 332 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 333 ValueVT.bitsLT(PartEVT)) { 334 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 335 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 336 } 337 338 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 339 } 340 341 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 342 const Twine &ErrMsg) { 343 const Instruction *I = dyn_cast_or_null<Instruction>(V); 344 if (!V) 345 return Ctx.emitError(ErrMsg); 346 347 const char *AsmError = ", possible invalid constraint for vector type"; 348 if (const CallInst *CI = dyn_cast<CallInst>(I)) 349 if (isa<InlineAsm>(CI->getCalledValue())) 350 return Ctx.emitError(I, ErrMsg + AsmError); 351 352 return Ctx.emitError(I, ErrMsg); 353 } 354 355 /// getCopyFromPartsVector - Create a value that contains the specified legal 356 /// parts combined into the value they represent. If the parts combine to a 357 /// type larger than ValueVT then AssertOp can be used to specify whether the 358 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 359 /// ValueVT (ISD::AssertSext). 360 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 361 const SDValue *Parts, unsigned NumParts, 362 MVT PartVT, EVT ValueVT, const Value *V, 363 Optional<CallingConv::ID> CallConv) { 364 assert(ValueVT.isVector() && "Not a vector value"); 365 assert(NumParts > 0 && "No parts to assemble!"); 366 const bool IsABIRegCopy = CallConv.hasValue(); 367 368 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 369 SDValue Val = Parts[0]; 370 371 // Handle a multi-element vector. 372 if (NumParts > 1) { 373 EVT IntermediateVT; 374 MVT RegisterVT; 375 unsigned NumIntermediates; 376 unsigned NumRegs; 377 378 if (IsABIRegCopy) { 379 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 380 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 381 NumIntermediates, RegisterVT); 382 } else { 383 NumRegs = 384 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 385 NumIntermediates, RegisterVT); 386 } 387 388 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 389 NumParts = NumRegs; // Silence a compiler warning. 390 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 391 assert(RegisterVT.getSizeInBits() == 392 Parts[0].getSimpleValueType().getSizeInBits() && 393 "Part type sizes don't match!"); 394 395 // Assemble the parts into intermediate operands. 396 SmallVector<SDValue, 8> Ops(NumIntermediates); 397 if (NumIntermediates == NumParts) { 398 // If the register was not expanded, truncate or copy the value, 399 // as appropriate. 400 for (unsigned i = 0; i != NumParts; ++i) 401 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 402 PartVT, IntermediateVT, V); 403 } else if (NumParts > 0) { 404 // If the intermediate type was expanded, build the intermediate 405 // operands from the parts. 406 assert(NumParts % NumIntermediates == 0 && 407 "Must expand into a divisible number of parts!"); 408 unsigned Factor = NumParts / NumIntermediates; 409 for (unsigned i = 0; i != NumIntermediates; ++i) 410 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 411 PartVT, IntermediateVT, V); 412 } 413 414 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 415 // intermediate operands. 416 EVT BuiltVectorTy = 417 IntermediateVT.isVector() 418 ? EVT::getVectorVT( 419 *DAG.getContext(), IntermediateVT.getScalarType(), 420 IntermediateVT.getVectorElementCount() * NumParts) 421 : EVT::getVectorVT(*DAG.getContext(), 422 IntermediateVT.getScalarType(), 423 NumIntermediates); 424 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 425 : ISD::BUILD_VECTOR, 426 DL, BuiltVectorTy, Ops); 427 } 428 429 // There is now one part, held in Val. Correct it to match ValueVT. 430 EVT PartEVT = Val.getValueType(); 431 432 if (PartEVT == ValueVT) 433 return Val; 434 435 if (PartEVT.isVector()) { 436 // If the element type of the source/dest vectors are the same, but the 437 // parts vector has more elements than the value vector, then we have a 438 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 439 // elements we want. 440 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 441 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 442 "Cannot narrow, it would be a lossy transformation"); 443 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 444 DAG.getVectorIdxConstant(0, DL)); 445 } 446 447 // Vector/Vector bitcast. 448 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 449 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 450 451 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 452 "Cannot handle this kind of promotion"); 453 // Promoted vector extract 454 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 455 456 } 457 458 // Trivial bitcast if the types are the same size and the destination 459 // vector type is legal. 460 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 461 TLI.isTypeLegal(ValueVT)) 462 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 463 464 if (ValueVT.getVectorNumElements() != 1) { 465 // Certain ABIs require that vectors are passed as integers. For vectors 466 // are the same size, this is an obvious bitcast. 467 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 468 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 469 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 470 // Bitcast Val back the original type and extract the corresponding 471 // vector we want. 472 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 473 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 474 ValueVT.getVectorElementType(), Elts); 475 Val = DAG.getBitcast(WiderVecType, Val); 476 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 477 DAG.getVectorIdxConstant(0, DL)); 478 } 479 480 diagnosePossiblyInvalidConstraint( 481 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 482 return DAG.getUNDEF(ValueVT); 483 } 484 485 // Handle cases such as i8 -> <1 x i1> 486 EVT ValueSVT = ValueVT.getVectorElementType(); 487 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 488 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 489 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 490 else 491 Val = ValueVT.isFloatingPoint() 492 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 493 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 494 } 495 496 return DAG.getBuildVector(ValueVT, DL, Val); 497 } 498 499 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 500 SDValue Val, SDValue *Parts, unsigned NumParts, 501 MVT PartVT, const Value *V, 502 Optional<CallingConv::ID> CallConv); 503 504 /// getCopyToParts - Create a series of nodes that contain the specified value 505 /// split into legal parts. If the parts contain more bits than Val, then, for 506 /// integers, ExtendKind can be used to specify how to generate the extra bits. 507 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 508 SDValue *Parts, unsigned NumParts, MVT PartVT, 509 const Value *V, 510 Optional<CallingConv::ID> CallConv = None, 511 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 512 EVT ValueVT = Val.getValueType(); 513 514 // Handle the vector case separately. 515 if (ValueVT.isVector()) 516 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 517 CallConv); 518 519 unsigned PartBits = PartVT.getSizeInBits(); 520 unsigned OrigNumParts = NumParts; 521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 522 "Copying to an illegal type!"); 523 524 if (NumParts == 0) 525 return; 526 527 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 528 EVT PartEVT = PartVT; 529 if (PartEVT == ValueVT) { 530 assert(NumParts == 1 && "No-op copy with multiple parts!"); 531 Parts[0] = Val; 532 return; 533 } 534 535 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 536 // If the parts cover more bits than the value has, promote the value. 537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 538 assert(NumParts == 1 && "Do not know what to promote to!"); 539 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 540 } else { 541 if (ValueVT.isFloatingPoint()) { 542 // FP values need to be bitcast, then extended if they are being put 543 // into a larger container. 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 545 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 546 } 547 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 548 ValueVT.isInteger() && 549 "Unknown mismatch!"); 550 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 551 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 552 if (PartVT == MVT::x86mmx) 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 } else if (PartBits == ValueVT.getSizeInBits()) { 556 // Different types of the same size. 557 assert(NumParts == 1 && PartEVT != ValueVT); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 560 // If the parts cover less bits than value has, truncate the value. 561 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 562 ValueVT.isInteger() && 563 "Unknown mismatch!"); 564 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 565 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 566 if (PartVT == MVT::x86mmx) 567 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 568 } 569 570 // The value may have changed - recompute ValueVT. 571 ValueVT = Val.getValueType(); 572 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 573 "Failed to tile the value with PartVT!"); 574 575 if (NumParts == 1) { 576 if (PartEVT != ValueVT) { 577 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 578 "scalar-to-vector conversion failed"); 579 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 580 } 581 582 Parts[0] = Val; 583 return; 584 } 585 586 // Expand the value into multiple parts. 587 if (NumParts & (NumParts - 1)) { 588 // The number of parts is not a power of 2. Split off and copy the tail. 589 assert(PartVT.isInteger() && ValueVT.isInteger() && 590 "Do not know what to expand to!"); 591 unsigned RoundParts = 1 << Log2_32(NumParts); 592 unsigned RoundBits = RoundParts * PartBits; 593 unsigned OddParts = NumParts - RoundParts; 594 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 595 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 596 597 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 598 CallConv); 599 600 if (DAG.getDataLayout().isBigEndian()) 601 // The odd parts were reversed by getCopyToParts - unreverse them. 602 std::reverse(Parts + RoundParts, Parts + NumParts); 603 604 NumParts = RoundParts; 605 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 606 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 607 } 608 609 // The number of parts is a power of 2. Repeatedly bisect the value using 610 // EXTRACT_ELEMENT. 611 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 612 EVT::getIntegerVT(*DAG.getContext(), 613 ValueVT.getSizeInBits()), 614 Val); 615 616 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 617 for (unsigned i = 0; i < NumParts; i += StepSize) { 618 unsigned ThisBits = StepSize * PartBits / 2; 619 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 620 SDValue &Part0 = Parts[i]; 621 SDValue &Part1 = Parts[i+StepSize/2]; 622 623 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 625 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 627 628 if (ThisBits == PartBits && ThisVT != PartVT) { 629 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 630 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 631 } 632 } 633 } 634 635 if (DAG.getDataLayout().isBigEndian()) 636 std::reverse(Parts, Parts + OrigNumParts); 637 } 638 639 static SDValue widenVectorToPartType(SelectionDAG &DAG, 640 SDValue Val, const SDLoc &DL, EVT PartVT) { 641 if (!PartVT.isVector()) 642 return SDValue(); 643 644 EVT ValueVT = Val.getValueType(); 645 unsigned PartNumElts = PartVT.getVectorNumElements(); 646 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 647 if (PartNumElts > ValueNumElts && 648 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 649 EVT ElementVT = PartVT.getVectorElementType(); 650 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 651 // undef elements. 652 SmallVector<SDValue, 16> Ops; 653 DAG.ExtractVectorElements(Val, Ops); 654 SDValue EltUndef = DAG.getUNDEF(ElementVT); 655 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 656 Ops.push_back(EltUndef); 657 658 // FIXME: Use CONCAT for 2x -> 4x. 659 return DAG.getBuildVector(PartVT, DL, Ops); 660 } 661 662 return SDValue(); 663 } 664 665 /// getCopyToPartsVector - Create a series of nodes that contain the specified 666 /// value split into legal parts. 667 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 668 SDValue Val, SDValue *Parts, unsigned NumParts, 669 MVT PartVT, const Value *V, 670 Optional<CallingConv::ID> CallConv) { 671 EVT ValueVT = Val.getValueType(); 672 assert(ValueVT.isVector() && "Not a vector"); 673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 674 const bool IsABIRegCopy = CallConv.hasValue(); 675 676 if (NumParts == 1) { 677 EVT PartEVT = PartVT; 678 if (PartEVT == ValueVT) { 679 // Nothing to do. 680 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 681 // Bitconvert vector->vector case. 682 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 683 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 684 Val = Widened; 685 } else if (PartVT.isVector() && 686 PartEVT.getVectorElementType().bitsGE( 687 ValueVT.getVectorElementType()) && 688 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 689 690 // Promoted vector extract 691 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 692 } else { 693 if (ValueVT.getVectorNumElements() == 1) { 694 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 695 DAG.getVectorIdxConstant(0, DL)); 696 } else { 697 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 698 "lossy conversion of vector to scalar type"); 699 EVT IntermediateType = 700 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 701 Val = DAG.getBitcast(IntermediateType, Val); 702 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 703 } 704 } 705 706 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 707 Parts[0] = Val; 708 return; 709 } 710 711 // Handle a multi-element vector. 712 EVT IntermediateVT; 713 MVT RegisterVT; 714 unsigned NumIntermediates; 715 unsigned NumRegs; 716 if (IsABIRegCopy) { 717 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 718 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 719 NumIntermediates, RegisterVT); 720 } else { 721 NumRegs = 722 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 723 NumIntermediates, RegisterVT); 724 } 725 726 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 727 NumParts = NumRegs; // Silence a compiler warning. 728 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 729 730 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 731 IntermediateVT.getVectorNumElements() : 1; 732 733 // Convert the vector to the appropriate type if necessary. 734 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 735 736 EVT BuiltVectorTy = EVT::getVectorVT( 737 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 738 if (ValueVT != BuiltVectorTy) { 739 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 740 Val = Widened; 741 742 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 743 } 744 745 // Split the vector into intermediate operands. 746 SmallVector<SDValue, 8> Ops(NumIntermediates); 747 for (unsigned i = 0; i != NumIntermediates; ++i) { 748 if (IntermediateVT.isVector()) { 749 Ops[i] = 750 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 751 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 752 } else { 753 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 754 DAG.getVectorIdxConstant(i, DL)); 755 } 756 } 757 758 // Split the intermediate operands into legal parts. 759 if (NumParts == NumIntermediates) { 760 // If the register was not expanded, promote or copy the value, 761 // as appropriate. 762 for (unsigned i = 0; i != NumParts; ++i) 763 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 764 } else if (NumParts > 0) { 765 // If the intermediate type was expanded, split each the value into 766 // legal parts. 767 assert(NumIntermediates != 0 && "division by zero"); 768 assert(NumParts % NumIntermediates == 0 && 769 "Must expand into a divisible number of parts!"); 770 unsigned Factor = NumParts / NumIntermediates; 771 for (unsigned i = 0; i != NumIntermediates; ++i) 772 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 773 CallConv); 774 } 775 } 776 777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 778 EVT valuevt, Optional<CallingConv::ID> CC) 779 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 780 RegCount(1, regs.size()), CallConv(CC) {} 781 782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 783 const DataLayout &DL, unsigned Reg, Type *Ty, 784 Optional<CallingConv::ID> CC) { 785 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 786 787 CallConv = CC; 788 789 for (EVT ValueVT : ValueVTs) { 790 unsigned NumRegs = 791 isABIMangled() 792 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 793 : TLI.getNumRegisters(Context, ValueVT); 794 MVT RegisterVT = 795 isABIMangled() 796 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 797 : TLI.getRegisterType(Context, ValueVT); 798 for (unsigned i = 0; i != NumRegs; ++i) 799 Regs.push_back(Reg + i); 800 RegVTs.push_back(RegisterVT); 801 RegCount.push_back(NumRegs); 802 Reg += NumRegs; 803 } 804 } 805 806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 807 FunctionLoweringInfo &FuncInfo, 808 const SDLoc &dl, SDValue &Chain, 809 SDValue *Flag, const Value *V) const { 810 // A Value with type {} or [0 x %t] needs no registers. 811 if (ValueVTs.empty()) 812 return SDValue(); 813 814 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 815 816 // Assemble the legal parts into the final values. 817 SmallVector<SDValue, 4> Values(ValueVTs.size()); 818 SmallVector<SDValue, 8> Parts; 819 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 820 // Copy the legal parts from the registers. 821 EVT ValueVT = ValueVTs[Value]; 822 unsigned NumRegs = RegCount[Value]; 823 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 824 *DAG.getContext(), 825 CallConv.getValue(), RegVTs[Value]) 826 : RegVTs[Value]; 827 828 Parts.resize(NumRegs); 829 for (unsigned i = 0; i != NumRegs; ++i) { 830 SDValue P; 831 if (!Flag) { 832 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 833 } else { 834 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 835 *Flag = P.getValue(2); 836 } 837 838 Chain = P.getValue(1); 839 Parts[i] = P; 840 841 // If the source register was virtual and if we know something about it, 842 // add an assert node. 843 if (!Register::isVirtualRegister(Regs[Part + i]) || 844 !RegisterVT.isInteger()) 845 continue; 846 847 const FunctionLoweringInfo::LiveOutInfo *LOI = 848 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 849 if (!LOI) 850 continue; 851 852 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 853 unsigned NumSignBits = LOI->NumSignBits; 854 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 855 856 if (NumZeroBits == RegSize) { 857 // The current value is a zero. 858 // Explicitly express that as it would be easier for 859 // optimizations to kick in. 860 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 861 continue; 862 } 863 864 // FIXME: We capture more information than the dag can represent. For 865 // now, just use the tightest assertzext/assertsext possible. 866 bool isSExt; 867 EVT FromVT(MVT::Other); 868 if (NumZeroBits) { 869 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 870 isSExt = false; 871 } else if (NumSignBits > 1) { 872 FromVT = 873 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 874 isSExt = true; 875 } else { 876 continue; 877 } 878 // Add an assertion node. 879 assert(FromVT != MVT::Other); 880 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 881 RegisterVT, P, DAG.getValueType(FromVT)); 882 } 883 884 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 885 RegisterVT, ValueVT, V, CallConv); 886 Part += NumRegs; 887 Parts.clear(); 888 } 889 890 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 891 } 892 893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 894 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 895 const Value *V, 896 ISD::NodeType PreferredExtendType) const { 897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 898 ISD::NodeType ExtendKind = PreferredExtendType; 899 900 // Get the list of the values's legal parts. 901 unsigned NumRegs = Regs.size(); 902 SmallVector<SDValue, 8> Parts(NumRegs); 903 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 904 unsigned NumParts = RegCount[Value]; 905 906 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 907 *DAG.getContext(), 908 CallConv.getValue(), RegVTs[Value]) 909 : RegVTs[Value]; 910 911 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 912 ExtendKind = ISD::ZERO_EXTEND; 913 914 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 915 NumParts, RegisterVT, V, CallConv, ExtendKind); 916 Part += NumParts; 917 } 918 919 // Copy the parts into the registers. 920 SmallVector<SDValue, 8> Chains(NumRegs); 921 for (unsigned i = 0; i != NumRegs; ++i) { 922 SDValue Part; 923 if (!Flag) { 924 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 925 } else { 926 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 927 *Flag = Part.getValue(1); 928 } 929 930 Chains[i] = Part.getValue(0); 931 } 932 933 if (NumRegs == 1 || Flag) 934 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 935 // flagged to it. That is the CopyToReg nodes and the user are considered 936 // a single scheduling unit. If we create a TokenFactor and return it as 937 // chain, then the TokenFactor is both a predecessor (operand) of the 938 // user as well as a successor (the TF operands are flagged to the user). 939 // c1, f1 = CopyToReg 940 // c2, f2 = CopyToReg 941 // c3 = TokenFactor c1, c2 942 // ... 943 // = op c3, ..., f2 944 Chain = Chains[NumRegs-1]; 945 else 946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 947 } 948 949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 950 unsigned MatchingIdx, const SDLoc &dl, 951 SelectionDAG &DAG, 952 std::vector<SDValue> &Ops) const { 953 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 954 955 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 956 if (HasMatching) 957 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 958 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 959 // Put the register class of the virtual registers in the flag word. That 960 // way, later passes can recompute register class constraints for inline 961 // assembly as well as normal instructions. 962 // Don't do this for tied operands that can use the regclass information 963 // from the def. 964 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 965 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 966 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 967 } 968 969 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 970 Ops.push_back(Res); 971 972 if (Code == InlineAsm::Kind_Clobber) { 973 // Clobbers should always have a 1:1 mapping with registers, and may 974 // reference registers that have illegal (e.g. vector) types. Hence, we 975 // shouldn't try to apply any sort of splitting logic to them. 976 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 977 "No 1:1 mapping from clobbers to regs?"); 978 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 979 (void)SP; 980 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 981 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 982 assert( 983 (Regs[I] != SP || 984 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 985 "If we clobbered the stack pointer, MFI should know about it."); 986 } 987 return; 988 } 989 990 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 991 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 992 MVT RegisterVT = RegVTs[Value]; 993 for (unsigned i = 0; i != NumRegs; ++i) { 994 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 995 unsigned TheReg = Regs[Reg++]; 996 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 997 } 998 } 999 } 1000 1001 SmallVector<std::pair<unsigned, unsigned>, 4> 1002 RegsForValue::getRegsAndSizes() const { 1003 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1004 unsigned I = 0; 1005 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1006 unsigned RegCount = std::get<0>(CountAndVT); 1007 MVT RegisterVT = std::get<1>(CountAndVT); 1008 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1009 for (unsigned E = I + RegCount; I != E; ++I) 1010 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1011 } 1012 return OutVec; 1013 } 1014 1015 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1016 const TargetLibraryInfo *li) { 1017 AA = aa; 1018 GFI = gfi; 1019 LibInfo = li; 1020 DL = &DAG.getDataLayout(); 1021 Context = DAG.getContext(); 1022 LPadToCallSiteMap.clear(); 1023 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1024 } 1025 1026 void SelectionDAGBuilder::clear() { 1027 NodeMap.clear(); 1028 UnusedArgNodeMap.clear(); 1029 PendingLoads.clear(); 1030 PendingExports.clear(); 1031 PendingConstrainedFP.clear(); 1032 PendingConstrainedFPStrict.clear(); 1033 CurInst = nullptr; 1034 HasTailCall = false; 1035 SDNodeOrder = LowestSDNodeOrder; 1036 StatepointLowering.clear(); 1037 } 1038 1039 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1040 DanglingDebugInfoMap.clear(); 1041 } 1042 1043 // Update DAG root to include dependencies on Pending chains. 1044 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1045 SDValue Root = DAG.getRoot(); 1046 1047 if (Pending.empty()) 1048 return Root; 1049 1050 // Add current root to PendingChains, unless we already indirectly 1051 // depend on it. 1052 if (Root.getOpcode() != ISD::EntryToken) { 1053 unsigned i = 0, e = Pending.size(); 1054 for (; i != e; ++i) { 1055 assert(Pending[i].getNode()->getNumOperands() > 1); 1056 if (Pending[i].getNode()->getOperand(0) == Root) 1057 break; // Don't add the root if we already indirectly depend on it. 1058 } 1059 1060 if (i == e) 1061 Pending.push_back(Root); 1062 } 1063 1064 if (Pending.size() == 1) 1065 Root = Pending[0]; 1066 else 1067 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1068 1069 DAG.setRoot(Root); 1070 Pending.clear(); 1071 return Root; 1072 } 1073 1074 SDValue SelectionDAGBuilder::getMemoryRoot() { 1075 return updateRoot(PendingLoads); 1076 } 1077 1078 SDValue SelectionDAGBuilder::getRoot() { 1079 // Chain up all pending constrained intrinsics together with all 1080 // pending loads, by simply appending them to PendingLoads and 1081 // then calling getMemoryRoot(). 1082 PendingLoads.reserve(PendingLoads.size() + 1083 PendingConstrainedFP.size() + 1084 PendingConstrainedFPStrict.size()); 1085 PendingLoads.append(PendingConstrainedFP.begin(), 1086 PendingConstrainedFP.end()); 1087 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1088 PendingConstrainedFPStrict.end()); 1089 PendingConstrainedFP.clear(); 1090 PendingConstrainedFPStrict.clear(); 1091 return getMemoryRoot(); 1092 } 1093 1094 SDValue SelectionDAGBuilder::getControlRoot() { 1095 // We need to emit pending fpexcept.strict constrained intrinsics, 1096 // so append them to the PendingExports list. 1097 PendingExports.append(PendingConstrainedFPStrict.begin(), 1098 PendingConstrainedFPStrict.end()); 1099 PendingConstrainedFPStrict.clear(); 1100 return updateRoot(PendingExports); 1101 } 1102 1103 void SelectionDAGBuilder::visit(const Instruction &I) { 1104 // Set up outgoing PHI node register values before emitting the terminator. 1105 if (I.isTerminator()) { 1106 HandlePHINodesInSuccessorBlocks(I.getParent()); 1107 } 1108 1109 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1110 if (!isa<DbgInfoIntrinsic>(I)) 1111 ++SDNodeOrder; 1112 1113 CurInst = &I; 1114 1115 visit(I.getOpcode(), I); 1116 1117 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1118 // ConstrainedFPIntrinsics handle their own FMF. 1119 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1120 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1121 // maps to this instruction. 1122 // TODO: We could handle all flags (nsw, etc) here. 1123 // TODO: If an IR instruction maps to >1 node, only the final node will have 1124 // flags set. 1125 if (SDNode *Node = getNodeForIRValue(&I)) { 1126 SDNodeFlags IncomingFlags; 1127 IncomingFlags.copyFMF(*FPMO); 1128 if (!Node->getFlags().isDefined()) 1129 Node->setFlags(IncomingFlags); 1130 else 1131 Node->intersectFlagsWith(IncomingFlags); 1132 } 1133 } 1134 } 1135 1136 if (!I.isTerminator() && !HasTailCall && 1137 !isStatepoint(&I)) // statepoints handle their exports internally 1138 CopyToExportRegsIfNeeded(&I); 1139 1140 CurInst = nullptr; 1141 } 1142 1143 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1144 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1145 } 1146 1147 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1148 // Note: this doesn't use InstVisitor, because it has to work with 1149 // ConstantExpr's in addition to instructions. 1150 switch (Opcode) { 1151 default: llvm_unreachable("Unknown instruction type encountered!"); 1152 // Build the switch statement using the Instruction.def file. 1153 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1154 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1155 #include "llvm/IR/Instruction.def" 1156 } 1157 } 1158 1159 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1160 const DIExpression *Expr) { 1161 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1162 const DbgValueInst *DI = DDI.getDI(); 1163 DIVariable *DanglingVariable = DI->getVariable(); 1164 DIExpression *DanglingExpr = DI->getExpression(); 1165 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1166 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1167 return true; 1168 } 1169 return false; 1170 }; 1171 1172 for (auto &DDIMI : DanglingDebugInfoMap) { 1173 DanglingDebugInfoVector &DDIV = DDIMI.second; 1174 1175 // If debug info is to be dropped, run it through final checks to see 1176 // whether it can be salvaged. 1177 for (auto &DDI : DDIV) 1178 if (isMatchingDbgValue(DDI)) 1179 salvageUnresolvedDbgValue(DDI); 1180 1181 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1182 } 1183 } 1184 1185 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1186 // generate the debug data structures now that we've seen its definition. 1187 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1188 SDValue Val) { 1189 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1190 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1191 return; 1192 1193 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1194 for (auto &DDI : DDIV) { 1195 const DbgValueInst *DI = DDI.getDI(); 1196 assert(DI && "Ill-formed DanglingDebugInfo"); 1197 DebugLoc dl = DDI.getdl(); 1198 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1199 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1200 DILocalVariable *Variable = DI->getVariable(); 1201 DIExpression *Expr = DI->getExpression(); 1202 assert(Variable->isValidLocationForIntrinsic(dl) && 1203 "Expected inlined-at fields to agree"); 1204 SDDbgValue *SDV; 1205 if (Val.getNode()) { 1206 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1207 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1208 // we couldn't resolve it directly when examining the DbgValue intrinsic 1209 // in the first place we should not be more successful here). Unless we 1210 // have some test case that prove this to be correct we should avoid 1211 // calling EmitFuncArgumentDbgValue here. 1212 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1213 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1214 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1215 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1216 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1217 // inserted after the definition of Val when emitting the instructions 1218 // after ISel. An alternative could be to teach 1219 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1220 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1221 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1222 << ValSDNodeOrder << "\n"); 1223 SDV = getDbgValue(Val, Variable, Expr, dl, 1224 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1225 DAG.AddDbgValue(SDV, Val.getNode(), false); 1226 } else 1227 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1228 << "in EmitFuncArgumentDbgValue\n"); 1229 } else { 1230 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1231 auto Undef = 1232 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1233 auto SDV = 1234 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1235 DAG.AddDbgValue(SDV, nullptr, false); 1236 } 1237 } 1238 DDIV.clear(); 1239 } 1240 1241 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1242 Value *V = DDI.getDI()->getValue(); 1243 DILocalVariable *Var = DDI.getDI()->getVariable(); 1244 DIExpression *Expr = DDI.getDI()->getExpression(); 1245 DebugLoc DL = DDI.getdl(); 1246 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1247 unsigned SDOrder = DDI.getSDNodeOrder(); 1248 1249 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1250 // that DW_OP_stack_value is desired. 1251 assert(isa<DbgValueInst>(DDI.getDI())); 1252 bool StackValue = true; 1253 1254 // Can this Value can be encoded without any further work? 1255 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1256 return; 1257 1258 // Attempt to salvage back through as many instructions as possible. Bail if 1259 // a non-instruction is seen, such as a constant expression or global 1260 // variable. FIXME: Further work could recover those too. 1261 while (isa<Instruction>(V)) { 1262 Instruction &VAsInst = *cast<Instruction>(V); 1263 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1264 1265 // If we cannot salvage any further, and haven't yet found a suitable debug 1266 // expression, bail out. 1267 if (!NewExpr) 1268 break; 1269 1270 // New value and expr now represent this debuginfo. 1271 V = VAsInst.getOperand(0); 1272 Expr = NewExpr; 1273 1274 // Some kind of simplification occurred: check whether the operand of the 1275 // salvaged debug expression can be encoded in this DAG. 1276 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1277 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1278 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1279 return; 1280 } 1281 } 1282 1283 // This was the final opportunity to salvage this debug information, and it 1284 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1285 // any earlier variable location. 1286 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1287 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1288 DAG.AddDbgValue(SDV, nullptr, false); 1289 1290 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1291 << "\n"); 1292 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1293 << "\n"); 1294 } 1295 1296 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1297 DIExpression *Expr, DebugLoc dl, 1298 DebugLoc InstDL, unsigned Order) { 1299 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1300 SDDbgValue *SDV; 1301 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1302 isa<ConstantPointerNull>(V)) { 1303 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1304 DAG.AddDbgValue(SDV, nullptr, false); 1305 return true; 1306 } 1307 1308 // If the Value is a frame index, we can create a FrameIndex debug value 1309 // without relying on the DAG at all. 1310 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1311 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1312 if (SI != FuncInfo.StaticAllocaMap.end()) { 1313 auto SDV = 1314 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1315 /*IsIndirect*/ false, dl, SDNodeOrder); 1316 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1317 // is still available even if the SDNode gets optimized out. 1318 DAG.AddDbgValue(SDV, nullptr, false); 1319 return true; 1320 } 1321 } 1322 1323 // Do not use getValue() in here; we don't want to generate code at 1324 // this point if it hasn't been done yet. 1325 SDValue N = NodeMap[V]; 1326 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1327 N = UnusedArgNodeMap[V]; 1328 if (N.getNode()) { 1329 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1330 return true; 1331 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1332 DAG.AddDbgValue(SDV, N.getNode(), false); 1333 return true; 1334 } 1335 1336 // Special rules apply for the first dbg.values of parameter variables in a 1337 // function. Identify them by the fact they reference Argument Values, that 1338 // they're parameters, and they are parameters of the current function. We 1339 // need to let them dangle until they get an SDNode. 1340 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1341 !InstDL.getInlinedAt(); 1342 if (!IsParamOfFunc) { 1343 // The value is not used in this block yet (or it would have an SDNode). 1344 // We still want the value to appear for the user if possible -- if it has 1345 // an associated VReg, we can refer to that instead. 1346 auto VMI = FuncInfo.ValueMap.find(V); 1347 if (VMI != FuncInfo.ValueMap.end()) { 1348 unsigned Reg = VMI->second; 1349 // If this is a PHI node, it may be split up into several MI PHI nodes 1350 // (in FunctionLoweringInfo::set). 1351 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1352 V->getType(), None); 1353 if (RFV.occupiesMultipleRegs()) { 1354 unsigned Offset = 0; 1355 unsigned BitsToDescribe = 0; 1356 if (auto VarSize = Var->getSizeInBits()) 1357 BitsToDescribe = *VarSize; 1358 if (auto Fragment = Expr->getFragmentInfo()) 1359 BitsToDescribe = Fragment->SizeInBits; 1360 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1361 unsigned RegisterSize = RegAndSize.second; 1362 // Bail out if all bits are described already. 1363 if (Offset >= BitsToDescribe) 1364 break; 1365 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1366 ? BitsToDescribe - Offset 1367 : RegisterSize; 1368 auto FragmentExpr = DIExpression::createFragmentExpression( 1369 Expr, Offset, FragmentSize); 1370 if (!FragmentExpr) 1371 continue; 1372 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1373 false, dl, SDNodeOrder); 1374 DAG.AddDbgValue(SDV, nullptr, false); 1375 Offset += RegisterSize; 1376 } 1377 } else { 1378 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1379 DAG.AddDbgValue(SDV, nullptr, false); 1380 } 1381 return true; 1382 } 1383 } 1384 1385 return false; 1386 } 1387 1388 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1389 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1390 for (auto &Pair : DanglingDebugInfoMap) 1391 for (auto &DDI : Pair.second) 1392 salvageUnresolvedDbgValue(DDI); 1393 clearDanglingDebugInfo(); 1394 } 1395 1396 /// getCopyFromRegs - If there was virtual register allocated for the value V 1397 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1398 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1399 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1400 SDValue Result; 1401 1402 if (It != FuncInfo.ValueMap.end()) { 1403 Register InReg = It->second; 1404 1405 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1406 DAG.getDataLayout(), InReg, Ty, 1407 None); // This is not an ABI copy. 1408 SDValue Chain = DAG.getEntryNode(); 1409 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1410 V); 1411 resolveDanglingDebugInfo(V, Result); 1412 } 1413 1414 return Result; 1415 } 1416 1417 /// getValue - Return an SDValue for the given Value. 1418 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1419 // If we already have an SDValue for this value, use it. It's important 1420 // to do this first, so that we don't create a CopyFromReg if we already 1421 // have a regular SDValue. 1422 SDValue &N = NodeMap[V]; 1423 if (N.getNode()) return N; 1424 1425 // If there's a virtual register allocated and initialized for this 1426 // value, use it. 1427 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1428 return copyFromReg; 1429 1430 // Otherwise create a new SDValue and remember it. 1431 SDValue Val = getValueImpl(V); 1432 NodeMap[V] = Val; 1433 resolveDanglingDebugInfo(V, Val); 1434 return Val; 1435 } 1436 1437 /// getNonRegisterValue - Return an SDValue for the given Value, but 1438 /// don't look in FuncInfo.ValueMap for a virtual register. 1439 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1440 // If we already have an SDValue for this value, use it. 1441 SDValue &N = NodeMap[V]; 1442 if (N.getNode()) { 1443 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1444 // Remove the debug location from the node as the node is about to be used 1445 // in a location which may differ from the original debug location. This 1446 // is relevant to Constant and ConstantFP nodes because they can appear 1447 // as constant expressions inside PHI nodes. 1448 N->setDebugLoc(DebugLoc()); 1449 } 1450 return N; 1451 } 1452 1453 // Otherwise create a new SDValue and remember it. 1454 SDValue Val = getValueImpl(V); 1455 NodeMap[V] = Val; 1456 resolveDanglingDebugInfo(V, Val); 1457 return Val; 1458 } 1459 1460 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1461 /// Create an SDValue for the given value. 1462 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1463 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1464 1465 if (const Constant *C = dyn_cast<Constant>(V)) { 1466 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1467 1468 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1469 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1470 1471 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1472 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1473 1474 if (isa<ConstantPointerNull>(C)) { 1475 unsigned AS = V->getType()->getPointerAddressSpace(); 1476 return DAG.getConstant(0, getCurSDLoc(), 1477 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1478 } 1479 1480 if (match(C, m_VScale(DAG.getDataLayout()))) 1481 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1482 1483 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1484 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1485 1486 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1487 return DAG.getUNDEF(VT); 1488 1489 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1490 visit(CE->getOpcode(), *CE); 1491 SDValue N1 = NodeMap[V]; 1492 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1493 return N1; 1494 } 1495 1496 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1497 SmallVector<SDValue, 4> Constants; 1498 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1499 OI != OE; ++OI) { 1500 SDNode *Val = getValue(*OI).getNode(); 1501 // If the operand is an empty aggregate, there are no values. 1502 if (!Val) continue; 1503 // Add each leaf value from the operand to the Constants list 1504 // to form a flattened list of all the values. 1505 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1506 Constants.push_back(SDValue(Val, i)); 1507 } 1508 1509 return DAG.getMergeValues(Constants, getCurSDLoc()); 1510 } 1511 1512 if (const ConstantDataSequential *CDS = 1513 dyn_cast<ConstantDataSequential>(C)) { 1514 SmallVector<SDValue, 4> Ops; 1515 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1516 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1517 // Add each leaf value from the operand to the Constants list 1518 // to form a flattened list of all the values. 1519 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1520 Ops.push_back(SDValue(Val, i)); 1521 } 1522 1523 if (isa<ArrayType>(CDS->getType())) 1524 return DAG.getMergeValues(Ops, getCurSDLoc()); 1525 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1526 } 1527 1528 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1529 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1530 "Unknown struct or array constant!"); 1531 1532 SmallVector<EVT, 4> ValueVTs; 1533 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1534 unsigned NumElts = ValueVTs.size(); 1535 if (NumElts == 0) 1536 return SDValue(); // empty struct 1537 SmallVector<SDValue, 4> Constants(NumElts); 1538 for (unsigned i = 0; i != NumElts; ++i) { 1539 EVT EltVT = ValueVTs[i]; 1540 if (isa<UndefValue>(C)) 1541 Constants[i] = DAG.getUNDEF(EltVT); 1542 else if (EltVT.isFloatingPoint()) 1543 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1544 else 1545 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1546 } 1547 1548 return DAG.getMergeValues(Constants, getCurSDLoc()); 1549 } 1550 1551 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1552 return DAG.getBlockAddress(BA, VT); 1553 1554 VectorType *VecTy = cast<VectorType>(V->getType()); 1555 unsigned NumElements = VecTy->getNumElements(); 1556 1557 // Now that we know the number and type of the elements, get that number of 1558 // elements into the Ops array based on what kind of constant it is. 1559 SmallVector<SDValue, 16> Ops; 1560 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1561 for (unsigned i = 0; i != NumElements; ++i) 1562 Ops.push_back(getValue(CV->getOperand(i))); 1563 } else { 1564 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1565 EVT EltVT = 1566 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1567 1568 SDValue Op; 1569 if (EltVT.isFloatingPoint()) 1570 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1571 else 1572 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1573 Ops.assign(NumElements, Op); 1574 } 1575 1576 // Create a BUILD_VECTOR node. 1577 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1578 } 1579 1580 // If this is a static alloca, generate it as the frameindex instead of 1581 // computation. 1582 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1583 DenseMap<const AllocaInst*, int>::iterator SI = 1584 FuncInfo.StaticAllocaMap.find(AI); 1585 if (SI != FuncInfo.StaticAllocaMap.end()) 1586 return DAG.getFrameIndex(SI->second, 1587 TLI.getFrameIndexTy(DAG.getDataLayout())); 1588 } 1589 1590 // If this is an instruction which fast-isel has deferred, select it now. 1591 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1592 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1593 1594 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1595 Inst->getType(), getABIRegCopyCC(V)); 1596 SDValue Chain = DAG.getEntryNode(); 1597 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1598 } 1599 1600 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1601 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1602 } 1603 llvm_unreachable("Can't get register for value!"); 1604 } 1605 1606 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1607 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1608 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1609 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1610 bool IsSEH = isAsynchronousEHPersonality(Pers); 1611 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1612 if (!IsSEH) 1613 CatchPadMBB->setIsEHScopeEntry(); 1614 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1615 if (IsMSVCCXX || IsCoreCLR) 1616 CatchPadMBB->setIsEHFuncletEntry(); 1617 } 1618 1619 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1620 // Update machine-CFG edge. 1621 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1622 FuncInfo.MBB->addSuccessor(TargetMBB); 1623 1624 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1625 bool IsSEH = isAsynchronousEHPersonality(Pers); 1626 if (IsSEH) { 1627 // If this is not a fall-through branch or optimizations are switched off, 1628 // emit the branch. 1629 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1630 TM.getOptLevel() == CodeGenOpt::None) 1631 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1632 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1633 return; 1634 } 1635 1636 // Figure out the funclet membership for the catchret's successor. 1637 // This will be used by the FuncletLayout pass to determine how to order the 1638 // BB's. 1639 // A 'catchret' returns to the outer scope's color. 1640 Value *ParentPad = I.getCatchSwitchParentPad(); 1641 const BasicBlock *SuccessorColor; 1642 if (isa<ConstantTokenNone>(ParentPad)) 1643 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1644 else 1645 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1646 assert(SuccessorColor && "No parent funclet for catchret!"); 1647 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1648 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1649 1650 // Create the terminator node. 1651 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1652 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1653 DAG.getBasicBlock(SuccessorColorMBB)); 1654 DAG.setRoot(Ret); 1655 } 1656 1657 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1658 // Don't emit any special code for the cleanuppad instruction. It just marks 1659 // the start of an EH scope/funclet. 1660 FuncInfo.MBB->setIsEHScopeEntry(); 1661 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1662 if (Pers != EHPersonality::Wasm_CXX) { 1663 FuncInfo.MBB->setIsEHFuncletEntry(); 1664 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1665 } 1666 } 1667 1668 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1669 // the control flow always stops at the single catch pad, as it does for a 1670 // cleanup pad. In case the exception caught is not of the types the catch pad 1671 // catches, it will be rethrown by a rethrow. 1672 static void findWasmUnwindDestinations( 1673 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1674 BranchProbability Prob, 1675 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1676 &UnwindDests) { 1677 while (EHPadBB) { 1678 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1679 if (isa<CleanupPadInst>(Pad)) { 1680 // Stop on cleanup pads. 1681 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1682 UnwindDests.back().first->setIsEHScopeEntry(); 1683 break; 1684 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1685 // Add the catchpad handlers to the possible destinations. We don't 1686 // continue to the unwind destination of the catchswitch for wasm. 1687 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1688 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1689 UnwindDests.back().first->setIsEHScopeEntry(); 1690 } 1691 break; 1692 } else { 1693 continue; 1694 } 1695 } 1696 } 1697 1698 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1699 /// many places it could ultimately go. In the IR, we have a single unwind 1700 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1701 /// This function skips over imaginary basic blocks that hold catchswitch 1702 /// instructions, and finds all the "real" machine 1703 /// basic block destinations. As those destinations may not be successors of 1704 /// EHPadBB, here we also calculate the edge probability to those destinations. 1705 /// The passed-in Prob is the edge probability to EHPadBB. 1706 static void findUnwindDestinations( 1707 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1708 BranchProbability Prob, 1709 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1710 &UnwindDests) { 1711 EHPersonality Personality = 1712 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1713 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1714 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1715 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1716 bool IsSEH = isAsynchronousEHPersonality(Personality); 1717 1718 if (IsWasmCXX) { 1719 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1720 assert(UnwindDests.size() <= 1 && 1721 "There should be at most one unwind destination for wasm"); 1722 return; 1723 } 1724 1725 while (EHPadBB) { 1726 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1727 BasicBlock *NewEHPadBB = nullptr; 1728 if (isa<LandingPadInst>(Pad)) { 1729 // Stop on landingpads. They are not funclets. 1730 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1731 break; 1732 } else if (isa<CleanupPadInst>(Pad)) { 1733 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1734 // personalities. 1735 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1736 UnwindDests.back().first->setIsEHScopeEntry(); 1737 UnwindDests.back().first->setIsEHFuncletEntry(); 1738 break; 1739 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1740 // Add the catchpad handlers to the possible destinations. 1741 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1742 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1743 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1744 if (IsMSVCCXX || IsCoreCLR) 1745 UnwindDests.back().first->setIsEHFuncletEntry(); 1746 if (!IsSEH) 1747 UnwindDests.back().first->setIsEHScopeEntry(); 1748 } 1749 NewEHPadBB = CatchSwitch->getUnwindDest(); 1750 } else { 1751 continue; 1752 } 1753 1754 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1755 if (BPI && NewEHPadBB) 1756 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1757 EHPadBB = NewEHPadBB; 1758 } 1759 } 1760 1761 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1762 // Update successor info. 1763 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1764 auto UnwindDest = I.getUnwindDest(); 1765 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1766 BranchProbability UnwindDestProb = 1767 (BPI && UnwindDest) 1768 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1769 : BranchProbability::getZero(); 1770 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1771 for (auto &UnwindDest : UnwindDests) { 1772 UnwindDest.first->setIsEHPad(); 1773 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1774 } 1775 FuncInfo.MBB->normalizeSuccProbs(); 1776 1777 // Create the terminator node. 1778 SDValue Ret = 1779 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1780 DAG.setRoot(Ret); 1781 } 1782 1783 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1784 report_fatal_error("visitCatchSwitch not yet implemented!"); 1785 } 1786 1787 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1788 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1789 auto &DL = DAG.getDataLayout(); 1790 SDValue Chain = getControlRoot(); 1791 SmallVector<ISD::OutputArg, 8> Outs; 1792 SmallVector<SDValue, 8> OutVals; 1793 1794 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1795 // lower 1796 // 1797 // %val = call <ty> @llvm.experimental.deoptimize() 1798 // ret <ty> %val 1799 // 1800 // differently. 1801 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1802 LowerDeoptimizingReturn(); 1803 return; 1804 } 1805 1806 if (!FuncInfo.CanLowerReturn) { 1807 unsigned DemoteReg = FuncInfo.DemoteRegister; 1808 const Function *F = I.getParent()->getParent(); 1809 1810 // Emit a store of the return value through the virtual register. 1811 // Leave Outs empty so that LowerReturn won't try to load return 1812 // registers the usual way. 1813 SmallVector<EVT, 1> PtrValueVTs; 1814 ComputeValueVTs(TLI, DL, 1815 F->getReturnType()->getPointerTo( 1816 DAG.getDataLayout().getAllocaAddrSpace()), 1817 PtrValueVTs); 1818 1819 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1820 DemoteReg, PtrValueVTs[0]); 1821 SDValue RetOp = getValue(I.getOperand(0)); 1822 1823 SmallVector<EVT, 4> ValueVTs, MemVTs; 1824 SmallVector<uint64_t, 4> Offsets; 1825 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1826 &Offsets); 1827 unsigned NumValues = ValueVTs.size(); 1828 1829 SmallVector<SDValue, 4> Chains(NumValues); 1830 for (unsigned i = 0; i != NumValues; ++i) { 1831 // An aggregate return value cannot wrap around the address space, so 1832 // offsets to its parts don't wrap either. 1833 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1834 1835 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1836 if (MemVTs[i] != ValueVTs[i]) 1837 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1838 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1839 // FIXME: better loc info would be nice. 1840 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1841 } 1842 1843 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1844 MVT::Other, Chains); 1845 } else if (I.getNumOperands() != 0) { 1846 SmallVector<EVT, 4> ValueVTs; 1847 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1848 unsigned NumValues = ValueVTs.size(); 1849 if (NumValues) { 1850 SDValue RetOp = getValue(I.getOperand(0)); 1851 1852 const Function *F = I.getParent()->getParent(); 1853 1854 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1855 I.getOperand(0)->getType(), F->getCallingConv(), 1856 /*IsVarArg*/ false); 1857 1858 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1859 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1860 Attribute::SExt)) 1861 ExtendKind = ISD::SIGN_EXTEND; 1862 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1863 Attribute::ZExt)) 1864 ExtendKind = ISD::ZERO_EXTEND; 1865 1866 LLVMContext &Context = F->getContext(); 1867 bool RetInReg = F->getAttributes().hasAttribute( 1868 AttributeList::ReturnIndex, Attribute::InReg); 1869 1870 for (unsigned j = 0; j != NumValues; ++j) { 1871 EVT VT = ValueVTs[j]; 1872 1873 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1874 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1875 1876 CallingConv::ID CC = F->getCallingConv(); 1877 1878 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1879 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1880 SmallVector<SDValue, 4> Parts(NumParts); 1881 getCopyToParts(DAG, getCurSDLoc(), 1882 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1883 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1884 1885 // 'inreg' on function refers to return value 1886 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1887 if (RetInReg) 1888 Flags.setInReg(); 1889 1890 if (I.getOperand(0)->getType()->isPointerTy()) { 1891 Flags.setPointer(); 1892 Flags.setPointerAddrSpace( 1893 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1894 } 1895 1896 if (NeedsRegBlock) { 1897 Flags.setInConsecutiveRegs(); 1898 if (j == NumValues - 1) 1899 Flags.setInConsecutiveRegsLast(); 1900 } 1901 1902 // Propagate extension type if any 1903 if (ExtendKind == ISD::SIGN_EXTEND) 1904 Flags.setSExt(); 1905 else if (ExtendKind == ISD::ZERO_EXTEND) 1906 Flags.setZExt(); 1907 1908 for (unsigned i = 0; i < NumParts; ++i) { 1909 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1910 VT, /*isfixed=*/true, 0, 0)); 1911 OutVals.push_back(Parts[i]); 1912 } 1913 } 1914 } 1915 } 1916 1917 // Push in swifterror virtual register as the last element of Outs. This makes 1918 // sure swifterror virtual register will be returned in the swifterror 1919 // physical register. 1920 const Function *F = I.getParent()->getParent(); 1921 if (TLI.supportSwiftError() && 1922 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1923 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1924 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1925 Flags.setSwiftError(); 1926 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1927 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1928 true /*isfixed*/, 1 /*origidx*/, 1929 0 /*partOffs*/)); 1930 // Create SDNode for the swifterror virtual register. 1931 OutVals.push_back( 1932 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1933 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1934 EVT(TLI.getPointerTy(DL)))); 1935 } 1936 1937 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1938 CallingConv::ID CallConv = 1939 DAG.getMachineFunction().getFunction().getCallingConv(); 1940 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1941 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1942 1943 // Verify that the target's LowerReturn behaved as expected. 1944 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1945 "LowerReturn didn't return a valid chain!"); 1946 1947 // Update the DAG with the new chain value resulting from return lowering. 1948 DAG.setRoot(Chain); 1949 } 1950 1951 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1952 /// created for it, emit nodes to copy the value into the virtual 1953 /// registers. 1954 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1955 // Skip empty types 1956 if (V->getType()->isEmptyTy()) 1957 return; 1958 1959 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1960 if (VMI != FuncInfo.ValueMap.end()) { 1961 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1962 CopyValueToVirtualRegister(V, VMI->second); 1963 } 1964 } 1965 1966 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1967 /// the current basic block, add it to ValueMap now so that we'll get a 1968 /// CopyTo/FromReg. 1969 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1970 // No need to export constants. 1971 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1972 1973 // Already exported? 1974 if (FuncInfo.isExportedInst(V)) return; 1975 1976 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1977 CopyValueToVirtualRegister(V, Reg); 1978 } 1979 1980 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1981 const BasicBlock *FromBB) { 1982 // The operands of the setcc have to be in this block. We don't know 1983 // how to export them from some other block. 1984 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1985 // Can export from current BB. 1986 if (VI->getParent() == FromBB) 1987 return true; 1988 1989 // Is already exported, noop. 1990 return FuncInfo.isExportedInst(V); 1991 } 1992 1993 // If this is an argument, we can export it if the BB is the entry block or 1994 // if it is already exported. 1995 if (isa<Argument>(V)) { 1996 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1997 return true; 1998 1999 // Otherwise, can only export this if it is already exported. 2000 return FuncInfo.isExportedInst(V); 2001 } 2002 2003 // Otherwise, constants can always be exported. 2004 return true; 2005 } 2006 2007 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2008 BranchProbability 2009 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2010 const MachineBasicBlock *Dst) const { 2011 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2012 const BasicBlock *SrcBB = Src->getBasicBlock(); 2013 const BasicBlock *DstBB = Dst->getBasicBlock(); 2014 if (!BPI) { 2015 // If BPI is not available, set the default probability as 1 / N, where N is 2016 // the number of successors. 2017 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2018 return BranchProbability(1, SuccSize); 2019 } 2020 return BPI->getEdgeProbability(SrcBB, DstBB); 2021 } 2022 2023 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2024 MachineBasicBlock *Dst, 2025 BranchProbability Prob) { 2026 if (!FuncInfo.BPI) 2027 Src->addSuccessorWithoutProb(Dst); 2028 else { 2029 if (Prob.isUnknown()) 2030 Prob = getEdgeProbability(Src, Dst); 2031 Src->addSuccessor(Dst, Prob); 2032 } 2033 } 2034 2035 static bool InBlock(const Value *V, const BasicBlock *BB) { 2036 if (const Instruction *I = dyn_cast<Instruction>(V)) 2037 return I->getParent() == BB; 2038 return true; 2039 } 2040 2041 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2042 /// This function emits a branch and is used at the leaves of an OR or an 2043 /// AND operator tree. 2044 void 2045 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2046 MachineBasicBlock *TBB, 2047 MachineBasicBlock *FBB, 2048 MachineBasicBlock *CurBB, 2049 MachineBasicBlock *SwitchBB, 2050 BranchProbability TProb, 2051 BranchProbability FProb, 2052 bool InvertCond) { 2053 const BasicBlock *BB = CurBB->getBasicBlock(); 2054 2055 // If the leaf of the tree is a comparison, merge the condition into 2056 // the caseblock. 2057 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2058 // The operands of the cmp have to be in this block. We don't know 2059 // how to export them from some other block. If this is the first block 2060 // of the sequence, no exporting is needed. 2061 if (CurBB == SwitchBB || 2062 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2063 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2064 ISD::CondCode Condition; 2065 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2066 ICmpInst::Predicate Pred = 2067 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2068 Condition = getICmpCondCode(Pred); 2069 } else { 2070 const FCmpInst *FC = cast<FCmpInst>(Cond); 2071 FCmpInst::Predicate Pred = 2072 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2073 Condition = getFCmpCondCode(Pred); 2074 if (TM.Options.NoNaNsFPMath) 2075 Condition = getFCmpCodeWithoutNaN(Condition); 2076 } 2077 2078 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2079 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2080 SL->SwitchCases.push_back(CB); 2081 return; 2082 } 2083 } 2084 2085 // Create a CaseBlock record representing this branch. 2086 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2087 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2088 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2089 SL->SwitchCases.push_back(CB); 2090 } 2091 2092 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2093 MachineBasicBlock *TBB, 2094 MachineBasicBlock *FBB, 2095 MachineBasicBlock *CurBB, 2096 MachineBasicBlock *SwitchBB, 2097 Instruction::BinaryOps Opc, 2098 BranchProbability TProb, 2099 BranchProbability FProb, 2100 bool InvertCond) { 2101 // Skip over not part of the tree and remember to invert op and operands at 2102 // next level. 2103 Value *NotCond; 2104 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2105 InBlock(NotCond, CurBB->getBasicBlock())) { 2106 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2107 !InvertCond); 2108 return; 2109 } 2110 2111 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2112 // Compute the effective opcode for Cond, taking into account whether it needs 2113 // to be inverted, e.g. 2114 // and (not (or A, B)), C 2115 // gets lowered as 2116 // and (and (not A, not B), C) 2117 unsigned BOpc = 0; 2118 if (BOp) { 2119 BOpc = BOp->getOpcode(); 2120 if (InvertCond) { 2121 if (BOpc == Instruction::And) 2122 BOpc = Instruction::Or; 2123 else if (BOpc == Instruction::Or) 2124 BOpc = Instruction::And; 2125 } 2126 } 2127 2128 // If this node is not part of the or/and tree, emit it as a branch. 2129 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2130 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2131 BOp->getParent() != CurBB->getBasicBlock() || 2132 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2133 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2134 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2135 TProb, FProb, InvertCond); 2136 return; 2137 } 2138 2139 // Create TmpBB after CurBB. 2140 MachineFunction::iterator BBI(CurBB); 2141 MachineFunction &MF = DAG.getMachineFunction(); 2142 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2143 CurBB->getParent()->insert(++BBI, TmpBB); 2144 2145 if (Opc == Instruction::Or) { 2146 // Codegen X | Y as: 2147 // BB1: 2148 // jmp_if_X TBB 2149 // jmp TmpBB 2150 // TmpBB: 2151 // jmp_if_Y TBB 2152 // jmp FBB 2153 // 2154 2155 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2156 // The requirement is that 2157 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2158 // = TrueProb for original BB. 2159 // Assuming the original probabilities are A and B, one choice is to set 2160 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2161 // A/(1+B) and 2B/(1+B). This choice assumes that 2162 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2163 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2164 // TmpBB, but the math is more complicated. 2165 2166 auto NewTrueProb = TProb / 2; 2167 auto NewFalseProb = TProb / 2 + FProb; 2168 // Emit the LHS condition. 2169 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2170 NewTrueProb, NewFalseProb, InvertCond); 2171 2172 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2173 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2174 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2175 // Emit the RHS condition into TmpBB. 2176 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2177 Probs[0], Probs[1], InvertCond); 2178 } else { 2179 assert(Opc == Instruction::And && "Unknown merge op!"); 2180 // Codegen X & Y as: 2181 // BB1: 2182 // jmp_if_X TmpBB 2183 // jmp FBB 2184 // TmpBB: 2185 // jmp_if_Y TBB 2186 // jmp FBB 2187 // 2188 // This requires creation of TmpBB after CurBB. 2189 2190 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2191 // The requirement is that 2192 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2193 // = FalseProb for original BB. 2194 // Assuming the original probabilities are A and B, one choice is to set 2195 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2196 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2197 // TrueProb for BB1 * FalseProb for TmpBB. 2198 2199 auto NewTrueProb = TProb + FProb / 2; 2200 auto NewFalseProb = FProb / 2; 2201 // Emit the LHS condition. 2202 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2203 NewTrueProb, NewFalseProb, InvertCond); 2204 2205 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2206 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2207 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2208 // Emit the RHS condition into TmpBB. 2209 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2210 Probs[0], Probs[1], InvertCond); 2211 } 2212 } 2213 2214 /// If the set of cases should be emitted as a series of branches, return true. 2215 /// If we should emit this as a bunch of and/or'd together conditions, return 2216 /// false. 2217 bool 2218 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2219 if (Cases.size() != 2) return true; 2220 2221 // If this is two comparisons of the same values or'd or and'd together, they 2222 // will get folded into a single comparison, so don't emit two blocks. 2223 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2224 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2225 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2226 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2227 return false; 2228 } 2229 2230 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2231 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2232 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2233 Cases[0].CC == Cases[1].CC && 2234 isa<Constant>(Cases[0].CmpRHS) && 2235 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2236 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2237 return false; 2238 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2239 return false; 2240 } 2241 2242 return true; 2243 } 2244 2245 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2246 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2247 2248 // Update machine-CFG edges. 2249 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2250 2251 if (I.isUnconditional()) { 2252 // Update machine-CFG edges. 2253 BrMBB->addSuccessor(Succ0MBB); 2254 2255 // If this is not a fall-through branch or optimizations are switched off, 2256 // emit the branch. 2257 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2258 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2259 MVT::Other, getControlRoot(), 2260 DAG.getBasicBlock(Succ0MBB))); 2261 2262 return; 2263 } 2264 2265 // If this condition is one of the special cases we handle, do special stuff 2266 // now. 2267 const Value *CondVal = I.getCondition(); 2268 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2269 2270 // If this is a series of conditions that are or'd or and'd together, emit 2271 // this as a sequence of branches instead of setcc's with and/or operations. 2272 // As long as jumps are not expensive, this should improve performance. 2273 // For example, instead of something like: 2274 // cmp A, B 2275 // C = seteq 2276 // cmp D, E 2277 // F = setle 2278 // or C, F 2279 // jnz foo 2280 // Emit: 2281 // cmp A, B 2282 // je foo 2283 // cmp D, E 2284 // jle foo 2285 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2286 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2287 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2288 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2289 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2290 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2291 Opcode, 2292 getEdgeProbability(BrMBB, Succ0MBB), 2293 getEdgeProbability(BrMBB, Succ1MBB), 2294 /*InvertCond=*/false); 2295 // If the compares in later blocks need to use values not currently 2296 // exported from this block, export them now. This block should always 2297 // be the first entry. 2298 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2299 2300 // Allow some cases to be rejected. 2301 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2302 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2303 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2304 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2305 } 2306 2307 // Emit the branch for this block. 2308 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2309 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2310 return; 2311 } 2312 2313 // Okay, we decided not to do this, remove any inserted MBB's and clear 2314 // SwitchCases. 2315 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2316 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2317 2318 SL->SwitchCases.clear(); 2319 } 2320 } 2321 2322 // Create a CaseBlock record representing this branch. 2323 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2324 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2325 2326 // Use visitSwitchCase to actually insert the fast branch sequence for this 2327 // cond branch. 2328 visitSwitchCase(CB, BrMBB); 2329 } 2330 2331 /// visitSwitchCase - Emits the necessary code to represent a single node in 2332 /// the binary search tree resulting from lowering a switch instruction. 2333 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2334 MachineBasicBlock *SwitchBB) { 2335 SDValue Cond; 2336 SDValue CondLHS = getValue(CB.CmpLHS); 2337 SDLoc dl = CB.DL; 2338 2339 if (CB.CC == ISD::SETTRUE) { 2340 // Branch or fall through to TrueBB. 2341 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2342 SwitchBB->normalizeSuccProbs(); 2343 if (CB.TrueBB != NextBlock(SwitchBB)) { 2344 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2345 DAG.getBasicBlock(CB.TrueBB))); 2346 } 2347 return; 2348 } 2349 2350 auto &TLI = DAG.getTargetLoweringInfo(); 2351 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2352 2353 // Build the setcc now. 2354 if (!CB.CmpMHS) { 2355 // Fold "(X == true)" to X and "(X == false)" to !X to 2356 // handle common cases produced by branch lowering. 2357 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2358 CB.CC == ISD::SETEQ) 2359 Cond = CondLHS; 2360 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2361 CB.CC == ISD::SETEQ) { 2362 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2363 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2364 } else { 2365 SDValue CondRHS = getValue(CB.CmpRHS); 2366 2367 // If a pointer's DAG type is larger than its memory type then the DAG 2368 // values are zero-extended. This breaks signed comparisons so truncate 2369 // back to the underlying type before doing the compare. 2370 if (CondLHS.getValueType() != MemVT) { 2371 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2372 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2373 } 2374 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2375 } 2376 } else { 2377 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2378 2379 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2380 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2381 2382 SDValue CmpOp = getValue(CB.CmpMHS); 2383 EVT VT = CmpOp.getValueType(); 2384 2385 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2386 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2387 ISD::SETLE); 2388 } else { 2389 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2390 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2391 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2392 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2393 } 2394 } 2395 2396 // Update successor info 2397 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2398 // TrueBB and FalseBB are always different unless the incoming IR is 2399 // degenerate. This only happens when running llc on weird IR. 2400 if (CB.TrueBB != CB.FalseBB) 2401 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2402 SwitchBB->normalizeSuccProbs(); 2403 2404 // If the lhs block is the next block, invert the condition so that we can 2405 // fall through to the lhs instead of the rhs block. 2406 if (CB.TrueBB == NextBlock(SwitchBB)) { 2407 std::swap(CB.TrueBB, CB.FalseBB); 2408 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2409 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2410 } 2411 2412 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2413 MVT::Other, getControlRoot(), Cond, 2414 DAG.getBasicBlock(CB.TrueBB)); 2415 2416 // Insert the false branch. Do this even if it's a fall through branch, 2417 // this makes it easier to do DAG optimizations which require inverting 2418 // the branch condition. 2419 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2420 DAG.getBasicBlock(CB.FalseBB)); 2421 2422 DAG.setRoot(BrCond); 2423 } 2424 2425 /// visitJumpTable - Emit JumpTable node in the current MBB 2426 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2427 // Emit the code for the jump table 2428 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2429 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2430 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2431 JT.Reg, PTy); 2432 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2433 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2434 MVT::Other, Index.getValue(1), 2435 Table, Index); 2436 DAG.setRoot(BrJumpTable); 2437 } 2438 2439 /// visitJumpTableHeader - This function emits necessary code to produce index 2440 /// in the JumpTable from switch case. 2441 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2442 JumpTableHeader &JTH, 2443 MachineBasicBlock *SwitchBB) { 2444 SDLoc dl = getCurSDLoc(); 2445 2446 // Subtract the lowest switch case value from the value being switched on. 2447 SDValue SwitchOp = getValue(JTH.SValue); 2448 EVT VT = SwitchOp.getValueType(); 2449 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2450 DAG.getConstant(JTH.First, dl, VT)); 2451 2452 // The SDNode we just created, which holds the value being switched on minus 2453 // the smallest case value, needs to be copied to a virtual register so it 2454 // can be used as an index into the jump table in a subsequent basic block. 2455 // This value may be smaller or larger than the target's pointer type, and 2456 // therefore require extension or truncating. 2457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2458 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2459 2460 unsigned JumpTableReg = 2461 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2462 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2463 JumpTableReg, SwitchOp); 2464 JT.Reg = JumpTableReg; 2465 2466 if (!JTH.OmitRangeCheck) { 2467 // Emit the range check for the jump table, and branch to the default block 2468 // for the switch statement if the value being switched on exceeds the 2469 // largest case in the switch. 2470 SDValue CMP = DAG.getSetCC( 2471 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2472 Sub.getValueType()), 2473 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2474 2475 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2476 MVT::Other, CopyTo, CMP, 2477 DAG.getBasicBlock(JT.Default)); 2478 2479 // Avoid emitting unnecessary branches to the next block. 2480 if (JT.MBB != NextBlock(SwitchBB)) 2481 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2482 DAG.getBasicBlock(JT.MBB)); 2483 2484 DAG.setRoot(BrCond); 2485 } else { 2486 // Avoid emitting unnecessary branches to the next block. 2487 if (JT.MBB != NextBlock(SwitchBB)) 2488 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2489 DAG.getBasicBlock(JT.MBB))); 2490 else 2491 DAG.setRoot(CopyTo); 2492 } 2493 } 2494 2495 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2496 /// variable if there exists one. 2497 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2498 SDValue &Chain) { 2499 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2500 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2501 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2502 MachineFunction &MF = DAG.getMachineFunction(); 2503 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2504 MachineSDNode *Node = 2505 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2506 if (Global) { 2507 MachinePointerInfo MPInfo(Global); 2508 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2509 MachineMemOperand::MODereferenceable; 2510 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2511 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2512 DAG.setNodeMemRefs(Node, {MemRef}); 2513 } 2514 if (PtrTy != PtrMemTy) 2515 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2516 return SDValue(Node, 0); 2517 } 2518 2519 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2520 /// tail spliced into a stack protector check success bb. 2521 /// 2522 /// For a high level explanation of how this fits into the stack protector 2523 /// generation see the comment on the declaration of class 2524 /// StackProtectorDescriptor. 2525 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2526 MachineBasicBlock *ParentBB) { 2527 2528 // First create the loads to the guard/stack slot for the comparison. 2529 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2530 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2531 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2532 2533 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2534 int FI = MFI.getStackProtectorIndex(); 2535 2536 SDValue Guard; 2537 SDLoc dl = getCurSDLoc(); 2538 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2539 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2540 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2541 2542 // Generate code to load the content of the guard slot. 2543 SDValue GuardVal = DAG.getLoad( 2544 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2545 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2546 MachineMemOperand::MOVolatile); 2547 2548 if (TLI.useStackGuardXorFP()) 2549 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2550 2551 // Retrieve guard check function, nullptr if instrumentation is inlined. 2552 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2553 // The target provides a guard check function to validate the guard value. 2554 // Generate a call to that function with the content of the guard slot as 2555 // argument. 2556 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2557 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2558 2559 TargetLowering::ArgListTy Args; 2560 TargetLowering::ArgListEntry Entry; 2561 Entry.Node = GuardVal; 2562 Entry.Ty = FnTy->getParamType(0); 2563 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2564 Entry.IsInReg = true; 2565 Args.push_back(Entry); 2566 2567 TargetLowering::CallLoweringInfo CLI(DAG); 2568 CLI.setDebugLoc(getCurSDLoc()) 2569 .setChain(DAG.getEntryNode()) 2570 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2571 getValue(GuardCheckFn), std::move(Args)); 2572 2573 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2574 DAG.setRoot(Result.second); 2575 return; 2576 } 2577 2578 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2579 // Otherwise, emit a volatile load to retrieve the stack guard value. 2580 SDValue Chain = DAG.getEntryNode(); 2581 if (TLI.useLoadStackGuardNode()) { 2582 Guard = getLoadStackGuard(DAG, dl, Chain); 2583 } else { 2584 const Value *IRGuard = TLI.getSDagStackGuard(M); 2585 SDValue GuardPtr = getValue(IRGuard); 2586 2587 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2588 MachinePointerInfo(IRGuard, 0), Align, 2589 MachineMemOperand::MOVolatile); 2590 } 2591 2592 // Perform the comparison via a getsetcc. 2593 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2594 *DAG.getContext(), 2595 Guard.getValueType()), 2596 Guard, GuardVal, ISD::SETNE); 2597 2598 // If the guard/stackslot do not equal, branch to failure MBB. 2599 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2600 MVT::Other, GuardVal.getOperand(0), 2601 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2602 // Otherwise branch to success MBB. 2603 SDValue Br = DAG.getNode(ISD::BR, dl, 2604 MVT::Other, BrCond, 2605 DAG.getBasicBlock(SPD.getSuccessMBB())); 2606 2607 DAG.setRoot(Br); 2608 } 2609 2610 /// Codegen the failure basic block for a stack protector check. 2611 /// 2612 /// A failure stack protector machine basic block consists simply of a call to 2613 /// __stack_chk_fail(). 2614 /// 2615 /// For a high level explanation of how this fits into the stack protector 2616 /// generation see the comment on the declaration of class 2617 /// StackProtectorDescriptor. 2618 void 2619 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2620 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2621 TargetLowering::MakeLibCallOptions CallOptions; 2622 CallOptions.setDiscardResult(true); 2623 SDValue Chain = 2624 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2625 None, CallOptions, getCurSDLoc()).second; 2626 // On PS4, the "return address" must still be within the calling function, 2627 // even if it's at the very end, so emit an explicit TRAP here. 2628 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2629 if (TM.getTargetTriple().isPS4CPU()) 2630 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2631 2632 DAG.setRoot(Chain); 2633 } 2634 2635 /// visitBitTestHeader - This function emits necessary code to produce value 2636 /// suitable for "bit tests" 2637 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2638 MachineBasicBlock *SwitchBB) { 2639 SDLoc dl = getCurSDLoc(); 2640 2641 // Subtract the minimum value. 2642 SDValue SwitchOp = getValue(B.SValue); 2643 EVT VT = SwitchOp.getValueType(); 2644 SDValue RangeSub = 2645 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2646 2647 // Determine the type of the test operands. 2648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2649 bool UsePtrType = false; 2650 if (!TLI.isTypeLegal(VT)) { 2651 UsePtrType = true; 2652 } else { 2653 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2654 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2655 // Switch table case range are encoded into series of masks. 2656 // Just use pointer type, it's guaranteed to fit. 2657 UsePtrType = true; 2658 break; 2659 } 2660 } 2661 SDValue Sub = RangeSub; 2662 if (UsePtrType) { 2663 VT = TLI.getPointerTy(DAG.getDataLayout()); 2664 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2665 } 2666 2667 B.RegVT = VT.getSimpleVT(); 2668 B.Reg = FuncInfo.CreateReg(B.RegVT); 2669 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2670 2671 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2672 2673 if (!B.OmitRangeCheck) 2674 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2675 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2676 SwitchBB->normalizeSuccProbs(); 2677 2678 SDValue Root = CopyTo; 2679 if (!B.OmitRangeCheck) { 2680 // Conditional branch to the default block. 2681 SDValue RangeCmp = DAG.getSetCC(dl, 2682 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2683 RangeSub.getValueType()), 2684 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2685 ISD::SETUGT); 2686 2687 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2688 DAG.getBasicBlock(B.Default)); 2689 } 2690 2691 // Avoid emitting unnecessary branches to the next block. 2692 if (MBB != NextBlock(SwitchBB)) 2693 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2694 2695 DAG.setRoot(Root); 2696 } 2697 2698 /// visitBitTestCase - this function produces one "bit test" 2699 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2700 MachineBasicBlock* NextMBB, 2701 BranchProbability BranchProbToNext, 2702 unsigned Reg, 2703 BitTestCase &B, 2704 MachineBasicBlock *SwitchBB) { 2705 SDLoc dl = getCurSDLoc(); 2706 MVT VT = BB.RegVT; 2707 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2708 SDValue Cmp; 2709 unsigned PopCount = countPopulation(B.Mask); 2710 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2711 if (PopCount == 1) { 2712 // Testing for a single bit; just compare the shift count with what it 2713 // would need to be to shift a 1 bit in that position. 2714 Cmp = DAG.getSetCC( 2715 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2716 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2717 ISD::SETEQ); 2718 } else if (PopCount == BB.Range) { 2719 // There is only one zero bit in the range, test for it directly. 2720 Cmp = DAG.getSetCC( 2721 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2722 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2723 ISD::SETNE); 2724 } else { 2725 // Make desired shift 2726 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2727 DAG.getConstant(1, dl, VT), ShiftOp); 2728 2729 // Emit bit tests and jumps 2730 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2731 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2732 Cmp = DAG.getSetCC( 2733 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2734 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2735 } 2736 2737 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2738 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2739 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2740 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2741 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2742 // one as they are relative probabilities (and thus work more like weights), 2743 // and hence we need to normalize them to let the sum of them become one. 2744 SwitchBB->normalizeSuccProbs(); 2745 2746 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2747 MVT::Other, getControlRoot(), 2748 Cmp, DAG.getBasicBlock(B.TargetBB)); 2749 2750 // Avoid emitting unnecessary branches to the next block. 2751 if (NextMBB != NextBlock(SwitchBB)) 2752 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2753 DAG.getBasicBlock(NextMBB)); 2754 2755 DAG.setRoot(BrAnd); 2756 } 2757 2758 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2759 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2760 2761 // Retrieve successors. Look through artificial IR level blocks like 2762 // catchswitch for successors. 2763 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2764 const BasicBlock *EHPadBB = I.getSuccessor(1); 2765 2766 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2767 // have to do anything here to lower funclet bundles. 2768 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2769 LLVMContext::OB_funclet, 2770 LLVMContext::OB_cfguardtarget}) && 2771 "Cannot lower invokes with arbitrary operand bundles yet!"); 2772 2773 const Value *Callee(I.getCalledValue()); 2774 const Function *Fn = dyn_cast<Function>(Callee); 2775 if (isa<InlineAsm>(Callee)) 2776 visitInlineAsm(I); 2777 else if (Fn && Fn->isIntrinsic()) { 2778 switch (Fn->getIntrinsicID()) { 2779 default: 2780 llvm_unreachable("Cannot invoke this intrinsic"); 2781 case Intrinsic::donothing: 2782 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2783 break; 2784 case Intrinsic::experimental_patchpoint_void: 2785 case Intrinsic::experimental_patchpoint_i64: 2786 visitPatchpoint(I, EHPadBB); 2787 break; 2788 case Intrinsic::experimental_gc_statepoint: 2789 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2790 break; 2791 case Intrinsic::wasm_rethrow_in_catch: { 2792 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2793 // special because it can be invoked, so we manually lower it to a DAG 2794 // node here. 2795 SmallVector<SDValue, 8> Ops; 2796 Ops.push_back(getRoot()); // inchain 2797 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2798 Ops.push_back( 2799 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2800 TLI.getPointerTy(DAG.getDataLayout()))); 2801 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2802 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2803 break; 2804 } 2805 } 2806 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2807 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2808 // Eventually we will support lowering the @llvm.experimental.deoptimize 2809 // intrinsic, and right now there are no plans to support other intrinsics 2810 // with deopt state. 2811 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2812 } else { 2813 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2814 } 2815 2816 // If the value of the invoke is used outside of its defining block, make it 2817 // available as a virtual register. 2818 // We already took care of the exported value for the statepoint instruction 2819 // during call to the LowerStatepoint. 2820 if (!isStatepoint(I)) { 2821 CopyToExportRegsIfNeeded(&I); 2822 } 2823 2824 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2825 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2826 BranchProbability EHPadBBProb = 2827 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2828 : BranchProbability::getZero(); 2829 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2830 2831 // Update successor info. 2832 addSuccessorWithProb(InvokeMBB, Return); 2833 for (auto &UnwindDest : UnwindDests) { 2834 UnwindDest.first->setIsEHPad(); 2835 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2836 } 2837 InvokeMBB->normalizeSuccProbs(); 2838 2839 // Drop into normal successor. 2840 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2841 DAG.getBasicBlock(Return))); 2842 } 2843 2844 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2845 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2846 2847 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2848 // have to do anything here to lower funclet bundles. 2849 assert(!I.hasOperandBundlesOtherThan( 2850 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2851 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2852 2853 assert(isa<InlineAsm>(I.getCalledValue()) && 2854 "Only know how to handle inlineasm callbr"); 2855 visitInlineAsm(I); 2856 CopyToExportRegsIfNeeded(&I); 2857 2858 // Retrieve successors. 2859 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2860 Return->setInlineAsmBrDefaultTarget(); 2861 2862 // Update successor info. 2863 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2864 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2865 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2866 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2867 CallBrMBB->addInlineAsmBrIndirectTarget(Target); 2868 } 2869 CallBrMBB->normalizeSuccProbs(); 2870 2871 // Drop into default successor. 2872 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2873 MVT::Other, getControlRoot(), 2874 DAG.getBasicBlock(Return))); 2875 } 2876 2877 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2878 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2879 } 2880 2881 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2882 assert(FuncInfo.MBB->isEHPad() && 2883 "Call to landingpad not in landing pad!"); 2884 2885 // If there aren't registers to copy the values into (e.g., during SjLj 2886 // exceptions), then don't bother to create these DAG nodes. 2887 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2888 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2889 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2890 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2891 return; 2892 2893 // If landingpad's return type is token type, we don't create DAG nodes 2894 // for its exception pointer and selector value. The extraction of exception 2895 // pointer or selector value from token type landingpads is not currently 2896 // supported. 2897 if (LP.getType()->isTokenTy()) 2898 return; 2899 2900 SmallVector<EVT, 2> ValueVTs; 2901 SDLoc dl = getCurSDLoc(); 2902 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2903 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2904 2905 // Get the two live-in registers as SDValues. The physregs have already been 2906 // copied into virtual registers. 2907 SDValue Ops[2]; 2908 if (FuncInfo.ExceptionPointerVirtReg) { 2909 Ops[0] = DAG.getZExtOrTrunc( 2910 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2911 FuncInfo.ExceptionPointerVirtReg, 2912 TLI.getPointerTy(DAG.getDataLayout())), 2913 dl, ValueVTs[0]); 2914 } else { 2915 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2916 } 2917 Ops[1] = DAG.getZExtOrTrunc( 2918 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2919 FuncInfo.ExceptionSelectorVirtReg, 2920 TLI.getPointerTy(DAG.getDataLayout())), 2921 dl, ValueVTs[1]); 2922 2923 // Merge into one. 2924 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2925 DAG.getVTList(ValueVTs), Ops); 2926 setValue(&LP, Res); 2927 } 2928 2929 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2930 MachineBasicBlock *Last) { 2931 // Update JTCases. 2932 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2933 if (SL->JTCases[i].first.HeaderBB == First) 2934 SL->JTCases[i].first.HeaderBB = Last; 2935 2936 // Update BitTestCases. 2937 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2938 if (SL->BitTestCases[i].Parent == First) 2939 SL->BitTestCases[i].Parent = Last; 2940 2941 // SelectionDAGISel::FinishBasicBlock will add PHI operands for the 2942 // successors of the fallthrough block. Here, we add PHI operands for the 2943 // successors of the INLINEASM_BR block itself. 2944 if (First->getFirstTerminator()->getOpcode() == TargetOpcode::INLINEASM_BR) 2945 for (std::pair<MachineInstr *, unsigned> &pair : FuncInfo.PHINodesToUpdate) 2946 if (First->isSuccessor(pair.first->getParent())) 2947 MachineInstrBuilder(*First->getParent(), pair.first) 2948 .addReg(pair.second) 2949 .addMBB(First); 2950 } 2951 2952 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2953 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2954 2955 // Update machine-CFG edges with unique successors. 2956 SmallSet<BasicBlock*, 32> Done; 2957 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2958 BasicBlock *BB = I.getSuccessor(i); 2959 bool Inserted = Done.insert(BB).second; 2960 if (!Inserted) 2961 continue; 2962 2963 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2964 addSuccessorWithProb(IndirectBrMBB, Succ); 2965 } 2966 IndirectBrMBB->normalizeSuccProbs(); 2967 2968 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2969 MVT::Other, getControlRoot(), 2970 getValue(I.getAddress()))); 2971 } 2972 2973 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2974 if (!DAG.getTarget().Options.TrapUnreachable) 2975 return; 2976 2977 // We may be able to ignore unreachable behind a noreturn call. 2978 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2979 const BasicBlock &BB = *I.getParent(); 2980 if (&I != &BB.front()) { 2981 BasicBlock::const_iterator PredI = 2982 std::prev(BasicBlock::const_iterator(&I)); 2983 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2984 if (Call->doesNotReturn()) 2985 return; 2986 } 2987 } 2988 } 2989 2990 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2991 } 2992 2993 void SelectionDAGBuilder::visitFSub(const User &I) { 2994 // -0.0 - X --> fneg 2995 Type *Ty = I.getType(); 2996 if (isa<Constant>(I.getOperand(0)) && 2997 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2998 SDValue Op2 = getValue(I.getOperand(1)); 2999 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 3000 Op2.getValueType(), Op2)); 3001 return; 3002 } 3003 3004 visitBinary(I, ISD::FSUB); 3005 } 3006 3007 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3008 SDNodeFlags Flags; 3009 3010 SDValue Op = getValue(I.getOperand(0)); 3011 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3012 Op, Flags); 3013 setValue(&I, UnNodeValue); 3014 } 3015 3016 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3017 SDNodeFlags Flags; 3018 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3019 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3020 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3021 } 3022 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3023 Flags.setExact(ExactOp->isExact()); 3024 } 3025 3026 SDValue Op1 = getValue(I.getOperand(0)); 3027 SDValue Op2 = getValue(I.getOperand(1)); 3028 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3029 Op1, Op2, Flags); 3030 setValue(&I, BinNodeValue); 3031 } 3032 3033 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3034 SDValue Op1 = getValue(I.getOperand(0)); 3035 SDValue Op2 = getValue(I.getOperand(1)); 3036 3037 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3038 Op1.getValueType(), DAG.getDataLayout()); 3039 3040 // Coerce the shift amount to the right type if we can. 3041 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3042 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3043 unsigned Op2Size = Op2.getValueSizeInBits(); 3044 SDLoc DL = getCurSDLoc(); 3045 3046 // If the operand is smaller than the shift count type, promote it. 3047 if (ShiftSize > Op2Size) 3048 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3049 3050 // If the operand is larger than the shift count type but the shift 3051 // count type has enough bits to represent any shift value, truncate 3052 // it now. This is a common case and it exposes the truncate to 3053 // optimization early. 3054 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3055 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3056 // Otherwise we'll need to temporarily settle for some other convenient 3057 // type. Type legalization will make adjustments once the shiftee is split. 3058 else 3059 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3060 } 3061 3062 bool nuw = false; 3063 bool nsw = false; 3064 bool exact = false; 3065 3066 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3067 3068 if (const OverflowingBinaryOperator *OFBinOp = 3069 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3070 nuw = OFBinOp->hasNoUnsignedWrap(); 3071 nsw = OFBinOp->hasNoSignedWrap(); 3072 } 3073 if (const PossiblyExactOperator *ExactOp = 3074 dyn_cast<const PossiblyExactOperator>(&I)) 3075 exact = ExactOp->isExact(); 3076 } 3077 SDNodeFlags Flags; 3078 Flags.setExact(exact); 3079 Flags.setNoSignedWrap(nsw); 3080 Flags.setNoUnsignedWrap(nuw); 3081 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3082 Flags); 3083 setValue(&I, Res); 3084 } 3085 3086 void SelectionDAGBuilder::visitSDiv(const User &I) { 3087 SDValue Op1 = getValue(I.getOperand(0)); 3088 SDValue Op2 = getValue(I.getOperand(1)); 3089 3090 SDNodeFlags Flags; 3091 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3092 cast<PossiblyExactOperator>(&I)->isExact()); 3093 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3094 Op2, Flags)); 3095 } 3096 3097 void SelectionDAGBuilder::visitICmp(const User &I) { 3098 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3099 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3100 predicate = IC->getPredicate(); 3101 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3102 predicate = ICmpInst::Predicate(IC->getPredicate()); 3103 SDValue Op1 = getValue(I.getOperand(0)); 3104 SDValue Op2 = getValue(I.getOperand(1)); 3105 ISD::CondCode Opcode = getICmpCondCode(predicate); 3106 3107 auto &TLI = DAG.getTargetLoweringInfo(); 3108 EVT MemVT = 3109 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3110 3111 // If a pointer's DAG type is larger than its memory type then the DAG values 3112 // are zero-extended. This breaks signed comparisons so truncate back to the 3113 // underlying type before doing the compare. 3114 if (Op1.getValueType() != MemVT) { 3115 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3116 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3117 } 3118 3119 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3120 I.getType()); 3121 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3122 } 3123 3124 void SelectionDAGBuilder::visitFCmp(const User &I) { 3125 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3126 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3127 predicate = FC->getPredicate(); 3128 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3129 predicate = FCmpInst::Predicate(FC->getPredicate()); 3130 SDValue Op1 = getValue(I.getOperand(0)); 3131 SDValue Op2 = getValue(I.getOperand(1)); 3132 3133 ISD::CondCode Condition = getFCmpCondCode(predicate); 3134 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3135 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3136 Condition = getFCmpCodeWithoutNaN(Condition); 3137 3138 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3139 I.getType()); 3140 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3141 } 3142 3143 // Check if the condition of the select has one use or two users that are both 3144 // selects with the same condition. 3145 static bool hasOnlySelectUsers(const Value *Cond) { 3146 return llvm::all_of(Cond->users(), [](const Value *V) { 3147 return isa<SelectInst>(V); 3148 }); 3149 } 3150 3151 void SelectionDAGBuilder::visitSelect(const User &I) { 3152 SmallVector<EVT, 4> ValueVTs; 3153 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3154 ValueVTs); 3155 unsigned NumValues = ValueVTs.size(); 3156 if (NumValues == 0) return; 3157 3158 SmallVector<SDValue, 4> Values(NumValues); 3159 SDValue Cond = getValue(I.getOperand(0)); 3160 SDValue LHSVal = getValue(I.getOperand(1)); 3161 SDValue RHSVal = getValue(I.getOperand(2)); 3162 SmallVector<SDValue, 1> BaseOps(1, Cond); 3163 ISD::NodeType OpCode = 3164 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3165 3166 bool IsUnaryAbs = false; 3167 3168 // Min/max matching is only viable if all output VTs are the same. 3169 if (is_splat(ValueVTs)) { 3170 EVT VT = ValueVTs[0]; 3171 LLVMContext &Ctx = *DAG.getContext(); 3172 auto &TLI = DAG.getTargetLoweringInfo(); 3173 3174 // We care about the legality of the operation after it has been type 3175 // legalized. 3176 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3177 VT = TLI.getTypeToTransformTo(Ctx, VT); 3178 3179 // If the vselect is legal, assume we want to leave this as a vector setcc + 3180 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3181 // min/max is legal on the scalar type. 3182 bool UseScalarMinMax = VT.isVector() && 3183 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3184 3185 Value *LHS, *RHS; 3186 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3187 ISD::NodeType Opc = ISD::DELETED_NODE; 3188 switch (SPR.Flavor) { 3189 case SPF_UMAX: Opc = ISD::UMAX; break; 3190 case SPF_UMIN: Opc = ISD::UMIN; break; 3191 case SPF_SMAX: Opc = ISD::SMAX; break; 3192 case SPF_SMIN: Opc = ISD::SMIN; break; 3193 case SPF_FMINNUM: 3194 switch (SPR.NaNBehavior) { 3195 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3196 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3197 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3198 case SPNB_RETURNS_ANY: { 3199 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3200 Opc = ISD::FMINNUM; 3201 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3202 Opc = ISD::FMINIMUM; 3203 else if (UseScalarMinMax) 3204 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3205 ISD::FMINNUM : ISD::FMINIMUM; 3206 break; 3207 } 3208 } 3209 break; 3210 case SPF_FMAXNUM: 3211 switch (SPR.NaNBehavior) { 3212 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3213 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3214 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3215 case SPNB_RETURNS_ANY: 3216 3217 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3218 Opc = ISD::FMAXNUM; 3219 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3220 Opc = ISD::FMAXIMUM; 3221 else if (UseScalarMinMax) 3222 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3223 ISD::FMAXNUM : ISD::FMAXIMUM; 3224 break; 3225 } 3226 break; 3227 case SPF_ABS: 3228 IsUnaryAbs = true; 3229 Opc = ISD::ABS; 3230 break; 3231 case SPF_NABS: 3232 // TODO: we need to produce sub(0, abs(X)). 3233 default: break; 3234 } 3235 3236 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3237 (TLI.isOperationLegalOrCustom(Opc, VT) || 3238 (UseScalarMinMax && 3239 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3240 // If the underlying comparison instruction is used by any other 3241 // instruction, the consumed instructions won't be destroyed, so it is 3242 // not profitable to convert to a min/max. 3243 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3244 OpCode = Opc; 3245 LHSVal = getValue(LHS); 3246 RHSVal = getValue(RHS); 3247 BaseOps.clear(); 3248 } 3249 3250 if (IsUnaryAbs) { 3251 OpCode = Opc; 3252 LHSVal = getValue(LHS); 3253 BaseOps.clear(); 3254 } 3255 } 3256 3257 if (IsUnaryAbs) { 3258 for (unsigned i = 0; i != NumValues; ++i) { 3259 Values[i] = 3260 DAG.getNode(OpCode, getCurSDLoc(), 3261 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3262 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3263 } 3264 } else { 3265 for (unsigned i = 0; i != NumValues; ++i) { 3266 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3267 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3268 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3269 Values[i] = DAG.getNode( 3270 OpCode, getCurSDLoc(), 3271 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3272 } 3273 } 3274 3275 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3276 DAG.getVTList(ValueVTs), Values)); 3277 } 3278 3279 void SelectionDAGBuilder::visitTrunc(const User &I) { 3280 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3281 SDValue N = getValue(I.getOperand(0)); 3282 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3283 I.getType()); 3284 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3285 } 3286 3287 void SelectionDAGBuilder::visitZExt(const User &I) { 3288 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3289 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3290 SDValue N = getValue(I.getOperand(0)); 3291 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3292 I.getType()); 3293 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3294 } 3295 3296 void SelectionDAGBuilder::visitSExt(const User &I) { 3297 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3298 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3299 SDValue N = getValue(I.getOperand(0)); 3300 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3301 I.getType()); 3302 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3303 } 3304 3305 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3306 // FPTrunc is never a no-op cast, no need to check 3307 SDValue N = getValue(I.getOperand(0)); 3308 SDLoc dl = getCurSDLoc(); 3309 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3310 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3311 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3312 DAG.getTargetConstant( 3313 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3314 } 3315 3316 void SelectionDAGBuilder::visitFPExt(const User &I) { 3317 // FPExt is never a no-op cast, no need to check 3318 SDValue N = getValue(I.getOperand(0)); 3319 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3320 I.getType()); 3321 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3322 } 3323 3324 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3325 // FPToUI is never a no-op cast, no need to check 3326 SDValue N = getValue(I.getOperand(0)); 3327 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3328 I.getType()); 3329 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3330 } 3331 3332 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3333 // FPToSI is never a no-op cast, no need to check 3334 SDValue N = getValue(I.getOperand(0)); 3335 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3336 I.getType()); 3337 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3338 } 3339 3340 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3341 // UIToFP is never a no-op cast, no need to check 3342 SDValue N = getValue(I.getOperand(0)); 3343 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3344 I.getType()); 3345 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3346 } 3347 3348 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3349 // SIToFP is never a no-op cast, no need to check 3350 SDValue N = getValue(I.getOperand(0)); 3351 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3352 I.getType()); 3353 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3354 } 3355 3356 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3357 // What to do depends on the size of the integer and the size of the pointer. 3358 // We can either truncate, zero extend, or no-op, accordingly. 3359 SDValue N = getValue(I.getOperand(0)); 3360 auto &TLI = DAG.getTargetLoweringInfo(); 3361 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3362 I.getType()); 3363 EVT PtrMemVT = 3364 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3365 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3366 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3367 setValue(&I, N); 3368 } 3369 3370 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3371 // What to do depends on the size of the integer and the size of the pointer. 3372 // We can either truncate, zero extend, or no-op, accordingly. 3373 SDValue N = getValue(I.getOperand(0)); 3374 auto &TLI = DAG.getTargetLoweringInfo(); 3375 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3376 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3377 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3378 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3379 setValue(&I, N); 3380 } 3381 3382 void SelectionDAGBuilder::visitBitCast(const User &I) { 3383 SDValue N = getValue(I.getOperand(0)); 3384 SDLoc dl = getCurSDLoc(); 3385 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3386 I.getType()); 3387 3388 // BitCast assures us that source and destination are the same size so this is 3389 // either a BITCAST or a no-op. 3390 if (DestVT != N.getValueType()) 3391 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3392 DestVT, N)); // convert types. 3393 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3394 // might fold any kind of constant expression to an integer constant and that 3395 // is not what we are looking for. Only recognize a bitcast of a genuine 3396 // constant integer as an opaque constant. 3397 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3398 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3399 /*isOpaque*/true)); 3400 else 3401 setValue(&I, N); // noop cast. 3402 } 3403 3404 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3405 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3406 const Value *SV = I.getOperand(0); 3407 SDValue N = getValue(SV); 3408 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3409 3410 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3411 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3412 3413 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3414 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3415 3416 setValue(&I, N); 3417 } 3418 3419 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3421 SDValue InVec = getValue(I.getOperand(0)); 3422 SDValue InVal = getValue(I.getOperand(1)); 3423 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3424 TLI.getVectorIdxTy(DAG.getDataLayout())); 3425 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3426 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3427 InVec, InVal, InIdx)); 3428 } 3429 3430 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3431 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3432 SDValue InVec = getValue(I.getOperand(0)); 3433 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3434 TLI.getVectorIdxTy(DAG.getDataLayout())); 3435 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3436 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3437 InVec, InIdx)); 3438 } 3439 3440 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3441 SDValue Src1 = getValue(I.getOperand(0)); 3442 SDValue Src2 = getValue(I.getOperand(1)); 3443 ArrayRef<int> Mask; 3444 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3445 Mask = SVI->getShuffleMask(); 3446 else 3447 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3448 SDLoc DL = getCurSDLoc(); 3449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3450 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3451 EVT SrcVT = Src1.getValueType(); 3452 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3453 3454 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3455 VT.isScalableVector()) { 3456 // Canonical splat form of first element of first input vector. 3457 SDValue FirstElt = 3458 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3459 DAG.getVectorIdxConstant(0, DL)); 3460 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3461 return; 3462 } 3463 3464 // For now, we only handle splats for scalable vectors. 3465 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3466 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3467 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3468 3469 unsigned MaskNumElts = Mask.size(); 3470 3471 if (SrcNumElts == MaskNumElts) { 3472 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3473 return; 3474 } 3475 3476 // Normalize the shuffle vector since mask and vector length don't match. 3477 if (SrcNumElts < MaskNumElts) { 3478 // Mask is longer than the source vectors. We can use concatenate vector to 3479 // make the mask and vectors lengths match. 3480 3481 if (MaskNumElts % SrcNumElts == 0) { 3482 // Mask length is a multiple of the source vector length. 3483 // Check if the shuffle is some kind of concatenation of the input 3484 // vectors. 3485 unsigned NumConcat = MaskNumElts / SrcNumElts; 3486 bool IsConcat = true; 3487 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3488 for (unsigned i = 0; i != MaskNumElts; ++i) { 3489 int Idx = Mask[i]; 3490 if (Idx < 0) 3491 continue; 3492 // Ensure the indices in each SrcVT sized piece are sequential and that 3493 // the same source is used for the whole piece. 3494 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3495 (ConcatSrcs[i / SrcNumElts] >= 0 && 3496 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3497 IsConcat = false; 3498 break; 3499 } 3500 // Remember which source this index came from. 3501 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3502 } 3503 3504 // The shuffle is concatenating multiple vectors together. Just emit 3505 // a CONCAT_VECTORS operation. 3506 if (IsConcat) { 3507 SmallVector<SDValue, 8> ConcatOps; 3508 for (auto Src : ConcatSrcs) { 3509 if (Src < 0) 3510 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3511 else if (Src == 0) 3512 ConcatOps.push_back(Src1); 3513 else 3514 ConcatOps.push_back(Src2); 3515 } 3516 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3517 return; 3518 } 3519 } 3520 3521 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3522 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3523 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3524 PaddedMaskNumElts); 3525 3526 // Pad both vectors with undefs to make them the same length as the mask. 3527 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3528 3529 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3530 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3531 MOps1[0] = Src1; 3532 MOps2[0] = Src2; 3533 3534 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3535 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3536 3537 // Readjust mask for new input vector length. 3538 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3539 for (unsigned i = 0; i != MaskNumElts; ++i) { 3540 int Idx = Mask[i]; 3541 if (Idx >= (int)SrcNumElts) 3542 Idx -= SrcNumElts - PaddedMaskNumElts; 3543 MappedOps[i] = Idx; 3544 } 3545 3546 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3547 3548 // If the concatenated vector was padded, extract a subvector with the 3549 // correct number of elements. 3550 if (MaskNumElts != PaddedMaskNumElts) 3551 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3552 DAG.getVectorIdxConstant(0, DL)); 3553 3554 setValue(&I, Result); 3555 return; 3556 } 3557 3558 if (SrcNumElts > MaskNumElts) { 3559 // Analyze the access pattern of the vector to see if we can extract 3560 // two subvectors and do the shuffle. 3561 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3562 bool CanExtract = true; 3563 for (int Idx : Mask) { 3564 unsigned Input = 0; 3565 if (Idx < 0) 3566 continue; 3567 3568 if (Idx >= (int)SrcNumElts) { 3569 Input = 1; 3570 Idx -= SrcNumElts; 3571 } 3572 3573 // If all the indices come from the same MaskNumElts sized portion of 3574 // the sources we can use extract. Also make sure the extract wouldn't 3575 // extract past the end of the source. 3576 int NewStartIdx = alignDown(Idx, MaskNumElts); 3577 if (NewStartIdx + MaskNumElts > SrcNumElts || 3578 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3579 CanExtract = false; 3580 // Make sure we always update StartIdx as we use it to track if all 3581 // elements are undef. 3582 StartIdx[Input] = NewStartIdx; 3583 } 3584 3585 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3586 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3587 return; 3588 } 3589 if (CanExtract) { 3590 // Extract appropriate subvector and generate a vector shuffle 3591 for (unsigned Input = 0; Input < 2; ++Input) { 3592 SDValue &Src = Input == 0 ? Src1 : Src2; 3593 if (StartIdx[Input] < 0) 3594 Src = DAG.getUNDEF(VT); 3595 else { 3596 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3597 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3598 } 3599 } 3600 3601 // Calculate new mask. 3602 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3603 for (int &Idx : MappedOps) { 3604 if (Idx >= (int)SrcNumElts) 3605 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3606 else if (Idx >= 0) 3607 Idx -= StartIdx[0]; 3608 } 3609 3610 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3611 return; 3612 } 3613 } 3614 3615 // We can't use either concat vectors or extract subvectors so fall back to 3616 // replacing the shuffle with extract and build vector. 3617 // to insert and build vector. 3618 EVT EltVT = VT.getVectorElementType(); 3619 SmallVector<SDValue,8> Ops; 3620 for (int Idx : Mask) { 3621 SDValue Res; 3622 3623 if (Idx < 0) { 3624 Res = DAG.getUNDEF(EltVT); 3625 } else { 3626 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3627 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3628 3629 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3630 DAG.getVectorIdxConstant(Idx, DL)); 3631 } 3632 3633 Ops.push_back(Res); 3634 } 3635 3636 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3637 } 3638 3639 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3640 ArrayRef<unsigned> Indices; 3641 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3642 Indices = IV->getIndices(); 3643 else 3644 Indices = cast<ConstantExpr>(&I)->getIndices(); 3645 3646 const Value *Op0 = I.getOperand(0); 3647 const Value *Op1 = I.getOperand(1); 3648 Type *AggTy = I.getType(); 3649 Type *ValTy = Op1->getType(); 3650 bool IntoUndef = isa<UndefValue>(Op0); 3651 bool FromUndef = isa<UndefValue>(Op1); 3652 3653 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3654 3655 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3656 SmallVector<EVT, 4> AggValueVTs; 3657 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3658 SmallVector<EVT, 4> ValValueVTs; 3659 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3660 3661 unsigned NumAggValues = AggValueVTs.size(); 3662 unsigned NumValValues = ValValueVTs.size(); 3663 SmallVector<SDValue, 4> Values(NumAggValues); 3664 3665 // Ignore an insertvalue that produces an empty object 3666 if (!NumAggValues) { 3667 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3668 return; 3669 } 3670 3671 SDValue Agg = getValue(Op0); 3672 unsigned i = 0; 3673 // Copy the beginning value(s) from the original aggregate. 3674 for (; i != LinearIndex; ++i) 3675 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3676 SDValue(Agg.getNode(), Agg.getResNo() + i); 3677 // Copy values from the inserted value(s). 3678 if (NumValValues) { 3679 SDValue Val = getValue(Op1); 3680 for (; i != LinearIndex + NumValValues; ++i) 3681 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3682 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3683 } 3684 // Copy remaining value(s) from the original aggregate. 3685 for (; i != NumAggValues; ++i) 3686 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3687 SDValue(Agg.getNode(), Agg.getResNo() + i); 3688 3689 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3690 DAG.getVTList(AggValueVTs), Values)); 3691 } 3692 3693 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3694 ArrayRef<unsigned> Indices; 3695 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3696 Indices = EV->getIndices(); 3697 else 3698 Indices = cast<ConstantExpr>(&I)->getIndices(); 3699 3700 const Value *Op0 = I.getOperand(0); 3701 Type *AggTy = Op0->getType(); 3702 Type *ValTy = I.getType(); 3703 bool OutOfUndef = isa<UndefValue>(Op0); 3704 3705 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3706 3707 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3708 SmallVector<EVT, 4> ValValueVTs; 3709 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3710 3711 unsigned NumValValues = ValValueVTs.size(); 3712 3713 // Ignore a extractvalue that produces an empty object 3714 if (!NumValValues) { 3715 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3716 return; 3717 } 3718 3719 SmallVector<SDValue, 4> Values(NumValValues); 3720 3721 SDValue Agg = getValue(Op0); 3722 // Copy out the selected value(s). 3723 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3724 Values[i - LinearIndex] = 3725 OutOfUndef ? 3726 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3727 SDValue(Agg.getNode(), Agg.getResNo() + i); 3728 3729 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3730 DAG.getVTList(ValValueVTs), Values)); 3731 } 3732 3733 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3734 Value *Op0 = I.getOperand(0); 3735 // Note that the pointer operand may be a vector of pointers. Take the scalar 3736 // element which holds a pointer. 3737 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3738 SDValue N = getValue(Op0); 3739 SDLoc dl = getCurSDLoc(); 3740 auto &TLI = DAG.getTargetLoweringInfo(); 3741 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3742 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3743 3744 // Normalize Vector GEP - all scalar operands should be converted to the 3745 // splat vector. 3746 bool IsVectorGEP = I.getType()->isVectorTy(); 3747 ElementCount VectorElementCount = 3748 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3749 : ElementCount(0, false); 3750 3751 if (IsVectorGEP && !N.getValueType().isVector()) { 3752 LLVMContext &Context = *DAG.getContext(); 3753 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3754 if (VectorElementCount.Scalable) 3755 N = DAG.getSplatVector(VT, dl, N); 3756 else 3757 N = DAG.getSplatBuildVector(VT, dl, N); 3758 } 3759 3760 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3761 GTI != E; ++GTI) { 3762 const Value *Idx = GTI.getOperand(); 3763 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3764 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3765 if (Field) { 3766 // N = N + Offset 3767 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3768 3769 // In an inbounds GEP with an offset that is nonnegative even when 3770 // interpreted as signed, assume there is no unsigned overflow. 3771 SDNodeFlags Flags; 3772 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3773 Flags.setNoUnsignedWrap(true); 3774 3775 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3776 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3777 } 3778 } else { 3779 // IdxSize is the width of the arithmetic according to IR semantics. 3780 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3781 // (and fix up the result later). 3782 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3783 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3784 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3785 // We intentionally mask away the high bits here; ElementSize may not 3786 // fit in IdxTy. 3787 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3788 bool ElementScalable = ElementSize.isScalable(); 3789 3790 // If this is a scalar constant or a splat vector of constants, 3791 // handle it quickly. 3792 const auto *C = dyn_cast<Constant>(Idx); 3793 if (C && isa<VectorType>(C->getType())) 3794 C = C->getSplatValue(); 3795 3796 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3797 if (CI && CI->isZero()) 3798 continue; 3799 if (CI && !ElementScalable) { 3800 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3801 LLVMContext &Context = *DAG.getContext(); 3802 SDValue OffsVal; 3803 if (IsVectorGEP) 3804 OffsVal = DAG.getConstant( 3805 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3806 else 3807 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3808 3809 // In an inbounds GEP with an offset that is nonnegative even when 3810 // interpreted as signed, assume there is no unsigned overflow. 3811 SDNodeFlags Flags; 3812 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3813 Flags.setNoUnsignedWrap(true); 3814 3815 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3816 3817 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3818 continue; 3819 } 3820 3821 // N = N + Idx * ElementMul; 3822 SDValue IdxN = getValue(Idx); 3823 3824 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3825 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3826 VectorElementCount); 3827 if (VectorElementCount.Scalable) 3828 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3829 else 3830 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3831 } 3832 3833 // If the index is smaller or larger than intptr_t, truncate or extend 3834 // it. 3835 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3836 3837 if (ElementScalable) { 3838 EVT VScaleTy = N.getValueType().getScalarType(); 3839 SDValue VScale = DAG.getNode( 3840 ISD::VSCALE, dl, VScaleTy, 3841 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3842 if (IsVectorGEP) 3843 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3844 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3845 } else { 3846 // If this is a multiply by a power of two, turn it into a shl 3847 // immediately. This is a very common case. 3848 if (ElementMul != 1) { 3849 if (ElementMul.isPowerOf2()) { 3850 unsigned Amt = ElementMul.logBase2(); 3851 IdxN = DAG.getNode(ISD::SHL, dl, 3852 N.getValueType(), IdxN, 3853 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3854 } else { 3855 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3856 IdxN.getValueType()); 3857 IdxN = DAG.getNode(ISD::MUL, dl, 3858 N.getValueType(), IdxN, Scale); 3859 } 3860 } 3861 } 3862 3863 N = DAG.getNode(ISD::ADD, dl, 3864 N.getValueType(), N, IdxN); 3865 } 3866 } 3867 3868 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3869 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3870 3871 setValue(&I, N); 3872 } 3873 3874 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3875 // If this is a fixed sized alloca in the entry block of the function, 3876 // allocate it statically on the stack. 3877 if (FuncInfo.StaticAllocaMap.count(&I)) 3878 return; // getValue will auto-populate this. 3879 3880 SDLoc dl = getCurSDLoc(); 3881 Type *Ty = I.getAllocatedType(); 3882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3883 auto &DL = DAG.getDataLayout(); 3884 uint64_t TySize = DL.getTypeAllocSize(Ty); 3885 MaybeAlign Alignment = max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3886 3887 SDValue AllocSize = getValue(I.getArraySize()); 3888 3889 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3890 if (AllocSize.getValueType() != IntPtr) 3891 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3892 3893 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3894 AllocSize, 3895 DAG.getConstant(TySize, dl, IntPtr)); 3896 3897 // Handle alignment. If the requested alignment is less than or equal to 3898 // the stack alignment, ignore it. If the size is greater than or equal to 3899 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3900 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3901 if (Alignment <= StackAlign) 3902 Alignment = None; 3903 3904 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3905 // Round the size of the allocation up to the stack alignment size 3906 // by add SA-1 to the size. This doesn't overflow because we're computing 3907 // an address inside an alloca. 3908 SDNodeFlags Flags; 3909 Flags.setNoUnsignedWrap(true); 3910 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3911 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3912 3913 // Mask out the low bits for alignment purposes. 3914 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3915 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3916 3917 SDValue Ops[] = { 3918 getRoot(), AllocSize, 3919 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3920 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3921 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3922 setValue(&I, DSA); 3923 DAG.setRoot(DSA.getValue(1)); 3924 3925 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3926 } 3927 3928 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3929 if (I.isAtomic()) 3930 return visitAtomicLoad(I); 3931 3932 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3933 const Value *SV = I.getOperand(0); 3934 if (TLI.supportSwiftError()) { 3935 // Swifterror values can come from either a function parameter with 3936 // swifterror attribute or an alloca with swifterror attribute. 3937 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3938 if (Arg->hasSwiftErrorAttr()) 3939 return visitLoadFromSwiftError(I); 3940 } 3941 3942 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3943 if (Alloca->isSwiftError()) 3944 return visitLoadFromSwiftError(I); 3945 } 3946 } 3947 3948 SDValue Ptr = getValue(SV); 3949 3950 Type *Ty = I.getType(); 3951 Align Alignment = DL->getValueOrABITypeAlignment(I.getAlign(), Ty); 3952 3953 AAMDNodes AAInfo; 3954 I.getAAMetadata(AAInfo); 3955 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3956 3957 SmallVector<EVT, 4> ValueVTs, MemVTs; 3958 SmallVector<uint64_t, 4> Offsets; 3959 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3960 unsigned NumValues = ValueVTs.size(); 3961 if (NumValues == 0) 3962 return; 3963 3964 bool isVolatile = I.isVolatile(); 3965 3966 SDValue Root; 3967 bool ConstantMemory = false; 3968 if (isVolatile) 3969 // Serialize volatile loads with other side effects. 3970 Root = getRoot(); 3971 else if (NumValues > MaxParallelChains) 3972 Root = getMemoryRoot(); 3973 else if (AA && 3974 AA->pointsToConstantMemory(MemoryLocation( 3975 SV, 3976 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3977 AAInfo))) { 3978 // Do not serialize (non-volatile) loads of constant memory with anything. 3979 Root = DAG.getEntryNode(); 3980 ConstantMemory = true; 3981 } else { 3982 // Do not serialize non-volatile loads against each other. 3983 Root = DAG.getRoot(); 3984 } 3985 3986 SDLoc dl = getCurSDLoc(); 3987 3988 if (isVolatile) 3989 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3990 3991 // An aggregate load cannot wrap around the address space, so offsets to its 3992 // parts don't wrap either. 3993 SDNodeFlags Flags; 3994 Flags.setNoUnsignedWrap(true); 3995 3996 SmallVector<SDValue, 4> Values(NumValues); 3997 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3998 EVT PtrVT = Ptr.getValueType(); 3999 4000 MachineMemOperand::Flags MMOFlags 4001 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4002 4003 unsigned ChainI = 0; 4004 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4005 // Serializing loads here may result in excessive register pressure, and 4006 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4007 // could recover a bit by hoisting nodes upward in the chain by recognizing 4008 // they are side-effect free or do not alias. The optimizer should really 4009 // avoid this case by converting large object/array copies to llvm.memcpy 4010 // (MaxParallelChains should always remain as failsafe). 4011 if (ChainI == MaxParallelChains) { 4012 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4013 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4014 makeArrayRef(Chains.data(), ChainI)); 4015 Root = Chain; 4016 ChainI = 0; 4017 } 4018 SDValue A = DAG.getNode(ISD::ADD, dl, 4019 PtrVT, Ptr, 4020 DAG.getConstant(Offsets[i], dl, PtrVT), 4021 Flags); 4022 4023 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4024 MachinePointerInfo(SV, Offsets[i]), Alignment, 4025 MMOFlags, AAInfo, Ranges); 4026 Chains[ChainI] = L.getValue(1); 4027 4028 if (MemVTs[i] != ValueVTs[i]) 4029 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4030 4031 Values[i] = L; 4032 } 4033 4034 if (!ConstantMemory) { 4035 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4036 makeArrayRef(Chains.data(), ChainI)); 4037 if (isVolatile) 4038 DAG.setRoot(Chain); 4039 else 4040 PendingLoads.push_back(Chain); 4041 } 4042 4043 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4044 DAG.getVTList(ValueVTs), Values)); 4045 } 4046 4047 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4048 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4049 "call visitStoreToSwiftError when backend supports swifterror"); 4050 4051 SmallVector<EVT, 4> ValueVTs; 4052 SmallVector<uint64_t, 4> Offsets; 4053 const Value *SrcV = I.getOperand(0); 4054 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4055 SrcV->getType(), ValueVTs, &Offsets); 4056 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4057 "expect a single EVT for swifterror"); 4058 4059 SDValue Src = getValue(SrcV); 4060 // Create a virtual register, then update the virtual register. 4061 Register VReg = 4062 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4063 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4064 // Chain can be getRoot or getControlRoot. 4065 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4066 SDValue(Src.getNode(), Src.getResNo())); 4067 DAG.setRoot(CopyNode); 4068 } 4069 4070 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4071 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4072 "call visitLoadFromSwiftError when backend supports swifterror"); 4073 4074 assert(!I.isVolatile() && 4075 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4076 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4077 "Support volatile, non temporal, invariant for load_from_swift_error"); 4078 4079 const Value *SV = I.getOperand(0); 4080 Type *Ty = I.getType(); 4081 AAMDNodes AAInfo; 4082 I.getAAMetadata(AAInfo); 4083 assert( 4084 (!AA || 4085 !AA->pointsToConstantMemory(MemoryLocation( 4086 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4087 AAInfo))) && 4088 "load_from_swift_error should not be constant memory"); 4089 4090 SmallVector<EVT, 4> ValueVTs; 4091 SmallVector<uint64_t, 4> Offsets; 4092 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4093 ValueVTs, &Offsets); 4094 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4095 "expect a single EVT for swifterror"); 4096 4097 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4098 SDValue L = DAG.getCopyFromReg( 4099 getRoot(), getCurSDLoc(), 4100 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4101 4102 setValue(&I, L); 4103 } 4104 4105 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4106 if (I.isAtomic()) 4107 return visitAtomicStore(I); 4108 4109 const Value *SrcV = I.getOperand(0); 4110 const Value *PtrV = I.getOperand(1); 4111 4112 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4113 if (TLI.supportSwiftError()) { 4114 // Swifterror values can come from either a function parameter with 4115 // swifterror attribute or an alloca with swifterror attribute. 4116 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4117 if (Arg->hasSwiftErrorAttr()) 4118 return visitStoreToSwiftError(I); 4119 } 4120 4121 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4122 if (Alloca->isSwiftError()) 4123 return visitStoreToSwiftError(I); 4124 } 4125 } 4126 4127 SmallVector<EVT, 4> ValueVTs, MemVTs; 4128 SmallVector<uint64_t, 4> Offsets; 4129 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4130 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4131 unsigned NumValues = ValueVTs.size(); 4132 if (NumValues == 0) 4133 return; 4134 4135 // Get the lowered operands. Note that we do this after 4136 // checking if NumResults is zero, because with zero results 4137 // the operands won't have values in the map. 4138 SDValue Src = getValue(SrcV); 4139 SDValue Ptr = getValue(PtrV); 4140 4141 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4142 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4143 SDLoc dl = getCurSDLoc(); 4144 Align Alignment = 4145 DL->getValueOrABITypeAlignment(I.getAlign(), SrcV->getType()); 4146 AAMDNodes AAInfo; 4147 I.getAAMetadata(AAInfo); 4148 4149 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4150 4151 // An aggregate load cannot wrap around the address space, so offsets to its 4152 // parts don't wrap either. 4153 SDNodeFlags Flags; 4154 Flags.setNoUnsignedWrap(true); 4155 4156 unsigned ChainI = 0; 4157 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4158 // See visitLoad comments. 4159 if (ChainI == MaxParallelChains) { 4160 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4161 makeArrayRef(Chains.data(), ChainI)); 4162 Root = Chain; 4163 ChainI = 0; 4164 } 4165 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4166 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4167 if (MemVTs[i] != ValueVTs[i]) 4168 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4169 SDValue St = 4170 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4171 Alignment, MMOFlags, AAInfo); 4172 Chains[ChainI] = St; 4173 } 4174 4175 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4176 makeArrayRef(Chains.data(), ChainI)); 4177 DAG.setRoot(StoreNode); 4178 } 4179 4180 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4181 bool IsCompressing) { 4182 SDLoc sdl = getCurSDLoc(); 4183 4184 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4185 MaybeAlign &Alignment) { 4186 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4187 Src0 = I.getArgOperand(0); 4188 Ptr = I.getArgOperand(1); 4189 Alignment = 4190 MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4191 Mask = I.getArgOperand(3); 4192 }; 4193 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4194 MaybeAlign &Alignment) { 4195 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4196 Src0 = I.getArgOperand(0); 4197 Ptr = I.getArgOperand(1); 4198 Mask = I.getArgOperand(2); 4199 Alignment = None; 4200 }; 4201 4202 Value *PtrOperand, *MaskOperand, *Src0Operand; 4203 MaybeAlign Alignment; 4204 if (IsCompressing) 4205 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4206 else 4207 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4208 4209 SDValue Ptr = getValue(PtrOperand); 4210 SDValue Src0 = getValue(Src0Operand); 4211 SDValue Mask = getValue(MaskOperand); 4212 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4213 4214 EVT VT = Src0.getValueType(); 4215 if (!Alignment) 4216 Alignment = DAG.getEVTAlign(VT); 4217 4218 AAMDNodes AAInfo; 4219 I.getAAMetadata(AAInfo); 4220 4221 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4222 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4223 // TODO: Make MachineMemOperands aware of scalable 4224 // vectors. 4225 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4226 SDValue StoreNode = 4227 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4228 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4229 DAG.setRoot(StoreNode); 4230 setValue(&I, StoreNode); 4231 } 4232 4233 // Get a uniform base for the Gather/Scatter intrinsic. 4234 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4235 // We try to represent it as a base pointer + vector of indices. 4236 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4237 // The first operand of the GEP may be a single pointer or a vector of pointers 4238 // Example: 4239 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4240 // or 4241 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4242 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4243 // 4244 // When the first GEP operand is a single pointer - it is the uniform base we 4245 // are looking for. If first operand of the GEP is a splat vector - we 4246 // extract the splat value and use it as a uniform base. 4247 // In all other cases the function returns 'false'. 4248 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4249 ISD::MemIndexType &IndexType, SDValue &Scale, 4250 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4251 SelectionDAG& DAG = SDB->DAG; 4252 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4253 const DataLayout &DL = DAG.getDataLayout(); 4254 4255 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4256 4257 // Handle splat constant pointer. 4258 if (auto *C = dyn_cast<Constant>(Ptr)) { 4259 C = C->getSplatValue(); 4260 if (!C) 4261 return false; 4262 4263 Base = SDB->getValue(C); 4264 4265 unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements(); 4266 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4267 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4268 IndexType = ISD::SIGNED_SCALED; 4269 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4270 return true; 4271 } 4272 4273 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4274 if (!GEP || GEP->getParent() != CurBB) 4275 return false; 4276 4277 if (GEP->getNumOperands() != 2) 4278 return false; 4279 4280 const Value *BasePtr = GEP->getPointerOperand(); 4281 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4282 4283 // Make sure the base is scalar and the index is a vector. 4284 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4285 return false; 4286 4287 Base = SDB->getValue(BasePtr); 4288 Index = SDB->getValue(IndexVal); 4289 IndexType = ISD::SIGNED_SCALED; 4290 Scale = DAG.getTargetConstant( 4291 DL.getTypeAllocSize(GEP->getResultElementType()), 4292 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4293 return true; 4294 } 4295 4296 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4297 SDLoc sdl = getCurSDLoc(); 4298 4299 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4300 const Value *Ptr = I.getArgOperand(1); 4301 SDValue Src0 = getValue(I.getArgOperand(0)); 4302 SDValue Mask = getValue(I.getArgOperand(3)); 4303 EVT VT = Src0.getValueType(); 4304 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4305 if (!Alignment) 4306 Alignment = DAG.getEVTAlign(VT); 4307 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4308 4309 AAMDNodes AAInfo; 4310 I.getAAMetadata(AAInfo); 4311 4312 SDValue Base; 4313 SDValue Index; 4314 ISD::MemIndexType IndexType; 4315 SDValue Scale; 4316 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4317 I.getParent()); 4318 4319 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4320 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4321 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4322 // TODO: Make MachineMemOperands aware of scalable 4323 // vectors. 4324 MemoryLocation::UnknownSize, *Alignment, AAInfo); 4325 if (!UniformBase) { 4326 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4327 Index = getValue(Ptr); 4328 IndexType = ISD::SIGNED_SCALED; 4329 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4330 } 4331 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4332 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4333 Ops, MMO, IndexType); 4334 DAG.setRoot(Scatter); 4335 setValue(&I, Scatter); 4336 } 4337 4338 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4339 SDLoc sdl = getCurSDLoc(); 4340 4341 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4342 MaybeAlign &Alignment) { 4343 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4344 Ptr = I.getArgOperand(0); 4345 Alignment = 4346 MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4347 Mask = I.getArgOperand(2); 4348 Src0 = I.getArgOperand(3); 4349 }; 4350 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4351 MaybeAlign &Alignment) { 4352 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4353 Ptr = I.getArgOperand(0); 4354 Alignment = None; 4355 Mask = I.getArgOperand(1); 4356 Src0 = I.getArgOperand(2); 4357 }; 4358 4359 Value *PtrOperand, *MaskOperand, *Src0Operand; 4360 MaybeAlign Alignment; 4361 if (IsExpanding) 4362 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4363 else 4364 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4365 4366 SDValue Ptr = getValue(PtrOperand); 4367 SDValue Src0 = getValue(Src0Operand); 4368 SDValue Mask = getValue(MaskOperand); 4369 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4370 4371 EVT VT = Src0.getValueType(); 4372 if (!Alignment) 4373 Alignment = DAG.getEVTAlign(VT); 4374 4375 AAMDNodes AAInfo; 4376 I.getAAMetadata(AAInfo); 4377 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4378 4379 // Do not serialize masked loads of constant memory with anything. 4380 MemoryLocation ML; 4381 if (VT.isScalableVector()) 4382 ML = MemoryLocation(PtrOperand); 4383 else 4384 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4385 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4386 AAInfo); 4387 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4388 4389 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4390 4391 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4392 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4393 // TODO: Make MachineMemOperands aware of scalable 4394 // vectors. 4395 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4396 4397 SDValue Load = 4398 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4399 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4400 if (AddToChain) 4401 PendingLoads.push_back(Load.getValue(1)); 4402 setValue(&I, Load); 4403 } 4404 4405 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4406 SDLoc sdl = getCurSDLoc(); 4407 4408 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4409 const Value *Ptr = I.getArgOperand(0); 4410 SDValue Src0 = getValue(I.getArgOperand(3)); 4411 SDValue Mask = getValue(I.getArgOperand(2)); 4412 4413 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4414 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4415 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4416 if (!Alignment) 4417 Alignment = DAG.getEVTAlign(VT); 4418 4419 AAMDNodes AAInfo; 4420 I.getAAMetadata(AAInfo); 4421 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4422 4423 SDValue Root = DAG.getRoot(); 4424 SDValue Base; 4425 SDValue Index; 4426 ISD::MemIndexType IndexType; 4427 SDValue Scale; 4428 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4429 I.getParent()); 4430 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4431 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4432 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4433 // TODO: Make MachineMemOperands aware of scalable 4434 // vectors. 4435 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4436 4437 if (!UniformBase) { 4438 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4439 Index = getValue(Ptr); 4440 IndexType = ISD::SIGNED_SCALED; 4441 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4442 } 4443 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4444 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4445 Ops, MMO, IndexType); 4446 4447 PendingLoads.push_back(Gather.getValue(1)); 4448 setValue(&I, Gather); 4449 } 4450 4451 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4452 SDLoc dl = getCurSDLoc(); 4453 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4454 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4455 SyncScope::ID SSID = I.getSyncScopeID(); 4456 4457 SDValue InChain = getRoot(); 4458 4459 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4460 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4461 4462 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4463 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4464 4465 MachineFunction &MF = DAG.getMachineFunction(); 4466 MachineMemOperand *MMO = MF.getMachineMemOperand( 4467 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4468 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4469 FailureOrdering); 4470 4471 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4472 dl, MemVT, VTs, InChain, 4473 getValue(I.getPointerOperand()), 4474 getValue(I.getCompareOperand()), 4475 getValue(I.getNewValOperand()), MMO); 4476 4477 SDValue OutChain = L.getValue(2); 4478 4479 setValue(&I, L); 4480 DAG.setRoot(OutChain); 4481 } 4482 4483 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4484 SDLoc dl = getCurSDLoc(); 4485 ISD::NodeType NT; 4486 switch (I.getOperation()) { 4487 default: llvm_unreachable("Unknown atomicrmw operation"); 4488 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4489 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4490 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4491 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4492 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4493 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4494 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4495 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4496 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4497 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4498 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4499 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4500 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4501 } 4502 AtomicOrdering Ordering = I.getOrdering(); 4503 SyncScope::ID SSID = I.getSyncScopeID(); 4504 4505 SDValue InChain = getRoot(); 4506 4507 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4509 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4510 4511 MachineFunction &MF = DAG.getMachineFunction(); 4512 MachineMemOperand *MMO = MF.getMachineMemOperand( 4513 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4514 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4515 4516 SDValue L = 4517 DAG.getAtomic(NT, dl, MemVT, InChain, 4518 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4519 MMO); 4520 4521 SDValue OutChain = L.getValue(1); 4522 4523 setValue(&I, L); 4524 DAG.setRoot(OutChain); 4525 } 4526 4527 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4528 SDLoc dl = getCurSDLoc(); 4529 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4530 SDValue Ops[3]; 4531 Ops[0] = getRoot(); 4532 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4533 TLI.getFenceOperandTy(DAG.getDataLayout())); 4534 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4535 TLI.getFenceOperandTy(DAG.getDataLayout())); 4536 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4537 } 4538 4539 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4540 SDLoc dl = getCurSDLoc(); 4541 AtomicOrdering Order = I.getOrdering(); 4542 SyncScope::ID SSID = I.getSyncScopeID(); 4543 4544 SDValue InChain = getRoot(); 4545 4546 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4547 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4548 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4549 4550 if (!TLI.supportsUnalignedAtomics() && 4551 I.getAlignment() < MemVT.getSizeInBits() / 8) 4552 report_fatal_error("Cannot generate unaligned atomic load"); 4553 4554 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4555 4556 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4557 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4558 *I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4559 4560 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4561 4562 SDValue Ptr = getValue(I.getPointerOperand()); 4563 4564 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4565 // TODO: Once this is better exercised by tests, it should be merged with 4566 // the normal path for loads to prevent future divergence. 4567 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4568 if (MemVT != VT) 4569 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4570 4571 setValue(&I, L); 4572 SDValue OutChain = L.getValue(1); 4573 if (!I.isUnordered()) 4574 DAG.setRoot(OutChain); 4575 else 4576 PendingLoads.push_back(OutChain); 4577 return; 4578 } 4579 4580 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4581 Ptr, MMO); 4582 4583 SDValue OutChain = L.getValue(1); 4584 if (MemVT != VT) 4585 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4586 4587 setValue(&I, L); 4588 DAG.setRoot(OutChain); 4589 } 4590 4591 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4592 SDLoc dl = getCurSDLoc(); 4593 4594 AtomicOrdering Ordering = I.getOrdering(); 4595 SyncScope::ID SSID = I.getSyncScopeID(); 4596 4597 SDValue InChain = getRoot(); 4598 4599 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4600 EVT MemVT = 4601 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4602 4603 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4604 report_fatal_error("Cannot generate unaligned atomic store"); 4605 4606 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4607 4608 MachineFunction &MF = DAG.getMachineFunction(); 4609 MachineMemOperand *MMO = MF.getMachineMemOperand( 4610 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4611 *I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4612 4613 SDValue Val = getValue(I.getValueOperand()); 4614 if (Val.getValueType() != MemVT) 4615 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4616 SDValue Ptr = getValue(I.getPointerOperand()); 4617 4618 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4619 // TODO: Once this is better exercised by tests, it should be merged with 4620 // the normal path for stores to prevent future divergence. 4621 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4622 DAG.setRoot(S); 4623 return; 4624 } 4625 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4626 Ptr, Val, MMO); 4627 4628 4629 DAG.setRoot(OutChain); 4630 } 4631 4632 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4633 /// node. 4634 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4635 unsigned Intrinsic) { 4636 // Ignore the callsite's attributes. A specific call site may be marked with 4637 // readnone, but the lowering code will expect the chain based on the 4638 // definition. 4639 const Function *F = I.getCalledFunction(); 4640 bool HasChain = !F->doesNotAccessMemory(); 4641 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4642 4643 // Build the operand list. 4644 SmallVector<SDValue, 8> Ops; 4645 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4646 if (OnlyLoad) { 4647 // We don't need to serialize loads against other loads. 4648 Ops.push_back(DAG.getRoot()); 4649 } else { 4650 Ops.push_back(getRoot()); 4651 } 4652 } 4653 4654 // Info is set by getTgtMemInstrinsic 4655 TargetLowering::IntrinsicInfo Info; 4656 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4657 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4658 DAG.getMachineFunction(), 4659 Intrinsic); 4660 4661 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4662 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4663 Info.opc == ISD::INTRINSIC_W_CHAIN) 4664 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4665 TLI.getPointerTy(DAG.getDataLayout()))); 4666 4667 // Add all operands of the call to the operand list. 4668 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4669 const Value *Arg = I.getArgOperand(i); 4670 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4671 Ops.push_back(getValue(Arg)); 4672 continue; 4673 } 4674 4675 // Use TargetConstant instead of a regular constant for immarg. 4676 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4677 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4678 assert(CI->getBitWidth() <= 64 && 4679 "large intrinsic immediates not handled"); 4680 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4681 } else { 4682 Ops.push_back( 4683 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4684 } 4685 } 4686 4687 SmallVector<EVT, 4> ValueVTs; 4688 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4689 4690 if (HasChain) 4691 ValueVTs.push_back(MVT::Other); 4692 4693 SDVTList VTs = DAG.getVTList(ValueVTs); 4694 4695 // Create the node. 4696 SDValue Result; 4697 if (IsTgtIntrinsic) { 4698 // This is target intrinsic that touches memory 4699 AAMDNodes AAInfo; 4700 I.getAAMetadata(AAInfo); 4701 Result = 4702 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4703 MachinePointerInfo(Info.ptrVal, Info.offset), 4704 Info.align, Info.flags, Info.size, AAInfo); 4705 } else if (!HasChain) { 4706 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4707 } else if (!I.getType()->isVoidTy()) { 4708 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4709 } else { 4710 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4711 } 4712 4713 if (HasChain) { 4714 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4715 if (OnlyLoad) 4716 PendingLoads.push_back(Chain); 4717 else 4718 DAG.setRoot(Chain); 4719 } 4720 4721 if (!I.getType()->isVoidTy()) { 4722 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4723 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4724 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4725 } else 4726 Result = lowerRangeToAssertZExt(DAG, I, Result); 4727 4728 setValue(&I, Result); 4729 } 4730 } 4731 4732 /// GetSignificand - Get the significand and build it into a floating-point 4733 /// number with exponent of 1: 4734 /// 4735 /// Op = (Op & 0x007fffff) | 0x3f800000; 4736 /// 4737 /// where Op is the hexadecimal representation of floating point value. 4738 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4739 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4740 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4741 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4742 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4743 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4744 } 4745 4746 /// GetExponent - Get the exponent: 4747 /// 4748 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4749 /// 4750 /// where Op is the hexadecimal representation of floating point value. 4751 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4752 const TargetLowering &TLI, const SDLoc &dl) { 4753 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4754 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4755 SDValue t1 = DAG.getNode( 4756 ISD::SRL, dl, MVT::i32, t0, 4757 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4758 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4759 DAG.getConstant(127, dl, MVT::i32)); 4760 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4761 } 4762 4763 /// getF32Constant - Get 32-bit floating point constant. 4764 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4765 const SDLoc &dl) { 4766 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4767 MVT::f32); 4768 } 4769 4770 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4771 SelectionDAG &DAG) { 4772 // TODO: What fast-math-flags should be set on the floating-point nodes? 4773 4774 // IntegerPartOfX = ((int32_t)(t0); 4775 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4776 4777 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4778 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4779 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4780 4781 // IntegerPartOfX <<= 23; 4782 IntegerPartOfX = DAG.getNode( 4783 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4784 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4785 DAG.getDataLayout()))); 4786 4787 SDValue TwoToFractionalPartOfX; 4788 if (LimitFloatPrecision <= 6) { 4789 // For floating-point precision of 6: 4790 // 4791 // TwoToFractionalPartOfX = 4792 // 0.997535578f + 4793 // (0.735607626f + 0.252464424f * x) * x; 4794 // 4795 // error 0.0144103317, which is 6 bits 4796 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4797 getF32Constant(DAG, 0x3e814304, dl)); 4798 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4799 getF32Constant(DAG, 0x3f3c50c8, dl)); 4800 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4801 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4802 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4803 } else if (LimitFloatPrecision <= 12) { 4804 // For floating-point precision of 12: 4805 // 4806 // TwoToFractionalPartOfX = 4807 // 0.999892986f + 4808 // (0.696457318f + 4809 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4810 // 4811 // error 0.000107046256, which is 13 to 14 bits 4812 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4813 getF32Constant(DAG, 0x3da235e3, dl)); 4814 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4815 getF32Constant(DAG, 0x3e65b8f3, dl)); 4816 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4817 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4818 getF32Constant(DAG, 0x3f324b07, dl)); 4819 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4820 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4821 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4822 } else { // LimitFloatPrecision <= 18 4823 // For floating-point precision of 18: 4824 // 4825 // TwoToFractionalPartOfX = 4826 // 0.999999982f + 4827 // (0.693148872f + 4828 // (0.240227044f + 4829 // (0.554906021e-1f + 4830 // (0.961591928e-2f + 4831 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4832 // error 2.47208000*10^(-7), which is better than 18 bits 4833 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4834 getF32Constant(DAG, 0x3924b03e, dl)); 4835 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4836 getF32Constant(DAG, 0x3ab24b87, dl)); 4837 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4838 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4839 getF32Constant(DAG, 0x3c1d8c17, dl)); 4840 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4841 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4842 getF32Constant(DAG, 0x3d634a1d, dl)); 4843 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4844 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4845 getF32Constant(DAG, 0x3e75fe14, dl)); 4846 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4847 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4848 getF32Constant(DAG, 0x3f317234, dl)); 4849 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4850 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4851 getF32Constant(DAG, 0x3f800000, dl)); 4852 } 4853 4854 // Add the exponent into the result in integer domain. 4855 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4856 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4857 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4858 } 4859 4860 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4861 /// limited-precision mode. 4862 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4863 const TargetLowering &TLI) { 4864 if (Op.getValueType() == MVT::f32 && 4865 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4866 4867 // Put the exponent in the right bit position for later addition to the 4868 // final result: 4869 // 4870 // t0 = Op * log2(e) 4871 4872 // TODO: What fast-math-flags should be set here? 4873 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4874 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4875 return getLimitedPrecisionExp2(t0, dl, DAG); 4876 } 4877 4878 // No special expansion. 4879 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4880 } 4881 4882 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4883 /// limited-precision mode. 4884 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4885 const TargetLowering &TLI) { 4886 // TODO: What fast-math-flags should be set on the floating-point nodes? 4887 4888 if (Op.getValueType() == MVT::f32 && 4889 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4890 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4891 4892 // Scale the exponent by log(2). 4893 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4894 SDValue LogOfExponent = 4895 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4896 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4897 4898 // Get the significand and build it into a floating-point number with 4899 // exponent of 1. 4900 SDValue X = GetSignificand(DAG, Op1, dl); 4901 4902 SDValue LogOfMantissa; 4903 if (LimitFloatPrecision <= 6) { 4904 // For floating-point precision of 6: 4905 // 4906 // LogofMantissa = 4907 // -1.1609546f + 4908 // (1.4034025f - 0.23903021f * x) * x; 4909 // 4910 // error 0.0034276066, which is better than 8 bits 4911 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4912 getF32Constant(DAG, 0xbe74c456, dl)); 4913 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4914 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4915 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4916 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4917 getF32Constant(DAG, 0x3f949a29, dl)); 4918 } else if (LimitFloatPrecision <= 12) { 4919 // For floating-point precision of 12: 4920 // 4921 // LogOfMantissa = 4922 // -1.7417939f + 4923 // (2.8212026f + 4924 // (-1.4699568f + 4925 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4926 // 4927 // error 0.000061011436, which is 14 bits 4928 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4929 getF32Constant(DAG, 0xbd67b6d6, dl)); 4930 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4931 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4932 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4933 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4934 getF32Constant(DAG, 0x3fbc278b, dl)); 4935 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4936 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4937 getF32Constant(DAG, 0x40348e95, dl)); 4938 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4939 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4940 getF32Constant(DAG, 0x3fdef31a, dl)); 4941 } else { // LimitFloatPrecision <= 18 4942 // For floating-point precision of 18: 4943 // 4944 // LogOfMantissa = 4945 // -2.1072184f + 4946 // (4.2372794f + 4947 // (-3.7029485f + 4948 // (2.2781945f + 4949 // (-0.87823314f + 4950 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4951 // 4952 // error 0.0000023660568, which is better than 18 bits 4953 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4954 getF32Constant(DAG, 0xbc91e5ac, dl)); 4955 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4956 getF32Constant(DAG, 0x3e4350aa, dl)); 4957 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4958 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4959 getF32Constant(DAG, 0x3f60d3e3, dl)); 4960 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4961 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4962 getF32Constant(DAG, 0x4011cdf0, dl)); 4963 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4964 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4965 getF32Constant(DAG, 0x406cfd1c, dl)); 4966 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4967 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4968 getF32Constant(DAG, 0x408797cb, dl)); 4969 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4970 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4971 getF32Constant(DAG, 0x4006dcab, dl)); 4972 } 4973 4974 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4975 } 4976 4977 // No special expansion. 4978 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4979 } 4980 4981 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4982 /// limited-precision mode. 4983 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4984 const TargetLowering &TLI) { 4985 // TODO: What fast-math-flags should be set on the floating-point nodes? 4986 4987 if (Op.getValueType() == MVT::f32 && 4988 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4989 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4990 4991 // Get the exponent. 4992 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4993 4994 // Get the significand and build it into a floating-point number with 4995 // exponent of 1. 4996 SDValue X = GetSignificand(DAG, Op1, dl); 4997 4998 // Different possible minimax approximations of significand in 4999 // floating-point for various degrees of accuracy over [1,2]. 5000 SDValue Log2ofMantissa; 5001 if (LimitFloatPrecision <= 6) { 5002 // For floating-point precision of 6: 5003 // 5004 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5005 // 5006 // error 0.0049451742, which is more than 7 bits 5007 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5008 getF32Constant(DAG, 0xbeb08fe0, dl)); 5009 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5010 getF32Constant(DAG, 0x40019463, dl)); 5011 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5012 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5013 getF32Constant(DAG, 0x3fd6633d, dl)); 5014 } else if (LimitFloatPrecision <= 12) { 5015 // For floating-point precision of 12: 5016 // 5017 // Log2ofMantissa = 5018 // -2.51285454f + 5019 // (4.07009056f + 5020 // (-2.12067489f + 5021 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5022 // 5023 // error 0.0000876136000, which is better than 13 bits 5024 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5025 getF32Constant(DAG, 0xbda7262e, dl)); 5026 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5027 getF32Constant(DAG, 0x3f25280b, dl)); 5028 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5029 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5030 getF32Constant(DAG, 0x4007b923, dl)); 5031 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5032 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5033 getF32Constant(DAG, 0x40823e2f, dl)); 5034 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5035 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5036 getF32Constant(DAG, 0x4020d29c, dl)); 5037 } else { // LimitFloatPrecision <= 18 5038 // For floating-point precision of 18: 5039 // 5040 // Log2ofMantissa = 5041 // -3.0400495f + 5042 // (6.1129976f + 5043 // (-5.3420409f + 5044 // (3.2865683f + 5045 // (-1.2669343f + 5046 // (0.27515199f - 5047 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5048 // 5049 // error 0.0000018516, which is better than 18 bits 5050 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5051 getF32Constant(DAG, 0xbcd2769e, dl)); 5052 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5053 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5054 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5055 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5056 getF32Constant(DAG, 0x3fa22ae7, dl)); 5057 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5058 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5059 getF32Constant(DAG, 0x40525723, dl)); 5060 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5061 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5062 getF32Constant(DAG, 0x40aaf200, dl)); 5063 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5064 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5065 getF32Constant(DAG, 0x40c39dad, dl)); 5066 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5067 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5068 getF32Constant(DAG, 0x4042902c, dl)); 5069 } 5070 5071 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5072 } 5073 5074 // No special expansion. 5075 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5076 } 5077 5078 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5079 /// limited-precision mode. 5080 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5081 const TargetLowering &TLI) { 5082 // TODO: What fast-math-flags should be set on the floating-point nodes? 5083 5084 if (Op.getValueType() == MVT::f32 && 5085 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5086 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5087 5088 // Scale the exponent by log10(2) [0.30102999f]. 5089 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5090 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5091 getF32Constant(DAG, 0x3e9a209a, dl)); 5092 5093 // Get the significand and build it into a floating-point number with 5094 // exponent of 1. 5095 SDValue X = GetSignificand(DAG, Op1, dl); 5096 5097 SDValue Log10ofMantissa; 5098 if (LimitFloatPrecision <= 6) { 5099 // For floating-point precision of 6: 5100 // 5101 // Log10ofMantissa = 5102 // -0.50419619f + 5103 // (0.60948995f - 0.10380950f * x) * x; 5104 // 5105 // error 0.0014886165, which is 6 bits 5106 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5107 getF32Constant(DAG, 0xbdd49a13, dl)); 5108 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5109 getF32Constant(DAG, 0x3f1c0789, dl)); 5110 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5111 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5112 getF32Constant(DAG, 0x3f011300, dl)); 5113 } else if (LimitFloatPrecision <= 12) { 5114 // For floating-point precision of 12: 5115 // 5116 // Log10ofMantissa = 5117 // -0.64831180f + 5118 // (0.91751397f + 5119 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5120 // 5121 // error 0.00019228036, which is better than 12 bits 5122 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5123 getF32Constant(DAG, 0x3d431f31, dl)); 5124 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5125 getF32Constant(DAG, 0x3ea21fb2, dl)); 5126 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5127 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5128 getF32Constant(DAG, 0x3f6ae232, dl)); 5129 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5130 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5131 getF32Constant(DAG, 0x3f25f7c3, dl)); 5132 } else { // LimitFloatPrecision <= 18 5133 // For floating-point precision of 18: 5134 // 5135 // Log10ofMantissa = 5136 // -0.84299375f + 5137 // (1.5327582f + 5138 // (-1.0688956f + 5139 // (0.49102474f + 5140 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5141 // 5142 // error 0.0000037995730, which is better than 18 bits 5143 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5144 getF32Constant(DAG, 0x3c5d51ce, dl)); 5145 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5146 getF32Constant(DAG, 0x3e00685a, dl)); 5147 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5148 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5149 getF32Constant(DAG, 0x3efb6798, dl)); 5150 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5151 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5152 getF32Constant(DAG, 0x3f88d192, dl)); 5153 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5154 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5155 getF32Constant(DAG, 0x3fc4316c, dl)); 5156 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5157 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5158 getF32Constant(DAG, 0x3f57ce70, dl)); 5159 } 5160 5161 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5162 } 5163 5164 // No special expansion. 5165 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5166 } 5167 5168 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5169 /// limited-precision mode. 5170 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5171 const TargetLowering &TLI) { 5172 if (Op.getValueType() == MVT::f32 && 5173 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5174 return getLimitedPrecisionExp2(Op, dl, DAG); 5175 5176 // No special expansion. 5177 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5178 } 5179 5180 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5181 /// limited-precision mode with x == 10.0f. 5182 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5183 SelectionDAG &DAG, const TargetLowering &TLI) { 5184 bool IsExp10 = false; 5185 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5186 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5187 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5188 APFloat Ten(10.0f); 5189 IsExp10 = LHSC->isExactlyValue(Ten); 5190 } 5191 } 5192 5193 // TODO: What fast-math-flags should be set on the FMUL node? 5194 if (IsExp10) { 5195 // Put the exponent in the right bit position for later addition to the 5196 // final result: 5197 // 5198 // #define LOG2OF10 3.3219281f 5199 // t0 = Op * LOG2OF10; 5200 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5201 getF32Constant(DAG, 0x40549a78, dl)); 5202 return getLimitedPrecisionExp2(t0, dl, DAG); 5203 } 5204 5205 // No special expansion. 5206 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5207 } 5208 5209 /// ExpandPowI - Expand a llvm.powi intrinsic. 5210 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5211 SelectionDAG &DAG) { 5212 // If RHS is a constant, we can expand this out to a multiplication tree, 5213 // otherwise we end up lowering to a call to __powidf2 (for example). When 5214 // optimizing for size, we only want to do this if the expansion would produce 5215 // a small number of multiplies, otherwise we do the full expansion. 5216 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5217 // Get the exponent as a positive value. 5218 unsigned Val = RHSC->getSExtValue(); 5219 if ((int)Val < 0) Val = -Val; 5220 5221 // powi(x, 0) -> 1.0 5222 if (Val == 0) 5223 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5224 5225 bool OptForSize = DAG.shouldOptForSize(); 5226 if (!OptForSize || 5227 // If optimizing for size, don't insert too many multiplies. 5228 // This inserts up to 5 multiplies. 5229 countPopulation(Val) + Log2_32(Val) < 7) { 5230 // We use the simple binary decomposition method to generate the multiply 5231 // sequence. There are more optimal ways to do this (for example, 5232 // powi(x,15) generates one more multiply than it should), but this has 5233 // the benefit of being both really simple and much better than a libcall. 5234 SDValue Res; // Logically starts equal to 1.0 5235 SDValue CurSquare = LHS; 5236 // TODO: Intrinsics should have fast-math-flags that propagate to these 5237 // nodes. 5238 while (Val) { 5239 if (Val & 1) { 5240 if (Res.getNode()) 5241 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5242 else 5243 Res = CurSquare; // 1.0*CurSquare. 5244 } 5245 5246 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5247 CurSquare, CurSquare); 5248 Val >>= 1; 5249 } 5250 5251 // If the original was negative, invert the result, producing 1/(x*x*x). 5252 if (RHSC->getSExtValue() < 0) 5253 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5254 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5255 return Res; 5256 } 5257 } 5258 5259 // Otherwise, expand to a libcall. 5260 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5261 } 5262 5263 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5264 SDValue LHS, SDValue RHS, SDValue Scale, 5265 SelectionDAG &DAG, const TargetLowering &TLI) { 5266 EVT VT = LHS.getValueType(); 5267 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5268 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5269 LLVMContext &Ctx = *DAG.getContext(); 5270 5271 // If the type is legal but the operation isn't, this node might survive all 5272 // the way to operation legalization. If we end up there and we do not have 5273 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5274 // node. 5275 5276 // Coax the legalizer into expanding the node during type legalization instead 5277 // by bumping the size by one bit. This will force it to Promote, enabling the 5278 // early expansion and avoiding the need to expand later. 5279 5280 // We don't have to do this if Scale is 0; that can always be expanded, unless 5281 // it's a saturating signed operation. Those can experience true integer 5282 // division overflow, a case which we must avoid. 5283 5284 // FIXME: We wouldn't have to do this (or any of the early 5285 // expansion/promotion) if it was possible to expand a libcall of an 5286 // illegal type during operation legalization. But it's not, so things 5287 // get a bit hacky. 5288 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5289 if ((ScaleInt > 0 || (Saturating && Signed)) && 5290 (TLI.isTypeLegal(VT) || 5291 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5292 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5293 Opcode, VT, ScaleInt); 5294 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5295 EVT PromVT; 5296 if (VT.isScalarInteger()) 5297 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5298 else if (VT.isVector()) { 5299 PromVT = VT.getVectorElementType(); 5300 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5301 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5302 } else 5303 llvm_unreachable("Wrong VT for DIVFIX?"); 5304 if (Signed) { 5305 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5306 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5307 } else { 5308 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5309 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5310 } 5311 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5312 // For saturating operations, we need to shift up the LHS to get the 5313 // proper saturation width, and then shift down again afterwards. 5314 if (Saturating) 5315 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5316 DAG.getConstant(1, DL, ShiftTy)); 5317 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5318 if (Saturating) 5319 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5320 DAG.getConstant(1, DL, ShiftTy)); 5321 return DAG.getZExtOrTrunc(Res, DL, VT); 5322 } 5323 } 5324 5325 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5326 } 5327 5328 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5329 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5330 static void 5331 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5332 const SDValue &N) { 5333 switch (N.getOpcode()) { 5334 case ISD::CopyFromReg: { 5335 SDValue Op = N.getOperand(1); 5336 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5337 Op.getValueType().getSizeInBits()); 5338 return; 5339 } 5340 case ISD::BITCAST: 5341 case ISD::AssertZext: 5342 case ISD::AssertSext: 5343 case ISD::TRUNCATE: 5344 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5345 return; 5346 case ISD::BUILD_PAIR: 5347 case ISD::BUILD_VECTOR: 5348 case ISD::CONCAT_VECTORS: 5349 for (SDValue Op : N->op_values()) 5350 getUnderlyingArgRegs(Regs, Op); 5351 return; 5352 default: 5353 return; 5354 } 5355 } 5356 5357 /// If the DbgValueInst is a dbg_value of a function argument, create the 5358 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5359 /// instruction selection, they will be inserted to the entry BB. 5360 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5361 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5362 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5363 const Argument *Arg = dyn_cast<Argument>(V); 5364 if (!Arg) 5365 return false; 5366 5367 if (!IsDbgDeclare) { 5368 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5369 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5370 // the entry block. 5371 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5372 if (!IsInEntryBlock) 5373 return false; 5374 5375 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5376 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5377 // variable that also is a param. 5378 // 5379 // Although, if we are at the top of the entry block already, we can still 5380 // emit using ArgDbgValue. This might catch some situations when the 5381 // dbg.value refers to an argument that isn't used in the entry block, so 5382 // any CopyToReg node would be optimized out and the only way to express 5383 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5384 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5385 // we should only emit as ArgDbgValue if the Variable is an argument to the 5386 // current function, and the dbg.value intrinsic is found in the entry 5387 // block. 5388 bool VariableIsFunctionInputArg = Variable->isParameter() && 5389 !DL->getInlinedAt(); 5390 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5391 if (!IsInPrologue && !VariableIsFunctionInputArg) 5392 return false; 5393 5394 // Here we assume that a function argument on IR level only can be used to 5395 // describe one input parameter on source level. If we for example have 5396 // source code like this 5397 // 5398 // struct A { long x, y; }; 5399 // void foo(struct A a, long b) { 5400 // ... 5401 // b = a.x; 5402 // ... 5403 // } 5404 // 5405 // and IR like this 5406 // 5407 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5408 // entry: 5409 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5410 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5411 // call void @llvm.dbg.value(metadata i32 %b, "b", 5412 // ... 5413 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5414 // ... 5415 // 5416 // then the last dbg.value is describing a parameter "b" using a value that 5417 // is an argument. But since we already has used %a1 to describe a parameter 5418 // we should not handle that last dbg.value here (that would result in an 5419 // incorrect hoisting of the DBG_VALUE to the function entry). 5420 // Notice that we allow one dbg.value per IR level argument, to accommodate 5421 // for the situation with fragments above. 5422 if (VariableIsFunctionInputArg) { 5423 unsigned ArgNo = Arg->getArgNo(); 5424 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5425 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5426 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5427 return false; 5428 FuncInfo.DescribedArgs.set(ArgNo); 5429 } 5430 } 5431 5432 MachineFunction &MF = DAG.getMachineFunction(); 5433 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5434 5435 bool IsIndirect = false; 5436 Optional<MachineOperand> Op; 5437 // Some arguments' frame index is recorded during argument lowering. 5438 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5439 if (FI != std::numeric_limits<int>::max()) 5440 Op = MachineOperand::CreateFI(FI); 5441 5442 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5443 if (!Op && N.getNode()) { 5444 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5445 Register Reg; 5446 if (ArgRegsAndSizes.size() == 1) 5447 Reg = ArgRegsAndSizes.front().first; 5448 5449 if (Reg && Reg.isVirtual()) { 5450 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5451 Register PR = RegInfo.getLiveInPhysReg(Reg); 5452 if (PR) 5453 Reg = PR; 5454 } 5455 if (Reg) { 5456 Op = MachineOperand::CreateReg(Reg, false); 5457 IsIndirect = IsDbgDeclare; 5458 } 5459 } 5460 5461 if (!Op && N.getNode()) { 5462 // Check if frame index is available. 5463 SDValue LCandidate = peekThroughBitcasts(N); 5464 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5465 if (FrameIndexSDNode *FINode = 5466 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5467 Op = MachineOperand::CreateFI(FINode->getIndex()); 5468 } 5469 5470 if (!Op) { 5471 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5472 auto splitMultiRegDbgValue 5473 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5474 unsigned Offset = 0; 5475 for (auto RegAndSize : SplitRegs) { 5476 // If the expression is already a fragment, the current register 5477 // offset+size might extend beyond the fragment. In this case, only 5478 // the register bits that are inside the fragment are relevant. 5479 int RegFragmentSizeInBits = RegAndSize.second; 5480 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5481 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5482 // The register is entirely outside the expression fragment, 5483 // so is irrelevant for debug info. 5484 if (Offset >= ExprFragmentSizeInBits) 5485 break; 5486 // The register is partially outside the expression fragment, only 5487 // the low bits within the fragment are relevant for debug info. 5488 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5489 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5490 } 5491 } 5492 5493 auto FragmentExpr = DIExpression::createFragmentExpression( 5494 Expr, Offset, RegFragmentSizeInBits); 5495 Offset += RegAndSize.second; 5496 // If a valid fragment expression cannot be created, the variable's 5497 // correct value cannot be determined and so it is set as Undef. 5498 if (!FragmentExpr) { 5499 SDDbgValue *SDV = DAG.getConstantDbgValue( 5500 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5501 DAG.AddDbgValue(SDV, nullptr, false); 5502 continue; 5503 } 5504 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5505 FuncInfo.ArgDbgValues.push_back( 5506 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5507 RegAndSize.first, Variable, *FragmentExpr)); 5508 } 5509 }; 5510 5511 // Check if ValueMap has reg number. 5512 DenseMap<const Value *, Register>::const_iterator 5513 VMI = FuncInfo.ValueMap.find(V); 5514 if (VMI != FuncInfo.ValueMap.end()) { 5515 const auto &TLI = DAG.getTargetLoweringInfo(); 5516 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5517 V->getType(), getABIRegCopyCC(V)); 5518 if (RFV.occupiesMultipleRegs()) { 5519 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5520 return true; 5521 } 5522 5523 Op = MachineOperand::CreateReg(VMI->second, false); 5524 IsIndirect = IsDbgDeclare; 5525 } else if (ArgRegsAndSizes.size() > 1) { 5526 // This was split due to the calling convention, and no virtual register 5527 // mapping exists for the value. 5528 splitMultiRegDbgValue(ArgRegsAndSizes); 5529 return true; 5530 } 5531 } 5532 5533 if (!Op) 5534 return false; 5535 5536 assert(Variable->isValidLocationForIntrinsic(DL) && 5537 "Expected inlined-at fields to agree"); 5538 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5539 FuncInfo.ArgDbgValues.push_back( 5540 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5541 *Op, Variable, Expr)); 5542 5543 return true; 5544 } 5545 5546 /// Return the appropriate SDDbgValue based on N. 5547 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5548 DILocalVariable *Variable, 5549 DIExpression *Expr, 5550 const DebugLoc &dl, 5551 unsigned DbgSDNodeOrder) { 5552 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5553 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5554 // stack slot locations. 5555 // 5556 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5557 // debug values here after optimization: 5558 // 5559 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5560 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5561 // 5562 // Both describe the direct values of their associated variables. 5563 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5564 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5565 } 5566 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5567 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5568 } 5569 5570 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5571 switch (Intrinsic) { 5572 case Intrinsic::smul_fix: 5573 return ISD::SMULFIX; 5574 case Intrinsic::umul_fix: 5575 return ISD::UMULFIX; 5576 case Intrinsic::smul_fix_sat: 5577 return ISD::SMULFIXSAT; 5578 case Intrinsic::umul_fix_sat: 5579 return ISD::UMULFIXSAT; 5580 case Intrinsic::sdiv_fix: 5581 return ISD::SDIVFIX; 5582 case Intrinsic::udiv_fix: 5583 return ISD::UDIVFIX; 5584 case Intrinsic::sdiv_fix_sat: 5585 return ISD::SDIVFIXSAT; 5586 case Intrinsic::udiv_fix_sat: 5587 return ISD::UDIVFIXSAT; 5588 default: 5589 llvm_unreachable("Unhandled fixed point intrinsic"); 5590 } 5591 } 5592 5593 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5594 const char *FunctionName) { 5595 assert(FunctionName && "FunctionName must not be nullptr"); 5596 SDValue Callee = DAG.getExternalSymbol( 5597 FunctionName, 5598 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5599 LowerCallTo(I, Callee, I.isTailCall()); 5600 } 5601 5602 /// Lower the call to the specified intrinsic function. 5603 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5604 unsigned Intrinsic) { 5605 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5606 SDLoc sdl = getCurSDLoc(); 5607 DebugLoc dl = getCurDebugLoc(); 5608 SDValue Res; 5609 5610 switch (Intrinsic) { 5611 default: 5612 // By default, turn this into a target intrinsic node. 5613 visitTargetIntrinsic(I, Intrinsic); 5614 return; 5615 case Intrinsic::vscale: { 5616 match(&I, m_VScale(DAG.getDataLayout())); 5617 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5618 setValue(&I, 5619 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5620 return; 5621 } 5622 case Intrinsic::vastart: visitVAStart(I); return; 5623 case Intrinsic::vaend: visitVAEnd(I); return; 5624 case Intrinsic::vacopy: visitVACopy(I); return; 5625 case Intrinsic::returnaddress: 5626 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5627 TLI.getPointerTy(DAG.getDataLayout()), 5628 getValue(I.getArgOperand(0)))); 5629 return; 5630 case Intrinsic::addressofreturnaddress: 5631 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5632 TLI.getPointerTy(DAG.getDataLayout()))); 5633 return; 5634 case Intrinsic::sponentry: 5635 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5636 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5637 return; 5638 case Intrinsic::frameaddress: 5639 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5640 TLI.getFrameIndexTy(DAG.getDataLayout()), 5641 getValue(I.getArgOperand(0)))); 5642 return; 5643 case Intrinsic::read_register: { 5644 Value *Reg = I.getArgOperand(0); 5645 SDValue Chain = getRoot(); 5646 SDValue RegName = 5647 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5648 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5649 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5650 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5651 setValue(&I, Res); 5652 DAG.setRoot(Res.getValue(1)); 5653 return; 5654 } 5655 case Intrinsic::write_register: { 5656 Value *Reg = I.getArgOperand(0); 5657 Value *RegValue = I.getArgOperand(1); 5658 SDValue Chain = getRoot(); 5659 SDValue RegName = 5660 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5661 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5662 RegName, getValue(RegValue))); 5663 return; 5664 } 5665 case Intrinsic::memcpy: { 5666 const auto &MCI = cast<MemCpyInst>(I); 5667 SDValue Op1 = getValue(I.getArgOperand(0)); 5668 SDValue Op2 = getValue(I.getArgOperand(1)); 5669 SDValue Op3 = getValue(I.getArgOperand(2)); 5670 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5671 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5672 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5673 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5674 bool isVol = MCI.isVolatile(); 5675 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5676 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5677 // node. 5678 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5679 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5680 /* AlwaysInline */ false, isTC, 5681 MachinePointerInfo(I.getArgOperand(0)), 5682 MachinePointerInfo(I.getArgOperand(1))); 5683 updateDAGForMaybeTailCall(MC); 5684 return; 5685 } 5686 case Intrinsic::memcpy_inline: { 5687 const auto &MCI = cast<MemCpyInlineInst>(I); 5688 SDValue Dst = getValue(I.getArgOperand(0)); 5689 SDValue Src = getValue(I.getArgOperand(1)); 5690 SDValue Size = getValue(I.getArgOperand(2)); 5691 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5692 // @llvm.memcpy.inline 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 MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5701 /* AlwaysInline */ true, isTC, 5702 MachinePointerInfo(I.getArgOperand(0)), 5703 MachinePointerInfo(I.getArgOperand(1))); 5704 updateDAGForMaybeTailCall(MC); 5705 return; 5706 } 5707 case Intrinsic::memset: { 5708 const auto &MSI = cast<MemSetInst>(I); 5709 SDValue Op1 = getValue(I.getArgOperand(0)); 5710 SDValue Op2 = getValue(I.getArgOperand(1)); 5711 SDValue Op3 = getValue(I.getArgOperand(2)); 5712 // @llvm.memset defines 0 and 1 to both mean no alignment. 5713 Align Alignment = MSI.getDestAlign().valueOrOne(); 5714 bool isVol = MSI.isVolatile(); 5715 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5716 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5717 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5718 MachinePointerInfo(I.getArgOperand(0))); 5719 updateDAGForMaybeTailCall(MS); 5720 return; 5721 } 5722 case Intrinsic::memmove: { 5723 const auto &MMI = cast<MemMoveInst>(I); 5724 SDValue Op1 = getValue(I.getArgOperand(0)); 5725 SDValue Op2 = getValue(I.getArgOperand(1)); 5726 SDValue Op3 = getValue(I.getArgOperand(2)); 5727 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5728 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5729 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5730 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5731 bool isVol = MMI.isVolatile(); 5732 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5733 // FIXME: Support passing different dest/src alignments to the memmove DAG 5734 // node. 5735 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5736 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5737 isTC, MachinePointerInfo(I.getArgOperand(0)), 5738 MachinePointerInfo(I.getArgOperand(1))); 5739 updateDAGForMaybeTailCall(MM); 5740 return; 5741 } 5742 case Intrinsic::memcpy_element_unordered_atomic: { 5743 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5744 SDValue Dst = getValue(MI.getRawDest()); 5745 SDValue Src = getValue(MI.getRawSource()); 5746 SDValue Length = getValue(MI.getLength()); 5747 5748 unsigned DstAlign = MI.getDestAlignment(); 5749 unsigned SrcAlign = MI.getSourceAlignment(); 5750 Type *LengthTy = MI.getLength()->getType(); 5751 unsigned ElemSz = MI.getElementSizeInBytes(); 5752 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5753 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5754 SrcAlign, Length, LengthTy, ElemSz, isTC, 5755 MachinePointerInfo(MI.getRawDest()), 5756 MachinePointerInfo(MI.getRawSource())); 5757 updateDAGForMaybeTailCall(MC); 5758 return; 5759 } 5760 case Intrinsic::memmove_element_unordered_atomic: { 5761 auto &MI = cast<AtomicMemMoveInst>(I); 5762 SDValue Dst = getValue(MI.getRawDest()); 5763 SDValue Src = getValue(MI.getRawSource()); 5764 SDValue Length = getValue(MI.getLength()); 5765 5766 unsigned DstAlign = MI.getDestAlignment(); 5767 unsigned SrcAlign = MI.getSourceAlignment(); 5768 Type *LengthTy = MI.getLength()->getType(); 5769 unsigned ElemSz = MI.getElementSizeInBytes(); 5770 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5771 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5772 SrcAlign, Length, LengthTy, ElemSz, isTC, 5773 MachinePointerInfo(MI.getRawDest()), 5774 MachinePointerInfo(MI.getRawSource())); 5775 updateDAGForMaybeTailCall(MC); 5776 return; 5777 } 5778 case Intrinsic::memset_element_unordered_atomic: { 5779 auto &MI = cast<AtomicMemSetInst>(I); 5780 SDValue Dst = getValue(MI.getRawDest()); 5781 SDValue Val = getValue(MI.getValue()); 5782 SDValue Length = getValue(MI.getLength()); 5783 5784 unsigned DstAlign = MI.getDestAlignment(); 5785 Type *LengthTy = MI.getLength()->getType(); 5786 unsigned ElemSz = MI.getElementSizeInBytes(); 5787 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5788 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5789 LengthTy, ElemSz, isTC, 5790 MachinePointerInfo(MI.getRawDest())); 5791 updateDAGForMaybeTailCall(MC); 5792 return; 5793 } 5794 case Intrinsic::dbg_addr: 5795 case Intrinsic::dbg_declare: { 5796 const auto &DI = cast<DbgVariableIntrinsic>(I); 5797 DILocalVariable *Variable = DI.getVariable(); 5798 DIExpression *Expression = DI.getExpression(); 5799 dropDanglingDebugInfo(Variable, Expression); 5800 assert(Variable && "Missing variable"); 5801 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5802 << "\n"); 5803 // Check if address has undef value. 5804 const Value *Address = DI.getVariableLocation(); 5805 if (!Address || isa<UndefValue>(Address) || 5806 (Address->use_empty() && !isa<Argument>(Address))) { 5807 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5808 << " (bad/undef/unused-arg address)\n"); 5809 return; 5810 } 5811 5812 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5813 5814 // Check if this variable can be described by a frame index, typically 5815 // either as a static alloca or a byval parameter. 5816 int FI = std::numeric_limits<int>::max(); 5817 if (const auto *AI = 5818 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5819 if (AI->isStaticAlloca()) { 5820 auto I = FuncInfo.StaticAllocaMap.find(AI); 5821 if (I != FuncInfo.StaticAllocaMap.end()) 5822 FI = I->second; 5823 } 5824 } else if (const auto *Arg = dyn_cast<Argument>( 5825 Address->stripInBoundsConstantOffsets())) { 5826 FI = FuncInfo.getArgumentFrameIndex(Arg); 5827 } 5828 5829 // llvm.dbg.addr is control dependent and always generates indirect 5830 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5831 // the MachineFunction variable table. 5832 if (FI != std::numeric_limits<int>::max()) { 5833 if (Intrinsic == Intrinsic::dbg_addr) { 5834 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5835 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5836 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5837 } else { 5838 LLVM_DEBUG(dbgs() << "Skipping " << DI 5839 << " (variable info stashed in MF side table)\n"); 5840 } 5841 return; 5842 } 5843 5844 SDValue &N = NodeMap[Address]; 5845 if (!N.getNode() && isa<Argument>(Address)) 5846 // Check unused arguments map. 5847 N = UnusedArgNodeMap[Address]; 5848 SDDbgValue *SDV; 5849 if (N.getNode()) { 5850 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5851 Address = BCI->getOperand(0); 5852 // Parameters are handled specially. 5853 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5854 if (isParameter && FINode) { 5855 // Byval parameter. We have a frame index at this point. 5856 SDV = 5857 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5858 /*IsIndirect*/ true, dl, SDNodeOrder); 5859 } else if (isa<Argument>(Address)) { 5860 // Address is an argument, so try to emit its dbg value using 5861 // virtual register info from the FuncInfo.ValueMap. 5862 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5863 return; 5864 } else { 5865 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5866 true, dl, SDNodeOrder); 5867 } 5868 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5869 } else { 5870 // If Address is an argument then try to emit its dbg value using 5871 // virtual register info from the FuncInfo.ValueMap. 5872 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5873 N)) { 5874 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5875 << " (could not emit func-arg dbg_value)\n"); 5876 } 5877 } 5878 return; 5879 } 5880 case Intrinsic::dbg_label: { 5881 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5882 DILabel *Label = DI.getLabel(); 5883 assert(Label && "Missing label"); 5884 5885 SDDbgLabel *SDV; 5886 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5887 DAG.AddDbgLabel(SDV); 5888 return; 5889 } 5890 case Intrinsic::dbg_value: { 5891 const DbgValueInst &DI = cast<DbgValueInst>(I); 5892 assert(DI.getVariable() && "Missing variable"); 5893 5894 DILocalVariable *Variable = DI.getVariable(); 5895 DIExpression *Expression = DI.getExpression(); 5896 dropDanglingDebugInfo(Variable, Expression); 5897 const Value *V = DI.getValue(); 5898 if (!V) 5899 return; 5900 5901 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5902 SDNodeOrder)) 5903 return; 5904 5905 // TODO: Dangling debug info will eventually either be resolved or produce 5906 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5907 // between the original dbg.value location and its resolved DBG_VALUE, which 5908 // we should ideally fill with an extra Undef DBG_VALUE. 5909 5910 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5911 return; 5912 } 5913 5914 case Intrinsic::eh_typeid_for: { 5915 // Find the type id for the given typeinfo. 5916 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5917 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5918 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5919 setValue(&I, Res); 5920 return; 5921 } 5922 5923 case Intrinsic::eh_return_i32: 5924 case Intrinsic::eh_return_i64: 5925 DAG.getMachineFunction().setCallsEHReturn(true); 5926 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5927 MVT::Other, 5928 getControlRoot(), 5929 getValue(I.getArgOperand(0)), 5930 getValue(I.getArgOperand(1)))); 5931 return; 5932 case Intrinsic::eh_unwind_init: 5933 DAG.getMachineFunction().setCallsUnwindInit(true); 5934 return; 5935 case Intrinsic::eh_dwarf_cfa: 5936 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5937 TLI.getPointerTy(DAG.getDataLayout()), 5938 getValue(I.getArgOperand(0)))); 5939 return; 5940 case Intrinsic::eh_sjlj_callsite: { 5941 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5942 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5943 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5944 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5945 5946 MMI.setCurrentCallSite(CI->getZExtValue()); 5947 return; 5948 } 5949 case Intrinsic::eh_sjlj_functioncontext: { 5950 // Get and store the index of the function context. 5951 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5952 AllocaInst *FnCtx = 5953 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5954 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5955 MFI.setFunctionContextIndex(FI); 5956 return; 5957 } 5958 case Intrinsic::eh_sjlj_setjmp: { 5959 SDValue Ops[2]; 5960 Ops[0] = getRoot(); 5961 Ops[1] = getValue(I.getArgOperand(0)); 5962 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5963 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5964 setValue(&I, Op.getValue(0)); 5965 DAG.setRoot(Op.getValue(1)); 5966 return; 5967 } 5968 case Intrinsic::eh_sjlj_longjmp: 5969 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5970 getRoot(), getValue(I.getArgOperand(0)))); 5971 return; 5972 case Intrinsic::eh_sjlj_setup_dispatch: 5973 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5974 getRoot())); 5975 return; 5976 case Intrinsic::masked_gather: 5977 visitMaskedGather(I); 5978 return; 5979 case Intrinsic::masked_load: 5980 visitMaskedLoad(I); 5981 return; 5982 case Intrinsic::masked_scatter: 5983 visitMaskedScatter(I); 5984 return; 5985 case Intrinsic::masked_store: 5986 visitMaskedStore(I); 5987 return; 5988 case Intrinsic::masked_expandload: 5989 visitMaskedLoad(I, true /* IsExpanding */); 5990 return; 5991 case Intrinsic::masked_compressstore: 5992 visitMaskedStore(I, true /* IsCompressing */); 5993 return; 5994 case Intrinsic::powi: 5995 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5996 getValue(I.getArgOperand(1)), DAG)); 5997 return; 5998 case Intrinsic::log: 5999 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6000 return; 6001 case Intrinsic::log2: 6002 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6003 return; 6004 case Intrinsic::log10: 6005 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6006 return; 6007 case Intrinsic::exp: 6008 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6009 return; 6010 case Intrinsic::exp2: 6011 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6012 return; 6013 case Intrinsic::pow: 6014 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6015 getValue(I.getArgOperand(1)), DAG, TLI)); 6016 return; 6017 case Intrinsic::sqrt: 6018 case Intrinsic::fabs: 6019 case Intrinsic::sin: 6020 case Intrinsic::cos: 6021 case Intrinsic::floor: 6022 case Intrinsic::ceil: 6023 case Intrinsic::trunc: 6024 case Intrinsic::rint: 6025 case Intrinsic::nearbyint: 6026 case Intrinsic::round: 6027 case Intrinsic::canonicalize: { 6028 unsigned Opcode; 6029 switch (Intrinsic) { 6030 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6031 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6032 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6033 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6034 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6035 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6036 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6037 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6038 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6039 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6040 case Intrinsic::round: Opcode = ISD::FROUND; break; 6041 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6042 } 6043 6044 setValue(&I, DAG.getNode(Opcode, sdl, 6045 getValue(I.getArgOperand(0)).getValueType(), 6046 getValue(I.getArgOperand(0)))); 6047 return; 6048 } 6049 case Intrinsic::lround: 6050 case Intrinsic::llround: 6051 case Intrinsic::lrint: 6052 case Intrinsic::llrint: { 6053 unsigned Opcode; 6054 switch (Intrinsic) { 6055 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6056 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6057 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6058 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6059 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6060 } 6061 6062 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6063 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6064 getValue(I.getArgOperand(0)))); 6065 return; 6066 } 6067 case Intrinsic::minnum: 6068 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6069 getValue(I.getArgOperand(0)).getValueType(), 6070 getValue(I.getArgOperand(0)), 6071 getValue(I.getArgOperand(1)))); 6072 return; 6073 case Intrinsic::maxnum: 6074 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6075 getValue(I.getArgOperand(0)).getValueType(), 6076 getValue(I.getArgOperand(0)), 6077 getValue(I.getArgOperand(1)))); 6078 return; 6079 case Intrinsic::minimum: 6080 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6081 getValue(I.getArgOperand(0)).getValueType(), 6082 getValue(I.getArgOperand(0)), 6083 getValue(I.getArgOperand(1)))); 6084 return; 6085 case Intrinsic::maximum: 6086 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6087 getValue(I.getArgOperand(0)).getValueType(), 6088 getValue(I.getArgOperand(0)), 6089 getValue(I.getArgOperand(1)))); 6090 return; 6091 case Intrinsic::copysign: 6092 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6093 getValue(I.getArgOperand(0)).getValueType(), 6094 getValue(I.getArgOperand(0)), 6095 getValue(I.getArgOperand(1)))); 6096 return; 6097 case Intrinsic::fma: 6098 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6099 getValue(I.getArgOperand(0)).getValueType(), 6100 getValue(I.getArgOperand(0)), 6101 getValue(I.getArgOperand(1)), 6102 getValue(I.getArgOperand(2)))); 6103 return; 6104 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6105 case Intrinsic::INTRINSIC: 6106 #include "llvm/IR/ConstrainedOps.def" 6107 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6108 return; 6109 case Intrinsic::fmuladd: { 6110 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6111 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6112 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6113 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6114 getValue(I.getArgOperand(0)).getValueType(), 6115 getValue(I.getArgOperand(0)), 6116 getValue(I.getArgOperand(1)), 6117 getValue(I.getArgOperand(2)))); 6118 } else { 6119 // TODO: Intrinsic calls should have fast-math-flags. 6120 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6121 getValue(I.getArgOperand(0)).getValueType(), 6122 getValue(I.getArgOperand(0)), 6123 getValue(I.getArgOperand(1))); 6124 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6125 getValue(I.getArgOperand(0)).getValueType(), 6126 Mul, 6127 getValue(I.getArgOperand(2))); 6128 setValue(&I, Add); 6129 } 6130 return; 6131 } 6132 case Intrinsic::convert_to_fp16: 6133 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6134 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6135 getValue(I.getArgOperand(0)), 6136 DAG.getTargetConstant(0, sdl, 6137 MVT::i32)))); 6138 return; 6139 case Intrinsic::convert_from_fp16: 6140 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6141 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6142 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6143 getValue(I.getArgOperand(0))))); 6144 return; 6145 case Intrinsic::pcmarker: { 6146 SDValue Tmp = getValue(I.getArgOperand(0)); 6147 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6148 return; 6149 } 6150 case Intrinsic::readcyclecounter: { 6151 SDValue Op = getRoot(); 6152 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6153 DAG.getVTList(MVT::i64, MVT::Other), Op); 6154 setValue(&I, Res); 6155 DAG.setRoot(Res.getValue(1)); 6156 return; 6157 } 6158 case Intrinsic::bitreverse: 6159 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6160 getValue(I.getArgOperand(0)).getValueType(), 6161 getValue(I.getArgOperand(0)))); 6162 return; 6163 case Intrinsic::bswap: 6164 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6165 getValue(I.getArgOperand(0)).getValueType(), 6166 getValue(I.getArgOperand(0)))); 6167 return; 6168 case Intrinsic::cttz: { 6169 SDValue Arg = getValue(I.getArgOperand(0)); 6170 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6171 EVT Ty = Arg.getValueType(); 6172 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6173 sdl, Ty, Arg)); 6174 return; 6175 } 6176 case Intrinsic::ctlz: { 6177 SDValue Arg = getValue(I.getArgOperand(0)); 6178 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6179 EVT Ty = Arg.getValueType(); 6180 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6181 sdl, Ty, Arg)); 6182 return; 6183 } 6184 case Intrinsic::ctpop: { 6185 SDValue Arg = getValue(I.getArgOperand(0)); 6186 EVT Ty = Arg.getValueType(); 6187 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6188 return; 6189 } 6190 case Intrinsic::fshl: 6191 case Intrinsic::fshr: { 6192 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6193 SDValue X = getValue(I.getArgOperand(0)); 6194 SDValue Y = getValue(I.getArgOperand(1)); 6195 SDValue Z = getValue(I.getArgOperand(2)); 6196 EVT VT = X.getValueType(); 6197 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6198 SDValue Zero = DAG.getConstant(0, sdl, VT); 6199 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6200 6201 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6202 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6203 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6204 return; 6205 } 6206 6207 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6208 // avoid the select that is necessary in the general case to filter out 6209 // the 0-shift possibility that leads to UB. 6210 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6211 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6212 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6213 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6214 return; 6215 } 6216 6217 // Some targets only rotate one way. Try the opposite direction. 6218 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6219 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6220 // Negate the shift amount because it is safe to ignore the high bits. 6221 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6222 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6223 return; 6224 } 6225 6226 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6227 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6228 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6229 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6230 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6231 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6232 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6233 return; 6234 } 6235 6236 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6237 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6238 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6239 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6240 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6241 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6242 6243 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6244 // and that is undefined. We must compare and select to avoid UB. 6245 EVT CCVT = MVT::i1; 6246 if (VT.isVector()) 6247 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6248 6249 // For fshl, 0-shift returns the 1st arg (X). 6250 // For fshr, 0-shift returns the 2nd arg (Y). 6251 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6252 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6253 return; 6254 } 6255 case Intrinsic::sadd_sat: { 6256 SDValue Op1 = getValue(I.getArgOperand(0)); 6257 SDValue Op2 = getValue(I.getArgOperand(1)); 6258 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6259 return; 6260 } 6261 case Intrinsic::uadd_sat: { 6262 SDValue Op1 = getValue(I.getArgOperand(0)); 6263 SDValue Op2 = getValue(I.getArgOperand(1)); 6264 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6265 return; 6266 } 6267 case Intrinsic::ssub_sat: { 6268 SDValue Op1 = getValue(I.getArgOperand(0)); 6269 SDValue Op2 = getValue(I.getArgOperand(1)); 6270 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6271 return; 6272 } 6273 case Intrinsic::usub_sat: { 6274 SDValue Op1 = getValue(I.getArgOperand(0)); 6275 SDValue Op2 = getValue(I.getArgOperand(1)); 6276 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6277 return; 6278 } 6279 case Intrinsic::smul_fix: 6280 case Intrinsic::umul_fix: 6281 case Intrinsic::smul_fix_sat: 6282 case Intrinsic::umul_fix_sat: { 6283 SDValue Op1 = getValue(I.getArgOperand(0)); 6284 SDValue Op2 = getValue(I.getArgOperand(1)); 6285 SDValue Op3 = getValue(I.getArgOperand(2)); 6286 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6287 Op1.getValueType(), Op1, Op2, Op3)); 6288 return; 6289 } 6290 case Intrinsic::sdiv_fix: 6291 case Intrinsic::udiv_fix: 6292 case Intrinsic::sdiv_fix_sat: 6293 case Intrinsic::udiv_fix_sat: { 6294 SDValue Op1 = getValue(I.getArgOperand(0)); 6295 SDValue Op2 = getValue(I.getArgOperand(1)); 6296 SDValue Op3 = getValue(I.getArgOperand(2)); 6297 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6298 Op1, Op2, Op3, DAG, TLI)); 6299 return; 6300 } 6301 case Intrinsic::stacksave: { 6302 SDValue Op = getRoot(); 6303 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6304 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6305 setValue(&I, Res); 6306 DAG.setRoot(Res.getValue(1)); 6307 return; 6308 } 6309 case Intrinsic::stackrestore: 6310 Res = getValue(I.getArgOperand(0)); 6311 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6312 return; 6313 case Intrinsic::get_dynamic_area_offset: { 6314 SDValue Op = getRoot(); 6315 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6316 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6317 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6318 // target. 6319 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6320 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6321 " intrinsic!"); 6322 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6323 Op); 6324 DAG.setRoot(Op); 6325 setValue(&I, Res); 6326 return; 6327 } 6328 case Intrinsic::stackguard: { 6329 MachineFunction &MF = DAG.getMachineFunction(); 6330 const Module &M = *MF.getFunction().getParent(); 6331 SDValue Chain = getRoot(); 6332 if (TLI.useLoadStackGuardNode()) { 6333 Res = getLoadStackGuard(DAG, sdl, Chain); 6334 } else { 6335 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6336 const Value *Global = TLI.getSDagStackGuard(M); 6337 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6338 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6339 MachinePointerInfo(Global, 0), Align, 6340 MachineMemOperand::MOVolatile); 6341 } 6342 if (TLI.useStackGuardXorFP()) 6343 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6344 DAG.setRoot(Chain); 6345 setValue(&I, Res); 6346 return; 6347 } 6348 case Intrinsic::stackprotector: { 6349 // Emit code into the DAG to store the stack guard onto the stack. 6350 MachineFunction &MF = DAG.getMachineFunction(); 6351 MachineFrameInfo &MFI = MF.getFrameInfo(); 6352 SDValue Src, Chain = getRoot(); 6353 6354 if (TLI.useLoadStackGuardNode()) 6355 Src = getLoadStackGuard(DAG, sdl, Chain); 6356 else 6357 Src = getValue(I.getArgOperand(0)); // The guard's value. 6358 6359 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6360 6361 int FI = FuncInfo.StaticAllocaMap[Slot]; 6362 MFI.setStackProtectorIndex(FI); 6363 EVT PtrTy = Src.getValueType(); 6364 6365 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6366 6367 // Store the stack protector onto the stack. 6368 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6369 DAG.getMachineFunction(), FI), 6370 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6371 setValue(&I, Res); 6372 DAG.setRoot(Res); 6373 return; 6374 } 6375 case Intrinsic::objectsize: 6376 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6377 6378 case Intrinsic::is_constant: 6379 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6380 6381 case Intrinsic::annotation: 6382 case Intrinsic::ptr_annotation: 6383 case Intrinsic::launder_invariant_group: 6384 case Intrinsic::strip_invariant_group: 6385 // Drop the intrinsic, but forward the value 6386 setValue(&I, getValue(I.getOperand(0))); 6387 return; 6388 case Intrinsic::assume: 6389 case Intrinsic::var_annotation: 6390 case Intrinsic::sideeffect: 6391 // Discard annotate attributes, assumptions, and artificial side-effects. 6392 return; 6393 6394 case Intrinsic::codeview_annotation: { 6395 // Emit a label associated with this metadata. 6396 MachineFunction &MF = DAG.getMachineFunction(); 6397 MCSymbol *Label = 6398 MF.getMMI().getContext().createTempSymbol("annotation", true); 6399 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6400 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6401 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6402 DAG.setRoot(Res); 6403 return; 6404 } 6405 6406 case Intrinsic::init_trampoline: { 6407 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6408 6409 SDValue Ops[6]; 6410 Ops[0] = getRoot(); 6411 Ops[1] = getValue(I.getArgOperand(0)); 6412 Ops[2] = getValue(I.getArgOperand(1)); 6413 Ops[3] = getValue(I.getArgOperand(2)); 6414 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6415 Ops[5] = DAG.getSrcValue(F); 6416 6417 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6418 6419 DAG.setRoot(Res); 6420 return; 6421 } 6422 case Intrinsic::adjust_trampoline: 6423 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6424 TLI.getPointerTy(DAG.getDataLayout()), 6425 getValue(I.getArgOperand(0)))); 6426 return; 6427 case Intrinsic::gcroot: { 6428 assert(DAG.getMachineFunction().getFunction().hasGC() && 6429 "only valid in functions with gc specified, enforced by Verifier"); 6430 assert(GFI && "implied by previous"); 6431 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6432 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6433 6434 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6435 GFI->addStackRoot(FI->getIndex(), TypeMap); 6436 return; 6437 } 6438 case Intrinsic::gcread: 6439 case Intrinsic::gcwrite: 6440 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6441 case Intrinsic::flt_rounds: 6442 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6443 setValue(&I, Res); 6444 DAG.setRoot(Res.getValue(1)); 6445 return; 6446 6447 case Intrinsic::expect: 6448 // Just replace __builtin_expect(exp, c) with EXP. 6449 setValue(&I, getValue(I.getArgOperand(0))); 6450 return; 6451 6452 case Intrinsic::debugtrap: 6453 case Intrinsic::trap: { 6454 StringRef TrapFuncName = 6455 I.getAttributes() 6456 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6457 .getValueAsString(); 6458 if (TrapFuncName.empty()) { 6459 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6460 ISD::TRAP : ISD::DEBUGTRAP; 6461 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6462 return; 6463 } 6464 TargetLowering::ArgListTy Args; 6465 6466 TargetLowering::CallLoweringInfo CLI(DAG); 6467 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6468 CallingConv::C, I.getType(), 6469 DAG.getExternalSymbol(TrapFuncName.data(), 6470 TLI.getPointerTy(DAG.getDataLayout())), 6471 std::move(Args)); 6472 6473 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6474 DAG.setRoot(Result.second); 6475 return; 6476 } 6477 6478 case Intrinsic::uadd_with_overflow: 6479 case Intrinsic::sadd_with_overflow: 6480 case Intrinsic::usub_with_overflow: 6481 case Intrinsic::ssub_with_overflow: 6482 case Intrinsic::umul_with_overflow: 6483 case Intrinsic::smul_with_overflow: { 6484 ISD::NodeType Op; 6485 switch (Intrinsic) { 6486 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6487 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6488 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6489 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6490 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6491 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6492 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6493 } 6494 SDValue Op1 = getValue(I.getArgOperand(0)); 6495 SDValue Op2 = getValue(I.getArgOperand(1)); 6496 6497 EVT ResultVT = Op1.getValueType(); 6498 EVT OverflowVT = MVT::i1; 6499 if (ResultVT.isVector()) 6500 OverflowVT = EVT::getVectorVT( 6501 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6502 6503 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6504 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6505 return; 6506 } 6507 case Intrinsic::prefetch: { 6508 SDValue Ops[5]; 6509 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6510 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6511 Ops[0] = DAG.getRoot(); 6512 Ops[1] = getValue(I.getArgOperand(0)); 6513 Ops[2] = getValue(I.getArgOperand(1)); 6514 Ops[3] = getValue(I.getArgOperand(2)); 6515 Ops[4] = getValue(I.getArgOperand(3)); 6516 SDValue Result = DAG.getMemIntrinsicNode( 6517 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6518 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6519 /* align */ None, Flags); 6520 6521 // Chain the prefetch in parallell with any pending loads, to stay out of 6522 // the way of later optimizations. 6523 PendingLoads.push_back(Result); 6524 Result = getRoot(); 6525 DAG.setRoot(Result); 6526 return; 6527 } 6528 case Intrinsic::lifetime_start: 6529 case Intrinsic::lifetime_end: { 6530 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6531 // Stack coloring is not enabled in O0, discard region information. 6532 if (TM.getOptLevel() == CodeGenOpt::None) 6533 return; 6534 6535 const int64_t ObjectSize = 6536 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6537 Value *const ObjectPtr = I.getArgOperand(1); 6538 SmallVector<const Value *, 4> Allocas; 6539 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6540 6541 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6542 E = Allocas.end(); Object != E; ++Object) { 6543 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6544 6545 // Could not find an Alloca. 6546 if (!LifetimeObject) 6547 continue; 6548 6549 // First check that the Alloca is static, otherwise it won't have a 6550 // valid frame index. 6551 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6552 if (SI == FuncInfo.StaticAllocaMap.end()) 6553 return; 6554 6555 const int FrameIndex = SI->second; 6556 int64_t Offset; 6557 if (GetPointerBaseWithConstantOffset( 6558 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6559 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6560 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6561 Offset); 6562 DAG.setRoot(Res); 6563 } 6564 return; 6565 } 6566 case Intrinsic::invariant_start: 6567 // Discard region information. 6568 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6569 return; 6570 case Intrinsic::invariant_end: 6571 // Discard region information. 6572 return; 6573 case Intrinsic::clear_cache: 6574 /// FunctionName may be null. 6575 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6576 lowerCallToExternalSymbol(I, FunctionName); 6577 return; 6578 case Intrinsic::donothing: 6579 // ignore 6580 return; 6581 case Intrinsic::experimental_stackmap: 6582 visitStackmap(I); 6583 return; 6584 case Intrinsic::experimental_patchpoint_void: 6585 case Intrinsic::experimental_patchpoint_i64: 6586 visitPatchpoint(I); 6587 return; 6588 case Intrinsic::experimental_gc_statepoint: 6589 LowerStatepoint(ImmutableStatepoint(&I)); 6590 return; 6591 case Intrinsic::experimental_gc_result: 6592 visitGCResult(cast<GCResultInst>(I)); 6593 return; 6594 case Intrinsic::experimental_gc_relocate: 6595 visitGCRelocate(cast<GCRelocateInst>(I)); 6596 return; 6597 case Intrinsic::instrprof_increment: 6598 llvm_unreachable("instrprof failed to lower an increment"); 6599 case Intrinsic::instrprof_value_profile: 6600 llvm_unreachable("instrprof failed to lower a value profiling call"); 6601 case Intrinsic::localescape: { 6602 MachineFunction &MF = DAG.getMachineFunction(); 6603 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6604 6605 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6606 // is the same on all targets. 6607 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6608 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6609 if (isa<ConstantPointerNull>(Arg)) 6610 continue; // Skip null pointers. They represent a hole in index space. 6611 AllocaInst *Slot = cast<AllocaInst>(Arg); 6612 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6613 "can only escape static allocas"); 6614 int FI = FuncInfo.StaticAllocaMap[Slot]; 6615 MCSymbol *FrameAllocSym = 6616 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6617 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6618 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6619 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6620 .addSym(FrameAllocSym) 6621 .addFrameIndex(FI); 6622 } 6623 6624 return; 6625 } 6626 6627 case Intrinsic::localrecover: { 6628 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6629 MachineFunction &MF = DAG.getMachineFunction(); 6630 6631 // Get the symbol that defines the frame offset. 6632 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6633 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6634 unsigned IdxVal = 6635 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6636 MCSymbol *FrameAllocSym = 6637 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6638 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6639 6640 Value *FP = I.getArgOperand(1); 6641 SDValue FPVal = getValue(FP); 6642 EVT PtrVT = FPVal.getValueType(); 6643 6644 // Create a MCSymbol for the label to avoid any target lowering 6645 // that would make this PC relative. 6646 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6647 SDValue OffsetVal = 6648 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6649 6650 // Add the offset to the FP. 6651 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6652 setValue(&I, Add); 6653 6654 return; 6655 } 6656 6657 case Intrinsic::eh_exceptionpointer: 6658 case Intrinsic::eh_exceptioncode: { 6659 // Get the exception pointer vreg, copy from it, and resize it to fit. 6660 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6661 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6662 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6663 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6664 SDValue N = 6665 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6666 if (Intrinsic == Intrinsic::eh_exceptioncode) 6667 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6668 setValue(&I, N); 6669 return; 6670 } 6671 case Intrinsic::xray_customevent: { 6672 // Here we want to make sure that the intrinsic behaves as if it has a 6673 // specific calling convention, and only for x86_64. 6674 // FIXME: Support other platforms later. 6675 const auto &Triple = DAG.getTarget().getTargetTriple(); 6676 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6677 return; 6678 6679 SDLoc DL = getCurSDLoc(); 6680 SmallVector<SDValue, 8> Ops; 6681 6682 // We want to say that we always want the arguments in registers. 6683 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6684 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6685 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6686 SDValue Chain = getRoot(); 6687 Ops.push_back(LogEntryVal); 6688 Ops.push_back(StrSizeVal); 6689 Ops.push_back(Chain); 6690 6691 // We need to enforce the calling convention for the callsite, so that 6692 // argument ordering is enforced correctly, and that register allocation can 6693 // see that some registers may be assumed clobbered and have to preserve 6694 // them across calls to the intrinsic. 6695 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6696 DL, NodeTys, Ops); 6697 SDValue patchableNode = SDValue(MN, 0); 6698 DAG.setRoot(patchableNode); 6699 setValue(&I, patchableNode); 6700 return; 6701 } 6702 case Intrinsic::xray_typedevent: { 6703 // Here we want to make sure that the intrinsic behaves as if it has a 6704 // specific calling convention, and only for x86_64. 6705 // FIXME: Support other platforms later. 6706 const auto &Triple = DAG.getTarget().getTargetTriple(); 6707 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6708 return; 6709 6710 SDLoc DL = getCurSDLoc(); 6711 SmallVector<SDValue, 8> Ops; 6712 6713 // We want to say that we always want the arguments in registers. 6714 // It's unclear to me how manipulating the selection DAG here forces callers 6715 // to provide arguments in registers instead of on the stack. 6716 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6717 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6718 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6719 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6720 SDValue Chain = getRoot(); 6721 Ops.push_back(LogTypeId); 6722 Ops.push_back(LogEntryVal); 6723 Ops.push_back(StrSizeVal); 6724 Ops.push_back(Chain); 6725 6726 // We need to enforce the calling convention for the callsite, so that 6727 // argument ordering is enforced correctly, and that register allocation can 6728 // see that some registers may be assumed clobbered and have to preserve 6729 // them across calls to the intrinsic. 6730 MachineSDNode *MN = DAG.getMachineNode( 6731 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6732 SDValue patchableNode = SDValue(MN, 0); 6733 DAG.setRoot(patchableNode); 6734 setValue(&I, patchableNode); 6735 return; 6736 } 6737 case Intrinsic::experimental_deoptimize: 6738 LowerDeoptimizeCall(&I); 6739 return; 6740 6741 case Intrinsic::experimental_vector_reduce_v2_fadd: 6742 case Intrinsic::experimental_vector_reduce_v2_fmul: 6743 case Intrinsic::experimental_vector_reduce_add: 6744 case Intrinsic::experimental_vector_reduce_mul: 6745 case Intrinsic::experimental_vector_reduce_and: 6746 case Intrinsic::experimental_vector_reduce_or: 6747 case Intrinsic::experimental_vector_reduce_xor: 6748 case Intrinsic::experimental_vector_reduce_smax: 6749 case Intrinsic::experimental_vector_reduce_smin: 6750 case Intrinsic::experimental_vector_reduce_umax: 6751 case Intrinsic::experimental_vector_reduce_umin: 6752 case Intrinsic::experimental_vector_reduce_fmax: 6753 case Intrinsic::experimental_vector_reduce_fmin: 6754 visitVectorReduce(I, Intrinsic); 6755 return; 6756 6757 case Intrinsic::icall_branch_funnel: { 6758 SmallVector<SDValue, 16> Ops; 6759 Ops.push_back(getValue(I.getArgOperand(0))); 6760 6761 int64_t Offset; 6762 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6763 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6764 if (!Base) 6765 report_fatal_error( 6766 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6767 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6768 6769 struct BranchFunnelTarget { 6770 int64_t Offset; 6771 SDValue Target; 6772 }; 6773 SmallVector<BranchFunnelTarget, 8> Targets; 6774 6775 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6776 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6777 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6778 if (ElemBase != Base) 6779 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6780 "to the same GlobalValue"); 6781 6782 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6783 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6784 if (!GA) 6785 report_fatal_error( 6786 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6787 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6788 GA->getGlobal(), getCurSDLoc(), 6789 Val.getValueType(), GA->getOffset())}); 6790 } 6791 llvm::sort(Targets, 6792 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6793 return T1.Offset < T2.Offset; 6794 }); 6795 6796 for (auto &T : Targets) { 6797 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6798 Ops.push_back(T.Target); 6799 } 6800 6801 Ops.push_back(DAG.getRoot()); // Chain 6802 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6803 getCurSDLoc(), MVT::Other, Ops), 6804 0); 6805 DAG.setRoot(N); 6806 setValue(&I, N); 6807 HasTailCall = true; 6808 return; 6809 } 6810 6811 case Intrinsic::wasm_landingpad_index: 6812 // Information this intrinsic contained has been transferred to 6813 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6814 // delete it now. 6815 return; 6816 6817 case Intrinsic::aarch64_settag: 6818 case Intrinsic::aarch64_settag_zero: { 6819 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6820 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6821 SDValue Val = TSI.EmitTargetCodeForSetTag( 6822 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6823 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6824 ZeroMemory); 6825 DAG.setRoot(Val); 6826 setValue(&I, Val); 6827 return; 6828 } 6829 case Intrinsic::ptrmask: { 6830 SDValue Ptr = getValue(I.getOperand(0)); 6831 SDValue Const = getValue(I.getOperand(1)); 6832 6833 EVT DestVT = 6834 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6835 6836 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6837 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6838 return; 6839 } 6840 } 6841 } 6842 6843 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6844 const ConstrainedFPIntrinsic &FPI) { 6845 SDLoc sdl = getCurSDLoc(); 6846 6847 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6848 SmallVector<EVT, 4> ValueVTs; 6849 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6850 ValueVTs.push_back(MVT::Other); // Out chain 6851 6852 // We do not need to serialize constrained FP intrinsics against 6853 // each other or against (nonvolatile) loads, so they can be 6854 // chained like loads. 6855 SDValue Chain = DAG.getRoot(); 6856 SmallVector<SDValue, 4> Opers; 6857 Opers.push_back(Chain); 6858 if (FPI.isUnaryOp()) { 6859 Opers.push_back(getValue(FPI.getArgOperand(0))); 6860 } else if (FPI.isTernaryOp()) { 6861 Opers.push_back(getValue(FPI.getArgOperand(0))); 6862 Opers.push_back(getValue(FPI.getArgOperand(1))); 6863 Opers.push_back(getValue(FPI.getArgOperand(2))); 6864 } else { 6865 Opers.push_back(getValue(FPI.getArgOperand(0))); 6866 Opers.push_back(getValue(FPI.getArgOperand(1))); 6867 } 6868 6869 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6870 assert(Result.getNode()->getNumValues() == 2); 6871 6872 // Push node to the appropriate list so that future instructions can be 6873 // chained up correctly. 6874 SDValue OutChain = Result.getValue(1); 6875 switch (EB) { 6876 case fp::ExceptionBehavior::ebIgnore: 6877 // The only reason why ebIgnore nodes still need to be chained is that 6878 // they might depend on the current rounding mode, and therefore must 6879 // not be moved across instruction that may change that mode. 6880 LLVM_FALLTHROUGH; 6881 case fp::ExceptionBehavior::ebMayTrap: 6882 // These must not be moved across calls or instructions that may change 6883 // floating-point exception masks. 6884 PendingConstrainedFP.push_back(OutChain); 6885 break; 6886 case fp::ExceptionBehavior::ebStrict: 6887 // These must not be moved across calls or instructions that may change 6888 // floating-point exception masks or read floating-point exception flags. 6889 // In addition, they cannot be optimized out even if unused. 6890 PendingConstrainedFPStrict.push_back(OutChain); 6891 break; 6892 } 6893 }; 6894 6895 SDVTList VTs = DAG.getVTList(ValueVTs); 6896 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 6897 6898 SDNodeFlags Flags; 6899 if (EB == fp::ExceptionBehavior::ebIgnore) 6900 Flags.setNoFPExcept(true); 6901 6902 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 6903 Flags.copyFMF(*FPOp); 6904 6905 unsigned Opcode; 6906 switch (FPI.getIntrinsicID()) { 6907 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6908 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6909 case Intrinsic::INTRINSIC: \ 6910 Opcode = ISD::STRICT_##DAGN; \ 6911 break; 6912 #include "llvm/IR/ConstrainedOps.def" 6913 case Intrinsic::experimental_constrained_fmuladd: { 6914 Opcode = ISD::STRICT_FMA; 6915 // Break fmuladd into fmul and fadd. 6916 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 6917 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 6918 ValueVTs[0])) { 6919 Opers.pop_back(); 6920 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 6921 pushOutChain(Mul, EB); 6922 Opcode = ISD::STRICT_FADD; 6923 Opers.clear(); 6924 Opers.push_back(Mul.getValue(1)); 6925 Opers.push_back(Mul.getValue(0)); 6926 Opers.push_back(getValue(FPI.getArgOperand(2))); 6927 } 6928 break; 6929 } 6930 } 6931 6932 // A few strict DAG nodes carry additional operands that are not 6933 // set up by the default code above. 6934 switch (Opcode) { 6935 default: break; 6936 case ISD::STRICT_FP_ROUND: 6937 Opers.push_back( 6938 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 6939 break; 6940 case ISD::STRICT_FSETCC: 6941 case ISD::STRICT_FSETCCS: { 6942 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 6943 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 6944 break; 6945 } 6946 } 6947 6948 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 6949 pushOutChain(Result, EB); 6950 6951 SDValue FPResult = Result.getValue(0); 6952 setValue(&FPI, FPResult); 6953 } 6954 6955 std::pair<SDValue, SDValue> 6956 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6957 const BasicBlock *EHPadBB) { 6958 MachineFunction &MF = DAG.getMachineFunction(); 6959 MachineModuleInfo &MMI = MF.getMMI(); 6960 MCSymbol *BeginLabel = nullptr; 6961 6962 if (EHPadBB) { 6963 // Insert a label before the invoke call to mark the try range. This can be 6964 // used to detect deletion of the invoke via the MachineModuleInfo. 6965 BeginLabel = MMI.getContext().createTempSymbol(); 6966 6967 // For SjLj, keep track of which landing pads go with which invokes 6968 // so as to maintain the ordering of pads in the LSDA. 6969 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6970 if (CallSiteIndex) { 6971 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6972 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6973 6974 // Now that the call site is handled, stop tracking it. 6975 MMI.setCurrentCallSite(0); 6976 } 6977 6978 // Both PendingLoads and PendingExports must be flushed here; 6979 // this call might not return. 6980 (void)getRoot(); 6981 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6982 6983 CLI.setChain(getRoot()); 6984 } 6985 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6986 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6987 6988 assert((CLI.IsTailCall || Result.second.getNode()) && 6989 "Non-null chain expected with non-tail call!"); 6990 assert((Result.second.getNode() || !Result.first.getNode()) && 6991 "Null value expected with tail call!"); 6992 6993 if (!Result.second.getNode()) { 6994 // As a special case, a null chain means that a tail call has been emitted 6995 // and the DAG root is already updated. 6996 HasTailCall = true; 6997 6998 // Since there's no actual continuation from this block, nothing can be 6999 // relying on us setting vregs for them. 7000 PendingExports.clear(); 7001 } else { 7002 DAG.setRoot(Result.second); 7003 } 7004 7005 if (EHPadBB) { 7006 // Insert a label at the end of the invoke call to mark the try range. This 7007 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7008 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7009 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7010 7011 // Inform MachineModuleInfo of range. 7012 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7013 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7014 // actually use outlined funclets and their LSDA info style. 7015 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7016 assert(CLI.CB); 7017 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7018 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7019 } else if (!isScopedEHPersonality(Pers)) { 7020 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7021 } 7022 } 7023 7024 return Result; 7025 } 7026 7027 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7028 bool isTailCall, 7029 const BasicBlock *EHPadBB) { 7030 auto &DL = DAG.getDataLayout(); 7031 FunctionType *FTy = CB.getFunctionType(); 7032 Type *RetTy = CB.getType(); 7033 7034 TargetLowering::ArgListTy Args; 7035 Args.reserve(CB.arg_size()); 7036 7037 const Value *SwiftErrorVal = nullptr; 7038 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7039 7040 if (isTailCall) { 7041 // Avoid emitting tail calls in functions with the disable-tail-calls 7042 // attribute. 7043 auto *Caller = CB.getParent()->getParent(); 7044 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7045 "true") 7046 isTailCall = false; 7047 7048 // We can't tail call inside a function with a swifterror argument. Lowering 7049 // does not support this yet. It would have to move into the swifterror 7050 // register before the call. 7051 if (TLI.supportSwiftError() && 7052 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7053 isTailCall = false; 7054 } 7055 7056 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7057 TargetLowering::ArgListEntry Entry; 7058 const Value *V = *I; 7059 7060 // Skip empty types 7061 if (V->getType()->isEmptyTy()) 7062 continue; 7063 7064 SDValue ArgNode = getValue(V); 7065 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7066 7067 Entry.setAttributes(&CB, I - CB.arg_begin()); 7068 7069 // Use swifterror virtual register as input to the call. 7070 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7071 SwiftErrorVal = V; 7072 // We find the virtual register for the actual swifterror argument. 7073 // Instead of using the Value, we use the virtual register instead. 7074 Entry.Node = 7075 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7076 EVT(TLI.getPointerTy(DL))); 7077 } 7078 7079 Args.push_back(Entry); 7080 7081 // If we have an explicit sret argument that is an Instruction, (i.e., it 7082 // might point to function-local memory), we can't meaningfully tail-call. 7083 if (Entry.IsSRet && isa<Instruction>(V)) 7084 isTailCall = false; 7085 } 7086 7087 // If call site has a cfguardtarget operand bundle, create and add an 7088 // additional ArgListEntry. 7089 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7090 TargetLowering::ArgListEntry Entry; 7091 Value *V = Bundle->Inputs[0]; 7092 SDValue ArgNode = getValue(V); 7093 Entry.Node = ArgNode; 7094 Entry.Ty = V->getType(); 7095 Entry.IsCFGuardTarget = true; 7096 Args.push_back(Entry); 7097 } 7098 7099 // Check if target-independent constraints permit a tail call here. 7100 // Target-dependent constraints are checked within TLI->LowerCallTo. 7101 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7102 isTailCall = false; 7103 7104 // Disable tail calls if there is an swifterror argument. Targets have not 7105 // been updated to support tail calls. 7106 if (TLI.supportSwiftError() && SwiftErrorVal) 7107 isTailCall = false; 7108 7109 TargetLowering::CallLoweringInfo CLI(DAG); 7110 CLI.setDebugLoc(getCurSDLoc()) 7111 .setChain(getRoot()) 7112 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7113 .setTailCall(isTailCall) 7114 .setConvergent(CB.isConvergent()); 7115 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7116 7117 if (Result.first.getNode()) { 7118 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7119 setValue(&CB, Result.first); 7120 } 7121 7122 // The last element of CLI.InVals has the SDValue for swifterror return. 7123 // Here we copy it to a virtual register and update SwiftErrorMap for 7124 // book-keeping. 7125 if (SwiftErrorVal && TLI.supportSwiftError()) { 7126 // Get the last element of InVals. 7127 SDValue Src = CLI.InVals.back(); 7128 Register VReg = 7129 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7130 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7131 DAG.setRoot(CopyNode); 7132 } 7133 } 7134 7135 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7136 SelectionDAGBuilder &Builder) { 7137 // Check to see if this load can be trivially constant folded, e.g. if the 7138 // input is from a string literal. 7139 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7140 // Cast pointer to the type we really want to load. 7141 Type *LoadTy = 7142 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7143 if (LoadVT.isVector()) 7144 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7145 7146 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7147 PointerType::getUnqual(LoadTy)); 7148 7149 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7150 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7151 return Builder.getValue(LoadCst); 7152 } 7153 7154 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7155 // still constant memory, the input chain can be the entry node. 7156 SDValue Root; 7157 bool ConstantMemory = false; 7158 7159 // Do not serialize (non-volatile) loads of constant memory with anything. 7160 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7161 Root = Builder.DAG.getEntryNode(); 7162 ConstantMemory = true; 7163 } else { 7164 // Do not serialize non-volatile loads against each other. 7165 Root = Builder.DAG.getRoot(); 7166 } 7167 7168 SDValue Ptr = Builder.getValue(PtrVal); 7169 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7170 Ptr, MachinePointerInfo(PtrVal), 7171 /* Alignment = */ 1); 7172 7173 if (!ConstantMemory) 7174 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7175 return LoadVal; 7176 } 7177 7178 /// Record the value for an instruction that produces an integer result, 7179 /// converting the type where necessary. 7180 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7181 SDValue Value, 7182 bool IsSigned) { 7183 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7184 I.getType(), true); 7185 if (IsSigned) 7186 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7187 else 7188 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7189 setValue(&I, Value); 7190 } 7191 7192 /// See if we can lower a memcmp call into an optimized form. If so, return 7193 /// true and lower it. Otherwise return false, and it will be lowered like a 7194 /// normal call. 7195 /// The caller already checked that \p I calls the appropriate LibFunc with a 7196 /// correct prototype. 7197 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7198 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7199 const Value *Size = I.getArgOperand(2); 7200 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7201 if (CSize && CSize->getZExtValue() == 0) { 7202 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7203 I.getType(), true); 7204 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7205 return true; 7206 } 7207 7208 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7209 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7210 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7211 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7212 if (Res.first.getNode()) { 7213 processIntegerCallValue(I, Res.first, true); 7214 PendingLoads.push_back(Res.second); 7215 return true; 7216 } 7217 7218 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7219 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7220 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7221 return false; 7222 7223 // If the target has a fast compare for the given size, it will return a 7224 // preferred load type for that size. Require that the load VT is legal and 7225 // that the target supports unaligned loads of that type. Otherwise, return 7226 // INVALID. 7227 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7228 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7229 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7230 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7231 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7232 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7233 // TODO: Check alignment of src and dest ptrs. 7234 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7235 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7236 if (!TLI.isTypeLegal(LVT) || 7237 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7238 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7239 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7240 } 7241 7242 return LVT; 7243 }; 7244 7245 // This turns into unaligned loads. We only do this if the target natively 7246 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7247 // we'll only produce a small number of byte loads. 7248 MVT LoadVT; 7249 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7250 switch (NumBitsToCompare) { 7251 default: 7252 return false; 7253 case 16: 7254 LoadVT = MVT::i16; 7255 break; 7256 case 32: 7257 LoadVT = MVT::i32; 7258 break; 7259 case 64: 7260 case 128: 7261 case 256: 7262 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7263 break; 7264 } 7265 7266 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7267 return false; 7268 7269 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7270 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7271 7272 // Bitcast to a wide integer type if the loads are vectors. 7273 if (LoadVT.isVector()) { 7274 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7275 LoadL = DAG.getBitcast(CmpVT, LoadL); 7276 LoadR = DAG.getBitcast(CmpVT, LoadR); 7277 } 7278 7279 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7280 processIntegerCallValue(I, Cmp, false); 7281 return true; 7282 } 7283 7284 /// See if we can lower a memchr call into an optimized form. If so, return 7285 /// true and lower it. Otherwise return false, and it will be lowered like a 7286 /// normal call. 7287 /// The caller already checked that \p I calls the appropriate LibFunc with a 7288 /// correct prototype. 7289 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7290 const Value *Src = I.getArgOperand(0); 7291 const Value *Char = I.getArgOperand(1); 7292 const Value *Length = I.getArgOperand(2); 7293 7294 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7295 std::pair<SDValue, SDValue> Res = 7296 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7297 getValue(Src), getValue(Char), getValue(Length), 7298 MachinePointerInfo(Src)); 7299 if (Res.first.getNode()) { 7300 setValue(&I, Res.first); 7301 PendingLoads.push_back(Res.second); 7302 return true; 7303 } 7304 7305 return false; 7306 } 7307 7308 /// See if we can lower a mempcpy call into an optimized form. If so, return 7309 /// true and lower it. Otherwise return false, and it will be lowered like a 7310 /// normal call. 7311 /// The caller already checked that \p I calls the appropriate LibFunc with a 7312 /// correct prototype. 7313 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7314 SDValue Dst = getValue(I.getArgOperand(0)); 7315 SDValue Src = getValue(I.getArgOperand(1)); 7316 SDValue Size = getValue(I.getArgOperand(2)); 7317 7318 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7319 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7320 // DAG::getMemcpy needs Alignment to be defined. 7321 Align Alignment = std::min(DstAlign, SrcAlign); 7322 7323 bool isVol = false; 7324 SDLoc sdl = getCurSDLoc(); 7325 7326 // In the mempcpy context we need to pass in a false value for isTailCall 7327 // because the return pointer needs to be adjusted by the size of 7328 // the copied memory. 7329 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7330 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7331 /*isTailCall=*/false, 7332 MachinePointerInfo(I.getArgOperand(0)), 7333 MachinePointerInfo(I.getArgOperand(1))); 7334 assert(MC.getNode() != nullptr && 7335 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7336 DAG.setRoot(MC); 7337 7338 // Check if Size needs to be truncated or extended. 7339 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7340 7341 // Adjust return pointer to point just past the last dst byte. 7342 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7343 Dst, Size); 7344 setValue(&I, DstPlusSize); 7345 return true; 7346 } 7347 7348 /// See if we can lower a strcpy call into an optimized form. If so, return 7349 /// true and lower it, otherwise return false and it will be lowered like a 7350 /// normal call. 7351 /// The caller already checked that \p I calls the appropriate LibFunc with a 7352 /// correct prototype. 7353 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7354 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7355 7356 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7357 std::pair<SDValue, SDValue> Res = 7358 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7359 getValue(Arg0), getValue(Arg1), 7360 MachinePointerInfo(Arg0), 7361 MachinePointerInfo(Arg1), isStpcpy); 7362 if (Res.first.getNode()) { 7363 setValue(&I, Res.first); 7364 DAG.setRoot(Res.second); 7365 return true; 7366 } 7367 7368 return false; 7369 } 7370 7371 /// See if we can lower a strcmp call into an optimized form. If so, return 7372 /// true and lower it, otherwise return false and it will be lowered like a 7373 /// normal call. 7374 /// The caller already checked that \p I calls the appropriate LibFunc with a 7375 /// correct prototype. 7376 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7377 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7378 7379 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7380 std::pair<SDValue, SDValue> Res = 7381 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7382 getValue(Arg0), getValue(Arg1), 7383 MachinePointerInfo(Arg0), 7384 MachinePointerInfo(Arg1)); 7385 if (Res.first.getNode()) { 7386 processIntegerCallValue(I, Res.first, true); 7387 PendingLoads.push_back(Res.second); 7388 return true; 7389 } 7390 7391 return false; 7392 } 7393 7394 /// See if we can lower a strlen call into an optimized form. If so, return 7395 /// true and lower it, otherwise return false and it will be lowered like a 7396 /// normal call. 7397 /// The caller already checked that \p I calls the appropriate LibFunc with a 7398 /// correct prototype. 7399 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7400 const Value *Arg0 = I.getArgOperand(0); 7401 7402 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7403 std::pair<SDValue, SDValue> Res = 7404 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7405 getValue(Arg0), MachinePointerInfo(Arg0)); 7406 if (Res.first.getNode()) { 7407 processIntegerCallValue(I, Res.first, false); 7408 PendingLoads.push_back(Res.second); 7409 return true; 7410 } 7411 7412 return false; 7413 } 7414 7415 /// See if we can lower a strnlen call into an optimized form. If so, return 7416 /// true and lower it, otherwise return false and it will be lowered like a 7417 /// normal call. 7418 /// The caller already checked that \p I calls the appropriate LibFunc with a 7419 /// correct prototype. 7420 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7421 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7422 7423 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7424 std::pair<SDValue, SDValue> Res = 7425 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7426 getValue(Arg0), getValue(Arg1), 7427 MachinePointerInfo(Arg0)); 7428 if (Res.first.getNode()) { 7429 processIntegerCallValue(I, Res.first, false); 7430 PendingLoads.push_back(Res.second); 7431 return true; 7432 } 7433 7434 return false; 7435 } 7436 7437 /// See if we can lower a unary floating-point operation into an SDNode with 7438 /// the specified Opcode. If so, return true and lower it, otherwise return 7439 /// false and it will be lowered like a normal call. 7440 /// The caller already checked that \p I calls the appropriate LibFunc with a 7441 /// correct prototype. 7442 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7443 unsigned Opcode) { 7444 // We already checked this call's prototype; verify it doesn't modify errno. 7445 if (!I.onlyReadsMemory()) 7446 return false; 7447 7448 SDValue Tmp = getValue(I.getArgOperand(0)); 7449 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7450 return true; 7451 } 7452 7453 /// See if we can lower a binary floating-point operation into an SDNode with 7454 /// the specified Opcode. If so, return true and lower it. Otherwise return 7455 /// false, and it will be lowered like a normal call. 7456 /// The caller already checked that \p I calls the appropriate LibFunc with a 7457 /// correct prototype. 7458 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7459 unsigned Opcode) { 7460 // We already checked this call's prototype; verify it doesn't modify errno. 7461 if (!I.onlyReadsMemory()) 7462 return false; 7463 7464 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7465 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7466 EVT VT = Tmp0.getValueType(); 7467 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7468 return true; 7469 } 7470 7471 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7472 // Handle inline assembly differently. 7473 if (isa<InlineAsm>(I.getCalledValue())) { 7474 visitInlineAsm(I); 7475 return; 7476 } 7477 7478 if (Function *F = I.getCalledFunction()) { 7479 if (F->isDeclaration()) { 7480 // Is this an LLVM intrinsic or a target-specific intrinsic? 7481 unsigned IID = F->getIntrinsicID(); 7482 if (!IID) 7483 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7484 IID = II->getIntrinsicID(F); 7485 7486 if (IID) { 7487 visitIntrinsicCall(I, IID); 7488 return; 7489 } 7490 } 7491 7492 // Check for well-known libc/libm calls. If the function is internal, it 7493 // can't be a library call. Don't do the check if marked as nobuiltin for 7494 // some reason or the call site requires strict floating point semantics. 7495 LibFunc Func; 7496 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7497 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7498 LibInfo->hasOptimizedCodeGen(Func)) { 7499 switch (Func) { 7500 default: break; 7501 case LibFunc_copysign: 7502 case LibFunc_copysignf: 7503 case LibFunc_copysignl: 7504 // We already checked this call's prototype; verify it doesn't modify 7505 // errno. 7506 if (I.onlyReadsMemory()) { 7507 SDValue LHS = getValue(I.getArgOperand(0)); 7508 SDValue RHS = getValue(I.getArgOperand(1)); 7509 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7510 LHS.getValueType(), LHS, RHS)); 7511 return; 7512 } 7513 break; 7514 case LibFunc_fabs: 7515 case LibFunc_fabsf: 7516 case LibFunc_fabsl: 7517 if (visitUnaryFloatCall(I, ISD::FABS)) 7518 return; 7519 break; 7520 case LibFunc_fmin: 7521 case LibFunc_fminf: 7522 case LibFunc_fminl: 7523 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7524 return; 7525 break; 7526 case LibFunc_fmax: 7527 case LibFunc_fmaxf: 7528 case LibFunc_fmaxl: 7529 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7530 return; 7531 break; 7532 case LibFunc_sin: 7533 case LibFunc_sinf: 7534 case LibFunc_sinl: 7535 if (visitUnaryFloatCall(I, ISD::FSIN)) 7536 return; 7537 break; 7538 case LibFunc_cos: 7539 case LibFunc_cosf: 7540 case LibFunc_cosl: 7541 if (visitUnaryFloatCall(I, ISD::FCOS)) 7542 return; 7543 break; 7544 case LibFunc_sqrt: 7545 case LibFunc_sqrtf: 7546 case LibFunc_sqrtl: 7547 case LibFunc_sqrt_finite: 7548 case LibFunc_sqrtf_finite: 7549 case LibFunc_sqrtl_finite: 7550 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7551 return; 7552 break; 7553 case LibFunc_floor: 7554 case LibFunc_floorf: 7555 case LibFunc_floorl: 7556 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7557 return; 7558 break; 7559 case LibFunc_nearbyint: 7560 case LibFunc_nearbyintf: 7561 case LibFunc_nearbyintl: 7562 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7563 return; 7564 break; 7565 case LibFunc_ceil: 7566 case LibFunc_ceilf: 7567 case LibFunc_ceill: 7568 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7569 return; 7570 break; 7571 case LibFunc_rint: 7572 case LibFunc_rintf: 7573 case LibFunc_rintl: 7574 if (visitUnaryFloatCall(I, ISD::FRINT)) 7575 return; 7576 break; 7577 case LibFunc_round: 7578 case LibFunc_roundf: 7579 case LibFunc_roundl: 7580 if (visitUnaryFloatCall(I, ISD::FROUND)) 7581 return; 7582 break; 7583 case LibFunc_trunc: 7584 case LibFunc_truncf: 7585 case LibFunc_truncl: 7586 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7587 return; 7588 break; 7589 case LibFunc_log2: 7590 case LibFunc_log2f: 7591 case LibFunc_log2l: 7592 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7593 return; 7594 break; 7595 case LibFunc_exp2: 7596 case LibFunc_exp2f: 7597 case LibFunc_exp2l: 7598 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7599 return; 7600 break; 7601 case LibFunc_memcmp: 7602 if (visitMemCmpCall(I)) 7603 return; 7604 break; 7605 case LibFunc_mempcpy: 7606 if (visitMemPCpyCall(I)) 7607 return; 7608 break; 7609 case LibFunc_memchr: 7610 if (visitMemChrCall(I)) 7611 return; 7612 break; 7613 case LibFunc_strcpy: 7614 if (visitStrCpyCall(I, false)) 7615 return; 7616 break; 7617 case LibFunc_stpcpy: 7618 if (visitStrCpyCall(I, true)) 7619 return; 7620 break; 7621 case LibFunc_strcmp: 7622 if (visitStrCmpCall(I)) 7623 return; 7624 break; 7625 case LibFunc_strlen: 7626 if (visitStrLenCall(I)) 7627 return; 7628 break; 7629 case LibFunc_strnlen: 7630 if (visitStrNLenCall(I)) 7631 return; 7632 break; 7633 } 7634 } 7635 } 7636 7637 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7638 // have to do anything here to lower funclet bundles. 7639 // CFGuardTarget bundles are lowered in LowerCallTo. 7640 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7641 LLVMContext::OB_funclet, 7642 LLVMContext::OB_cfguardtarget}) && 7643 "Cannot lower calls with arbitrary operand bundles!"); 7644 7645 SDValue Callee = getValue(I.getCalledValue()); 7646 7647 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7648 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7649 else 7650 // Check if we can potentially perform a tail call. More detailed checking 7651 // is be done within LowerCallTo, after more information about the call is 7652 // known. 7653 LowerCallTo(I, Callee, I.isTailCall()); 7654 } 7655 7656 namespace { 7657 7658 /// AsmOperandInfo - This contains information for each constraint that we are 7659 /// lowering. 7660 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7661 public: 7662 /// CallOperand - If this is the result output operand or a clobber 7663 /// this is null, otherwise it is the incoming operand to the CallInst. 7664 /// This gets modified as the asm is processed. 7665 SDValue CallOperand; 7666 7667 /// AssignedRegs - If this is a register or register class operand, this 7668 /// contains the set of register corresponding to the operand. 7669 RegsForValue AssignedRegs; 7670 7671 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7672 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7673 } 7674 7675 /// Whether or not this operand accesses memory 7676 bool hasMemory(const TargetLowering &TLI) const { 7677 // Indirect operand accesses access memory. 7678 if (isIndirect) 7679 return true; 7680 7681 for (const auto &Code : Codes) 7682 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7683 return true; 7684 7685 return false; 7686 } 7687 7688 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7689 /// corresponds to. If there is no Value* for this operand, it returns 7690 /// MVT::Other. 7691 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7692 const DataLayout &DL) const { 7693 if (!CallOperandVal) return MVT::Other; 7694 7695 if (isa<BasicBlock>(CallOperandVal)) 7696 return TLI.getProgramPointerTy(DL); 7697 7698 llvm::Type *OpTy = CallOperandVal->getType(); 7699 7700 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7701 // If this is an indirect operand, the operand is a pointer to the 7702 // accessed type. 7703 if (isIndirect) { 7704 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7705 if (!PtrTy) 7706 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7707 OpTy = PtrTy->getElementType(); 7708 } 7709 7710 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7711 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7712 if (STy->getNumElements() == 1) 7713 OpTy = STy->getElementType(0); 7714 7715 // If OpTy is not a single value, it may be a struct/union that we 7716 // can tile with integers. 7717 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7718 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7719 switch (BitSize) { 7720 default: break; 7721 case 1: 7722 case 8: 7723 case 16: 7724 case 32: 7725 case 64: 7726 case 128: 7727 OpTy = IntegerType::get(Context, BitSize); 7728 break; 7729 } 7730 } 7731 7732 return TLI.getValueType(DL, OpTy, true); 7733 } 7734 }; 7735 7736 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7737 7738 } // end anonymous namespace 7739 7740 /// Make sure that the output operand \p OpInfo and its corresponding input 7741 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7742 /// out). 7743 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7744 SDISelAsmOperandInfo &MatchingOpInfo, 7745 SelectionDAG &DAG) { 7746 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7747 return; 7748 7749 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7750 const auto &TLI = DAG.getTargetLoweringInfo(); 7751 7752 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7753 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7754 OpInfo.ConstraintVT); 7755 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7756 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7757 MatchingOpInfo.ConstraintVT); 7758 if ((OpInfo.ConstraintVT.isInteger() != 7759 MatchingOpInfo.ConstraintVT.isInteger()) || 7760 (MatchRC.second != InputRC.second)) { 7761 // FIXME: error out in a more elegant fashion 7762 report_fatal_error("Unsupported asm: input constraint" 7763 " with a matching output constraint of" 7764 " incompatible type!"); 7765 } 7766 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7767 } 7768 7769 /// Get a direct memory input to behave well as an indirect operand. 7770 /// This may introduce stores, hence the need for a \p Chain. 7771 /// \return The (possibly updated) chain. 7772 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7773 SDISelAsmOperandInfo &OpInfo, 7774 SelectionDAG &DAG) { 7775 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7776 7777 // If we don't have an indirect input, put it in the constpool if we can, 7778 // otherwise spill it to a stack slot. 7779 // TODO: This isn't quite right. We need to handle these according to 7780 // the addressing mode that the constraint wants. Also, this may take 7781 // an additional register for the computation and we don't want that 7782 // either. 7783 7784 // If the operand is a float, integer, or vector constant, spill to a 7785 // constant pool entry to get its address. 7786 const Value *OpVal = OpInfo.CallOperandVal; 7787 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7788 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7789 OpInfo.CallOperand = DAG.getConstantPool( 7790 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7791 return Chain; 7792 } 7793 7794 // Otherwise, create a stack slot and emit a store to it before the asm. 7795 Type *Ty = OpVal->getType(); 7796 auto &DL = DAG.getDataLayout(); 7797 uint64_t TySize = DL.getTypeAllocSize(Ty); 7798 unsigned Align = DL.getPrefTypeAlignment(Ty); 7799 MachineFunction &MF = DAG.getMachineFunction(); 7800 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7801 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7802 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7803 MachinePointerInfo::getFixedStack(MF, SSFI), 7804 TLI.getMemValueType(DL, Ty)); 7805 OpInfo.CallOperand = StackSlot; 7806 7807 return Chain; 7808 } 7809 7810 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7811 /// specified operand. We prefer to assign virtual registers, to allow the 7812 /// register allocator to handle the assignment process. However, if the asm 7813 /// uses features that we can't model on machineinstrs, we have SDISel do the 7814 /// allocation. This produces generally horrible, but correct, code. 7815 /// 7816 /// OpInfo describes the operand 7817 /// RefOpInfo describes the matching operand if any, the operand otherwise 7818 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7819 SDISelAsmOperandInfo &OpInfo, 7820 SDISelAsmOperandInfo &RefOpInfo) { 7821 LLVMContext &Context = *DAG.getContext(); 7822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7823 7824 MachineFunction &MF = DAG.getMachineFunction(); 7825 SmallVector<unsigned, 4> Regs; 7826 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7827 7828 // No work to do for memory operations. 7829 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7830 return; 7831 7832 // If this is a constraint for a single physreg, or a constraint for a 7833 // register class, find it. 7834 unsigned AssignedReg; 7835 const TargetRegisterClass *RC; 7836 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7837 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7838 // RC is unset only on failure. Return immediately. 7839 if (!RC) 7840 return; 7841 7842 // Get the actual register value type. This is important, because the user 7843 // may have asked for (e.g.) the AX register in i32 type. We need to 7844 // remember that AX is actually i16 to get the right extension. 7845 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7846 7847 if (OpInfo.ConstraintVT != MVT::Other) { 7848 // If this is an FP operand in an integer register (or visa versa), or more 7849 // generally if the operand value disagrees with the register class we plan 7850 // to stick it in, fix the operand type. 7851 // 7852 // If this is an input value, the bitcast to the new type is done now. 7853 // Bitcast for output value is done at the end of visitInlineAsm(). 7854 if ((OpInfo.Type == InlineAsm::isOutput || 7855 OpInfo.Type == InlineAsm::isInput) && 7856 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7857 // Try to convert to the first EVT that the reg class contains. If the 7858 // types are identical size, use a bitcast to convert (e.g. two differing 7859 // vector types). Note: output bitcast is done at the end of 7860 // visitInlineAsm(). 7861 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7862 // Exclude indirect inputs while they are unsupported because the code 7863 // to perform the load is missing and thus OpInfo.CallOperand still 7864 // refers to the input address rather than the pointed-to value. 7865 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7866 OpInfo.CallOperand = 7867 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7868 OpInfo.ConstraintVT = RegVT; 7869 // If the operand is an FP value and we want it in integer registers, 7870 // use the corresponding integer type. This turns an f64 value into 7871 // i64, which can be passed with two i32 values on a 32-bit machine. 7872 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7873 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7874 if (OpInfo.Type == InlineAsm::isInput) 7875 OpInfo.CallOperand = 7876 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7877 OpInfo.ConstraintVT = VT; 7878 } 7879 } 7880 } 7881 7882 // No need to allocate a matching input constraint since the constraint it's 7883 // matching to has already been allocated. 7884 if (OpInfo.isMatchingInputConstraint()) 7885 return; 7886 7887 EVT ValueVT = OpInfo.ConstraintVT; 7888 if (OpInfo.ConstraintVT == MVT::Other) 7889 ValueVT = RegVT; 7890 7891 // Initialize NumRegs. 7892 unsigned NumRegs = 1; 7893 if (OpInfo.ConstraintVT != MVT::Other) 7894 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7895 7896 // If this is a constraint for a specific physical register, like {r17}, 7897 // assign it now. 7898 7899 // If this associated to a specific register, initialize iterator to correct 7900 // place. If virtual, make sure we have enough registers 7901 7902 // Initialize iterator if necessary 7903 TargetRegisterClass::iterator I = RC->begin(); 7904 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7905 7906 // Do not check for single registers. 7907 if (AssignedReg) { 7908 for (; *I != AssignedReg; ++I) 7909 assert(I != RC->end() && "AssignedReg should be member of RC"); 7910 } 7911 7912 for (; NumRegs; --NumRegs, ++I) { 7913 assert(I != RC->end() && "Ran out of registers to allocate!"); 7914 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7915 Regs.push_back(R); 7916 } 7917 7918 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7919 } 7920 7921 static unsigned 7922 findMatchingInlineAsmOperand(unsigned OperandNo, 7923 const std::vector<SDValue> &AsmNodeOperands) { 7924 // Scan until we find the definition we already emitted of this operand. 7925 unsigned CurOp = InlineAsm::Op_FirstOperand; 7926 for (; OperandNo; --OperandNo) { 7927 // Advance to the next operand. 7928 unsigned OpFlag = 7929 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7930 assert((InlineAsm::isRegDefKind(OpFlag) || 7931 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7932 InlineAsm::isMemKind(OpFlag)) && 7933 "Skipped past definitions?"); 7934 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7935 } 7936 return CurOp; 7937 } 7938 7939 namespace { 7940 7941 class ExtraFlags { 7942 unsigned Flags = 0; 7943 7944 public: 7945 explicit ExtraFlags(const CallBase &Call) { 7946 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledValue()); 7947 if (IA->hasSideEffects()) 7948 Flags |= InlineAsm::Extra_HasSideEffects; 7949 if (IA->isAlignStack()) 7950 Flags |= InlineAsm::Extra_IsAlignStack; 7951 if (Call.isConvergent()) 7952 Flags |= InlineAsm::Extra_IsConvergent; 7953 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7954 } 7955 7956 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7957 // Ideally, we would only check against memory constraints. However, the 7958 // meaning of an Other constraint can be target-specific and we can't easily 7959 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7960 // for Other constraints as well. 7961 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7962 OpInfo.ConstraintType == TargetLowering::C_Other) { 7963 if (OpInfo.Type == InlineAsm::isInput) 7964 Flags |= InlineAsm::Extra_MayLoad; 7965 else if (OpInfo.Type == InlineAsm::isOutput) 7966 Flags |= InlineAsm::Extra_MayStore; 7967 else if (OpInfo.Type == InlineAsm::isClobber) 7968 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7969 } 7970 } 7971 7972 unsigned get() const { return Flags; } 7973 }; 7974 7975 } // end anonymous namespace 7976 7977 /// visitInlineAsm - Handle a call to an InlineAsm object. 7978 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 7979 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledValue()); 7980 7981 /// ConstraintOperands - Information about all of the constraints. 7982 SDISelAsmOperandInfoVector ConstraintOperands; 7983 7984 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7985 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7986 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 7987 7988 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7989 // AsmDialect, MayLoad, MayStore). 7990 bool HasSideEffect = IA->hasSideEffects(); 7991 ExtraFlags ExtraInfo(Call); 7992 7993 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7994 unsigned ResNo = 0; // ResNo - The result number of the next output. 7995 unsigned NumMatchingOps = 0; 7996 for (auto &T : TargetConstraints) { 7997 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7998 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7999 8000 // Compute the value type for each operand. 8001 if (OpInfo.Type == InlineAsm::isInput || 8002 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8003 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8004 8005 // Process the call argument. BasicBlocks are labels, currently appearing 8006 // only in asm's. 8007 if (isa<CallBrInst>(Call) && 8008 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8009 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8010 NumMatchingOps) && 8011 (NumMatchingOps == 0 || 8012 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8013 NumMatchingOps))) { 8014 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8015 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8016 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8017 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8018 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8019 } else { 8020 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8021 } 8022 8023 OpInfo.ConstraintVT = 8024 OpInfo 8025 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8026 .getSimpleVT(); 8027 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8028 // The return value of the call is this value. As such, there is no 8029 // corresponding argument. 8030 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8031 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8032 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8033 DAG.getDataLayout(), STy->getElementType(ResNo)); 8034 } else { 8035 assert(ResNo == 0 && "Asm only has one result!"); 8036 OpInfo.ConstraintVT = 8037 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8038 } 8039 ++ResNo; 8040 } else { 8041 OpInfo.ConstraintVT = MVT::Other; 8042 } 8043 8044 if (OpInfo.hasMatchingInput()) 8045 ++NumMatchingOps; 8046 8047 if (!HasSideEffect) 8048 HasSideEffect = OpInfo.hasMemory(TLI); 8049 8050 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8051 // FIXME: Could we compute this on OpInfo rather than T? 8052 8053 // Compute the constraint code and ConstraintType to use. 8054 TLI.ComputeConstraintToUse(T, SDValue()); 8055 8056 if (T.ConstraintType == TargetLowering::C_Immediate && 8057 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8058 // We've delayed emitting a diagnostic like the "n" constraint because 8059 // inlining could cause an integer showing up. 8060 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8061 "' expects an integer constant " 8062 "expression"); 8063 8064 ExtraInfo.update(T); 8065 } 8066 8067 8068 // We won't need to flush pending loads if this asm doesn't touch 8069 // memory and is nonvolatile. 8070 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8071 8072 bool IsCallBr = isa<CallBrInst>(Call); 8073 if (IsCallBr) { 8074 // If this is a callbr we need to flush pending exports since inlineasm_br 8075 // is a terminator. We need to do this before nodes are glued to 8076 // the inlineasm_br node. 8077 Chain = getControlRoot(); 8078 } 8079 8080 // Second pass over the constraints: compute which constraint option to use. 8081 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8082 // If this is an output operand with a matching input operand, look up the 8083 // matching input. If their types mismatch, e.g. one is an integer, the 8084 // other is floating point, or their sizes are different, flag it as an 8085 // error. 8086 if (OpInfo.hasMatchingInput()) { 8087 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8088 patchMatchingInput(OpInfo, Input, DAG); 8089 } 8090 8091 // Compute the constraint code and ConstraintType to use. 8092 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8093 8094 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8095 OpInfo.Type == InlineAsm::isClobber) 8096 continue; 8097 8098 // If this is a memory input, and if the operand is not indirect, do what we 8099 // need to provide an address for the memory input. 8100 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8101 !OpInfo.isIndirect) { 8102 assert((OpInfo.isMultipleAlternative || 8103 (OpInfo.Type == InlineAsm::isInput)) && 8104 "Can only indirectify direct input operands!"); 8105 8106 // Memory operands really want the address of the value. 8107 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8108 8109 // There is no longer a Value* corresponding to this operand. 8110 OpInfo.CallOperandVal = nullptr; 8111 8112 // It is now an indirect operand. 8113 OpInfo.isIndirect = true; 8114 } 8115 8116 } 8117 8118 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8119 std::vector<SDValue> AsmNodeOperands; 8120 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8121 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8122 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8123 8124 // If we have a !srcloc metadata node associated with it, we want to attach 8125 // this to the ultimately generated inline asm machineinstr. To do this, we 8126 // pass in the third operand as this (potentially null) inline asm MDNode. 8127 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8128 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8129 8130 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8131 // bits as operand 3. 8132 AsmNodeOperands.push_back(DAG.getTargetConstant( 8133 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8134 8135 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8136 // this, assign virtual and physical registers for inputs and otput. 8137 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8138 // Assign Registers. 8139 SDISelAsmOperandInfo &RefOpInfo = 8140 OpInfo.isMatchingInputConstraint() 8141 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8142 : OpInfo; 8143 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8144 8145 auto DetectWriteToReservedRegister = [&]() { 8146 const MachineFunction &MF = DAG.getMachineFunction(); 8147 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8148 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8149 if (Register::isPhysicalRegister(Reg) && 8150 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8151 const char *RegName = TRI.getName(Reg); 8152 emitInlineAsmError(Call, "write to reserved register '" + 8153 Twine(RegName) + "'"); 8154 return true; 8155 } 8156 } 8157 return false; 8158 }; 8159 8160 switch (OpInfo.Type) { 8161 case InlineAsm::isOutput: 8162 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8163 unsigned ConstraintID = 8164 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8165 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8166 "Failed to convert memory constraint code to constraint id."); 8167 8168 // Add information to the INLINEASM node to know about this output. 8169 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8170 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8171 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8172 MVT::i32)); 8173 AsmNodeOperands.push_back(OpInfo.CallOperand); 8174 } else { 8175 // Otherwise, this outputs to a register (directly for C_Register / 8176 // C_RegisterClass, and a target-defined fashion for 8177 // C_Immediate/C_Other). Find a register that we can use. 8178 if (OpInfo.AssignedRegs.Regs.empty()) { 8179 emitInlineAsmError( 8180 Call, "couldn't allocate output register for constraint '" + 8181 Twine(OpInfo.ConstraintCode) + "'"); 8182 return; 8183 } 8184 8185 if (DetectWriteToReservedRegister()) 8186 return; 8187 8188 // Add information to the INLINEASM node to know that this register is 8189 // set. 8190 OpInfo.AssignedRegs.AddInlineAsmOperands( 8191 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8192 : InlineAsm::Kind_RegDef, 8193 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8194 } 8195 break; 8196 8197 case InlineAsm::isInput: { 8198 SDValue InOperandVal = OpInfo.CallOperand; 8199 8200 if (OpInfo.isMatchingInputConstraint()) { 8201 // If this is required to match an output register we have already set, 8202 // just use its register. 8203 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8204 AsmNodeOperands); 8205 unsigned OpFlag = 8206 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8207 if (InlineAsm::isRegDefKind(OpFlag) || 8208 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8209 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8210 if (OpInfo.isIndirect) { 8211 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8212 emitInlineAsmError(Call, "inline asm not supported yet: " 8213 "don't know how to handle tied " 8214 "indirect register inputs"); 8215 return; 8216 } 8217 8218 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8219 SmallVector<unsigned, 4> Regs; 8220 8221 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8222 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8223 MachineRegisterInfo &RegInfo = 8224 DAG.getMachineFunction().getRegInfo(); 8225 for (unsigned i = 0; i != NumRegs; ++i) 8226 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8227 } else { 8228 emitInlineAsmError(Call, 8229 "inline asm error: This value type register " 8230 "class is not natively supported!"); 8231 return; 8232 } 8233 8234 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8235 8236 SDLoc dl = getCurSDLoc(); 8237 // Use the produced MatchedRegs object to 8238 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8239 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8240 true, OpInfo.getMatchedOperand(), dl, 8241 DAG, AsmNodeOperands); 8242 break; 8243 } 8244 8245 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8246 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8247 "Unexpected number of operands"); 8248 // Add information to the INLINEASM node to know about this input. 8249 // See InlineAsm.h isUseOperandTiedToDef. 8250 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8251 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8252 OpInfo.getMatchedOperand()); 8253 AsmNodeOperands.push_back(DAG.getTargetConstant( 8254 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8255 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8256 break; 8257 } 8258 8259 // Treat indirect 'X' constraint as memory. 8260 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8261 OpInfo.isIndirect) 8262 OpInfo.ConstraintType = TargetLowering::C_Memory; 8263 8264 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8265 OpInfo.ConstraintType == TargetLowering::C_Other) { 8266 std::vector<SDValue> Ops; 8267 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8268 Ops, DAG); 8269 if (Ops.empty()) { 8270 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8271 if (isa<ConstantSDNode>(InOperandVal)) { 8272 emitInlineAsmError(Call, "value out of range for constraint '" + 8273 Twine(OpInfo.ConstraintCode) + "'"); 8274 return; 8275 } 8276 8277 emitInlineAsmError(Call, 8278 "invalid operand for inline asm constraint '" + 8279 Twine(OpInfo.ConstraintCode) + "'"); 8280 return; 8281 } 8282 8283 // Add information to the INLINEASM node to know about this input. 8284 unsigned ResOpType = 8285 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8286 AsmNodeOperands.push_back(DAG.getTargetConstant( 8287 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8288 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8289 break; 8290 } 8291 8292 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8293 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8294 assert(InOperandVal.getValueType() == 8295 TLI.getPointerTy(DAG.getDataLayout()) && 8296 "Memory operands expect pointer values"); 8297 8298 unsigned ConstraintID = 8299 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8300 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8301 "Failed to convert memory constraint code to constraint id."); 8302 8303 // Add information to the INLINEASM node to know about this input. 8304 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8305 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8306 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8307 getCurSDLoc(), 8308 MVT::i32)); 8309 AsmNodeOperands.push_back(InOperandVal); 8310 break; 8311 } 8312 8313 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8314 OpInfo.ConstraintType == TargetLowering::C_Register) && 8315 "Unknown constraint type!"); 8316 8317 // TODO: Support this. 8318 if (OpInfo.isIndirect) { 8319 emitInlineAsmError( 8320 Call, "Don't know how to handle indirect register inputs yet " 8321 "for constraint '" + 8322 Twine(OpInfo.ConstraintCode) + "'"); 8323 return; 8324 } 8325 8326 // Copy the input into the appropriate registers. 8327 if (OpInfo.AssignedRegs.Regs.empty()) { 8328 emitInlineAsmError(Call, 8329 "couldn't allocate input reg for constraint '" + 8330 Twine(OpInfo.ConstraintCode) + "'"); 8331 return; 8332 } 8333 8334 if (DetectWriteToReservedRegister()) 8335 return; 8336 8337 SDLoc dl = getCurSDLoc(); 8338 8339 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8340 &Call); 8341 8342 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8343 dl, DAG, AsmNodeOperands); 8344 break; 8345 } 8346 case InlineAsm::isClobber: 8347 // Add the clobbered value to the operand list, so that the register 8348 // allocator is aware that the physreg got clobbered. 8349 if (!OpInfo.AssignedRegs.Regs.empty()) 8350 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8351 false, 0, getCurSDLoc(), DAG, 8352 AsmNodeOperands); 8353 break; 8354 } 8355 } 8356 8357 // Finish up input operands. Set the input chain and add the flag last. 8358 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8359 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8360 8361 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8362 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8363 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8364 Flag = Chain.getValue(1); 8365 8366 // Do additional work to generate outputs. 8367 8368 SmallVector<EVT, 1> ResultVTs; 8369 SmallVector<SDValue, 1> ResultValues; 8370 SmallVector<SDValue, 8> OutChains; 8371 8372 llvm::Type *CallResultType = Call.getType(); 8373 ArrayRef<Type *> ResultTypes; 8374 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8375 ResultTypes = StructResult->elements(); 8376 else if (!CallResultType->isVoidTy()) 8377 ResultTypes = makeArrayRef(CallResultType); 8378 8379 auto CurResultType = ResultTypes.begin(); 8380 auto handleRegAssign = [&](SDValue V) { 8381 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8382 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8383 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8384 ++CurResultType; 8385 // If the type of the inline asm call site return value is different but has 8386 // same size as the type of the asm output bitcast it. One example of this 8387 // is for vectors with different width / number of elements. This can 8388 // happen for register classes that can contain multiple different value 8389 // types. The preg or vreg allocated may not have the same VT as was 8390 // expected. 8391 // 8392 // This can also happen for a return value that disagrees with the register 8393 // class it is put in, eg. a double in a general-purpose register on a 8394 // 32-bit machine. 8395 if (ResultVT != V.getValueType() && 8396 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8397 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8398 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8399 V.getValueType().isInteger()) { 8400 // If a result value was tied to an input value, the computed result 8401 // may have a wider width than the expected result. Extract the 8402 // relevant portion. 8403 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8404 } 8405 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8406 ResultVTs.push_back(ResultVT); 8407 ResultValues.push_back(V); 8408 }; 8409 8410 // Deal with output operands. 8411 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8412 if (OpInfo.Type == InlineAsm::isOutput) { 8413 SDValue Val; 8414 // Skip trivial output operands. 8415 if (OpInfo.AssignedRegs.Regs.empty()) 8416 continue; 8417 8418 switch (OpInfo.ConstraintType) { 8419 case TargetLowering::C_Register: 8420 case TargetLowering::C_RegisterClass: 8421 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8422 Chain, &Flag, &Call); 8423 break; 8424 case TargetLowering::C_Immediate: 8425 case TargetLowering::C_Other: 8426 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8427 OpInfo, DAG); 8428 break; 8429 case TargetLowering::C_Memory: 8430 break; // Already handled. 8431 case TargetLowering::C_Unknown: 8432 assert(false && "Unexpected unknown constraint"); 8433 } 8434 8435 // Indirect output manifest as stores. Record output chains. 8436 if (OpInfo.isIndirect) { 8437 const Value *Ptr = OpInfo.CallOperandVal; 8438 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8439 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8440 MachinePointerInfo(Ptr)); 8441 OutChains.push_back(Store); 8442 } else { 8443 // generate CopyFromRegs to associated registers. 8444 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8445 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8446 for (const SDValue &V : Val->op_values()) 8447 handleRegAssign(V); 8448 } else 8449 handleRegAssign(Val); 8450 } 8451 } 8452 } 8453 8454 // Set results. 8455 if (!ResultValues.empty()) { 8456 assert(CurResultType == ResultTypes.end() && 8457 "Mismatch in number of ResultTypes"); 8458 assert(ResultValues.size() == ResultTypes.size() && 8459 "Mismatch in number of output operands in asm result"); 8460 8461 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8462 DAG.getVTList(ResultVTs), ResultValues); 8463 setValue(&Call, V); 8464 } 8465 8466 // Collect store chains. 8467 if (!OutChains.empty()) 8468 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8469 8470 // Only Update Root if inline assembly has a memory effect. 8471 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8472 DAG.setRoot(Chain); 8473 } 8474 8475 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8476 const Twine &Message) { 8477 LLVMContext &Ctx = *DAG.getContext(); 8478 Ctx.emitError(&Call, Message); 8479 8480 // Make sure we leave the DAG in a valid state 8481 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8482 SmallVector<EVT, 1> ValueVTs; 8483 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8484 8485 if (ValueVTs.empty()) 8486 return; 8487 8488 SmallVector<SDValue, 1> Ops; 8489 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8490 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8491 8492 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8493 } 8494 8495 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8496 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8497 MVT::Other, getRoot(), 8498 getValue(I.getArgOperand(0)), 8499 DAG.getSrcValue(I.getArgOperand(0)))); 8500 } 8501 8502 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8504 const DataLayout &DL = DAG.getDataLayout(); 8505 SDValue V = DAG.getVAArg( 8506 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8507 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8508 DL.getABITypeAlignment(I.getType())); 8509 DAG.setRoot(V.getValue(1)); 8510 8511 if (I.getType()->isPointerTy()) 8512 V = DAG.getPtrExtOrTrunc( 8513 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8514 setValue(&I, V); 8515 } 8516 8517 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8518 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8519 MVT::Other, getRoot(), 8520 getValue(I.getArgOperand(0)), 8521 DAG.getSrcValue(I.getArgOperand(0)))); 8522 } 8523 8524 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8525 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8526 MVT::Other, getRoot(), 8527 getValue(I.getArgOperand(0)), 8528 getValue(I.getArgOperand(1)), 8529 DAG.getSrcValue(I.getArgOperand(0)), 8530 DAG.getSrcValue(I.getArgOperand(1)))); 8531 } 8532 8533 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8534 const Instruction &I, 8535 SDValue Op) { 8536 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8537 if (!Range) 8538 return Op; 8539 8540 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8541 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8542 return Op; 8543 8544 APInt Lo = CR.getUnsignedMin(); 8545 if (!Lo.isMinValue()) 8546 return Op; 8547 8548 APInt Hi = CR.getUnsignedMax(); 8549 unsigned Bits = std::max(Hi.getActiveBits(), 8550 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8551 8552 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8553 8554 SDLoc SL = getCurSDLoc(); 8555 8556 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8557 DAG.getValueType(SmallVT)); 8558 unsigned NumVals = Op.getNode()->getNumValues(); 8559 if (NumVals == 1) 8560 return ZExt; 8561 8562 SmallVector<SDValue, 4> Ops; 8563 8564 Ops.push_back(ZExt); 8565 for (unsigned I = 1; I != NumVals; ++I) 8566 Ops.push_back(Op.getValue(I)); 8567 8568 return DAG.getMergeValues(Ops, SL); 8569 } 8570 8571 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8572 /// the call being lowered. 8573 /// 8574 /// This is a helper for lowering intrinsics that follow a target calling 8575 /// convention or require stack pointer adjustment. Only a subset of the 8576 /// intrinsic's operands need to participate in the calling convention. 8577 void SelectionDAGBuilder::populateCallLoweringInfo( 8578 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8579 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8580 bool IsPatchPoint) { 8581 TargetLowering::ArgListTy Args; 8582 Args.reserve(NumArgs); 8583 8584 // Populate the argument list. 8585 // Attributes for args start at offset 1, after the return attribute. 8586 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8587 ArgI != ArgE; ++ArgI) { 8588 const Value *V = Call->getOperand(ArgI); 8589 8590 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8591 8592 TargetLowering::ArgListEntry Entry; 8593 Entry.Node = getValue(V); 8594 Entry.Ty = V->getType(); 8595 Entry.setAttributes(Call, ArgI); 8596 Args.push_back(Entry); 8597 } 8598 8599 CLI.setDebugLoc(getCurSDLoc()) 8600 .setChain(getRoot()) 8601 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8602 .setDiscardResult(Call->use_empty()) 8603 .setIsPatchPoint(IsPatchPoint); 8604 } 8605 8606 /// Add a stack map intrinsic call's live variable operands to a stackmap 8607 /// or patchpoint target node's operand list. 8608 /// 8609 /// Constants are converted to TargetConstants purely as an optimization to 8610 /// avoid constant materialization and register allocation. 8611 /// 8612 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8613 /// generate addess computation nodes, and so FinalizeISel can convert the 8614 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8615 /// address materialization and register allocation, but may also be required 8616 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8617 /// alloca in the entry block, then the runtime may assume that the alloca's 8618 /// StackMap location can be read immediately after compilation and that the 8619 /// location is valid at any point during execution (this is similar to the 8620 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8621 /// only available in a register, then the runtime would need to trap when 8622 /// execution reaches the StackMap in order to read the alloca's location. 8623 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8624 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8625 SelectionDAGBuilder &Builder) { 8626 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8627 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8628 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8629 Ops.push_back( 8630 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8631 Ops.push_back( 8632 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8633 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8634 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8635 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8636 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8637 } else 8638 Ops.push_back(OpVal); 8639 } 8640 } 8641 8642 /// Lower llvm.experimental.stackmap directly to its target opcode. 8643 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8644 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8645 // [live variables...]) 8646 8647 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8648 8649 SDValue Chain, InFlag, Callee, NullPtr; 8650 SmallVector<SDValue, 32> Ops; 8651 8652 SDLoc DL = getCurSDLoc(); 8653 Callee = getValue(CI.getCalledValue()); 8654 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8655 8656 // The stackmap intrinsic only records the live variables (the arguments 8657 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8658 // intrinsic, this won't be lowered to a function call. This means we don't 8659 // have to worry about calling conventions and target specific lowering code. 8660 // Instead we perform the call lowering right here. 8661 // 8662 // chain, flag = CALLSEQ_START(chain, 0, 0) 8663 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8664 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8665 // 8666 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8667 InFlag = Chain.getValue(1); 8668 8669 // Add the <id> and <numBytes> constants. 8670 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8671 Ops.push_back(DAG.getTargetConstant( 8672 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8673 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8674 Ops.push_back(DAG.getTargetConstant( 8675 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8676 MVT::i32)); 8677 8678 // Push live variables for the stack map. 8679 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8680 8681 // We are not pushing any register mask info here on the operands list, 8682 // because the stackmap doesn't clobber anything. 8683 8684 // Push the chain and the glue flag. 8685 Ops.push_back(Chain); 8686 Ops.push_back(InFlag); 8687 8688 // Create the STACKMAP node. 8689 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8690 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8691 Chain = SDValue(SM, 0); 8692 InFlag = Chain.getValue(1); 8693 8694 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8695 8696 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8697 8698 // Set the root to the target-lowered call chain. 8699 DAG.setRoot(Chain); 8700 8701 // Inform the Frame Information that we have a stackmap in this function. 8702 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8703 } 8704 8705 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8706 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8707 const BasicBlock *EHPadBB) { 8708 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8709 // i32 <numBytes>, 8710 // i8* <target>, 8711 // i32 <numArgs>, 8712 // [Args...], 8713 // [live variables...]) 8714 8715 CallingConv::ID CC = CB.getCallingConv(); 8716 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8717 bool HasDef = !CB.getType()->isVoidTy(); 8718 SDLoc dl = getCurSDLoc(); 8719 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8720 8721 // Handle immediate and symbolic callees. 8722 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8723 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8724 /*isTarget=*/true); 8725 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8726 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8727 SDLoc(SymbolicCallee), 8728 SymbolicCallee->getValueType(0)); 8729 8730 // Get the real number of arguments participating in the call <numArgs> 8731 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8732 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8733 8734 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8735 // Intrinsics include all meta-operands up to but not including CC. 8736 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8737 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8738 "Not enough arguments provided to the patchpoint intrinsic"); 8739 8740 // For AnyRegCC the arguments are lowered later on manually. 8741 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8742 Type *ReturnTy = 8743 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8744 8745 TargetLowering::CallLoweringInfo CLI(DAG); 8746 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8747 ReturnTy, true); 8748 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8749 8750 SDNode *CallEnd = Result.second.getNode(); 8751 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8752 CallEnd = CallEnd->getOperand(0).getNode(); 8753 8754 /// Get a call instruction from the call sequence chain. 8755 /// Tail calls are not allowed. 8756 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8757 "Expected a callseq node."); 8758 SDNode *Call = CallEnd->getOperand(0).getNode(); 8759 bool HasGlue = Call->getGluedNode(); 8760 8761 // Replace the target specific call node with the patchable intrinsic. 8762 SmallVector<SDValue, 8> Ops; 8763 8764 // Add the <id> and <numBytes> constants. 8765 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8766 Ops.push_back(DAG.getTargetConstant( 8767 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8768 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8769 Ops.push_back(DAG.getTargetConstant( 8770 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8771 MVT::i32)); 8772 8773 // Add the callee. 8774 Ops.push_back(Callee); 8775 8776 // Adjust <numArgs> to account for any arguments that have been passed on the 8777 // stack instead. 8778 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8779 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8780 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8781 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8782 8783 // Add the calling convention 8784 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8785 8786 // Add the arguments we omitted previously. The register allocator should 8787 // place these in any free register. 8788 if (IsAnyRegCC) 8789 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8790 Ops.push_back(getValue(CB.getArgOperand(i))); 8791 8792 // Push the arguments from the call instruction up to the register mask. 8793 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8794 Ops.append(Call->op_begin() + 2, e); 8795 8796 // Push live variables for the stack map. 8797 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8798 8799 // Push the register mask info. 8800 if (HasGlue) 8801 Ops.push_back(*(Call->op_end()-2)); 8802 else 8803 Ops.push_back(*(Call->op_end()-1)); 8804 8805 // Push the chain (this is originally the first operand of the call, but 8806 // becomes now the last or second to last operand). 8807 Ops.push_back(*(Call->op_begin())); 8808 8809 // Push the glue flag (last operand). 8810 if (HasGlue) 8811 Ops.push_back(*(Call->op_end()-1)); 8812 8813 SDVTList NodeTys; 8814 if (IsAnyRegCC && HasDef) { 8815 // Create the return types based on the intrinsic definition 8816 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8817 SmallVector<EVT, 3> ValueVTs; 8818 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8819 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8820 8821 // There is always a chain and a glue type at the end 8822 ValueVTs.push_back(MVT::Other); 8823 ValueVTs.push_back(MVT::Glue); 8824 NodeTys = DAG.getVTList(ValueVTs); 8825 } else 8826 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8827 8828 // Replace the target specific call node with a PATCHPOINT node. 8829 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8830 dl, NodeTys, Ops); 8831 8832 // Update the NodeMap. 8833 if (HasDef) { 8834 if (IsAnyRegCC) 8835 setValue(&CB, SDValue(MN, 0)); 8836 else 8837 setValue(&CB, Result.first); 8838 } 8839 8840 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8841 // call sequence. Furthermore the location of the chain and glue can change 8842 // when the AnyReg calling convention is used and the intrinsic returns a 8843 // value. 8844 if (IsAnyRegCC && HasDef) { 8845 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8846 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8847 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8848 } else 8849 DAG.ReplaceAllUsesWith(Call, MN); 8850 DAG.DeleteNode(Call); 8851 8852 // Inform the Frame Information that we have a patchpoint in this function. 8853 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8854 } 8855 8856 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8857 unsigned Intrinsic) { 8858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8859 SDValue Op1 = getValue(I.getArgOperand(0)); 8860 SDValue Op2; 8861 if (I.getNumArgOperands() > 1) 8862 Op2 = getValue(I.getArgOperand(1)); 8863 SDLoc dl = getCurSDLoc(); 8864 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8865 SDValue Res; 8866 FastMathFlags FMF; 8867 if (isa<FPMathOperator>(I)) 8868 FMF = I.getFastMathFlags(); 8869 8870 switch (Intrinsic) { 8871 case Intrinsic::experimental_vector_reduce_v2_fadd: 8872 if (FMF.allowReassoc()) 8873 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8874 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8875 else 8876 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8877 break; 8878 case Intrinsic::experimental_vector_reduce_v2_fmul: 8879 if (FMF.allowReassoc()) 8880 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8881 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8882 else 8883 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8884 break; 8885 case Intrinsic::experimental_vector_reduce_add: 8886 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8887 break; 8888 case Intrinsic::experimental_vector_reduce_mul: 8889 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8890 break; 8891 case Intrinsic::experimental_vector_reduce_and: 8892 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8893 break; 8894 case Intrinsic::experimental_vector_reduce_or: 8895 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8896 break; 8897 case Intrinsic::experimental_vector_reduce_xor: 8898 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8899 break; 8900 case Intrinsic::experimental_vector_reduce_smax: 8901 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8902 break; 8903 case Intrinsic::experimental_vector_reduce_smin: 8904 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8905 break; 8906 case Intrinsic::experimental_vector_reduce_umax: 8907 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8908 break; 8909 case Intrinsic::experimental_vector_reduce_umin: 8910 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8911 break; 8912 case Intrinsic::experimental_vector_reduce_fmax: 8913 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8914 break; 8915 case Intrinsic::experimental_vector_reduce_fmin: 8916 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8917 break; 8918 default: 8919 llvm_unreachable("Unhandled vector reduce intrinsic"); 8920 } 8921 setValue(&I, Res); 8922 } 8923 8924 /// Returns an AttributeList representing the attributes applied to the return 8925 /// value of the given call. 8926 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8927 SmallVector<Attribute::AttrKind, 2> Attrs; 8928 if (CLI.RetSExt) 8929 Attrs.push_back(Attribute::SExt); 8930 if (CLI.RetZExt) 8931 Attrs.push_back(Attribute::ZExt); 8932 if (CLI.IsInReg) 8933 Attrs.push_back(Attribute::InReg); 8934 8935 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8936 Attrs); 8937 } 8938 8939 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8940 /// implementation, which just calls LowerCall. 8941 /// FIXME: When all targets are 8942 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8943 std::pair<SDValue, SDValue> 8944 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8945 // Handle the incoming return values from the call. 8946 CLI.Ins.clear(); 8947 Type *OrigRetTy = CLI.RetTy; 8948 SmallVector<EVT, 4> RetTys; 8949 SmallVector<uint64_t, 4> Offsets; 8950 auto &DL = CLI.DAG.getDataLayout(); 8951 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8952 8953 if (CLI.IsPostTypeLegalization) { 8954 // If we are lowering a libcall after legalization, split the return type. 8955 SmallVector<EVT, 4> OldRetTys; 8956 SmallVector<uint64_t, 4> OldOffsets; 8957 RetTys.swap(OldRetTys); 8958 Offsets.swap(OldOffsets); 8959 8960 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8961 EVT RetVT = OldRetTys[i]; 8962 uint64_t Offset = OldOffsets[i]; 8963 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8964 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8965 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8966 RetTys.append(NumRegs, RegisterVT); 8967 for (unsigned j = 0; j != NumRegs; ++j) 8968 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8969 } 8970 } 8971 8972 SmallVector<ISD::OutputArg, 4> Outs; 8973 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8974 8975 bool CanLowerReturn = 8976 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8977 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8978 8979 SDValue DemoteStackSlot; 8980 int DemoteStackIdx = -100; 8981 if (!CanLowerReturn) { 8982 // FIXME: equivalent assert? 8983 // assert(!CS.hasInAllocaArgument() && 8984 // "sret demotion is incompatible with inalloca"); 8985 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8986 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 8987 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8988 DemoteStackIdx = 8989 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 8990 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8991 DL.getAllocaAddrSpace()); 8992 8993 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8994 ArgListEntry Entry; 8995 Entry.Node = DemoteStackSlot; 8996 Entry.Ty = StackSlotPtrType; 8997 Entry.IsSExt = false; 8998 Entry.IsZExt = false; 8999 Entry.IsInReg = false; 9000 Entry.IsSRet = true; 9001 Entry.IsNest = false; 9002 Entry.IsByVal = false; 9003 Entry.IsReturned = false; 9004 Entry.IsSwiftSelf = false; 9005 Entry.IsSwiftError = false; 9006 Entry.IsCFGuardTarget = false; 9007 Entry.Alignment = Alignment; 9008 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9009 CLI.NumFixedArgs += 1; 9010 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9011 9012 // sret demotion isn't compatible with tail-calls, since the sret argument 9013 // points into the callers stack frame. 9014 CLI.IsTailCall = false; 9015 } else { 9016 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9017 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9018 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9019 ISD::ArgFlagsTy Flags; 9020 if (NeedsRegBlock) { 9021 Flags.setInConsecutiveRegs(); 9022 if (I == RetTys.size() - 1) 9023 Flags.setInConsecutiveRegsLast(); 9024 } 9025 EVT VT = RetTys[I]; 9026 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9027 CLI.CallConv, VT); 9028 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9029 CLI.CallConv, VT); 9030 for (unsigned i = 0; i != NumRegs; ++i) { 9031 ISD::InputArg MyFlags; 9032 MyFlags.Flags = Flags; 9033 MyFlags.VT = RegisterVT; 9034 MyFlags.ArgVT = VT; 9035 MyFlags.Used = CLI.IsReturnValueUsed; 9036 if (CLI.RetTy->isPointerTy()) { 9037 MyFlags.Flags.setPointer(); 9038 MyFlags.Flags.setPointerAddrSpace( 9039 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9040 } 9041 if (CLI.RetSExt) 9042 MyFlags.Flags.setSExt(); 9043 if (CLI.RetZExt) 9044 MyFlags.Flags.setZExt(); 9045 if (CLI.IsInReg) 9046 MyFlags.Flags.setInReg(); 9047 CLI.Ins.push_back(MyFlags); 9048 } 9049 } 9050 } 9051 9052 // We push in swifterror return as the last element of CLI.Ins. 9053 ArgListTy &Args = CLI.getArgs(); 9054 if (supportSwiftError()) { 9055 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9056 if (Args[i].IsSwiftError) { 9057 ISD::InputArg MyFlags; 9058 MyFlags.VT = getPointerTy(DL); 9059 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9060 MyFlags.Flags.setSwiftError(); 9061 CLI.Ins.push_back(MyFlags); 9062 } 9063 } 9064 } 9065 9066 // Handle all of the outgoing arguments. 9067 CLI.Outs.clear(); 9068 CLI.OutVals.clear(); 9069 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9070 SmallVector<EVT, 4> ValueVTs; 9071 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9072 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9073 Type *FinalType = Args[i].Ty; 9074 if (Args[i].IsByVal) 9075 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9076 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9077 FinalType, CLI.CallConv, CLI.IsVarArg); 9078 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9079 ++Value) { 9080 EVT VT = ValueVTs[Value]; 9081 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9082 SDValue Op = SDValue(Args[i].Node.getNode(), 9083 Args[i].Node.getResNo() + Value); 9084 ISD::ArgFlagsTy Flags; 9085 9086 // Certain targets (such as MIPS), may have a different ABI alignment 9087 // for a type depending on the context. Give the target a chance to 9088 // specify the alignment it wants. 9089 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9090 9091 if (Args[i].Ty->isPointerTy()) { 9092 Flags.setPointer(); 9093 Flags.setPointerAddrSpace( 9094 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9095 } 9096 if (Args[i].IsZExt) 9097 Flags.setZExt(); 9098 if (Args[i].IsSExt) 9099 Flags.setSExt(); 9100 if (Args[i].IsInReg) { 9101 // If we are using vectorcall calling convention, a structure that is 9102 // passed InReg - is surely an HVA 9103 if (CLI.CallConv == CallingConv::X86_VectorCall && 9104 isa<StructType>(FinalType)) { 9105 // The first value of a structure is marked 9106 if (0 == Value) 9107 Flags.setHvaStart(); 9108 Flags.setHva(); 9109 } 9110 // Set InReg Flag 9111 Flags.setInReg(); 9112 } 9113 if (Args[i].IsSRet) 9114 Flags.setSRet(); 9115 if (Args[i].IsSwiftSelf) 9116 Flags.setSwiftSelf(); 9117 if (Args[i].IsSwiftError) 9118 Flags.setSwiftError(); 9119 if (Args[i].IsCFGuardTarget) 9120 Flags.setCFGuardTarget(); 9121 if (Args[i].IsByVal) 9122 Flags.setByVal(); 9123 if (Args[i].IsInAlloca) { 9124 Flags.setInAlloca(); 9125 // Set the byval flag for CCAssignFn callbacks that don't know about 9126 // inalloca. This way we can know how many bytes we should've allocated 9127 // and how many bytes a callee cleanup function will pop. If we port 9128 // inalloca to more targets, we'll have to add custom inalloca handling 9129 // in the various CC lowering callbacks. 9130 Flags.setByVal(); 9131 } 9132 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9133 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9134 Type *ElementTy = Ty->getElementType(); 9135 9136 unsigned FrameSize = DL.getTypeAllocSize( 9137 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9138 Flags.setByValSize(FrameSize); 9139 9140 // info is not there but there are cases it cannot get right. 9141 Align FrameAlign; 9142 if (auto MA = Args[i].Alignment) 9143 FrameAlign = *MA; 9144 else 9145 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9146 Flags.setByValAlign(FrameAlign); 9147 } 9148 if (Args[i].IsNest) 9149 Flags.setNest(); 9150 if (NeedsRegBlock) 9151 Flags.setInConsecutiveRegs(); 9152 Flags.setOrigAlign(OriginalAlignment); 9153 9154 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9155 CLI.CallConv, VT); 9156 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9157 CLI.CallConv, VT); 9158 SmallVector<SDValue, 4> Parts(NumParts); 9159 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9160 9161 if (Args[i].IsSExt) 9162 ExtendKind = ISD::SIGN_EXTEND; 9163 else if (Args[i].IsZExt) 9164 ExtendKind = ISD::ZERO_EXTEND; 9165 9166 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9167 // for now. 9168 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9169 CanLowerReturn) { 9170 assert((CLI.RetTy == Args[i].Ty || 9171 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9172 CLI.RetTy->getPointerAddressSpace() == 9173 Args[i].Ty->getPointerAddressSpace())) && 9174 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9175 // Before passing 'returned' to the target lowering code, ensure that 9176 // either the register MVT and the actual EVT are the same size or that 9177 // the return value and argument are extended in the same way; in these 9178 // cases it's safe to pass the argument register value unchanged as the 9179 // return register value (although it's at the target's option whether 9180 // to do so) 9181 // TODO: allow code generation to take advantage of partially preserved 9182 // registers rather than clobbering the entire register when the 9183 // parameter extension method is not compatible with the return 9184 // extension method 9185 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9186 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9187 CLI.RetZExt == Args[i].IsZExt)) 9188 Flags.setReturned(); 9189 } 9190 9191 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9192 CLI.CallConv, ExtendKind); 9193 9194 for (unsigned j = 0; j != NumParts; ++j) { 9195 // if it isn't first piece, alignment must be 1 9196 // For scalable vectors the scalable part is currently handled 9197 // by individual targets, so we just use the known minimum size here. 9198 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9199 i < CLI.NumFixedArgs, i, 9200 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9201 if (NumParts > 1 && j == 0) 9202 MyFlags.Flags.setSplit(); 9203 else if (j != 0) { 9204 MyFlags.Flags.setOrigAlign(Align(1)); 9205 if (j == NumParts - 1) 9206 MyFlags.Flags.setSplitEnd(); 9207 } 9208 9209 CLI.Outs.push_back(MyFlags); 9210 CLI.OutVals.push_back(Parts[j]); 9211 } 9212 9213 if (NeedsRegBlock && Value == NumValues - 1) 9214 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9215 } 9216 } 9217 9218 SmallVector<SDValue, 4> InVals; 9219 CLI.Chain = LowerCall(CLI, InVals); 9220 9221 // Update CLI.InVals to use outside of this function. 9222 CLI.InVals = InVals; 9223 9224 // Verify that the target's LowerCall behaved as expected. 9225 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9226 "LowerCall didn't return a valid chain!"); 9227 assert((!CLI.IsTailCall || InVals.empty()) && 9228 "LowerCall emitted a return value for a tail call!"); 9229 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9230 "LowerCall didn't emit the correct number of values!"); 9231 9232 // For a tail call, the return value is merely live-out and there aren't 9233 // any nodes in the DAG representing it. Return a special value to 9234 // indicate that a tail call has been emitted and no more Instructions 9235 // should be processed in the current block. 9236 if (CLI.IsTailCall) { 9237 CLI.DAG.setRoot(CLI.Chain); 9238 return std::make_pair(SDValue(), SDValue()); 9239 } 9240 9241 #ifndef NDEBUG 9242 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9243 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9244 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9245 "LowerCall emitted a value with the wrong type!"); 9246 } 9247 #endif 9248 9249 SmallVector<SDValue, 4> ReturnValues; 9250 if (!CanLowerReturn) { 9251 // The instruction result is the result of loading from the 9252 // hidden sret parameter. 9253 SmallVector<EVT, 1> PVTs; 9254 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9255 9256 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9257 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9258 EVT PtrVT = PVTs[0]; 9259 9260 unsigned NumValues = RetTys.size(); 9261 ReturnValues.resize(NumValues); 9262 SmallVector<SDValue, 4> Chains(NumValues); 9263 9264 // An aggregate return value cannot wrap around the address space, so 9265 // offsets to its parts don't wrap either. 9266 SDNodeFlags Flags; 9267 Flags.setNoUnsignedWrap(true); 9268 9269 for (unsigned i = 0; i < NumValues; ++i) { 9270 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9271 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9272 PtrVT), Flags); 9273 SDValue L = CLI.DAG.getLoad( 9274 RetTys[i], CLI.DL, CLI.Chain, Add, 9275 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9276 DemoteStackIdx, Offsets[i]), 9277 /* Alignment = */ 1); 9278 ReturnValues[i] = L; 9279 Chains[i] = L.getValue(1); 9280 } 9281 9282 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9283 } else { 9284 // Collect the legal value parts into potentially illegal values 9285 // that correspond to the original function's return values. 9286 Optional<ISD::NodeType> AssertOp; 9287 if (CLI.RetSExt) 9288 AssertOp = ISD::AssertSext; 9289 else if (CLI.RetZExt) 9290 AssertOp = ISD::AssertZext; 9291 unsigned CurReg = 0; 9292 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9293 EVT VT = RetTys[I]; 9294 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9295 CLI.CallConv, VT); 9296 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9297 CLI.CallConv, VT); 9298 9299 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9300 NumRegs, RegisterVT, VT, nullptr, 9301 CLI.CallConv, AssertOp)); 9302 CurReg += NumRegs; 9303 } 9304 9305 // For a function returning void, there is no return value. We can't create 9306 // such a node, so we just return a null return value in that case. In 9307 // that case, nothing will actually look at the value. 9308 if (ReturnValues.empty()) 9309 return std::make_pair(SDValue(), CLI.Chain); 9310 } 9311 9312 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9313 CLI.DAG.getVTList(RetTys), ReturnValues); 9314 return std::make_pair(Res, CLI.Chain); 9315 } 9316 9317 void TargetLowering::LowerOperationWrapper(SDNode *N, 9318 SmallVectorImpl<SDValue> &Results, 9319 SelectionDAG &DAG) const { 9320 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9321 Results.push_back(Res); 9322 } 9323 9324 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9325 llvm_unreachable("LowerOperation not implemented for this target!"); 9326 } 9327 9328 void 9329 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9330 SDValue Op = getNonRegisterValue(V); 9331 assert((Op.getOpcode() != ISD::CopyFromReg || 9332 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9333 "Copy from a reg to the same reg!"); 9334 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9335 9336 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9337 // If this is an InlineAsm we have to match the registers required, not the 9338 // notional registers required by the type. 9339 9340 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9341 None); // This is not an ABI copy. 9342 SDValue Chain = DAG.getEntryNode(); 9343 9344 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9345 FuncInfo.PreferredExtendType.end()) 9346 ? ISD::ANY_EXTEND 9347 : FuncInfo.PreferredExtendType[V]; 9348 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9349 PendingExports.push_back(Chain); 9350 } 9351 9352 #include "llvm/CodeGen/SelectionDAGISel.h" 9353 9354 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9355 /// entry block, return true. This includes arguments used by switches, since 9356 /// the switch may expand into multiple basic blocks. 9357 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9358 // With FastISel active, we may be splitting blocks, so force creation 9359 // of virtual registers for all non-dead arguments. 9360 if (FastISel) 9361 return A->use_empty(); 9362 9363 const BasicBlock &Entry = A->getParent()->front(); 9364 for (const User *U : A->users()) 9365 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9366 return false; // Use not in entry block. 9367 9368 return true; 9369 } 9370 9371 using ArgCopyElisionMapTy = 9372 DenseMap<const Argument *, 9373 std::pair<const AllocaInst *, const StoreInst *>>; 9374 9375 /// Scan the entry block of the function in FuncInfo for arguments that look 9376 /// like copies into a local alloca. Record any copied arguments in 9377 /// ArgCopyElisionCandidates. 9378 static void 9379 findArgumentCopyElisionCandidates(const DataLayout &DL, 9380 FunctionLoweringInfo *FuncInfo, 9381 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9382 // Record the state of every static alloca used in the entry block. Argument 9383 // allocas are all used in the entry block, so we need approximately as many 9384 // entries as we have arguments. 9385 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9386 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9387 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9388 StaticAllocas.reserve(NumArgs * 2); 9389 9390 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9391 if (!V) 9392 return nullptr; 9393 V = V->stripPointerCasts(); 9394 const auto *AI = dyn_cast<AllocaInst>(V); 9395 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9396 return nullptr; 9397 auto Iter = StaticAllocas.insert({AI, Unknown}); 9398 return &Iter.first->second; 9399 }; 9400 9401 // Look for stores of arguments to static allocas. Look through bitcasts and 9402 // GEPs to handle type coercions, as long as the alloca is fully initialized 9403 // by the store. Any non-store use of an alloca escapes it and any subsequent 9404 // unanalyzed store might write it. 9405 // FIXME: Handle structs initialized with multiple stores. 9406 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9407 // Look for stores, and handle non-store uses conservatively. 9408 const auto *SI = dyn_cast<StoreInst>(&I); 9409 if (!SI) { 9410 // We will look through cast uses, so ignore them completely. 9411 if (I.isCast()) 9412 continue; 9413 // Ignore debug info intrinsics, they don't escape or store to allocas. 9414 if (isa<DbgInfoIntrinsic>(I)) 9415 continue; 9416 // This is an unknown instruction. Assume it escapes or writes to all 9417 // static alloca operands. 9418 for (const Use &U : I.operands()) { 9419 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9420 *Info = StaticAllocaInfo::Clobbered; 9421 } 9422 continue; 9423 } 9424 9425 // If the stored value is a static alloca, mark it as escaped. 9426 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9427 *Info = StaticAllocaInfo::Clobbered; 9428 9429 // Check if the destination is a static alloca. 9430 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9431 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9432 if (!Info) 9433 continue; 9434 const AllocaInst *AI = cast<AllocaInst>(Dst); 9435 9436 // Skip allocas that have been initialized or clobbered. 9437 if (*Info != StaticAllocaInfo::Unknown) 9438 continue; 9439 9440 // Check if the stored value is an argument, and that this store fully 9441 // initializes the alloca. Don't elide copies from the same argument twice. 9442 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9443 const auto *Arg = dyn_cast<Argument>(Val); 9444 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9445 Arg->getType()->isEmptyTy() || 9446 DL.getTypeStoreSize(Arg->getType()) != 9447 DL.getTypeAllocSize(AI->getAllocatedType()) || 9448 ArgCopyElisionCandidates.count(Arg)) { 9449 *Info = StaticAllocaInfo::Clobbered; 9450 continue; 9451 } 9452 9453 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9454 << '\n'); 9455 9456 // Mark this alloca and store for argument copy elision. 9457 *Info = StaticAllocaInfo::Elidable; 9458 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9459 9460 // Stop scanning if we've seen all arguments. This will happen early in -O0 9461 // builds, which is useful, because -O0 builds have large entry blocks and 9462 // many allocas. 9463 if (ArgCopyElisionCandidates.size() == NumArgs) 9464 break; 9465 } 9466 } 9467 9468 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9469 /// ArgVal is a load from a suitable fixed stack object. 9470 static void tryToElideArgumentCopy( 9471 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9472 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9473 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9474 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9475 SDValue ArgVal, bool &ArgHasUses) { 9476 // Check if this is a load from a fixed stack object. 9477 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9478 if (!LNode) 9479 return; 9480 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9481 if (!FINode) 9482 return; 9483 9484 // Check that the fixed stack object is the right size and alignment. 9485 // Look at the alignment that the user wrote on the alloca instead of looking 9486 // at the stack object. 9487 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9488 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9489 const AllocaInst *AI = ArgCopyIter->second.first; 9490 int FixedIndex = FINode->getIndex(); 9491 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9492 int OldIndex = AllocaIndex; 9493 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9494 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9495 LLVM_DEBUG( 9496 dbgs() << " argument copy elision failed due to bad fixed stack " 9497 "object size\n"); 9498 return; 9499 } 9500 Align RequiredAlignment = AI->getAlign().getValueOr( 9501 FuncInfo.MF->getDataLayout().getABITypeAlign(AI->getAllocatedType())); 9502 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9503 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9504 "greater than stack argument alignment (" 9505 << DebugStr(RequiredAlignment) << " vs " 9506 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9507 return; 9508 } 9509 9510 // Perform the elision. Delete the old stack object and replace its only use 9511 // in the variable info map. Mark the stack object as mutable. 9512 LLVM_DEBUG({ 9513 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9514 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9515 << '\n'; 9516 }); 9517 MFI.RemoveStackObject(OldIndex); 9518 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9519 AllocaIndex = FixedIndex; 9520 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9521 Chains.push_back(ArgVal.getValue(1)); 9522 9523 // Avoid emitting code for the store implementing the copy. 9524 const StoreInst *SI = ArgCopyIter->second.second; 9525 ElidedArgCopyInstrs.insert(SI); 9526 9527 // Check for uses of the argument again so that we can avoid exporting ArgVal 9528 // if it is't used by anything other than the store. 9529 for (const Value *U : Arg.users()) { 9530 if (U != SI) { 9531 ArgHasUses = true; 9532 break; 9533 } 9534 } 9535 } 9536 9537 void SelectionDAGISel::LowerArguments(const Function &F) { 9538 SelectionDAG &DAG = SDB->DAG; 9539 SDLoc dl = SDB->getCurSDLoc(); 9540 const DataLayout &DL = DAG.getDataLayout(); 9541 SmallVector<ISD::InputArg, 16> Ins; 9542 9543 if (!FuncInfo->CanLowerReturn) { 9544 // Put in an sret pointer parameter before all the other parameters. 9545 SmallVector<EVT, 1> ValueVTs; 9546 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9547 F.getReturnType()->getPointerTo( 9548 DAG.getDataLayout().getAllocaAddrSpace()), 9549 ValueVTs); 9550 9551 // NOTE: Assuming that a pointer will never break down to more than one VT 9552 // or one register. 9553 ISD::ArgFlagsTy Flags; 9554 Flags.setSRet(); 9555 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9556 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9557 ISD::InputArg::NoArgIndex, 0); 9558 Ins.push_back(RetArg); 9559 } 9560 9561 // Look for stores of arguments to static allocas. Mark such arguments with a 9562 // flag to ask the target to give us the memory location of that argument if 9563 // available. 9564 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9565 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9566 ArgCopyElisionCandidates); 9567 9568 // Set up the incoming argument description vector. 9569 for (const Argument &Arg : F.args()) { 9570 unsigned ArgNo = Arg.getArgNo(); 9571 SmallVector<EVT, 4> ValueVTs; 9572 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9573 bool isArgValueUsed = !Arg.use_empty(); 9574 unsigned PartBase = 0; 9575 Type *FinalType = Arg.getType(); 9576 if (Arg.hasAttribute(Attribute::ByVal)) 9577 FinalType = Arg.getParamByValType(); 9578 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9579 FinalType, F.getCallingConv(), F.isVarArg()); 9580 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9581 Value != NumValues; ++Value) { 9582 EVT VT = ValueVTs[Value]; 9583 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9584 ISD::ArgFlagsTy Flags; 9585 9586 // Certain targets (such as MIPS), may have a different ABI alignment 9587 // for a type depending on the context. Give the target a chance to 9588 // specify the alignment it wants. 9589 const Align OriginalAlignment( 9590 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9591 9592 if (Arg.getType()->isPointerTy()) { 9593 Flags.setPointer(); 9594 Flags.setPointerAddrSpace( 9595 cast<PointerType>(Arg.getType())->getAddressSpace()); 9596 } 9597 if (Arg.hasAttribute(Attribute::ZExt)) 9598 Flags.setZExt(); 9599 if (Arg.hasAttribute(Attribute::SExt)) 9600 Flags.setSExt(); 9601 if (Arg.hasAttribute(Attribute::InReg)) { 9602 // If we are using vectorcall calling convention, a structure that is 9603 // passed InReg - is surely an HVA 9604 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9605 isa<StructType>(Arg.getType())) { 9606 // The first value of a structure is marked 9607 if (0 == Value) 9608 Flags.setHvaStart(); 9609 Flags.setHva(); 9610 } 9611 // Set InReg Flag 9612 Flags.setInReg(); 9613 } 9614 if (Arg.hasAttribute(Attribute::StructRet)) 9615 Flags.setSRet(); 9616 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9617 Flags.setSwiftSelf(); 9618 if (Arg.hasAttribute(Attribute::SwiftError)) 9619 Flags.setSwiftError(); 9620 if (Arg.hasAttribute(Attribute::ByVal)) 9621 Flags.setByVal(); 9622 if (Arg.hasAttribute(Attribute::InAlloca)) { 9623 Flags.setInAlloca(); 9624 // Set the byval flag for CCAssignFn callbacks that don't know about 9625 // inalloca. This way we can know how many bytes we should've allocated 9626 // and how many bytes a callee cleanup function will pop. If we port 9627 // inalloca to more targets, we'll have to add custom inalloca handling 9628 // in the various CC lowering callbacks. 9629 Flags.setByVal(); 9630 } 9631 if (F.getCallingConv() == CallingConv::X86_INTR) { 9632 // IA Interrupt passes frame (1st parameter) by value in the stack. 9633 if (ArgNo == 0) 9634 Flags.setByVal(); 9635 } 9636 if (Flags.isByVal() || Flags.isInAlloca()) { 9637 Type *ElementTy = Arg.getParamByValType(); 9638 9639 // For ByVal, size and alignment should be passed from FE. BE will 9640 // guess if this info is not there but there are cases it cannot get 9641 // right. 9642 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9643 Flags.setByValSize(FrameSize); 9644 9645 unsigned FrameAlign; 9646 if (Arg.getParamAlignment()) 9647 FrameAlign = Arg.getParamAlignment(); 9648 else 9649 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9650 Flags.setByValAlign(Align(FrameAlign)); 9651 } 9652 if (Arg.hasAttribute(Attribute::Nest)) 9653 Flags.setNest(); 9654 if (NeedsRegBlock) 9655 Flags.setInConsecutiveRegs(); 9656 Flags.setOrigAlign(OriginalAlignment); 9657 if (ArgCopyElisionCandidates.count(&Arg)) 9658 Flags.setCopyElisionCandidate(); 9659 if (Arg.hasAttribute(Attribute::Returned)) 9660 Flags.setReturned(); 9661 9662 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9663 *CurDAG->getContext(), F.getCallingConv(), VT); 9664 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9665 *CurDAG->getContext(), F.getCallingConv(), VT); 9666 for (unsigned i = 0; i != NumRegs; ++i) { 9667 // For scalable vectors, use the minimum size; individual targets 9668 // are responsible for handling scalable vector arguments and 9669 // return values. 9670 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9671 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9672 if (NumRegs > 1 && i == 0) 9673 MyFlags.Flags.setSplit(); 9674 // if it isn't first piece, alignment must be 1 9675 else if (i > 0) { 9676 MyFlags.Flags.setOrigAlign(Align(1)); 9677 if (i == NumRegs - 1) 9678 MyFlags.Flags.setSplitEnd(); 9679 } 9680 Ins.push_back(MyFlags); 9681 } 9682 if (NeedsRegBlock && Value == NumValues - 1) 9683 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9684 PartBase += VT.getStoreSize().getKnownMinSize(); 9685 } 9686 } 9687 9688 // Call the target to set up the argument values. 9689 SmallVector<SDValue, 8> InVals; 9690 SDValue NewRoot = TLI->LowerFormalArguments( 9691 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9692 9693 // Verify that the target's LowerFormalArguments behaved as expected. 9694 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9695 "LowerFormalArguments didn't return a valid chain!"); 9696 assert(InVals.size() == Ins.size() && 9697 "LowerFormalArguments didn't emit the correct number of values!"); 9698 LLVM_DEBUG({ 9699 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9700 assert(InVals[i].getNode() && 9701 "LowerFormalArguments emitted a null value!"); 9702 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9703 "LowerFormalArguments emitted a value with the wrong type!"); 9704 } 9705 }); 9706 9707 // Update the DAG with the new chain value resulting from argument lowering. 9708 DAG.setRoot(NewRoot); 9709 9710 // Set up the argument values. 9711 unsigned i = 0; 9712 if (!FuncInfo->CanLowerReturn) { 9713 // Create a virtual register for the sret pointer, and put in a copy 9714 // from the sret argument into it. 9715 SmallVector<EVT, 1> ValueVTs; 9716 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9717 F.getReturnType()->getPointerTo( 9718 DAG.getDataLayout().getAllocaAddrSpace()), 9719 ValueVTs); 9720 MVT VT = ValueVTs[0].getSimpleVT(); 9721 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9722 Optional<ISD::NodeType> AssertOp = None; 9723 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9724 nullptr, F.getCallingConv(), AssertOp); 9725 9726 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9727 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9728 Register SRetReg = 9729 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9730 FuncInfo->DemoteRegister = SRetReg; 9731 NewRoot = 9732 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9733 DAG.setRoot(NewRoot); 9734 9735 // i indexes lowered arguments. Bump it past the hidden sret argument. 9736 ++i; 9737 } 9738 9739 SmallVector<SDValue, 4> Chains; 9740 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9741 for (const Argument &Arg : F.args()) { 9742 SmallVector<SDValue, 4> ArgValues; 9743 SmallVector<EVT, 4> ValueVTs; 9744 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9745 unsigned NumValues = ValueVTs.size(); 9746 if (NumValues == 0) 9747 continue; 9748 9749 bool ArgHasUses = !Arg.use_empty(); 9750 9751 // Elide the copying store if the target loaded this argument from a 9752 // suitable fixed stack object. 9753 if (Ins[i].Flags.isCopyElisionCandidate()) { 9754 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9755 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9756 InVals[i], ArgHasUses); 9757 } 9758 9759 // If this argument is unused then remember its value. It is used to generate 9760 // debugging information. 9761 bool isSwiftErrorArg = 9762 TLI->supportSwiftError() && 9763 Arg.hasAttribute(Attribute::SwiftError); 9764 if (!ArgHasUses && !isSwiftErrorArg) { 9765 SDB->setUnusedArgValue(&Arg, InVals[i]); 9766 9767 // Also remember any frame index for use in FastISel. 9768 if (FrameIndexSDNode *FI = 9769 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9770 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9771 } 9772 9773 for (unsigned Val = 0; Val != NumValues; ++Val) { 9774 EVT VT = ValueVTs[Val]; 9775 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9776 F.getCallingConv(), VT); 9777 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9778 *CurDAG->getContext(), F.getCallingConv(), VT); 9779 9780 // Even an apparent 'unused' swifterror argument needs to be returned. So 9781 // we do generate a copy for it that can be used on return from the 9782 // function. 9783 if (ArgHasUses || isSwiftErrorArg) { 9784 Optional<ISD::NodeType> AssertOp; 9785 if (Arg.hasAttribute(Attribute::SExt)) 9786 AssertOp = ISD::AssertSext; 9787 else if (Arg.hasAttribute(Attribute::ZExt)) 9788 AssertOp = ISD::AssertZext; 9789 9790 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9791 PartVT, VT, nullptr, 9792 F.getCallingConv(), AssertOp)); 9793 } 9794 9795 i += NumParts; 9796 } 9797 9798 // We don't need to do anything else for unused arguments. 9799 if (ArgValues.empty()) 9800 continue; 9801 9802 // Note down frame index. 9803 if (FrameIndexSDNode *FI = 9804 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9805 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9806 9807 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9808 SDB->getCurSDLoc()); 9809 9810 SDB->setValue(&Arg, Res); 9811 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9812 // We want to associate the argument with the frame index, among 9813 // involved operands, that correspond to the lowest address. The 9814 // getCopyFromParts function, called earlier, is swapping the order of 9815 // the operands to BUILD_PAIR depending on endianness. The result of 9816 // that swapping is that the least significant bits of the argument will 9817 // be in the first operand of the BUILD_PAIR node, and the most 9818 // significant bits will be in the second operand. 9819 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9820 if (LoadSDNode *LNode = 9821 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9822 if (FrameIndexSDNode *FI = 9823 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9824 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9825 } 9826 9827 // Analyses past this point are naive and don't expect an assertion. 9828 if (Res.getOpcode() == ISD::AssertZext) 9829 Res = Res.getOperand(0); 9830 9831 // Update the SwiftErrorVRegDefMap. 9832 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9833 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9834 if (Register::isVirtualRegister(Reg)) 9835 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9836 Reg); 9837 } 9838 9839 // If this argument is live outside of the entry block, insert a copy from 9840 // wherever we got it to the vreg that other BB's will reference it as. 9841 if (Res.getOpcode() == ISD::CopyFromReg) { 9842 // If we can, though, try to skip creating an unnecessary vreg. 9843 // FIXME: This isn't very clean... it would be nice to make this more 9844 // general. 9845 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9846 if (Register::isVirtualRegister(Reg)) { 9847 FuncInfo->ValueMap[&Arg] = Reg; 9848 continue; 9849 } 9850 } 9851 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9852 FuncInfo->InitializeRegForValue(&Arg); 9853 SDB->CopyToExportRegsIfNeeded(&Arg); 9854 } 9855 } 9856 9857 if (!Chains.empty()) { 9858 Chains.push_back(NewRoot); 9859 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9860 } 9861 9862 DAG.setRoot(NewRoot); 9863 9864 assert(i == InVals.size() && "Argument register count mismatch!"); 9865 9866 // If any argument copy elisions occurred and we have debug info, update the 9867 // stale frame indices used in the dbg.declare variable info table. 9868 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9869 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9870 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9871 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9872 if (I != ArgCopyElisionFrameIndexMap.end()) 9873 VI.Slot = I->second; 9874 } 9875 } 9876 9877 // Finally, if the target has anything special to do, allow it to do so. 9878 emitFunctionEntryCode(); 9879 } 9880 9881 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9882 /// ensure constants are generated when needed. Remember the virtual registers 9883 /// that need to be added to the Machine PHI nodes as input. We cannot just 9884 /// directly add them, because expansion might result in multiple MBB's for one 9885 /// BB. As such, the start of the BB might correspond to a different MBB than 9886 /// the end. 9887 void 9888 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9889 const Instruction *TI = LLVMBB->getTerminator(); 9890 9891 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9892 9893 // Check PHI nodes in successors that expect a value to be available from this 9894 // block. 9895 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9896 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9897 if (!isa<PHINode>(SuccBB->begin())) continue; 9898 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9899 9900 // If this terminator has multiple identical successors (common for 9901 // switches), only handle each succ once. 9902 if (!SuccsHandled.insert(SuccMBB).second) 9903 continue; 9904 9905 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9906 9907 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9908 // nodes and Machine PHI nodes, but the incoming operands have not been 9909 // emitted yet. 9910 for (const PHINode &PN : SuccBB->phis()) { 9911 // Ignore dead phi's. 9912 if (PN.use_empty()) 9913 continue; 9914 9915 // Skip empty types 9916 if (PN.getType()->isEmptyTy()) 9917 continue; 9918 9919 unsigned Reg; 9920 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9921 9922 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9923 unsigned &RegOut = ConstantsOut[C]; 9924 if (RegOut == 0) { 9925 RegOut = FuncInfo.CreateRegs(C); 9926 CopyValueToVirtualRegister(C, RegOut); 9927 } 9928 Reg = RegOut; 9929 } else { 9930 DenseMap<const Value *, Register>::iterator I = 9931 FuncInfo.ValueMap.find(PHIOp); 9932 if (I != FuncInfo.ValueMap.end()) 9933 Reg = I->second; 9934 else { 9935 assert(isa<AllocaInst>(PHIOp) && 9936 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9937 "Didn't codegen value into a register!??"); 9938 Reg = FuncInfo.CreateRegs(PHIOp); 9939 CopyValueToVirtualRegister(PHIOp, Reg); 9940 } 9941 } 9942 9943 // Remember that this register needs to added to the machine PHI node as 9944 // the input for this MBB. 9945 SmallVector<EVT, 4> ValueVTs; 9946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9947 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9948 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9949 EVT VT = ValueVTs[vti]; 9950 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9951 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9952 FuncInfo.PHINodesToUpdate.push_back( 9953 std::make_pair(&*MBBI++, Reg + i)); 9954 Reg += NumRegisters; 9955 } 9956 } 9957 } 9958 9959 ConstantsOut.clear(); 9960 } 9961 9962 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9963 /// is 0. 9964 MachineBasicBlock * 9965 SelectionDAGBuilder::StackProtectorDescriptor:: 9966 AddSuccessorMBB(const BasicBlock *BB, 9967 MachineBasicBlock *ParentMBB, 9968 bool IsLikely, 9969 MachineBasicBlock *SuccMBB) { 9970 // If SuccBB has not been created yet, create it. 9971 if (!SuccMBB) { 9972 MachineFunction *MF = ParentMBB->getParent(); 9973 MachineFunction::iterator BBI(ParentMBB); 9974 SuccMBB = MF->CreateMachineBasicBlock(BB); 9975 MF->insert(++BBI, SuccMBB); 9976 } 9977 // Add it as a successor of ParentMBB. 9978 ParentMBB->addSuccessor( 9979 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9980 return SuccMBB; 9981 } 9982 9983 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9984 MachineFunction::iterator I(MBB); 9985 if (++I == FuncInfo.MF->end()) 9986 return nullptr; 9987 return &*I; 9988 } 9989 9990 /// During lowering new call nodes can be created (such as memset, etc.). 9991 /// Those will become new roots of the current DAG, but complications arise 9992 /// when they are tail calls. In such cases, the call lowering will update 9993 /// the root, but the builder still needs to know that a tail call has been 9994 /// lowered in order to avoid generating an additional return. 9995 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9996 // If the node is null, we do have a tail call. 9997 if (MaybeTC.getNode() != nullptr) 9998 DAG.setRoot(MaybeTC); 9999 else 10000 HasTailCall = true; 10001 } 10002 10003 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10004 MachineBasicBlock *SwitchMBB, 10005 MachineBasicBlock *DefaultMBB) { 10006 MachineFunction *CurMF = FuncInfo.MF; 10007 MachineBasicBlock *NextMBB = nullptr; 10008 MachineFunction::iterator BBI(W.MBB); 10009 if (++BBI != FuncInfo.MF->end()) 10010 NextMBB = &*BBI; 10011 10012 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10013 10014 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10015 10016 if (Size == 2 && W.MBB == SwitchMBB) { 10017 // If any two of the cases has the same destination, and if one value 10018 // is the same as the other, but has one bit unset that the other has set, 10019 // use bit manipulation to do two compares at once. For example: 10020 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10021 // TODO: This could be extended to merge any 2 cases in switches with 3 10022 // cases. 10023 // TODO: Handle cases where W.CaseBB != SwitchBB. 10024 CaseCluster &Small = *W.FirstCluster; 10025 CaseCluster &Big = *W.LastCluster; 10026 10027 if (Small.Low == Small.High && Big.Low == Big.High && 10028 Small.MBB == Big.MBB) { 10029 const APInt &SmallValue = Small.Low->getValue(); 10030 const APInt &BigValue = Big.Low->getValue(); 10031 10032 // Check that there is only one bit different. 10033 APInt CommonBit = BigValue ^ SmallValue; 10034 if (CommonBit.isPowerOf2()) { 10035 SDValue CondLHS = getValue(Cond); 10036 EVT VT = CondLHS.getValueType(); 10037 SDLoc DL = getCurSDLoc(); 10038 10039 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10040 DAG.getConstant(CommonBit, DL, VT)); 10041 SDValue Cond = DAG.getSetCC( 10042 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10043 ISD::SETEQ); 10044 10045 // Update successor info. 10046 // Both Small and Big will jump to Small.BB, so we sum up the 10047 // probabilities. 10048 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10049 if (BPI) 10050 addSuccessorWithProb( 10051 SwitchMBB, DefaultMBB, 10052 // The default destination is the first successor in IR. 10053 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10054 else 10055 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10056 10057 // Insert the true branch. 10058 SDValue BrCond = 10059 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10060 DAG.getBasicBlock(Small.MBB)); 10061 // Insert the false branch. 10062 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10063 DAG.getBasicBlock(DefaultMBB)); 10064 10065 DAG.setRoot(BrCond); 10066 return; 10067 } 10068 } 10069 } 10070 10071 if (TM.getOptLevel() != CodeGenOpt::None) { 10072 // Here, we order cases by probability so the most likely case will be 10073 // checked first. However, two clusters can have the same probability in 10074 // which case their relative ordering is non-deterministic. So we use Low 10075 // as a tie-breaker as clusters are guaranteed to never overlap. 10076 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10077 [](const CaseCluster &a, const CaseCluster &b) { 10078 return a.Prob != b.Prob ? 10079 a.Prob > b.Prob : 10080 a.Low->getValue().slt(b.Low->getValue()); 10081 }); 10082 10083 // Rearrange the case blocks so that the last one falls through if possible 10084 // without changing the order of probabilities. 10085 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10086 --I; 10087 if (I->Prob > W.LastCluster->Prob) 10088 break; 10089 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10090 std::swap(*I, *W.LastCluster); 10091 break; 10092 } 10093 } 10094 } 10095 10096 // Compute total probability. 10097 BranchProbability DefaultProb = W.DefaultProb; 10098 BranchProbability UnhandledProbs = DefaultProb; 10099 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10100 UnhandledProbs += I->Prob; 10101 10102 MachineBasicBlock *CurMBB = W.MBB; 10103 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10104 bool FallthroughUnreachable = false; 10105 MachineBasicBlock *Fallthrough; 10106 if (I == W.LastCluster) { 10107 // For the last cluster, fall through to the default destination. 10108 Fallthrough = DefaultMBB; 10109 FallthroughUnreachable = isa<UnreachableInst>( 10110 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10111 } else { 10112 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10113 CurMF->insert(BBI, Fallthrough); 10114 // Put Cond in a virtual register to make it available from the new blocks. 10115 ExportFromCurrentBlock(Cond); 10116 } 10117 UnhandledProbs -= I->Prob; 10118 10119 switch (I->Kind) { 10120 case CC_JumpTable: { 10121 // FIXME: Optimize away range check based on pivot comparisons. 10122 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10123 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10124 10125 // The jump block hasn't been inserted yet; insert it here. 10126 MachineBasicBlock *JumpMBB = JT->MBB; 10127 CurMF->insert(BBI, JumpMBB); 10128 10129 auto JumpProb = I->Prob; 10130 auto FallthroughProb = UnhandledProbs; 10131 10132 // If the default statement is a target of the jump table, we evenly 10133 // distribute the default probability to successors of CurMBB. Also 10134 // update the probability on the edge from JumpMBB to Fallthrough. 10135 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10136 SE = JumpMBB->succ_end(); 10137 SI != SE; ++SI) { 10138 if (*SI == DefaultMBB) { 10139 JumpProb += DefaultProb / 2; 10140 FallthroughProb -= DefaultProb / 2; 10141 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10142 JumpMBB->normalizeSuccProbs(); 10143 break; 10144 } 10145 } 10146 10147 if (FallthroughUnreachable) { 10148 // Skip the range check if the fallthrough block is unreachable. 10149 JTH->OmitRangeCheck = true; 10150 } 10151 10152 if (!JTH->OmitRangeCheck) 10153 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10154 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10155 CurMBB->normalizeSuccProbs(); 10156 10157 // The jump table header will be inserted in our current block, do the 10158 // range check, and fall through to our fallthrough block. 10159 JTH->HeaderBB = CurMBB; 10160 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10161 10162 // If we're in the right place, emit the jump table header right now. 10163 if (CurMBB == SwitchMBB) { 10164 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10165 JTH->Emitted = true; 10166 } 10167 break; 10168 } 10169 case CC_BitTests: { 10170 // FIXME: Optimize away range check based on pivot comparisons. 10171 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10172 10173 // The bit test blocks haven't been inserted yet; insert them here. 10174 for (BitTestCase &BTC : BTB->Cases) 10175 CurMF->insert(BBI, BTC.ThisBB); 10176 10177 // Fill in fields of the BitTestBlock. 10178 BTB->Parent = CurMBB; 10179 BTB->Default = Fallthrough; 10180 10181 BTB->DefaultProb = UnhandledProbs; 10182 // If the cases in bit test don't form a contiguous range, we evenly 10183 // distribute the probability on the edge to Fallthrough to two 10184 // successors of CurMBB. 10185 if (!BTB->ContiguousRange) { 10186 BTB->Prob += DefaultProb / 2; 10187 BTB->DefaultProb -= DefaultProb / 2; 10188 } 10189 10190 if (FallthroughUnreachable) { 10191 // Skip the range check if the fallthrough block is unreachable. 10192 BTB->OmitRangeCheck = true; 10193 } 10194 10195 // If we're in the right place, emit the bit test header right now. 10196 if (CurMBB == SwitchMBB) { 10197 visitBitTestHeader(*BTB, SwitchMBB); 10198 BTB->Emitted = true; 10199 } 10200 break; 10201 } 10202 case CC_Range: { 10203 const Value *RHS, *LHS, *MHS; 10204 ISD::CondCode CC; 10205 if (I->Low == I->High) { 10206 // Check Cond == I->Low. 10207 CC = ISD::SETEQ; 10208 LHS = Cond; 10209 RHS=I->Low; 10210 MHS = nullptr; 10211 } else { 10212 // Check I->Low <= Cond <= I->High. 10213 CC = ISD::SETLE; 10214 LHS = I->Low; 10215 MHS = Cond; 10216 RHS = I->High; 10217 } 10218 10219 // If Fallthrough is unreachable, fold away the comparison. 10220 if (FallthroughUnreachable) 10221 CC = ISD::SETTRUE; 10222 10223 // The false probability is the sum of all unhandled cases. 10224 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10225 getCurSDLoc(), I->Prob, UnhandledProbs); 10226 10227 if (CurMBB == SwitchMBB) 10228 visitSwitchCase(CB, SwitchMBB); 10229 else 10230 SL->SwitchCases.push_back(CB); 10231 10232 break; 10233 } 10234 } 10235 CurMBB = Fallthrough; 10236 } 10237 } 10238 10239 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10240 CaseClusterIt First, 10241 CaseClusterIt Last) { 10242 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10243 if (X.Prob != CC.Prob) 10244 return X.Prob > CC.Prob; 10245 10246 // Ties are broken by comparing the case value. 10247 return X.Low->getValue().slt(CC.Low->getValue()); 10248 }); 10249 } 10250 10251 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10252 const SwitchWorkListItem &W, 10253 Value *Cond, 10254 MachineBasicBlock *SwitchMBB) { 10255 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10256 "Clusters not sorted?"); 10257 10258 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10259 10260 // Balance the tree based on branch probabilities to create a near-optimal (in 10261 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10262 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10263 CaseClusterIt LastLeft = W.FirstCluster; 10264 CaseClusterIt FirstRight = W.LastCluster; 10265 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10266 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10267 10268 // Move LastLeft and FirstRight towards each other from opposite directions to 10269 // find a partitioning of the clusters which balances the probability on both 10270 // sides. If LeftProb and RightProb are equal, alternate which side is 10271 // taken to ensure 0-probability nodes are distributed evenly. 10272 unsigned I = 0; 10273 while (LastLeft + 1 < FirstRight) { 10274 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10275 LeftProb += (++LastLeft)->Prob; 10276 else 10277 RightProb += (--FirstRight)->Prob; 10278 I++; 10279 } 10280 10281 while (true) { 10282 // Our binary search tree differs from a typical BST in that ours can have up 10283 // to three values in each leaf. The pivot selection above doesn't take that 10284 // into account, which means the tree might require more nodes and be less 10285 // efficient. We compensate for this here. 10286 10287 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10288 unsigned NumRight = W.LastCluster - FirstRight + 1; 10289 10290 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10291 // If one side has less than 3 clusters, and the other has more than 3, 10292 // consider taking a cluster from the other side. 10293 10294 if (NumLeft < NumRight) { 10295 // Consider moving the first cluster on the right to the left side. 10296 CaseCluster &CC = *FirstRight; 10297 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10298 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10299 if (LeftSideRank <= RightSideRank) { 10300 // Moving the cluster to the left does not demote it. 10301 ++LastLeft; 10302 ++FirstRight; 10303 continue; 10304 } 10305 } else { 10306 assert(NumRight < NumLeft); 10307 // Consider moving the last element on the left to the right side. 10308 CaseCluster &CC = *LastLeft; 10309 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10310 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10311 if (RightSideRank <= LeftSideRank) { 10312 // Moving the cluster to the right does not demot it. 10313 --LastLeft; 10314 --FirstRight; 10315 continue; 10316 } 10317 } 10318 } 10319 break; 10320 } 10321 10322 assert(LastLeft + 1 == FirstRight); 10323 assert(LastLeft >= W.FirstCluster); 10324 assert(FirstRight <= W.LastCluster); 10325 10326 // Use the first element on the right as pivot since we will make less-than 10327 // comparisons against it. 10328 CaseClusterIt PivotCluster = FirstRight; 10329 assert(PivotCluster > W.FirstCluster); 10330 assert(PivotCluster <= W.LastCluster); 10331 10332 CaseClusterIt FirstLeft = W.FirstCluster; 10333 CaseClusterIt LastRight = W.LastCluster; 10334 10335 const ConstantInt *Pivot = PivotCluster->Low; 10336 10337 // New blocks will be inserted immediately after the current one. 10338 MachineFunction::iterator BBI(W.MBB); 10339 ++BBI; 10340 10341 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10342 // we can branch to its destination directly if it's squeezed exactly in 10343 // between the known lower bound and Pivot - 1. 10344 MachineBasicBlock *LeftMBB; 10345 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10346 FirstLeft->Low == W.GE && 10347 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10348 LeftMBB = FirstLeft->MBB; 10349 } else { 10350 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10351 FuncInfo.MF->insert(BBI, LeftMBB); 10352 WorkList.push_back( 10353 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10354 // Put Cond in a virtual register to make it available from the new blocks. 10355 ExportFromCurrentBlock(Cond); 10356 } 10357 10358 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10359 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10360 // directly if RHS.High equals the current upper bound. 10361 MachineBasicBlock *RightMBB; 10362 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10363 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10364 RightMBB = FirstRight->MBB; 10365 } else { 10366 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10367 FuncInfo.MF->insert(BBI, RightMBB); 10368 WorkList.push_back( 10369 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10370 // Put Cond in a virtual register to make it available from the new blocks. 10371 ExportFromCurrentBlock(Cond); 10372 } 10373 10374 // Create the CaseBlock record that will be used to lower the branch. 10375 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10376 getCurSDLoc(), LeftProb, RightProb); 10377 10378 if (W.MBB == SwitchMBB) 10379 visitSwitchCase(CB, SwitchMBB); 10380 else 10381 SL->SwitchCases.push_back(CB); 10382 } 10383 10384 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10385 // from the swith statement. 10386 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10387 BranchProbability PeeledCaseProb) { 10388 if (PeeledCaseProb == BranchProbability::getOne()) 10389 return BranchProbability::getZero(); 10390 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10391 10392 uint32_t Numerator = CaseProb.getNumerator(); 10393 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10394 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10395 } 10396 10397 // Try to peel the top probability case if it exceeds the threshold. 10398 // Return current MachineBasicBlock for the switch statement if the peeling 10399 // does not occur. 10400 // If the peeling is performed, return the newly created MachineBasicBlock 10401 // for the peeled switch statement. Also update Clusters to remove the peeled 10402 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10403 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10404 const SwitchInst &SI, CaseClusterVector &Clusters, 10405 BranchProbability &PeeledCaseProb) { 10406 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10407 // Don't perform if there is only one cluster or optimizing for size. 10408 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10409 TM.getOptLevel() == CodeGenOpt::None || 10410 SwitchMBB->getParent()->getFunction().hasMinSize()) 10411 return SwitchMBB; 10412 10413 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10414 unsigned PeeledCaseIndex = 0; 10415 bool SwitchPeeled = false; 10416 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10417 CaseCluster &CC = Clusters[Index]; 10418 if (CC.Prob < TopCaseProb) 10419 continue; 10420 TopCaseProb = CC.Prob; 10421 PeeledCaseIndex = Index; 10422 SwitchPeeled = true; 10423 } 10424 if (!SwitchPeeled) 10425 return SwitchMBB; 10426 10427 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10428 << TopCaseProb << "\n"); 10429 10430 // Record the MBB for the peeled switch statement. 10431 MachineFunction::iterator BBI(SwitchMBB); 10432 ++BBI; 10433 MachineBasicBlock *PeeledSwitchMBB = 10434 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10435 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10436 10437 ExportFromCurrentBlock(SI.getCondition()); 10438 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10439 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10440 nullptr, nullptr, TopCaseProb.getCompl()}; 10441 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10442 10443 Clusters.erase(PeeledCaseIt); 10444 for (CaseCluster &CC : Clusters) { 10445 LLVM_DEBUG( 10446 dbgs() << "Scale the probablity for one cluster, before scaling: " 10447 << CC.Prob << "\n"); 10448 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10449 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10450 } 10451 PeeledCaseProb = TopCaseProb; 10452 return PeeledSwitchMBB; 10453 } 10454 10455 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10456 // Extract cases from the switch. 10457 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10458 CaseClusterVector Clusters; 10459 Clusters.reserve(SI.getNumCases()); 10460 for (auto I : SI.cases()) { 10461 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10462 const ConstantInt *CaseVal = I.getCaseValue(); 10463 BranchProbability Prob = 10464 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10465 : BranchProbability(1, SI.getNumCases() + 1); 10466 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10467 } 10468 10469 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10470 10471 // Cluster adjacent cases with the same destination. We do this at all 10472 // optimization levels because it's cheap to do and will make codegen faster 10473 // if there are many clusters. 10474 sortAndRangeify(Clusters); 10475 10476 // The branch probablity of the peeled case. 10477 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10478 MachineBasicBlock *PeeledSwitchMBB = 10479 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10480 10481 // If there is only the default destination, jump there directly. 10482 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10483 if (Clusters.empty()) { 10484 assert(PeeledSwitchMBB == SwitchMBB); 10485 SwitchMBB->addSuccessor(DefaultMBB); 10486 if (DefaultMBB != NextBlock(SwitchMBB)) { 10487 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10488 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10489 } 10490 return; 10491 } 10492 10493 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10494 SL->findBitTestClusters(Clusters, &SI); 10495 10496 LLVM_DEBUG({ 10497 dbgs() << "Case clusters: "; 10498 for (const CaseCluster &C : Clusters) { 10499 if (C.Kind == CC_JumpTable) 10500 dbgs() << "JT:"; 10501 if (C.Kind == CC_BitTests) 10502 dbgs() << "BT:"; 10503 10504 C.Low->getValue().print(dbgs(), true); 10505 if (C.Low != C.High) { 10506 dbgs() << '-'; 10507 C.High->getValue().print(dbgs(), true); 10508 } 10509 dbgs() << ' '; 10510 } 10511 dbgs() << '\n'; 10512 }); 10513 10514 assert(!Clusters.empty()); 10515 SwitchWorkList WorkList; 10516 CaseClusterIt First = Clusters.begin(); 10517 CaseClusterIt Last = Clusters.end() - 1; 10518 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10519 // Scale the branchprobability for DefaultMBB if the peel occurs and 10520 // DefaultMBB is not replaced. 10521 if (PeeledCaseProb != BranchProbability::getZero() && 10522 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10523 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10524 WorkList.push_back( 10525 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10526 10527 while (!WorkList.empty()) { 10528 SwitchWorkListItem W = WorkList.back(); 10529 WorkList.pop_back(); 10530 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10531 10532 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10533 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10534 // For optimized builds, lower large range as a balanced binary tree. 10535 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10536 continue; 10537 } 10538 10539 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10540 } 10541 } 10542 10543 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10544 SmallVector<EVT, 4> ValueVTs; 10545 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10546 ValueVTs); 10547 unsigned NumValues = ValueVTs.size(); 10548 if (NumValues == 0) return; 10549 10550 SmallVector<SDValue, 4> Values(NumValues); 10551 SDValue Op = getValue(I.getOperand(0)); 10552 10553 for (unsigned i = 0; i != NumValues; ++i) 10554 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10555 SDValue(Op.getNode(), Op.getResNo() + i)); 10556 10557 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10558 DAG.getVTList(ValueVTs), Values)); 10559 } 10560