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<bool> 139 InsertAssertAlign("insert-assert-align", cl::init(true), 140 cl::desc("Insert the experimental `assertalign` node."), 141 cl::ReallyHidden); 142 143 static cl::opt<unsigned, true> 144 LimitFPPrecision("limit-float-precision", 145 cl::desc("Generate low-precision inline sequences " 146 "for some float libcalls"), 147 cl::location(LimitFloatPrecision), cl::Hidden, 148 cl::init(0)); 149 150 static cl::opt<unsigned> SwitchPeelThreshold( 151 "switch-peel-threshold", cl::Hidden, cl::init(66), 152 cl::desc("Set the case probability threshold for peeling the case from a " 153 "switch statement. A value greater than 100 will void this " 154 "optimization")); 155 156 // Limit the width of DAG chains. This is important in general to prevent 157 // DAG-based analysis from blowing up. For example, alias analysis and 158 // load clustering may not complete in reasonable time. It is difficult to 159 // recognize and avoid this situation within each individual analysis, and 160 // future analyses are likely to have the same behavior. Limiting DAG width is 161 // the safe approach and will be especially important with global DAGs. 162 // 163 // MaxParallelChains default is arbitrarily high to avoid affecting 164 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 165 // sequence over this should have been converted to llvm.memcpy by the 166 // frontend. It is easy to induce this behavior with .ll code such as: 167 // %buffer = alloca [4096 x i8] 168 // %data = load [4096 x i8]* %argPtr 169 // store [4096 x i8] %data, [4096 x i8]* %buffer 170 static const unsigned MaxParallelChains = 64; 171 172 // Return the calling convention if the Value passed requires ABI mangling as it 173 // is a parameter to a function or a return value from a function which is not 174 // an intrinsic. 175 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 176 if (auto *R = dyn_cast<ReturnInst>(V)) 177 return R->getParent()->getParent()->getCallingConv(); 178 179 if (auto *CI = dyn_cast<CallInst>(V)) { 180 const bool IsInlineAsm = CI->isInlineAsm(); 181 const bool IsIndirectFunctionCall = 182 !IsInlineAsm && !CI->getCalledFunction(); 183 184 // It is possible that the call instruction is an inline asm statement or an 185 // indirect function call in which case the return value of 186 // getCalledFunction() would be nullptr. 187 const bool IsInstrinsicCall = 188 !IsInlineAsm && !IsIndirectFunctionCall && 189 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 190 191 if (!IsInlineAsm && !IsInstrinsicCall) 192 return CI->getCallingConv(); 193 } 194 195 return None; 196 } 197 198 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 199 const SDValue *Parts, unsigned NumParts, 200 MVT PartVT, EVT ValueVT, const Value *V, 201 Optional<CallingConv::ID> CC); 202 203 /// getCopyFromParts - Create a value that contains the specified legal parts 204 /// combined into the value they represent. If the parts combine to a type 205 /// larger than ValueVT then AssertOp can be used to specify whether the extra 206 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 207 /// (ISD::AssertSext). 208 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 209 const SDValue *Parts, unsigned NumParts, 210 MVT PartVT, EVT ValueVT, const Value *V, 211 Optional<CallingConv::ID> CC = None, 212 Optional<ISD::NodeType> AssertOp = None) { 213 // Let the target assemble the parts if it wants to 214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 215 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 216 PartVT, ValueVT, CC)) 217 return Val; 218 219 if (ValueVT.isVector()) 220 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 221 CC); 222 223 assert(NumParts > 0 && "No parts to assemble!"); 224 SDValue Val = Parts[0]; 225 226 if (NumParts > 1) { 227 // Assemble the value from multiple parts. 228 if (ValueVT.isInteger()) { 229 unsigned PartBits = PartVT.getSizeInBits(); 230 unsigned ValueBits = ValueVT.getSizeInBits(); 231 232 // Assemble the power of 2 part. 233 unsigned RoundParts = 234 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 235 unsigned RoundBits = PartBits * RoundParts; 236 EVT RoundVT = RoundBits == ValueBits ? 237 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 238 SDValue Lo, Hi; 239 240 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 241 242 if (RoundParts > 2) { 243 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 244 PartVT, HalfVT, V); 245 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 246 RoundParts / 2, PartVT, HalfVT, V); 247 } else { 248 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 249 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 250 } 251 252 if (DAG.getDataLayout().isBigEndian()) 253 std::swap(Lo, Hi); 254 255 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 256 257 if (RoundParts < NumParts) { 258 // Assemble the trailing non-power-of-2 part. 259 unsigned OddParts = NumParts - RoundParts; 260 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 261 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 262 OddVT, V, CC); 263 264 // Combine the round and odd parts. 265 Lo = Val; 266 if (DAG.getDataLayout().isBigEndian()) 267 std::swap(Lo, Hi); 268 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 269 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 270 Hi = 271 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 272 DAG.getConstant(Lo.getValueSizeInBits(), DL, 273 TLI.getPointerTy(DAG.getDataLayout()))); 274 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 275 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 276 } 277 } else if (PartVT.isFloatingPoint()) { 278 // FP split into multiple FP parts (for ppcf128) 279 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 280 "Unexpected split"); 281 SDValue Lo, Hi; 282 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 283 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 284 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 285 std::swap(Lo, Hi); 286 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 287 } else { 288 // FP split into integer parts (soft fp) 289 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 290 !PartVT.isVector() && "Unexpected split"); 291 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 292 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 293 } 294 } 295 296 // There is now one part, held in Val. Correct it to match ValueVT. 297 // PartEVT is the type of the register class that holds the value. 298 // ValueVT is the type of the inline asm operation. 299 EVT PartEVT = Val.getValueType(); 300 301 if (PartEVT == ValueVT) 302 return Val; 303 304 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 305 ValueVT.bitsLT(PartEVT)) { 306 // For an FP value in an integer part, we need to truncate to the right 307 // width first. 308 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 309 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 310 } 311 312 // Handle types that have the same size. 313 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 314 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 315 316 // Handle types with different sizes. 317 if (PartEVT.isInteger() && ValueVT.isInteger()) { 318 if (ValueVT.bitsLT(PartEVT)) { 319 // For a truncate, see if we have any information to 320 // indicate whether the truncated bits will always be 321 // zero or sign-extension. 322 if (AssertOp.hasValue()) 323 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 324 DAG.getValueType(ValueVT)); 325 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 326 } 327 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 328 } 329 330 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 331 // FP_ROUND's are always exact here. 332 if (ValueVT.bitsLT(Val.getValueType())) 333 return DAG.getNode( 334 ISD::FP_ROUND, DL, ValueVT, Val, 335 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 336 337 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 338 } 339 340 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 341 // then truncating. 342 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 343 ValueVT.bitsLT(PartEVT)) { 344 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 345 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 346 } 347 348 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 349 } 350 351 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 352 const Twine &ErrMsg) { 353 const Instruction *I = dyn_cast_or_null<Instruction>(V); 354 if (!V) 355 return Ctx.emitError(ErrMsg); 356 357 const char *AsmError = ", possible invalid constraint for vector type"; 358 if (const CallInst *CI = dyn_cast<CallInst>(I)) 359 if (CI->isInlineAsm()) 360 return Ctx.emitError(I, ErrMsg + AsmError); 361 362 return Ctx.emitError(I, ErrMsg); 363 } 364 365 /// getCopyFromPartsVector - Create a value that contains the specified legal 366 /// parts combined into the value they represent. If the parts combine to a 367 /// type larger than ValueVT then AssertOp can be used to specify whether the 368 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 369 /// ValueVT (ISD::AssertSext). 370 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 371 const SDValue *Parts, unsigned NumParts, 372 MVT PartVT, EVT ValueVT, const Value *V, 373 Optional<CallingConv::ID> CallConv) { 374 assert(ValueVT.isVector() && "Not a vector value"); 375 assert(NumParts > 0 && "No parts to assemble!"); 376 const bool IsABIRegCopy = CallConv.hasValue(); 377 378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 379 SDValue Val = Parts[0]; 380 381 // Handle a multi-element vector. 382 if (NumParts > 1) { 383 EVT IntermediateVT; 384 MVT RegisterVT; 385 unsigned NumIntermediates; 386 unsigned NumRegs; 387 388 if (IsABIRegCopy) { 389 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 390 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 391 NumIntermediates, RegisterVT); 392 } else { 393 NumRegs = 394 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 395 NumIntermediates, RegisterVT); 396 } 397 398 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 399 NumParts = NumRegs; // Silence a compiler warning. 400 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 401 assert(RegisterVT.getSizeInBits() == 402 Parts[0].getSimpleValueType().getSizeInBits() && 403 "Part type sizes don't match!"); 404 405 // Assemble the parts into intermediate operands. 406 SmallVector<SDValue, 8> Ops(NumIntermediates); 407 if (NumIntermediates == NumParts) { 408 // If the register was not expanded, truncate or copy the value, 409 // as appropriate. 410 for (unsigned i = 0; i != NumParts; ++i) 411 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 412 PartVT, IntermediateVT, V); 413 } else if (NumParts > 0) { 414 // If the intermediate type was expanded, build the intermediate 415 // operands from the parts. 416 assert(NumParts % NumIntermediates == 0 && 417 "Must expand into a divisible number of parts!"); 418 unsigned Factor = NumParts / NumIntermediates; 419 for (unsigned i = 0; i != NumIntermediates; ++i) 420 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 421 PartVT, IntermediateVT, V); 422 } 423 424 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 425 // intermediate operands. 426 EVT BuiltVectorTy = 427 IntermediateVT.isVector() 428 ? EVT::getVectorVT( 429 *DAG.getContext(), IntermediateVT.getScalarType(), 430 IntermediateVT.getVectorElementCount() * NumParts) 431 : EVT::getVectorVT(*DAG.getContext(), 432 IntermediateVT.getScalarType(), 433 NumIntermediates); 434 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 435 : ISD::BUILD_VECTOR, 436 DL, BuiltVectorTy, Ops); 437 } 438 439 // There is now one part, held in Val. Correct it to match ValueVT. 440 EVT PartEVT = Val.getValueType(); 441 442 if (PartEVT == ValueVT) 443 return Val; 444 445 if (PartEVT.isVector()) { 446 // If the element type of the source/dest vectors are the same, but the 447 // parts vector has more elements than the value vector, then we have a 448 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 449 // elements we want. 450 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 451 assert((PartEVT.getVectorElementCount().Min > 452 ValueVT.getVectorElementCount().Min) && 453 (PartEVT.getVectorElementCount().Scalable == 454 ValueVT.getVectorElementCount().Scalable) && 455 "Cannot narrow, it would be a lossy transformation"); 456 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 457 DAG.getVectorIdxConstant(0, DL)); 458 } 459 460 // Vector/Vector bitcast. 461 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 462 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 463 464 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 465 "Cannot handle this kind of promotion"); 466 // Promoted vector extract 467 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 468 469 } 470 471 // Trivial bitcast if the types are the same size and the destination 472 // vector type is legal. 473 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 474 TLI.isTypeLegal(ValueVT)) 475 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 476 477 if (ValueVT.getVectorNumElements() != 1) { 478 // Certain ABIs require that vectors are passed as integers. For vectors 479 // are the same size, this is an obvious bitcast. 480 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 481 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 482 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 483 // Bitcast Val back the original type and extract the corresponding 484 // vector we want. 485 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 486 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 487 ValueVT.getVectorElementType(), Elts); 488 Val = DAG.getBitcast(WiderVecType, Val); 489 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 490 DAG.getVectorIdxConstant(0, DL)); 491 } 492 493 diagnosePossiblyInvalidConstraint( 494 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 495 return DAG.getUNDEF(ValueVT); 496 } 497 498 // Handle cases such as i8 -> <1 x i1> 499 EVT ValueSVT = ValueVT.getVectorElementType(); 500 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 501 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 502 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 503 else 504 Val = ValueVT.isFloatingPoint() 505 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 506 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 507 } 508 509 return DAG.getBuildVector(ValueVT, DL, Val); 510 } 511 512 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 513 SDValue Val, SDValue *Parts, unsigned NumParts, 514 MVT PartVT, const Value *V, 515 Optional<CallingConv::ID> CallConv); 516 517 /// getCopyToParts - Create a series of nodes that contain the specified value 518 /// split into legal parts. If the parts contain more bits than Val, then, for 519 /// integers, ExtendKind can be used to specify how to generate the extra bits. 520 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 521 SDValue *Parts, unsigned NumParts, MVT PartVT, 522 const Value *V, 523 Optional<CallingConv::ID> CallConv = None, 524 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 525 // Let the target split the parts if it wants to 526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 527 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 528 CallConv)) 529 return; 530 EVT ValueVT = Val.getValueType(); 531 532 // Handle the vector case separately. 533 if (ValueVT.isVector()) 534 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 535 CallConv); 536 537 unsigned PartBits = PartVT.getSizeInBits(); 538 unsigned OrigNumParts = NumParts; 539 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 540 "Copying to an illegal type!"); 541 542 if (NumParts == 0) 543 return; 544 545 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 546 EVT PartEVT = PartVT; 547 if (PartEVT == ValueVT) { 548 assert(NumParts == 1 && "No-op copy with multiple parts!"); 549 Parts[0] = Val; 550 return; 551 } 552 553 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 554 // If the parts cover more bits than the value has, promote the value. 555 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 556 assert(NumParts == 1 && "Do not know what to promote to!"); 557 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 558 } else { 559 if (ValueVT.isFloatingPoint()) { 560 // FP values need to be bitcast, then extended if they are being put 561 // into a larger container. 562 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 563 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 564 } 565 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 566 ValueVT.isInteger() && 567 "Unknown mismatch!"); 568 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 569 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 570 if (PartVT == MVT::x86mmx) 571 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 572 } 573 } else if (PartBits == ValueVT.getSizeInBits()) { 574 // Different types of the same size. 575 assert(NumParts == 1 && PartEVT != ValueVT); 576 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 577 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 578 // If the parts cover less bits than value has, truncate the value. 579 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 580 ValueVT.isInteger() && 581 "Unknown mismatch!"); 582 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 583 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 584 if (PartVT == MVT::x86mmx) 585 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 586 } 587 588 // The value may have changed - recompute ValueVT. 589 ValueVT = Val.getValueType(); 590 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 591 "Failed to tile the value with PartVT!"); 592 593 if (NumParts == 1) { 594 if (PartEVT != ValueVT) { 595 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 596 "scalar-to-vector conversion failed"); 597 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 598 } 599 600 Parts[0] = Val; 601 return; 602 } 603 604 // Expand the value into multiple parts. 605 if (NumParts & (NumParts - 1)) { 606 // The number of parts is not a power of 2. Split off and copy the tail. 607 assert(PartVT.isInteger() && ValueVT.isInteger() && 608 "Do not know what to expand to!"); 609 unsigned RoundParts = 1 << Log2_32(NumParts); 610 unsigned RoundBits = RoundParts * PartBits; 611 unsigned OddParts = NumParts - RoundParts; 612 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 613 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 614 615 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 616 CallConv); 617 618 if (DAG.getDataLayout().isBigEndian()) 619 // The odd parts were reversed by getCopyToParts - unreverse them. 620 std::reverse(Parts + RoundParts, Parts + NumParts); 621 622 NumParts = RoundParts; 623 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 624 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 625 } 626 627 // The number of parts is a power of 2. Repeatedly bisect the value using 628 // EXTRACT_ELEMENT. 629 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 630 EVT::getIntegerVT(*DAG.getContext(), 631 ValueVT.getSizeInBits()), 632 Val); 633 634 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 635 for (unsigned i = 0; i < NumParts; i += StepSize) { 636 unsigned ThisBits = StepSize * PartBits / 2; 637 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 638 SDValue &Part0 = Parts[i]; 639 SDValue &Part1 = Parts[i+StepSize/2]; 640 641 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 642 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 643 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 644 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 645 646 if (ThisBits == PartBits && ThisVT != PartVT) { 647 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 648 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 649 } 650 } 651 } 652 653 if (DAG.getDataLayout().isBigEndian()) 654 std::reverse(Parts, Parts + OrigNumParts); 655 } 656 657 static SDValue widenVectorToPartType(SelectionDAG &DAG, 658 SDValue Val, const SDLoc &DL, EVT PartVT) { 659 if (!PartVT.isVector()) 660 return SDValue(); 661 662 EVT ValueVT = Val.getValueType(); 663 unsigned PartNumElts = PartVT.getVectorNumElements(); 664 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 665 if (PartNumElts > ValueNumElts && 666 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 667 EVT ElementVT = PartVT.getVectorElementType(); 668 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 669 // undef elements. 670 SmallVector<SDValue, 16> Ops; 671 DAG.ExtractVectorElements(Val, Ops); 672 SDValue EltUndef = DAG.getUNDEF(ElementVT); 673 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 674 Ops.push_back(EltUndef); 675 676 // FIXME: Use CONCAT for 2x -> 4x. 677 return DAG.getBuildVector(PartVT, DL, Ops); 678 } 679 680 return SDValue(); 681 } 682 683 /// getCopyToPartsVector - Create a series of nodes that contain the specified 684 /// value split into legal parts. 685 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 686 SDValue Val, SDValue *Parts, unsigned NumParts, 687 MVT PartVT, const Value *V, 688 Optional<CallingConv::ID> CallConv) { 689 EVT ValueVT = Val.getValueType(); 690 assert(ValueVT.isVector() && "Not a vector"); 691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 692 const bool IsABIRegCopy = CallConv.hasValue(); 693 694 if (NumParts == 1) { 695 EVT PartEVT = PartVT; 696 if (PartEVT == ValueVT) { 697 // Nothing to do. 698 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 699 // Bitconvert vector->vector case. 700 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 701 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 702 Val = Widened; 703 } else if (PartVT.isVector() && 704 PartEVT.getVectorElementType().bitsGE( 705 ValueVT.getVectorElementType()) && 706 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 707 708 // Promoted vector extract 709 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 710 } else { 711 if (ValueVT.getVectorNumElements() == 1) { 712 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 713 DAG.getVectorIdxConstant(0, DL)); 714 } else { 715 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 716 "lossy conversion of vector to scalar type"); 717 EVT IntermediateType = 718 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 719 Val = DAG.getBitcast(IntermediateType, Val); 720 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 721 } 722 } 723 724 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 725 Parts[0] = Val; 726 return; 727 } 728 729 // Handle a multi-element vector. 730 EVT IntermediateVT; 731 MVT RegisterVT; 732 unsigned NumIntermediates; 733 unsigned NumRegs; 734 if (IsABIRegCopy) { 735 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 736 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 737 NumIntermediates, RegisterVT); 738 } else { 739 NumRegs = 740 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 741 NumIntermediates, RegisterVT); 742 } 743 744 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 745 NumParts = NumRegs; // Silence a compiler warning. 746 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 747 748 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 749 IntermediateVT.getVectorNumElements() : 1; 750 751 // Convert the vector to the appropriate type if necessary. 752 auto DestEltCnt = ElementCount(NumIntermediates * IntermediateNumElts, 753 ValueVT.isScalableVector()); 754 EVT BuiltVectorTy = EVT::getVectorVT( 755 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt); 756 if (ValueVT != BuiltVectorTy) { 757 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 758 Val = Widened; 759 760 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 761 } 762 763 // Split the vector into intermediate operands. 764 SmallVector<SDValue, 8> Ops(NumIntermediates); 765 for (unsigned i = 0; i != NumIntermediates; ++i) { 766 if (IntermediateVT.isVector()) { 767 Ops[i] = 768 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 769 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 770 } else { 771 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 772 DAG.getVectorIdxConstant(i, DL)); 773 } 774 } 775 776 // Split the intermediate operands into legal parts. 777 if (NumParts == NumIntermediates) { 778 // If the register was not expanded, promote or copy the value, 779 // as appropriate. 780 for (unsigned i = 0; i != NumParts; ++i) 781 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 782 } else if (NumParts > 0) { 783 // If the intermediate type was expanded, split each the value into 784 // legal parts. 785 assert(NumIntermediates != 0 && "division by zero"); 786 assert(NumParts % NumIntermediates == 0 && 787 "Must expand into a divisible number of parts!"); 788 unsigned Factor = NumParts / NumIntermediates; 789 for (unsigned i = 0; i != NumIntermediates; ++i) 790 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 791 CallConv); 792 } 793 } 794 795 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 796 EVT valuevt, Optional<CallingConv::ID> CC) 797 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 798 RegCount(1, regs.size()), CallConv(CC) {} 799 800 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 801 const DataLayout &DL, unsigned Reg, Type *Ty, 802 Optional<CallingConv::ID> CC) { 803 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 804 805 CallConv = CC; 806 807 for (EVT ValueVT : ValueVTs) { 808 unsigned NumRegs = 809 isABIMangled() 810 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 811 : TLI.getNumRegisters(Context, ValueVT); 812 MVT RegisterVT = 813 isABIMangled() 814 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 815 : TLI.getRegisterType(Context, ValueVT); 816 for (unsigned i = 0; i != NumRegs; ++i) 817 Regs.push_back(Reg + i); 818 RegVTs.push_back(RegisterVT); 819 RegCount.push_back(NumRegs); 820 Reg += NumRegs; 821 } 822 } 823 824 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 825 FunctionLoweringInfo &FuncInfo, 826 const SDLoc &dl, SDValue &Chain, 827 SDValue *Flag, const Value *V) const { 828 // A Value with type {} or [0 x %t] needs no registers. 829 if (ValueVTs.empty()) 830 return SDValue(); 831 832 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 833 834 // Assemble the legal parts into the final values. 835 SmallVector<SDValue, 4> Values(ValueVTs.size()); 836 SmallVector<SDValue, 8> Parts; 837 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 838 // Copy the legal parts from the registers. 839 EVT ValueVT = ValueVTs[Value]; 840 unsigned NumRegs = RegCount[Value]; 841 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 842 *DAG.getContext(), 843 CallConv.getValue(), RegVTs[Value]) 844 : RegVTs[Value]; 845 846 Parts.resize(NumRegs); 847 for (unsigned i = 0; i != NumRegs; ++i) { 848 SDValue P; 849 if (!Flag) { 850 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 851 } else { 852 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 853 *Flag = P.getValue(2); 854 } 855 856 Chain = P.getValue(1); 857 Parts[i] = P; 858 859 // If the source register was virtual and if we know something about it, 860 // add an assert node. 861 if (!Register::isVirtualRegister(Regs[Part + i]) || 862 !RegisterVT.isInteger()) 863 continue; 864 865 const FunctionLoweringInfo::LiveOutInfo *LOI = 866 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 867 if (!LOI) 868 continue; 869 870 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 871 unsigned NumSignBits = LOI->NumSignBits; 872 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 873 874 if (NumZeroBits == RegSize) { 875 // The current value is a zero. 876 // Explicitly express that as it would be easier for 877 // optimizations to kick in. 878 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 879 continue; 880 } 881 882 // FIXME: We capture more information than the dag can represent. For 883 // now, just use the tightest assertzext/assertsext possible. 884 bool isSExt; 885 EVT FromVT(MVT::Other); 886 if (NumZeroBits) { 887 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 888 isSExt = false; 889 } else if (NumSignBits > 1) { 890 FromVT = 891 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 892 isSExt = true; 893 } else { 894 continue; 895 } 896 // Add an assertion node. 897 assert(FromVT != MVT::Other); 898 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 899 RegisterVT, P, DAG.getValueType(FromVT)); 900 } 901 902 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 903 RegisterVT, ValueVT, V, CallConv); 904 Part += NumRegs; 905 Parts.clear(); 906 } 907 908 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 909 } 910 911 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 912 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 913 const Value *V, 914 ISD::NodeType PreferredExtendType) const { 915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 916 ISD::NodeType ExtendKind = PreferredExtendType; 917 918 // Get the list of the values's legal parts. 919 unsigned NumRegs = Regs.size(); 920 SmallVector<SDValue, 8> Parts(NumRegs); 921 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 922 unsigned NumParts = RegCount[Value]; 923 924 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 925 *DAG.getContext(), 926 CallConv.getValue(), RegVTs[Value]) 927 : RegVTs[Value]; 928 929 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 930 ExtendKind = ISD::ZERO_EXTEND; 931 932 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 933 NumParts, RegisterVT, V, CallConv, ExtendKind); 934 Part += NumParts; 935 } 936 937 // Copy the parts into the registers. 938 SmallVector<SDValue, 8> Chains(NumRegs); 939 for (unsigned i = 0; i != NumRegs; ++i) { 940 SDValue Part; 941 if (!Flag) { 942 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 943 } else { 944 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 945 *Flag = Part.getValue(1); 946 } 947 948 Chains[i] = Part.getValue(0); 949 } 950 951 if (NumRegs == 1 || Flag) 952 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 953 // flagged to it. That is the CopyToReg nodes and the user are considered 954 // a single scheduling unit. If we create a TokenFactor and return it as 955 // chain, then the TokenFactor is both a predecessor (operand) of the 956 // user as well as a successor (the TF operands are flagged to the user). 957 // c1, f1 = CopyToReg 958 // c2, f2 = CopyToReg 959 // c3 = TokenFactor c1, c2 960 // ... 961 // = op c3, ..., f2 962 Chain = Chains[NumRegs-1]; 963 else 964 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 965 } 966 967 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 968 unsigned MatchingIdx, const SDLoc &dl, 969 SelectionDAG &DAG, 970 std::vector<SDValue> &Ops) const { 971 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 972 973 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 974 if (HasMatching) 975 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 976 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 977 // Put the register class of the virtual registers in the flag word. That 978 // way, later passes can recompute register class constraints for inline 979 // assembly as well as normal instructions. 980 // Don't do this for tied operands that can use the regclass information 981 // from the def. 982 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 983 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 984 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 985 } 986 987 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 988 Ops.push_back(Res); 989 990 if (Code == InlineAsm::Kind_Clobber) { 991 // Clobbers should always have a 1:1 mapping with registers, and may 992 // reference registers that have illegal (e.g. vector) types. Hence, we 993 // shouldn't try to apply any sort of splitting logic to them. 994 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 995 "No 1:1 mapping from clobbers to regs?"); 996 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 997 (void)SP; 998 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 999 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1000 assert( 1001 (Regs[I] != SP || 1002 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1003 "If we clobbered the stack pointer, MFI should know about it."); 1004 } 1005 return; 1006 } 1007 1008 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1009 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 1010 MVT RegisterVT = RegVTs[Value]; 1011 for (unsigned i = 0; i != NumRegs; ++i) { 1012 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1013 unsigned TheReg = Regs[Reg++]; 1014 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1015 } 1016 } 1017 } 1018 1019 SmallVector<std::pair<unsigned, unsigned>, 4> 1020 RegsForValue::getRegsAndSizes() const { 1021 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1022 unsigned I = 0; 1023 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1024 unsigned RegCount = std::get<0>(CountAndVT); 1025 MVT RegisterVT = std::get<1>(CountAndVT); 1026 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1027 for (unsigned E = I + RegCount; I != E; ++I) 1028 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1029 } 1030 return OutVec; 1031 } 1032 1033 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1034 const TargetLibraryInfo *li) { 1035 AA = aa; 1036 GFI = gfi; 1037 LibInfo = li; 1038 DL = &DAG.getDataLayout(); 1039 Context = DAG.getContext(); 1040 LPadToCallSiteMap.clear(); 1041 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1042 } 1043 1044 void SelectionDAGBuilder::clear() { 1045 NodeMap.clear(); 1046 UnusedArgNodeMap.clear(); 1047 PendingLoads.clear(); 1048 PendingExports.clear(); 1049 PendingConstrainedFP.clear(); 1050 PendingConstrainedFPStrict.clear(); 1051 CurInst = nullptr; 1052 HasTailCall = false; 1053 SDNodeOrder = LowestSDNodeOrder; 1054 StatepointLowering.clear(); 1055 } 1056 1057 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1058 DanglingDebugInfoMap.clear(); 1059 } 1060 1061 // Update DAG root to include dependencies on Pending chains. 1062 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1063 SDValue Root = DAG.getRoot(); 1064 1065 if (Pending.empty()) 1066 return Root; 1067 1068 // Add current root to PendingChains, unless we already indirectly 1069 // depend on it. 1070 if (Root.getOpcode() != ISD::EntryToken) { 1071 unsigned i = 0, e = Pending.size(); 1072 for (; i != e; ++i) { 1073 assert(Pending[i].getNode()->getNumOperands() > 1); 1074 if (Pending[i].getNode()->getOperand(0) == Root) 1075 break; // Don't add the root if we already indirectly depend on it. 1076 } 1077 1078 if (i == e) 1079 Pending.push_back(Root); 1080 } 1081 1082 if (Pending.size() == 1) 1083 Root = Pending[0]; 1084 else 1085 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1086 1087 DAG.setRoot(Root); 1088 Pending.clear(); 1089 return Root; 1090 } 1091 1092 SDValue SelectionDAGBuilder::getMemoryRoot() { 1093 return updateRoot(PendingLoads); 1094 } 1095 1096 SDValue SelectionDAGBuilder::getRoot() { 1097 // Chain up all pending constrained intrinsics together with all 1098 // pending loads, by simply appending them to PendingLoads and 1099 // then calling getMemoryRoot(). 1100 PendingLoads.reserve(PendingLoads.size() + 1101 PendingConstrainedFP.size() + 1102 PendingConstrainedFPStrict.size()); 1103 PendingLoads.append(PendingConstrainedFP.begin(), 1104 PendingConstrainedFP.end()); 1105 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1106 PendingConstrainedFPStrict.end()); 1107 PendingConstrainedFP.clear(); 1108 PendingConstrainedFPStrict.clear(); 1109 return getMemoryRoot(); 1110 } 1111 1112 SDValue SelectionDAGBuilder::getControlRoot() { 1113 // We need to emit pending fpexcept.strict constrained intrinsics, 1114 // so append them to the PendingExports list. 1115 PendingExports.append(PendingConstrainedFPStrict.begin(), 1116 PendingConstrainedFPStrict.end()); 1117 PendingConstrainedFPStrict.clear(); 1118 return updateRoot(PendingExports); 1119 } 1120 1121 void SelectionDAGBuilder::visit(const Instruction &I) { 1122 // Set up outgoing PHI node register values before emitting the terminator. 1123 if (I.isTerminator()) { 1124 HandlePHINodesInSuccessorBlocks(I.getParent()); 1125 } 1126 1127 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1128 if (!isa<DbgInfoIntrinsic>(I)) 1129 ++SDNodeOrder; 1130 1131 CurInst = &I; 1132 1133 visit(I.getOpcode(), I); 1134 1135 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1136 // ConstrainedFPIntrinsics handle their own FMF. 1137 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1138 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1139 // maps to this instruction. 1140 // TODO: We could handle all flags (nsw, etc) here. 1141 // TODO: If an IR instruction maps to >1 node, only the final node will have 1142 // flags set. 1143 if (SDNode *Node = getNodeForIRValue(&I)) { 1144 SDNodeFlags IncomingFlags; 1145 IncomingFlags.copyFMF(*FPMO); 1146 if (!Node->getFlags().isDefined()) 1147 Node->setFlags(IncomingFlags); 1148 else 1149 Node->intersectFlagsWith(IncomingFlags); 1150 } 1151 } 1152 } 1153 1154 if (!I.isTerminator() && !HasTailCall && 1155 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1156 CopyToExportRegsIfNeeded(&I); 1157 1158 CurInst = nullptr; 1159 } 1160 1161 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1162 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1163 } 1164 1165 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1166 // Note: this doesn't use InstVisitor, because it has to work with 1167 // ConstantExpr's in addition to instructions. 1168 switch (Opcode) { 1169 default: llvm_unreachable("Unknown instruction type encountered!"); 1170 // Build the switch statement using the Instruction.def file. 1171 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1172 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1173 #include "llvm/IR/Instruction.def" 1174 } 1175 } 1176 1177 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1178 const DIExpression *Expr) { 1179 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1180 const DbgValueInst *DI = DDI.getDI(); 1181 DIVariable *DanglingVariable = DI->getVariable(); 1182 DIExpression *DanglingExpr = DI->getExpression(); 1183 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1184 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1185 return true; 1186 } 1187 return false; 1188 }; 1189 1190 for (auto &DDIMI : DanglingDebugInfoMap) { 1191 DanglingDebugInfoVector &DDIV = DDIMI.second; 1192 1193 // If debug info is to be dropped, run it through final checks to see 1194 // whether it can be salvaged. 1195 for (auto &DDI : DDIV) 1196 if (isMatchingDbgValue(DDI)) 1197 salvageUnresolvedDbgValue(DDI); 1198 1199 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1200 } 1201 } 1202 1203 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1204 // generate the debug data structures now that we've seen its definition. 1205 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1206 SDValue Val) { 1207 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1208 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1209 return; 1210 1211 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1212 for (auto &DDI : DDIV) { 1213 const DbgValueInst *DI = DDI.getDI(); 1214 assert(DI && "Ill-formed DanglingDebugInfo"); 1215 DebugLoc dl = DDI.getdl(); 1216 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1217 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1218 DILocalVariable *Variable = DI->getVariable(); 1219 DIExpression *Expr = DI->getExpression(); 1220 assert(Variable->isValidLocationForIntrinsic(dl) && 1221 "Expected inlined-at fields to agree"); 1222 SDDbgValue *SDV; 1223 if (Val.getNode()) { 1224 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1225 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1226 // we couldn't resolve it directly when examining the DbgValue intrinsic 1227 // in the first place we should not be more successful here). Unless we 1228 // have some test case that prove this to be correct we should avoid 1229 // calling EmitFuncArgumentDbgValue here. 1230 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1231 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1232 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1233 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1234 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1235 // inserted after the definition of Val when emitting the instructions 1236 // after ISel. An alternative could be to teach 1237 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1238 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1239 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1240 << ValSDNodeOrder << "\n"); 1241 SDV = getDbgValue(Val, Variable, Expr, dl, 1242 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1243 DAG.AddDbgValue(SDV, Val.getNode(), false); 1244 } else 1245 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1246 << "in EmitFuncArgumentDbgValue\n"); 1247 } else { 1248 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1249 auto Undef = 1250 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1251 auto SDV = 1252 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1253 DAG.AddDbgValue(SDV, nullptr, false); 1254 } 1255 } 1256 DDIV.clear(); 1257 } 1258 1259 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1260 Value *V = DDI.getDI()->getValue(); 1261 DILocalVariable *Var = DDI.getDI()->getVariable(); 1262 DIExpression *Expr = DDI.getDI()->getExpression(); 1263 DebugLoc DL = DDI.getdl(); 1264 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1265 unsigned SDOrder = DDI.getSDNodeOrder(); 1266 1267 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1268 // that DW_OP_stack_value is desired. 1269 assert(isa<DbgValueInst>(DDI.getDI())); 1270 bool StackValue = true; 1271 1272 // Can this Value can be encoded without any further work? 1273 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1274 return; 1275 1276 // Attempt to salvage back through as many instructions as possible. Bail if 1277 // a non-instruction is seen, such as a constant expression or global 1278 // variable. FIXME: Further work could recover those too. 1279 while (isa<Instruction>(V)) { 1280 Instruction &VAsInst = *cast<Instruction>(V); 1281 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1282 1283 // If we cannot salvage any further, and haven't yet found a suitable debug 1284 // expression, bail out. 1285 if (!NewExpr) 1286 break; 1287 1288 // New value and expr now represent this debuginfo. 1289 V = VAsInst.getOperand(0); 1290 Expr = NewExpr; 1291 1292 // Some kind of simplification occurred: check whether the operand of the 1293 // salvaged debug expression can be encoded in this DAG. 1294 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1295 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1296 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1297 return; 1298 } 1299 } 1300 1301 // This was the final opportunity to salvage this debug information, and it 1302 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1303 // any earlier variable location. 1304 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1305 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1306 DAG.AddDbgValue(SDV, nullptr, false); 1307 1308 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1309 << "\n"); 1310 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1311 << "\n"); 1312 } 1313 1314 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1315 DIExpression *Expr, DebugLoc dl, 1316 DebugLoc InstDL, unsigned Order) { 1317 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1318 SDDbgValue *SDV; 1319 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1320 isa<ConstantPointerNull>(V)) { 1321 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1322 DAG.AddDbgValue(SDV, nullptr, false); 1323 return true; 1324 } 1325 1326 // If the Value is a frame index, we can create a FrameIndex debug value 1327 // without relying on the DAG at all. 1328 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1329 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1330 if (SI != FuncInfo.StaticAllocaMap.end()) { 1331 auto SDV = 1332 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1333 /*IsIndirect*/ false, dl, SDNodeOrder); 1334 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1335 // is still available even if the SDNode gets optimized out. 1336 DAG.AddDbgValue(SDV, nullptr, false); 1337 return true; 1338 } 1339 } 1340 1341 // Do not use getValue() in here; we don't want to generate code at 1342 // this point if it hasn't been done yet. 1343 SDValue N = NodeMap[V]; 1344 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1345 N = UnusedArgNodeMap[V]; 1346 if (N.getNode()) { 1347 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1348 return true; 1349 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1350 DAG.AddDbgValue(SDV, N.getNode(), false); 1351 return true; 1352 } 1353 1354 // Special rules apply for the first dbg.values of parameter variables in a 1355 // function. Identify them by the fact they reference Argument Values, that 1356 // they're parameters, and they are parameters of the current function. We 1357 // need to let them dangle until they get an SDNode. 1358 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1359 !InstDL.getInlinedAt(); 1360 if (!IsParamOfFunc) { 1361 // The value is not used in this block yet (or it would have an SDNode). 1362 // We still want the value to appear for the user if possible -- if it has 1363 // an associated VReg, we can refer to that instead. 1364 auto VMI = FuncInfo.ValueMap.find(V); 1365 if (VMI != FuncInfo.ValueMap.end()) { 1366 unsigned Reg = VMI->second; 1367 // If this is a PHI node, it may be split up into several MI PHI nodes 1368 // (in FunctionLoweringInfo::set). 1369 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1370 V->getType(), None); 1371 if (RFV.occupiesMultipleRegs()) { 1372 unsigned Offset = 0; 1373 unsigned BitsToDescribe = 0; 1374 if (auto VarSize = Var->getSizeInBits()) 1375 BitsToDescribe = *VarSize; 1376 if (auto Fragment = Expr->getFragmentInfo()) 1377 BitsToDescribe = Fragment->SizeInBits; 1378 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1379 unsigned RegisterSize = RegAndSize.second; 1380 // Bail out if all bits are described already. 1381 if (Offset >= BitsToDescribe) 1382 break; 1383 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1384 ? BitsToDescribe - Offset 1385 : RegisterSize; 1386 auto FragmentExpr = DIExpression::createFragmentExpression( 1387 Expr, Offset, FragmentSize); 1388 if (!FragmentExpr) 1389 continue; 1390 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1391 false, dl, SDNodeOrder); 1392 DAG.AddDbgValue(SDV, nullptr, false); 1393 Offset += RegisterSize; 1394 } 1395 } else { 1396 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1397 DAG.AddDbgValue(SDV, nullptr, false); 1398 } 1399 return true; 1400 } 1401 } 1402 1403 return false; 1404 } 1405 1406 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1407 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1408 for (auto &Pair : DanglingDebugInfoMap) 1409 for (auto &DDI : Pair.second) 1410 salvageUnresolvedDbgValue(DDI); 1411 clearDanglingDebugInfo(); 1412 } 1413 1414 /// getCopyFromRegs - If there was virtual register allocated for the value V 1415 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1416 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1417 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1418 SDValue Result; 1419 1420 if (It != FuncInfo.ValueMap.end()) { 1421 Register InReg = It->second; 1422 1423 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1424 DAG.getDataLayout(), InReg, Ty, 1425 None); // This is not an ABI copy. 1426 SDValue Chain = DAG.getEntryNode(); 1427 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1428 V); 1429 resolveDanglingDebugInfo(V, Result); 1430 } 1431 1432 return Result; 1433 } 1434 1435 /// getValue - Return an SDValue for the given Value. 1436 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1437 // If we already have an SDValue for this value, use it. It's important 1438 // to do this first, so that we don't create a CopyFromReg if we already 1439 // have a regular SDValue. 1440 SDValue &N = NodeMap[V]; 1441 if (N.getNode()) return N; 1442 1443 // If there's a virtual register allocated and initialized for this 1444 // value, use it. 1445 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1446 return copyFromReg; 1447 1448 // Otherwise create a new SDValue and remember it. 1449 SDValue Val = getValueImpl(V); 1450 NodeMap[V] = Val; 1451 resolveDanglingDebugInfo(V, Val); 1452 return Val; 1453 } 1454 1455 /// getNonRegisterValue - Return an SDValue for the given Value, but 1456 /// don't look in FuncInfo.ValueMap for a virtual register. 1457 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1458 // If we already have an SDValue for this value, use it. 1459 SDValue &N = NodeMap[V]; 1460 if (N.getNode()) { 1461 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1462 // Remove the debug location from the node as the node is about to be used 1463 // in a location which may differ from the original debug location. This 1464 // is relevant to Constant and ConstantFP nodes because they can appear 1465 // as constant expressions inside PHI nodes. 1466 N->setDebugLoc(DebugLoc()); 1467 } 1468 return N; 1469 } 1470 1471 // Otherwise create a new SDValue and remember it. 1472 SDValue Val = getValueImpl(V); 1473 NodeMap[V] = Val; 1474 resolveDanglingDebugInfo(V, Val); 1475 return Val; 1476 } 1477 1478 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1479 /// Create an SDValue for the given value. 1480 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1481 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1482 1483 if (const Constant *C = dyn_cast<Constant>(V)) { 1484 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1485 1486 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1487 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1488 1489 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1490 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1491 1492 if (isa<ConstantPointerNull>(C)) { 1493 unsigned AS = V->getType()->getPointerAddressSpace(); 1494 return DAG.getConstant(0, getCurSDLoc(), 1495 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1496 } 1497 1498 if (match(C, m_VScale(DAG.getDataLayout()))) 1499 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1500 1501 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1502 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1503 1504 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1505 return DAG.getUNDEF(VT); 1506 1507 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1508 visit(CE->getOpcode(), *CE); 1509 SDValue N1 = NodeMap[V]; 1510 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1511 return N1; 1512 } 1513 1514 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1515 SmallVector<SDValue, 4> Constants; 1516 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1517 OI != OE; ++OI) { 1518 SDNode *Val = getValue(*OI).getNode(); 1519 // If the operand is an empty aggregate, there are no values. 1520 if (!Val) continue; 1521 // Add each leaf value from the operand to the Constants list 1522 // to form a flattened list of all the values. 1523 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1524 Constants.push_back(SDValue(Val, i)); 1525 } 1526 1527 return DAG.getMergeValues(Constants, getCurSDLoc()); 1528 } 1529 1530 if (const ConstantDataSequential *CDS = 1531 dyn_cast<ConstantDataSequential>(C)) { 1532 SmallVector<SDValue, 4> Ops; 1533 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1534 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1535 // Add each leaf value from the operand to the Constants list 1536 // to form a flattened list of all the values. 1537 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1538 Ops.push_back(SDValue(Val, i)); 1539 } 1540 1541 if (isa<ArrayType>(CDS->getType())) 1542 return DAG.getMergeValues(Ops, getCurSDLoc()); 1543 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1544 } 1545 1546 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1547 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1548 "Unknown struct or array constant!"); 1549 1550 SmallVector<EVT, 4> ValueVTs; 1551 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1552 unsigned NumElts = ValueVTs.size(); 1553 if (NumElts == 0) 1554 return SDValue(); // empty struct 1555 SmallVector<SDValue, 4> Constants(NumElts); 1556 for (unsigned i = 0; i != NumElts; ++i) { 1557 EVT EltVT = ValueVTs[i]; 1558 if (isa<UndefValue>(C)) 1559 Constants[i] = DAG.getUNDEF(EltVT); 1560 else if (EltVT.isFloatingPoint()) 1561 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1562 else 1563 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1564 } 1565 1566 return DAG.getMergeValues(Constants, getCurSDLoc()); 1567 } 1568 1569 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1570 return DAG.getBlockAddress(BA, VT); 1571 1572 VectorType *VecTy = cast<VectorType>(V->getType()); 1573 1574 // Now that we know the number and type of the elements, get that number of 1575 // elements into the Ops array based on what kind of constant it is. 1576 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1577 SmallVector<SDValue, 16> Ops; 1578 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1579 for (unsigned i = 0; i != NumElements; ++i) 1580 Ops.push_back(getValue(CV->getOperand(i))); 1581 1582 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1583 } else if (isa<ConstantAggregateZero>(C)) { 1584 EVT EltVT = 1585 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1586 1587 SDValue Op; 1588 if (EltVT.isFloatingPoint()) 1589 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1590 else 1591 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1592 1593 if (isa<ScalableVectorType>(VecTy)) 1594 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1595 else { 1596 SmallVector<SDValue, 16> Ops; 1597 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1598 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1599 } 1600 } 1601 llvm_unreachable("Unknown vector constant"); 1602 } 1603 1604 // If this is a static alloca, generate it as the frameindex instead of 1605 // computation. 1606 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1607 DenseMap<const AllocaInst*, int>::iterator SI = 1608 FuncInfo.StaticAllocaMap.find(AI); 1609 if (SI != FuncInfo.StaticAllocaMap.end()) 1610 return DAG.getFrameIndex(SI->second, 1611 TLI.getFrameIndexTy(DAG.getDataLayout())); 1612 } 1613 1614 // If this is an instruction which fast-isel has deferred, select it now. 1615 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1616 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1617 1618 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1619 Inst->getType(), getABIRegCopyCC(V)); 1620 SDValue Chain = DAG.getEntryNode(); 1621 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1622 } 1623 1624 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1625 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1626 } 1627 llvm_unreachable("Can't get register for value!"); 1628 } 1629 1630 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1631 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1632 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1633 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1634 bool IsSEH = isAsynchronousEHPersonality(Pers); 1635 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1636 if (!IsSEH) 1637 CatchPadMBB->setIsEHScopeEntry(); 1638 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1639 if (IsMSVCCXX || IsCoreCLR) 1640 CatchPadMBB->setIsEHFuncletEntry(); 1641 } 1642 1643 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1644 // Update machine-CFG edge. 1645 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1646 FuncInfo.MBB->addSuccessor(TargetMBB); 1647 1648 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1649 bool IsSEH = isAsynchronousEHPersonality(Pers); 1650 if (IsSEH) { 1651 // If this is not a fall-through branch or optimizations are switched off, 1652 // emit the branch. 1653 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1654 TM.getOptLevel() == CodeGenOpt::None) 1655 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1656 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1657 return; 1658 } 1659 1660 // Figure out the funclet membership for the catchret's successor. 1661 // This will be used by the FuncletLayout pass to determine how to order the 1662 // BB's. 1663 // A 'catchret' returns to the outer scope's color. 1664 Value *ParentPad = I.getCatchSwitchParentPad(); 1665 const BasicBlock *SuccessorColor; 1666 if (isa<ConstantTokenNone>(ParentPad)) 1667 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1668 else 1669 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1670 assert(SuccessorColor && "No parent funclet for catchret!"); 1671 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1672 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1673 1674 // Create the terminator node. 1675 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1676 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1677 DAG.getBasicBlock(SuccessorColorMBB)); 1678 DAG.setRoot(Ret); 1679 } 1680 1681 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1682 // Don't emit any special code for the cleanuppad instruction. It just marks 1683 // the start of an EH scope/funclet. 1684 FuncInfo.MBB->setIsEHScopeEntry(); 1685 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1686 if (Pers != EHPersonality::Wasm_CXX) { 1687 FuncInfo.MBB->setIsEHFuncletEntry(); 1688 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1689 } 1690 } 1691 1692 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1693 // the control flow always stops at the single catch pad, as it does for a 1694 // cleanup pad. In case the exception caught is not of the types the catch pad 1695 // catches, it will be rethrown by a rethrow. 1696 static void findWasmUnwindDestinations( 1697 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1698 BranchProbability Prob, 1699 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1700 &UnwindDests) { 1701 while (EHPadBB) { 1702 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1703 if (isa<CleanupPadInst>(Pad)) { 1704 // Stop on cleanup pads. 1705 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1706 UnwindDests.back().first->setIsEHScopeEntry(); 1707 break; 1708 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1709 // Add the catchpad handlers to the possible destinations. We don't 1710 // continue to the unwind destination of the catchswitch for wasm. 1711 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1712 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1713 UnwindDests.back().first->setIsEHScopeEntry(); 1714 } 1715 break; 1716 } else { 1717 continue; 1718 } 1719 } 1720 } 1721 1722 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1723 /// many places it could ultimately go. In the IR, we have a single unwind 1724 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1725 /// This function skips over imaginary basic blocks that hold catchswitch 1726 /// instructions, and finds all the "real" machine 1727 /// basic block destinations. As those destinations may not be successors of 1728 /// EHPadBB, here we also calculate the edge probability to those destinations. 1729 /// The passed-in Prob is the edge probability to EHPadBB. 1730 static void findUnwindDestinations( 1731 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1732 BranchProbability Prob, 1733 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1734 &UnwindDests) { 1735 EHPersonality Personality = 1736 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1737 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1738 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1739 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1740 bool IsSEH = isAsynchronousEHPersonality(Personality); 1741 1742 if (IsWasmCXX) { 1743 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1744 assert(UnwindDests.size() <= 1 && 1745 "There should be at most one unwind destination for wasm"); 1746 return; 1747 } 1748 1749 while (EHPadBB) { 1750 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1751 BasicBlock *NewEHPadBB = nullptr; 1752 if (isa<LandingPadInst>(Pad)) { 1753 // Stop on landingpads. They are not funclets. 1754 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1755 break; 1756 } else if (isa<CleanupPadInst>(Pad)) { 1757 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1758 // personalities. 1759 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1760 UnwindDests.back().first->setIsEHScopeEntry(); 1761 UnwindDests.back().first->setIsEHFuncletEntry(); 1762 break; 1763 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1764 // Add the catchpad handlers to the possible destinations. 1765 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1766 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1767 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1768 if (IsMSVCCXX || IsCoreCLR) 1769 UnwindDests.back().first->setIsEHFuncletEntry(); 1770 if (!IsSEH) 1771 UnwindDests.back().first->setIsEHScopeEntry(); 1772 } 1773 NewEHPadBB = CatchSwitch->getUnwindDest(); 1774 } else { 1775 continue; 1776 } 1777 1778 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1779 if (BPI && NewEHPadBB) 1780 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1781 EHPadBB = NewEHPadBB; 1782 } 1783 } 1784 1785 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1786 // Update successor info. 1787 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1788 auto UnwindDest = I.getUnwindDest(); 1789 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1790 BranchProbability UnwindDestProb = 1791 (BPI && UnwindDest) 1792 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1793 : BranchProbability::getZero(); 1794 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1795 for (auto &UnwindDest : UnwindDests) { 1796 UnwindDest.first->setIsEHPad(); 1797 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1798 } 1799 FuncInfo.MBB->normalizeSuccProbs(); 1800 1801 // Create the terminator node. 1802 SDValue Ret = 1803 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1804 DAG.setRoot(Ret); 1805 } 1806 1807 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1808 report_fatal_error("visitCatchSwitch not yet implemented!"); 1809 } 1810 1811 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1812 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1813 auto &DL = DAG.getDataLayout(); 1814 SDValue Chain = getControlRoot(); 1815 SmallVector<ISD::OutputArg, 8> Outs; 1816 SmallVector<SDValue, 8> OutVals; 1817 1818 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1819 // lower 1820 // 1821 // %val = call <ty> @llvm.experimental.deoptimize() 1822 // ret <ty> %val 1823 // 1824 // differently. 1825 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1826 LowerDeoptimizingReturn(); 1827 return; 1828 } 1829 1830 if (!FuncInfo.CanLowerReturn) { 1831 unsigned DemoteReg = FuncInfo.DemoteRegister; 1832 const Function *F = I.getParent()->getParent(); 1833 1834 // Emit a store of the return value through the virtual register. 1835 // Leave Outs empty so that LowerReturn won't try to load return 1836 // registers the usual way. 1837 SmallVector<EVT, 1> PtrValueVTs; 1838 ComputeValueVTs(TLI, DL, 1839 F->getReturnType()->getPointerTo( 1840 DAG.getDataLayout().getAllocaAddrSpace()), 1841 PtrValueVTs); 1842 1843 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1844 DemoteReg, PtrValueVTs[0]); 1845 SDValue RetOp = getValue(I.getOperand(0)); 1846 1847 SmallVector<EVT, 4> ValueVTs, MemVTs; 1848 SmallVector<uint64_t, 4> Offsets; 1849 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1850 &Offsets); 1851 unsigned NumValues = ValueVTs.size(); 1852 1853 SmallVector<SDValue, 4> Chains(NumValues); 1854 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1855 for (unsigned i = 0; i != NumValues; ++i) { 1856 // An aggregate return value cannot wrap around the address space, so 1857 // offsets to its parts don't wrap either. 1858 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1859 1860 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1861 if (MemVTs[i] != ValueVTs[i]) 1862 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1863 Chains[i] = DAG.getStore( 1864 Chain, getCurSDLoc(), Val, 1865 // FIXME: better loc info would be nice. 1866 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1867 commonAlignment(BaseAlign, Offsets[i])); 1868 } 1869 1870 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1871 MVT::Other, Chains); 1872 } else if (I.getNumOperands() != 0) { 1873 SmallVector<EVT, 4> ValueVTs; 1874 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1875 unsigned NumValues = ValueVTs.size(); 1876 if (NumValues) { 1877 SDValue RetOp = getValue(I.getOperand(0)); 1878 1879 const Function *F = I.getParent()->getParent(); 1880 1881 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1882 I.getOperand(0)->getType(), F->getCallingConv(), 1883 /*IsVarArg*/ false); 1884 1885 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1886 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1887 Attribute::SExt)) 1888 ExtendKind = ISD::SIGN_EXTEND; 1889 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1890 Attribute::ZExt)) 1891 ExtendKind = ISD::ZERO_EXTEND; 1892 1893 LLVMContext &Context = F->getContext(); 1894 bool RetInReg = F->getAttributes().hasAttribute( 1895 AttributeList::ReturnIndex, Attribute::InReg); 1896 1897 for (unsigned j = 0; j != NumValues; ++j) { 1898 EVT VT = ValueVTs[j]; 1899 1900 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1901 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1902 1903 CallingConv::ID CC = F->getCallingConv(); 1904 1905 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1906 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1907 SmallVector<SDValue, 4> Parts(NumParts); 1908 getCopyToParts(DAG, getCurSDLoc(), 1909 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1910 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1911 1912 // 'inreg' on function refers to return value 1913 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1914 if (RetInReg) 1915 Flags.setInReg(); 1916 1917 if (I.getOperand(0)->getType()->isPointerTy()) { 1918 Flags.setPointer(); 1919 Flags.setPointerAddrSpace( 1920 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1921 } 1922 1923 if (NeedsRegBlock) { 1924 Flags.setInConsecutiveRegs(); 1925 if (j == NumValues - 1) 1926 Flags.setInConsecutiveRegsLast(); 1927 } 1928 1929 // Propagate extension type if any 1930 if (ExtendKind == ISD::SIGN_EXTEND) 1931 Flags.setSExt(); 1932 else if (ExtendKind == ISD::ZERO_EXTEND) 1933 Flags.setZExt(); 1934 1935 for (unsigned i = 0; i < NumParts; ++i) { 1936 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1937 VT, /*isfixed=*/true, 0, 0)); 1938 OutVals.push_back(Parts[i]); 1939 } 1940 } 1941 } 1942 } 1943 1944 // Push in swifterror virtual register as the last element of Outs. This makes 1945 // sure swifterror virtual register will be returned in the swifterror 1946 // physical register. 1947 const Function *F = I.getParent()->getParent(); 1948 if (TLI.supportSwiftError() && 1949 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1950 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1951 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1952 Flags.setSwiftError(); 1953 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1954 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1955 true /*isfixed*/, 1 /*origidx*/, 1956 0 /*partOffs*/)); 1957 // Create SDNode for the swifterror virtual register. 1958 OutVals.push_back( 1959 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1960 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1961 EVT(TLI.getPointerTy(DL)))); 1962 } 1963 1964 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1965 CallingConv::ID CallConv = 1966 DAG.getMachineFunction().getFunction().getCallingConv(); 1967 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1968 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1969 1970 // Verify that the target's LowerReturn behaved as expected. 1971 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1972 "LowerReturn didn't return a valid chain!"); 1973 1974 // Update the DAG with the new chain value resulting from return lowering. 1975 DAG.setRoot(Chain); 1976 } 1977 1978 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1979 /// created for it, emit nodes to copy the value into the virtual 1980 /// registers. 1981 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1982 // Skip empty types 1983 if (V->getType()->isEmptyTy()) 1984 return; 1985 1986 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1987 if (VMI != FuncInfo.ValueMap.end()) { 1988 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1989 CopyValueToVirtualRegister(V, VMI->second); 1990 } 1991 } 1992 1993 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1994 /// the current basic block, add it to ValueMap now so that we'll get a 1995 /// CopyTo/FromReg. 1996 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1997 // No need to export constants. 1998 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1999 2000 // Already exported? 2001 if (FuncInfo.isExportedInst(V)) return; 2002 2003 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2004 CopyValueToVirtualRegister(V, Reg); 2005 } 2006 2007 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2008 const BasicBlock *FromBB) { 2009 // The operands of the setcc have to be in this block. We don't know 2010 // how to export them from some other block. 2011 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2012 // Can export from current BB. 2013 if (VI->getParent() == FromBB) 2014 return true; 2015 2016 // Is already exported, noop. 2017 return FuncInfo.isExportedInst(V); 2018 } 2019 2020 // If this is an argument, we can export it if the BB is the entry block or 2021 // if it is already exported. 2022 if (isa<Argument>(V)) { 2023 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2024 return true; 2025 2026 // Otherwise, can only export this if it is already exported. 2027 return FuncInfo.isExportedInst(V); 2028 } 2029 2030 // Otherwise, constants can always be exported. 2031 return true; 2032 } 2033 2034 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2035 BranchProbability 2036 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2037 const MachineBasicBlock *Dst) const { 2038 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2039 const BasicBlock *SrcBB = Src->getBasicBlock(); 2040 const BasicBlock *DstBB = Dst->getBasicBlock(); 2041 if (!BPI) { 2042 // If BPI is not available, set the default probability as 1 / N, where N is 2043 // the number of successors. 2044 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2045 return BranchProbability(1, SuccSize); 2046 } 2047 return BPI->getEdgeProbability(SrcBB, DstBB); 2048 } 2049 2050 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2051 MachineBasicBlock *Dst, 2052 BranchProbability Prob) { 2053 if (!FuncInfo.BPI) 2054 Src->addSuccessorWithoutProb(Dst); 2055 else { 2056 if (Prob.isUnknown()) 2057 Prob = getEdgeProbability(Src, Dst); 2058 Src->addSuccessor(Dst, Prob); 2059 } 2060 } 2061 2062 static bool InBlock(const Value *V, const BasicBlock *BB) { 2063 if (const Instruction *I = dyn_cast<Instruction>(V)) 2064 return I->getParent() == BB; 2065 return true; 2066 } 2067 2068 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2069 /// This function emits a branch and is used at the leaves of an OR or an 2070 /// AND operator tree. 2071 void 2072 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2073 MachineBasicBlock *TBB, 2074 MachineBasicBlock *FBB, 2075 MachineBasicBlock *CurBB, 2076 MachineBasicBlock *SwitchBB, 2077 BranchProbability TProb, 2078 BranchProbability FProb, 2079 bool InvertCond) { 2080 const BasicBlock *BB = CurBB->getBasicBlock(); 2081 2082 // If the leaf of the tree is a comparison, merge the condition into 2083 // the caseblock. 2084 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2085 // The operands of the cmp have to be in this block. We don't know 2086 // how to export them from some other block. If this is the first block 2087 // of the sequence, no exporting is needed. 2088 if (CurBB == SwitchBB || 2089 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2090 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2091 ISD::CondCode Condition; 2092 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2093 ICmpInst::Predicate Pred = 2094 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2095 Condition = getICmpCondCode(Pred); 2096 } else { 2097 const FCmpInst *FC = cast<FCmpInst>(Cond); 2098 FCmpInst::Predicate Pred = 2099 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2100 Condition = getFCmpCondCode(Pred); 2101 if (TM.Options.NoNaNsFPMath) 2102 Condition = getFCmpCodeWithoutNaN(Condition); 2103 } 2104 2105 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2106 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2107 SL->SwitchCases.push_back(CB); 2108 return; 2109 } 2110 } 2111 2112 // Create a CaseBlock record representing this branch. 2113 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2114 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2115 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2116 SL->SwitchCases.push_back(CB); 2117 } 2118 2119 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2120 MachineBasicBlock *TBB, 2121 MachineBasicBlock *FBB, 2122 MachineBasicBlock *CurBB, 2123 MachineBasicBlock *SwitchBB, 2124 Instruction::BinaryOps Opc, 2125 BranchProbability TProb, 2126 BranchProbability FProb, 2127 bool InvertCond) { 2128 // Skip over not part of the tree and remember to invert op and operands at 2129 // next level. 2130 Value *NotCond; 2131 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2132 InBlock(NotCond, CurBB->getBasicBlock())) { 2133 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2134 !InvertCond); 2135 return; 2136 } 2137 2138 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2139 // Compute the effective opcode for Cond, taking into account whether it needs 2140 // to be inverted, e.g. 2141 // and (not (or A, B)), C 2142 // gets lowered as 2143 // and (and (not A, not B), C) 2144 unsigned BOpc = 0; 2145 if (BOp) { 2146 BOpc = BOp->getOpcode(); 2147 if (InvertCond) { 2148 if (BOpc == Instruction::And) 2149 BOpc = Instruction::Or; 2150 else if (BOpc == Instruction::Or) 2151 BOpc = Instruction::And; 2152 } 2153 } 2154 2155 // If this node is not part of the or/and tree, emit it as a branch. 2156 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2157 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2158 BOp->getParent() != CurBB->getBasicBlock() || 2159 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2160 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2161 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2162 TProb, FProb, InvertCond); 2163 return; 2164 } 2165 2166 // Create TmpBB after CurBB. 2167 MachineFunction::iterator BBI(CurBB); 2168 MachineFunction &MF = DAG.getMachineFunction(); 2169 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2170 CurBB->getParent()->insert(++BBI, TmpBB); 2171 2172 if (Opc == Instruction::Or) { 2173 // Codegen X | Y as: 2174 // BB1: 2175 // jmp_if_X TBB 2176 // jmp TmpBB 2177 // TmpBB: 2178 // jmp_if_Y TBB 2179 // jmp FBB 2180 // 2181 2182 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2183 // The requirement is that 2184 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2185 // = TrueProb for original BB. 2186 // Assuming the original probabilities are A and B, one choice is to set 2187 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2188 // A/(1+B) and 2B/(1+B). This choice assumes that 2189 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2190 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2191 // TmpBB, but the math is more complicated. 2192 2193 auto NewTrueProb = TProb / 2; 2194 auto NewFalseProb = TProb / 2 + FProb; 2195 // Emit the LHS condition. 2196 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2197 NewTrueProb, NewFalseProb, InvertCond); 2198 2199 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2200 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2201 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2202 // Emit the RHS condition into TmpBB. 2203 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2204 Probs[0], Probs[1], InvertCond); 2205 } else { 2206 assert(Opc == Instruction::And && "Unknown merge op!"); 2207 // Codegen X & Y as: 2208 // BB1: 2209 // jmp_if_X TmpBB 2210 // jmp FBB 2211 // TmpBB: 2212 // jmp_if_Y TBB 2213 // jmp FBB 2214 // 2215 // This requires creation of TmpBB after CurBB. 2216 2217 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2218 // The requirement is that 2219 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2220 // = FalseProb for original BB. 2221 // Assuming the original probabilities are A and B, one choice is to set 2222 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2223 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2224 // TrueProb for BB1 * FalseProb for TmpBB. 2225 2226 auto NewTrueProb = TProb + FProb / 2; 2227 auto NewFalseProb = FProb / 2; 2228 // Emit the LHS condition. 2229 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2230 NewTrueProb, NewFalseProb, InvertCond); 2231 2232 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2233 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2234 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2235 // Emit the RHS condition into TmpBB. 2236 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2237 Probs[0], Probs[1], InvertCond); 2238 } 2239 } 2240 2241 /// If the set of cases should be emitted as a series of branches, return true. 2242 /// If we should emit this as a bunch of and/or'd together conditions, return 2243 /// false. 2244 bool 2245 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2246 if (Cases.size() != 2) return true; 2247 2248 // If this is two comparisons of the same values or'd or and'd together, they 2249 // will get folded into a single comparison, so don't emit two blocks. 2250 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2251 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2252 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2253 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2254 return false; 2255 } 2256 2257 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2258 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2259 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2260 Cases[0].CC == Cases[1].CC && 2261 isa<Constant>(Cases[0].CmpRHS) && 2262 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2263 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2264 return false; 2265 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2266 return false; 2267 } 2268 2269 return true; 2270 } 2271 2272 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2273 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2274 2275 // Update machine-CFG edges. 2276 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2277 2278 if (I.isUnconditional()) { 2279 // Update machine-CFG edges. 2280 BrMBB->addSuccessor(Succ0MBB); 2281 2282 // If this is not a fall-through branch or optimizations are switched off, 2283 // emit the branch. 2284 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2285 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2286 MVT::Other, getControlRoot(), 2287 DAG.getBasicBlock(Succ0MBB))); 2288 2289 return; 2290 } 2291 2292 // If this condition is one of the special cases we handle, do special stuff 2293 // now. 2294 const Value *CondVal = I.getCondition(); 2295 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2296 2297 // If this is a series of conditions that are or'd or and'd together, emit 2298 // this as a sequence of branches instead of setcc's with and/or operations. 2299 // As long as jumps are not expensive, this should improve performance. 2300 // For example, instead of something like: 2301 // cmp A, B 2302 // C = seteq 2303 // cmp D, E 2304 // F = setle 2305 // or C, F 2306 // jnz foo 2307 // Emit: 2308 // cmp A, B 2309 // je foo 2310 // cmp D, E 2311 // jle foo 2312 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2313 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2314 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2315 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2316 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2317 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2318 Opcode, 2319 getEdgeProbability(BrMBB, Succ0MBB), 2320 getEdgeProbability(BrMBB, Succ1MBB), 2321 /*InvertCond=*/false); 2322 // If the compares in later blocks need to use values not currently 2323 // exported from this block, export them now. This block should always 2324 // be the first entry. 2325 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2326 2327 // Allow some cases to be rejected. 2328 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2329 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2330 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2331 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2332 } 2333 2334 // Emit the branch for this block. 2335 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2336 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2337 return; 2338 } 2339 2340 // Okay, we decided not to do this, remove any inserted MBB's and clear 2341 // SwitchCases. 2342 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2343 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2344 2345 SL->SwitchCases.clear(); 2346 } 2347 } 2348 2349 // Create a CaseBlock record representing this branch. 2350 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2351 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2352 2353 // Use visitSwitchCase to actually insert the fast branch sequence for this 2354 // cond branch. 2355 visitSwitchCase(CB, BrMBB); 2356 } 2357 2358 /// visitSwitchCase - Emits the necessary code to represent a single node in 2359 /// the binary search tree resulting from lowering a switch instruction. 2360 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2361 MachineBasicBlock *SwitchBB) { 2362 SDValue Cond; 2363 SDValue CondLHS = getValue(CB.CmpLHS); 2364 SDLoc dl = CB.DL; 2365 2366 if (CB.CC == ISD::SETTRUE) { 2367 // Branch or fall through to TrueBB. 2368 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2369 SwitchBB->normalizeSuccProbs(); 2370 if (CB.TrueBB != NextBlock(SwitchBB)) { 2371 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2372 DAG.getBasicBlock(CB.TrueBB))); 2373 } 2374 return; 2375 } 2376 2377 auto &TLI = DAG.getTargetLoweringInfo(); 2378 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2379 2380 // Build the setcc now. 2381 if (!CB.CmpMHS) { 2382 // Fold "(X == true)" to X and "(X == false)" to !X to 2383 // handle common cases produced by branch lowering. 2384 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2385 CB.CC == ISD::SETEQ) 2386 Cond = CondLHS; 2387 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2388 CB.CC == ISD::SETEQ) { 2389 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2390 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2391 } else { 2392 SDValue CondRHS = getValue(CB.CmpRHS); 2393 2394 // If a pointer's DAG type is larger than its memory type then the DAG 2395 // values are zero-extended. This breaks signed comparisons so truncate 2396 // back to the underlying type before doing the compare. 2397 if (CondLHS.getValueType() != MemVT) { 2398 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2399 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2400 } 2401 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2402 } 2403 } else { 2404 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2405 2406 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2407 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2408 2409 SDValue CmpOp = getValue(CB.CmpMHS); 2410 EVT VT = CmpOp.getValueType(); 2411 2412 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2413 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2414 ISD::SETLE); 2415 } else { 2416 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2417 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2418 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2419 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2420 } 2421 } 2422 2423 // Update successor info 2424 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2425 // TrueBB and FalseBB are always different unless the incoming IR is 2426 // degenerate. This only happens when running llc on weird IR. 2427 if (CB.TrueBB != CB.FalseBB) 2428 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2429 SwitchBB->normalizeSuccProbs(); 2430 2431 // If the lhs block is the next block, invert the condition so that we can 2432 // fall through to the lhs instead of the rhs block. 2433 if (CB.TrueBB == NextBlock(SwitchBB)) { 2434 std::swap(CB.TrueBB, CB.FalseBB); 2435 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2436 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2437 } 2438 2439 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2440 MVT::Other, getControlRoot(), Cond, 2441 DAG.getBasicBlock(CB.TrueBB)); 2442 2443 // Insert the false branch. Do this even if it's a fall through branch, 2444 // this makes it easier to do DAG optimizations which require inverting 2445 // the branch condition. 2446 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2447 DAG.getBasicBlock(CB.FalseBB)); 2448 2449 DAG.setRoot(BrCond); 2450 } 2451 2452 /// visitJumpTable - Emit JumpTable node in the current MBB 2453 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2454 // Emit the code for the jump table 2455 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2456 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2457 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2458 JT.Reg, PTy); 2459 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2460 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2461 MVT::Other, Index.getValue(1), 2462 Table, Index); 2463 DAG.setRoot(BrJumpTable); 2464 } 2465 2466 /// visitJumpTableHeader - This function emits necessary code to produce index 2467 /// in the JumpTable from switch case. 2468 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2469 JumpTableHeader &JTH, 2470 MachineBasicBlock *SwitchBB) { 2471 SDLoc dl = getCurSDLoc(); 2472 2473 // Subtract the lowest switch case value from the value being switched on. 2474 SDValue SwitchOp = getValue(JTH.SValue); 2475 EVT VT = SwitchOp.getValueType(); 2476 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2477 DAG.getConstant(JTH.First, dl, VT)); 2478 2479 // The SDNode we just created, which holds the value being switched on minus 2480 // the smallest case value, needs to be copied to a virtual register so it 2481 // can be used as an index into the jump table in a subsequent basic block. 2482 // This value may be smaller or larger than the target's pointer type, and 2483 // therefore require extension or truncating. 2484 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2485 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2486 2487 unsigned JumpTableReg = 2488 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2489 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2490 JumpTableReg, SwitchOp); 2491 JT.Reg = JumpTableReg; 2492 2493 if (!JTH.OmitRangeCheck) { 2494 // Emit the range check for the jump table, and branch to the default block 2495 // for the switch statement if the value being switched on exceeds the 2496 // largest case in the switch. 2497 SDValue CMP = DAG.getSetCC( 2498 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2499 Sub.getValueType()), 2500 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2501 2502 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2503 MVT::Other, CopyTo, CMP, 2504 DAG.getBasicBlock(JT.Default)); 2505 2506 // Avoid emitting unnecessary branches to the next block. 2507 if (JT.MBB != NextBlock(SwitchBB)) 2508 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2509 DAG.getBasicBlock(JT.MBB)); 2510 2511 DAG.setRoot(BrCond); 2512 } else { 2513 // Avoid emitting unnecessary branches to the next block. 2514 if (JT.MBB != NextBlock(SwitchBB)) 2515 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2516 DAG.getBasicBlock(JT.MBB))); 2517 else 2518 DAG.setRoot(CopyTo); 2519 } 2520 } 2521 2522 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2523 /// variable if there exists one. 2524 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2525 SDValue &Chain) { 2526 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2527 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2528 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2529 MachineFunction &MF = DAG.getMachineFunction(); 2530 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2531 MachineSDNode *Node = 2532 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2533 if (Global) { 2534 MachinePointerInfo MPInfo(Global); 2535 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2536 MachineMemOperand::MODereferenceable; 2537 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2538 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2539 DAG.setNodeMemRefs(Node, {MemRef}); 2540 } 2541 if (PtrTy != PtrMemTy) 2542 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2543 return SDValue(Node, 0); 2544 } 2545 2546 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2547 /// tail spliced into a stack protector check success bb. 2548 /// 2549 /// For a high level explanation of how this fits into the stack protector 2550 /// generation see the comment on the declaration of class 2551 /// StackProtectorDescriptor. 2552 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2553 MachineBasicBlock *ParentBB) { 2554 2555 // First create the loads to the guard/stack slot for the comparison. 2556 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2557 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2558 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2559 2560 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2561 int FI = MFI.getStackProtectorIndex(); 2562 2563 SDValue Guard; 2564 SDLoc dl = getCurSDLoc(); 2565 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2566 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2567 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2568 2569 // Generate code to load the content of the guard slot. 2570 SDValue GuardVal = DAG.getLoad( 2571 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2572 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2573 MachineMemOperand::MOVolatile); 2574 2575 if (TLI.useStackGuardXorFP()) 2576 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2577 2578 // Retrieve guard check function, nullptr if instrumentation is inlined. 2579 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2580 // The target provides a guard check function to validate the guard value. 2581 // Generate a call to that function with the content of the guard slot as 2582 // argument. 2583 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2584 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2585 2586 TargetLowering::ArgListTy Args; 2587 TargetLowering::ArgListEntry Entry; 2588 Entry.Node = GuardVal; 2589 Entry.Ty = FnTy->getParamType(0); 2590 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2591 Entry.IsInReg = true; 2592 Args.push_back(Entry); 2593 2594 TargetLowering::CallLoweringInfo CLI(DAG); 2595 CLI.setDebugLoc(getCurSDLoc()) 2596 .setChain(DAG.getEntryNode()) 2597 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2598 getValue(GuardCheckFn), std::move(Args)); 2599 2600 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2601 DAG.setRoot(Result.second); 2602 return; 2603 } 2604 2605 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2606 // Otherwise, emit a volatile load to retrieve the stack guard value. 2607 SDValue Chain = DAG.getEntryNode(); 2608 if (TLI.useLoadStackGuardNode()) { 2609 Guard = getLoadStackGuard(DAG, dl, Chain); 2610 } else { 2611 const Value *IRGuard = TLI.getSDagStackGuard(M); 2612 SDValue GuardPtr = getValue(IRGuard); 2613 2614 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2615 MachinePointerInfo(IRGuard, 0), Align, 2616 MachineMemOperand::MOVolatile); 2617 } 2618 2619 // Perform the comparison via a getsetcc. 2620 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2621 *DAG.getContext(), 2622 Guard.getValueType()), 2623 Guard, GuardVal, ISD::SETNE); 2624 2625 // If the guard/stackslot do not equal, branch to failure MBB. 2626 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2627 MVT::Other, GuardVal.getOperand(0), 2628 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2629 // Otherwise branch to success MBB. 2630 SDValue Br = DAG.getNode(ISD::BR, dl, 2631 MVT::Other, BrCond, 2632 DAG.getBasicBlock(SPD.getSuccessMBB())); 2633 2634 DAG.setRoot(Br); 2635 } 2636 2637 /// Codegen the failure basic block for a stack protector check. 2638 /// 2639 /// A failure stack protector machine basic block consists simply of a call to 2640 /// __stack_chk_fail(). 2641 /// 2642 /// For a high level explanation of how this fits into the stack protector 2643 /// generation see the comment on the declaration of class 2644 /// StackProtectorDescriptor. 2645 void 2646 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2647 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2648 TargetLowering::MakeLibCallOptions CallOptions; 2649 CallOptions.setDiscardResult(true); 2650 SDValue Chain = 2651 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2652 None, CallOptions, getCurSDLoc()).second; 2653 // On PS4, the "return address" must still be within the calling function, 2654 // even if it's at the very end, so emit an explicit TRAP here. 2655 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2656 if (TM.getTargetTriple().isPS4CPU()) 2657 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2658 2659 DAG.setRoot(Chain); 2660 } 2661 2662 /// visitBitTestHeader - This function emits necessary code to produce value 2663 /// suitable for "bit tests" 2664 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2665 MachineBasicBlock *SwitchBB) { 2666 SDLoc dl = getCurSDLoc(); 2667 2668 // Subtract the minimum value. 2669 SDValue SwitchOp = getValue(B.SValue); 2670 EVT VT = SwitchOp.getValueType(); 2671 SDValue RangeSub = 2672 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2673 2674 // Determine the type of the test operands. 2675 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2676 bool UsePtrType = false; 2677 if (!TLI.isTypeLegal(VT)) { 2678 UsePtrType = true; 2679 } else { 2680 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2681 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2682 // Switch table case range are encoded into series of masks. 2683 // Just use pointer type, it's guaranteed to fit. 2684 UsePtrType = true; 2685 break; 2686 } 2687 } 2688 SDValue Sub = RangeSub; 2689 if (UsePtrType) { 2690 VT = TLI.getPointerTy(DAG.getDataLayout()); 2691 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2692 } 2693 2694 B.RegVT = VT.getSimpleVT(); 2695 B.Reg = FuncInfo.CreateReg(B.RegVT); 2696 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2697 2698 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2699 2700 if (!B.OmitRangeCheck) 2701 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2702 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2703 SwitchBB->normalizeSuccProbs(); 2704 2705 SDValue Root = CopyTo; 2706 if (!B.OmitRangeCheck) { 2707 // Conditional branch to the default block. 2708 SDValue RangeCmp = DAG.getSetCC(dl, 2709 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2710 RangeSub.getValueType()), 2711 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2712 ISD::SETUGT); 2713 2714 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2715 DAG.getBasicBlock(B.Default)); 2716 } 2717 2718 // Avoid emitting unnecessary branches to the next block. 2719 if (MBB != NextBlock(SwitchBB)) 2720 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2721 2722 DAG.setRoot(Root); 2723 } 2724 2725 /// visitBitTestCase - this function produces one "bit test" 2726 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2727 MachineBasicBlock* NextMBB, 2728 BranchProbability BranchProbToNext, 2729 unsigned Reg, 2730 BitTestCase &B, 2731 MachineBasicBlock *SwitchBB) { 2732 SDLoc dl = getCurSDLoc(); 2733 MVT VT = BB.RegVT; 2734 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2735 SDValue Cmp; 2736 unsigned PopCount = countPopulation(B.Mask); 2737 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2738 if (PopCount == 1) { 2739 // Testing for a single bit; just compare the shift count with what it 2740 // would need to be to shift a 1 bit in that position. 2741 Cmp = DAG.getSetCC( 2742 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2743 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2744 ISD::SETEQ); 2745 } else if (PopCount == BB.Range) { 2746 // There is only one zero bit in the range, test for it directly. 2747 Cmp = DAG.getSetCC( 2748 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2749 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2750 ISD::SETNE); 2751 } else { 2752 // Make desired shift 2753 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2754 DAG.getConstant(1, dl, VT), ShiftOp); 2755 2756 // Emit bit tests and jumps 2757 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2758 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2759 Cmp = DAG.getSetCC( 2760 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2761 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2762 } 2763 2764 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2765 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2766 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2767 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2768 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2769 // one as they are relative probabilities (and thus work more like weights), 2770 // and hence we need to normalize them to let the sum of them become one. 2771 SwitchBB->normalizeSuccProbs(); 2772 2773 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2774 MVT::Other, getControlRoot(), 2775 Cmp, DAG.getBasicBlock(B.TargetBB)); 2776 2777 // Avoid emitting unnecessary branches to the next block. 2778 if (NextMBB != NextBlock(SwitchBB)) 2779 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2780 DAG.getBasicBlock(NextMBB)); 2781 2782 DAG.setRoot(BrAnd); 2783 } 2784 2785 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2786 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2787 2788 // Retrieve successors. Look through artificial IR level blocks like 2789 // catchswitch for successors. 2790 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2791 const BasicBlock *EHPadBB = I.getSuccessor(1); 2792 2793 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2794 // have to do anything here to lower funclet bundles. 2795 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2796 LLVMContext::OB_gc_transition, 2797 LLVMContext::OB_gc_live, 2798 LLVMContext::OB_funclet, 2799 LLVMContext::OB_cfguardtarget}) && 2800 "Cannot lower invokes with arbitrary operand bundles yet!"); 2801 2802 const Value *Callee(I.getCalledOperand()); 2803 const Function *Fn = dyn_cast<Function>(Callee); 2804 if (isa<InlineAsm>(Callee)) 2805 visitInlineAsm(I); 2806 else if (Fn && Fn->isIntrinsic()) { 2807 switch (Fn->getIntrinsicID()) { 2808 default: 2809 llvm_unreachable("Cannot invoke this intrinsic"); 2810 case Intrinsic::donothing: 2811 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2812 break; 2813 case Intrinsic::experimental_patchpoint_void: 2814 case Intrinsic::experimental_patchpoint_i64: 2815 visitPatchpoint(I, EHPadBB); 2816 break; 2817 case Intrinsic::experimental_gc_statepoint: 2818 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2819 break; 2820 case Intrinsic::wasm_rethrow_in_catch: { 2821 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2822 // special because it can be invoked, so we manually lower it to a DAG 2823 // node here. 2824 SmallVector<SDValue, 8> Ops; 2825 Ops.push_back(getRoot()); // inchain 2826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2827 Ops.push_back( 2828 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2829 TLI.getPointerTy(DAG.getDataLayout()))); 2830 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2831 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2832 break; 2833 } 2834 } 2835 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2836 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2837 // Eventually we will support lowering the @llvm.experimental.deoptimize 2838 // intrinsic, and right now there are no plans to support other intrinsics 2839 // with deopt state. 2840 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2841 } else { 2842 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2843 } 2844 2845 // If the value of the invoke is used outside of its defining block, make it 2846 // available as a virtual register. 2847 // We already took care of the exported value for the statepoint instruction 2848 // during call to the LowerStatepoint. 2849 if (!isa<GCStatepointInst>(I)) { 2850 CopyToExportRegsIfNeeded(&I); 2851 } 2852 2853 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2854 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2855 BranchProbability EHPadBBProb = 2856 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2857 : BranchProbability::getZero(); 2858 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2859 2860 // Update successor info. 2861 addSuccessorWithProb(InvokeMBB, Return); 2862 for (auto &UnwindDest : UnwindDests) { 2863 UnwindDest.first->setIsEHPad(); 2864 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2865 } 2866 InvokeMBB->normalizeSuccProbs(); 2867 2868 // Drop into normal successor. 2869 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2870 DAG.getBasicBlock(Return))); 2871 } 2872 2873 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2874 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2875 2876 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2877 // have to do anything here to lower funclet bundles. 2878 assert(!I.hasOperandBundlesOtherThan( 2879 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2880 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2881 2882 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2883 visitInlineAsm(I); 2884 CopyToExportRegsIfNeeded(&I); 2885 2886 // Retrieve successors. 2887 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2888 Return->setInlineAsmBrDefaultTarget(); 2889 2890 // Update successor info. 2891 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2892 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2893 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2894 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2895 CallBrMBB->addInlineAsmBrIndirectTarget(Target); 2896 } 2897 CallBrMBB->normalizeSuccProbs(); 2898 2899 // Drop into default successor. 2900 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2901 MVT::Other, getControlRoot(), 2902 DAG.getBasicBlock(Return))); 2903 } 2904 2905 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2906 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2907 } 2908 2909 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2910 assert(FuncInfo.MBB->isEHPad() && 2911 "Call to landingpad not in landing pad!"); 2912 2913 // If there aren't registers to copy the values into (e.g., during SjLj 2914 // exceptions), then don't bother to create these DAG nodes. 2915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2916 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2917 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2918 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2919 return; 2920 2921 // If landingpad's return type is token type, we don't create DAG nodes 2922 // for its exception pointer and selector value. The extraction of exception 2923 // pointer or selector value from token type landingpads is not currently 2924 // supported. 2925 if (LP.getType()->isTokenTy()) 2926 return; 2927 2928 SmallVector<EVT, 2> ValueVTs; 2929 SDLoc dl = getCurSDLoc(); 2930 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2931 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2932 2933 // Get the two live-in registers as SDValues. The physregs have already been 2934 // copied into virtual registers. 2935 SDValue Ops[2]; 2936 if (FuncInfo.ExceptionPointerVirtReg) { 2937 Ops[0] = DAG.getZExtOrTrunc( 2938 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2939 FuncInfo.ExceptionPointerVirtReg, 2940 TLI.getPointerTy(DAG.getDataLayout())), 2941 dl, ValueVTs[0]); 2942 } else { 2943 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2944 } 2945 Ops[1] = DAG.getZExtOrTrunc( 2946 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2947 FuncInfo.ExceptionSelectorVirtReg, 2948 TLI.getPointerTy(DAG.getDataLayout())), 2949 dl, ValueVTs[1]); 2950 2951 // Merge into one. 2952 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2953 DAG.getVTList(ValueVTs), Ops); 2954 setValue(&LP, Res); 2955 } 2956 2957 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2958 MachineBasicBlock *Last) { 2959 // Update JTCases. 2960 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2961 if (SL->JTCases[i].first.HeaderBB == First) 2962 SL->JTCases[i].first.HeaderBB = Last; 2963 2964 // Update BitTestCases. 2965 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2966 if (SL->BitTestCases[i].Parent == First) 2967 SL->BitTestCases[i].Parent = Last; 2968 2969 // SelectionDAGISel::FinishBasicBlock will add PHI operands for the 2970 // successors of the fallthrough block. Here, we add PHI operands for the 2971 // successors of the INLINEASM_BR block itself. 2972 if (First->getFirstTerminator()->getOpcode() == TargetOpcode::INLINEASM_BR) 2973 for (std::pair<MachineInstr *, unsigned> &pair : FuncInfo.PHINodesToUpdate) 2974 if (First->isSuccessor(pair.first->getParent())) 2975 MachineInstrBuilder(*First->getParent(), pair.first) 2976 .addReg(pair.second) 2977 .addMBB(First); 2978 } 2979 2980 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2981 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2982 2983 // Update machine-CFG edges with unique successors. 2984 SmallSet<BasicBlock*, 32> Done; 2985 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2986 BasicBlock *BB = I.getSuccessor(i); 2987 bool Inserted = Done.insert(BB).second; 2988 if (!Inserted) 2989 continue; 2990 2991 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2992 addSuccessorWithProb(IndirectBrMBB, Succ); 2993 } 2994 IndirectBrMBB->normalizeSuccProbs(); 2995 2996 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2997 MVT::Other, getControlRoot(), 2998 getValue(I.getAddress()))); 2999 } 3000 3001 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3002 if (!DAG.getTarget().Options.TrapUnreachable) 3003 return; 3004 3005 // We may be able to ignore unreachable behind a noreturn call. 3006 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3007 const BasicBlock &BB = *I.getParent(); 3008 if (&I != &BB.front()) { 3009 BasicBlock::const_iterator PredI = 3010 std::prev(BasicBlock::const_iterator(&I)); 3011 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3012 if (Call->doesNotReturn()) 3013 return; 3014 } 3015 } 3016 } 3017 3018 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3019 } 3020 3021 void SelectionDAGBuilder::visitFSub(const User &I) { 3022 // -0.0 - X --> fneg 3023 Type *Ty = I.getType(); 3024 if (isa<Constant>(I.getOperand(0)) && 3025 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 3026 SDValue Op2 = getValue(I.getOperand(1)); 3027 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 3028 Op2.getValueType(), Op2)); 3029 return; 3030 } 3031 3032 visitBinary(I, ISD::FSUB); 3033 } 3034 3035 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3036 SDNodeFlags Flags; 3037 3038 SDValue Op = getValue(I.getOperand(0)); 3039 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3040 Op, Flags); 3041 setValue(&I, UnNodeValue); 3042 } 3043 3044 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3045 SDNodeFlags Flags; 3046 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3047 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3048 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3049 } 3050 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3051 Flags.setExact(ExactOp->isExact()); 3052 } 3053 3054 SDValue Op1 = getValue(I.getOperand(0)); 3055 SDValue Op2 = getValue(I.getOperand(1)); 3056 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3057 Op1, Op2, Flags); 3058 setValue(&I, BinNodeValue); 3059 } 3060 3061 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3062 SDValue Op1 = getValue(I.getOperand(0)); 3063 SDValue Op2 = getValue(I.getOperand(1)); 3064 3065 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3066 Op1.getValueType(), DAG.getDataLayout()); 3067 3068 // Coerce the shift amount to the right type if we can. 3069 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3070 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3071 unsigned Op2Size = Op2.getValueSizeInBits(); 3072 SDLoc DL = getCurSDLoc(); 3073 3074 // If the operand is smaller than the shift count type, promote it. 3075 if (ShiftSize > Op2Size) 3076 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3077 3078 // If the operand is larger than the shift count type but the shift 3079 // count type has enough bits to represent any shift value, truncate 3080 // it now. This is a common case and it exposes the truncate to 3081 // optimization early. 3082 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3083 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3084 // Otherwise we'll need to temporarily settle for some other convenient 3085 // type. Type legalization will make adjustments once the shiftee is split. 3086 else 3087 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3088 } 3089 3090 bool nuw = false; 3091 bool nsw = false; 3092 bool exact = false; 3093 3094 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3095 3096 if (const OverflowingBinaryOperator *OFBinOp = 3097 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3098 nuw = OFBinOp->hasNoUnsignedWrap(); 3099 nsw = OFBinOp->hasNoSignedWrap(); 3100 } 3101 if (const PossiblyExactOperator *ExactOp = 3102 dyn_cast<const PossiblyExactOperator>(&I)) 3103 exact = ExactOp->isExact(); 3104 } 3105 SDNodeFlags Flags; 3106 Flags.setExact(exact); 3107 Flags.setNoSignedWrap(nsw); 3108 Flags.setNoUnsignedWrap(nuw); 3109 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3110 Flags); 3111 setValue(&I, Res); 3112 } 3113 3114 void SelectionDAGBuilder::visitSDiv(const User &I) { 3115 SDValue Op1 = getValue(I.getOperand(0)); 3116 SDValue Op2 = getValue(I.getOperand(1)); 3117 3118 SDNodeFlags Flags; 3119 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3120 cast<PossiblyExactOperator>(&I)->isExact()); 3121 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3122 Op2, Flags)); 3123 } 3124 3125 void SelectionDAGBuilder::visitICmp(const User &I) { 3126 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3127 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3128 predicate = IC->getPredicate(); 3129 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3130 predicate = ICmpInst::Predicate(IC->getPredicate()); 3131 SDValue Op1 = getValue(I.getOperand(0)); 3132 SDValue Op2 = getValue(I.getOperand(1)); 3133 ISD::CondCode Opcode = getICmpCondCode(predicate); 3134 3135 auto &TLI = DAG.getTargetLoweringInfo(); 3136 EVT MemVT = 3137 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3138 3139 // If a pointer's DAG type is larger than its memory type then the DAG values 3140 // are zero-extended. This breaks signed comparisons so truncate back to the 3141 // underlying type before doing the compare. 3142 if (Op1.getValueType() != MemVT) { 3143 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3144 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3145 } 3146 3147 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3148 I.getType()); 3149 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3150 } 3151 3152 void SelectionDAGBuilder::visitFCmp(const User &I) { 3153 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3154 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3155 predicate = FC->getPredicate(); 3156 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3157 predicate = FCmpInst::Predicate(FC->getPredicate()); 3158 SDValue Op1 = getValue(I.getOperand(0)); 3159 SDValue Op2 = getValue(I.getOperand(1)); 3160 3161 ISD::CondCode Condition = getFCmpCondCode(predicate); 3162 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3163 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3164 Condition = getFCmpCodeWithoutNaN(Condition); 3165 3166 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3167 I.getType()); 3168 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3169 } 3170 3171 // Check if the condition of the select has one use or two users that are both 3172 // selects with the same condition. 3173 static bool hasOnlySelectUsers(const Value *Cond) { 3174 return llvm::all_of(Cond->users(), [](const Value *V) { 3175 return isa<SelectInst>(V); 3176 }); 3177 } 3178 3179 void SelectionDAGBuilder::visitSelect(const User &I) { 3180 SmallVector<EVT, 4> ValueVTs; 3181 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3182 ValueVTs); 3183 unsigned NumValues = ValueVTs.size(); 3184 if (NumValues == 0) return; 3185 3186 SmallVector<SDValue, 4> Values(NumValues); 3187 SDValue Cond = getValue(I.getOperand(0)); 3188 SDValue LHSVal = getValue(I.getOperand(1)); 3189 SDValue RHSVal = getValue(I.getOperand(2)); 3190 SmallVector<SDValue, 1> BaseOps(1, Cond); 3191 ISD::NodeType OpCode = 3192 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3193 3194 bool IsUnaryAbs = false; 3195 3196 // Min/max matching is only viable if all output VTs are the same. 3197 if (is_splat(ValueVTs)) { 3198 EVT VT = ValueVTs[0]; 3199 LLVMContext &Ctx = *DAG.getContext(); 3200 auto &TLI = DAG.getTargetLoweringInfo(); 3201 3202 // We care about the legality of the operation after it has been type 3203 // legalized. 3204 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3205 VT = TLI.getTypeToTransformTo(Ctx, VT); 3206 3207 // If the vselect is legal, assume we want to leave this as a vector setcc + 3208 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3209 // min/max is legal on the scalar type. 3210 bool UseScalarMinMax = VT.isVector() && 3211 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3212 3213 Value *LHS, *RHS; 3214 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3215 ISD::NodeType Opc = ISD::DELETED_NODE; 3216 switch (SPR.Flavor) { 3217 case SPF_UMAX: Opc = ISD::UMAX; break; 3218 case SPF_UMIN: Opc = ISD::UMIN; break; 3219 case SPF_SMAX: Opc = ISD::SMAX; break; 3220 case SPF_SMIN: Opc = ISD::SMIN; break; 3221 case SPF_FMINNUM: 3222 switch (SPR.NaNBehavior) { 3223 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3224 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3225 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3226 case SPNB_RETURNS_ANY: { 3227 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3228 Opc = ISD::FMINNUM; 3229 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3230 Opc = ISD::FMINIMUM; 3231 else if (UseScalarMinMax) 3232 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3233 ISD::FMINNUM : ISD::FMINIMUM; 3234 break; 3235 } 3236 } 3237 break; 3238 case SPF_FMAXNUM: 3239 switch (SPR.NaNBehavior) { 3240 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3241 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3242 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3243 case SPNB_RETURNS_ANY: 3244 3245 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3246 Opc = ISD::FMAXNUM; 3247 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3248 Opc = ISD::FMAXIMUM; 3249 else if (UseScalarMinMax) 3250 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3251 ISD::FMAXNUM : ISD::FMAXIMUM; 3252 break; 3253 } 3254 break; 3255 case SPF_ABS: 3256 IsUnaryAbs = true; 3257 Opc = ISD::ABS; 3258 break; 3259 case SPF_NABS: 3260 // TODO: we need to produce sub(0, abs(X)). 3261 default: break; 3262 } 3263 3264 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3265 (TLI.isOperationLegalOrCustom(Opc, VT) || 3266 (UseScalarMinMax && 3267 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3268 // If the underlying comparison instruction is used by any other 3269 // instruction, the consumed instructions won't be destroyed, so it is 3270 // not profitable to convert to a min/max. 3271 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3272 OpCode = Opc; 3273 LHSVal = getValue(LHS); 3274 RHSVal = getValue(RHS); 3275 BaseOps.clear(); 3276 } 3277 3278 if (IsUnaryAbs) { 3279 OpCode = Opc; 3280 LHSVal = getValue(LHS); 3281 BaseOps.clear(); 3282 } 3283 } 3284 3285 if (IsUnaryAbs) { 3286 for (unsigned i = 0; i != NumValues; ++i) { 3287 Values[i] = 3288 DAG.getNode(OpCode, getCurSDLoc(), 3289 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3290 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3291 } 3292 } else { 3293 for (unsigned i = 0; i != NumValues; ++i) { 3294 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3295 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3296 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3297 Values[i] = DAG.getNode( 3298 OpCode, getCurSDLoc(), 3299 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3300 } 3301 } 3302 3303 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3304 DAG.getVTList(ValueVTs), Values)); 3305 } 3306 3307 void SelectionDAGBuilder::visitTrunc(const User &I) { 3308 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3309 SDValue N = getValue(I.getOperand(0)); 3310 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3311 I.getType()); 3312 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3313 } 3314 3315 void SelectionDAGBuilder::visitZExt(const User &I) { 3316 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3317 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3318 SDValue N = getValue(I.getOperand(0)); 3319 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3320 I.getType()); 3321 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3322 } 3323 3324 void SelectionDAGBuilder::visitSExt(const User &I) { 3325 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3326 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3327 SDValue N = getValue(I.getOperand(0)); 3328 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3329 I.getType()); 3330 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3331 } 3332 3333 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3334 // FPTrunc is never a no-op cast, no need to check 3335 SDValue N = getValue(I.getOperand(0)); 3336 SDLoc dl = getCurSDLoc(); 3337 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3338 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3339 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3340 DAG.getTargetConstant( 3341 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3342 } 3343 3344 void SelectionDAGBuilder::visitFPExt(const User &I) { 3345 // FPExt is never a no-op cast, no need to check 3346 SDValue N = getValue(I.getOperand(0)); 3347 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3348 I.getType()); 3349 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3350 } 3351 3352 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3353 // FPToUI is never a no-op cast, no need to check 3354 SDValue N = getValue(I.getOperand(0)); 3355 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3356 I.getType()); 3357 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3358 } 3359 3360 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3361 // FPToSI is never a no-op cast, no need to check 3362 SDValue N = getValue(I.getOperand(0)); 3363 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3364 I.getType()); 3365 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3366 } 3367 3368 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3369 // UIToFP is never a no-op cast, no need to check 3370 SDValue N = getValue(I.getOperand(0)); 3371 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3372 I.getType()); 3373 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3374 } 3375 3376 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3377 // SIToFP is never a no-op cast, no need to check 3378 SDValue N = getValue(I.getOperand(0)); 3379 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3380 I.getType()); 3381 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3382 } 3383 3384 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3385 // What to do depends on the size of the integer and the size of the pointer. 3386 // We can either truncate, zero extend, or no-op, accordingly. 3387 SDValue N = getValue(I.getOperand(0)); 3388 auto &TLI = DAG.getTargetLoweringInfo(); 3389 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3390 I.getType()); 3391 EVT PtrMemVT = 3392 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3393 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3394 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3395 setValue(&I, N); 3396 } 3397 3398 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3399 // What to do depends on the size of the integer and the size of the pointer. 3400 // We can either truncate, zero extend, or no-op, accordingly. 3401 SDValue N = getValue(I.getOperand(0)); 3402 auto &TLI = DAG.getTargetLoweringInfo(); 3403 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3404 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3405 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3406 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3407 setValue(&I, N); 3408 } 3409 3410 void SelectionDAGBuilder::visitBitCast(const User &I) { 3411 SDValue N = getValue(I.getOperand(0)); 3412 SDLoc dl = getCurSDLoc(); 3413 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3414 I.getType()); 3415 3416 // BitCast assures us that source and destination are the same size so this is 3417 // either a BITCAST or a no-op. 3418 if (DestVT != N.getValueType()) 3419 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3420 DestVT, N)); // convert types. 3421 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3422 // might fold any kind of constant expression to an integer constant and that 3423 // is not what we are looking for. Only recognize a bitcast of a genuine 3424 // constant integer as an opaque constant. 3425 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3426 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3427 /*isOpaque*/true)); 3428 else 3429 setValue(&I, N); // noop cast. 3430 } 3431 3432 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3433 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3434 const Value *SV = I.getOperand(0); 3435 SDValue N = getValue(SV); 3436 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3437 3438 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3439 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3440 3441 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3442 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3443 3444 setValue(&I, N); 3445 } 3446 3447 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3449 SDValue InVec = getValue(I.getOperand(0)); 3450 SDValue InVal = getValue(I.getOperand(1)); 3451 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3452 TLI.getVectorIdxTy(DAG.getDataLayout())); 3453 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3454 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3455 InVec, InVal, InIdx)); 3456 } 3457 3458 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3459 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3460 SDValue InVec = getValue(I.getOperand(0)); 3461 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3462 TLI.getVectorIdxTy(DAG.getDataLayout())); 3463 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3464 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3465 InVec, InIdx)); 3466 } 3467 3468 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3469 SDValue Src1 = getValue(I.getOperand(0)); 3470 SDValue Src2 = getValue(I.getOperand(1)); 3471 ArrayRef<int> Mask; 3472 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3473 Mask = SVI->getShuffleMask(); 3474 else 3475 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3476 SDLoc DL = getCurSDLoc(); 3477 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3478 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3479 EVT SrcVT = Src1.getValueType(); 3480 3481 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3482 VT.isScalableVector()) { 3483 // Canonical splat form of first element of first input vector. 3484 SDValue FirstElt = 3485 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3486 DAG.getVectorIdxConstant(0, DL)); 3487 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3488 return; 3489 } 3490 3491 // For now, we only handle splats for scalable vectors. 3492 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3493 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3494 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3495 3496 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3497 unsigned MaskNumElts = Mask.size(); 3498 3499 if (SrcNumElts == MaskNumElts) { 3500 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3501 return; 3502 } 3503 3504 // Normalize the shuffle vector since mask and vector length don't match. 3505 if (SrcNumElts < MaskNumElts) { 3506 // Mask is longer than the source vectors. We can use concatenate vector to 3507 // make the mask and vectors lengths match. 3508 3509 if (MaskNumElts % SrcNumElts == 0) { 3510 // Mask length is a multiple of the source vector length. 3511 // Check if the shuffle is some kind of concatenation of the input 3512 // vectors. 3513 unsigned NumConcat = MaskNumElts / SrcNumElts; 3514 bool IsConcat = true; 3515 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3516 for (unsigned i = 0; i != MaskNumElts; ++i) { 3517 int Idx = Mask[i]; 3518 if (Idx < 0) 3519 continue; 3520 // Ensure the indices in each SrcVT sized piece are sequential and that 3521 // the same source is used for the whole piece. 3522 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3523 (ConcatSrcs[i / SrcNumElts] >= 0 && 3524 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3525 IsConcat = false; 3526 break; 3527 } 3528 // Remember which source this index came from. 3529 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3530 } 3531 3532 // The shuffle is concatenating multiple vectors together. Just emit 3533 // a CONCAT_VECTORS operation. 3534 if (IsConcat) { 3535 SmallVector<SDValue, 8> ConcatOps; 3536 for (auto Src : ConcatSrcs) { 3537 if (Src < 0) 3538 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3539 else if (Src == 0) 3540 ConcatOps.push_back(Src1); 3541 else 3542 ConcatOps.push_back(Src2); 3543 } 3544 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3545 return; 3546 } 3547 } 3548 3549 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3550 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3551 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3552 PaddedMaskNumElts); 3553 3554 // Pad both vectors with undefs to make them the same length as the mask. 3555 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3556 3557 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3558 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3559 MOps1[0] = Src1; 3560 MOps2[0] = Src2; 3561 3562 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3563 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3564 3565 // Readjust mask for new input vector length. 3566 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3567 for (unsigned i = 0; i != MaskNumElts; ++i) { 3568 int Idx = Mask[i]; 3569 if (Idx >= (int)SrcNumElts) 3570 Idx -= SrcNumElts - PaddedMaskNumElts; 3571 MappedOps[i] = Idx; 3572 } 3573 3574 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3575 3576 // If the concatenated vector was padded, extract a subvector with the 3577 // correct number of elements. 3578 if (MaskNumElts != PaddedMaskNumElts) 3579 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3580 DAG.getVectorIdxConstant(0, DL)); 3581 3582 setValue(&I, Result); 3583 return; 3584 } 3585 3586 if (SrcNumElts > MaskNumElts) { 3587 // Analyze the access pattern of the vector to see if we can extract 3588 // two subvectors and do the shuffle. 3589 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3590 bool CanExtract = true; 3591 for (int Idx : Mask) { 3592 unsigned Input = 0; 3593 if (Idx < 0) 3594 continue; 3595 3596 if (Idx >= (int)SrcNumElts) { 3597 Input = 1; 3598 Idx -= SrcNumElts; 3599 } 3600 3601 // If all the indices come from the same MaskNumElts sized portion of 3602 // the sources we can use extract. Also make sure the extract wouldn't 3603 // extract past the end of the source. 3604 int NewStartIdx = alignDown(Idx, MaskNumElts); 3605 if (NewStartIdx + MaskNumElts > SrcNumElts || 3606 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3607 CanExtract = false; 3608 // Make sure we always update StartIdx as we use it to track if all 3609 // elements are undef. 3610 StartIdx[Input] = NewStartIdx; 3611 } 3612 3613 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3614 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3615 return; 3616 } 3617 if (CanExtract) { 3618 // Extract appropriate subvector and generate a vector shuffle 3619 for (unsigned Input = 0; Input < 2; ++Input) { 3620 SDValue &Src = Input == 0 ? Src1 : Src2; 3621 if (StartIdx[Input] < 0) 3622 Src = DAG.getUNDEF(VT); 3623 else { 3624 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3625 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3626 } 3627 } 3628 3629 // Calculate new mask. 3630 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3631 for (int &Idx : MappedOps) { 3632 if (Idx >= (int)SrcNumElts) 3633 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3634 else if (Idx >= 0) 3635 Idx -= StartIdx[0]; 3636 } 3637 3638 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3639 return; 3640 } 3641 } 3642 3643 // We can't use either concat vectors or extract subvectors so fall back to 3644 // replacing the shuffle with extract and build vector. 3645 // to insert and build vector. 3646 EVT EltVT = VT.getVectorElementType(); 3647 SmallVector<SDValue,8> Ops; 3648 for (int Idx : Mask) { 3649 SDValue Res; 3650 3651 if (Idx < 0) { 3652 Res = DAG.getUNDEF(EltVT); 3653 } else { 3654 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3655 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3656 3657 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3658 DAG.getVectorIdxConstant(Idx, DL)); 3659 } 3660 3661 Ops.push_back(Res); 3662 } 3663 3664 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3665 } 3666 3667 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3668 ArrayRef<unsigned> Indices; 3669 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3670 Indices = IV->getIndices(); 3671 else 3672 Indices = cast<ConstantExpr>(&I)->getIndices(); 3673 3674 const Value *Op0 = I.getOperand(0); 3675 const Value *Op1 = I.getOperand(1); 3676 Type *AggTy = I.getType(); 3677 Type *ValTy = Op1->getType(); 3678 bool IntoUndef = isa<UndefValue>(Op0); 3679 bool FromUndef = isa<UndefValue>(Op1); 3680 3681 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3682 3683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3684 SmallVector<EVT, 4> AggValueVTs; 3685 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3686 SmallVector<EVT, 4> ValValueVTs; 3687 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3688 3689 unsigned NumAggValues = AggValueVTs.size(); 3690 unsigned NumValValues = ValValueVTs.size(); 3691 SmallVector<SDValue, 4> Values(NumAggValues); 3692 3693 // Ignore an insertvalue that produces an empty object 3694 if (!NumAggValues) { 3695 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3696 return; 3697 } 3698 3699 SDValue Agg = getValue(Op0); 3700 unsigned i = 0; 3701 // Copy the beginning value(s) from the original aggregate. 3702 for (; i != LinearIndex; ++i) 3703 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3704 SDValue(Agg.getNode(), Agg.getResNo() + i); 3705 // Copy values from the inserted value(s). 3706 if (NumValValues) { 3707 SDValue Val = getValue(Op1); 3708 for (; i != LinearIndex + NumValValues; ++i) 3709 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3710 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3711 } 3712 // Copy remaining value(s) from the original aggregate. 3713 for (; i != NumAggValues; ++i) 3714 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3715 SDValue(Agg.getNode(), Agg.getResNo() + i); 3716 3717 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3718 DAG.getVTList(AggValueVTs), Values)); 3719 } 3720 3721 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3722 ArrayRef<unsigned> Indices; 3723 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3724 Indices = EV->getIndices(); 3725 else 3726 Indices = cast<ConstantExpr>(&I)->getIndices(); 3727 3728 const Value *Op0 = I.getOperand(0); 3729 Type *AggTy = Op0->getType(); 3730 Type *ValTy = I.getType(); 3731 bool OutOfUndef = isa<UndefValue>(Op0); 3732 3733 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3734 3735 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3736 SmallVector<EVT, 4> ValValueVTs; 3737 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3738 3739 unsigned NumValValues = ValValueVTs.size(); 3740 3741 // Ignore a extractvalue that produces an empty object 3742 if (!NumValValues) { 3743 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3744 return; 3745 } 3746 3747 SmallVector<SDValue, 4> Values(NumValValues); 3748 3749 SDValue Agg = getValue(Op0); 3750 // Copy out the selected value(s). 3751 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3752 Values[i - LinearIndex] = 3753 OutOfUndef ? 3754 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3755 SDValue(Agg.getNode(), Agg.getResNo() + i); 3756 3757 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3758 DAG.getVTList(ValValueVTs), Values)); 3759 } 3760 3761 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3762 Value *Op0 = I.getOperand(0); 3763 // Note that the pointer operand may be a vector of pointers. Take the scalar 3764 // element which holds a pointer. 3765 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3766 SDValue N = getValue(Op0); 3767 SDLoc dl = getCurSDLoc(); 3768 auto &TLI = DAG.getTargetLoweringInfo(); 3769 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3770 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3771 3772 // Normalize Vector GEP - all scalar operands should be converted to the 3773 // splat vector. 3774 bool IsVectorGEP = I.getType()->isVectorTy(); 3775 ElementCount VectorElementCount = 3776 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3777 : ElementCount(0, false); 3778 3779 if (IsVectorGEP && !N.getValueType().isVector()) { 3780 LLVMContext &Context = *DAG.getContext(); 3781 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3782 if (VectorElementCount.Scalable) 3783 N = DAG.getSplatVector(VT, dl, N); 3784 else 3785 N = DAG.getSplatBuildVector(VT, dl, N); 3786 } 3787 3788 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3789 GTI != E; ++GTI) { 3790 const Value *Idx = GTI.getOperand(); 3791 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3792 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3793 if (Field) { 3794 // N = N + Offset 3795 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3796 3797 // In an inbounds GEP with an offset that is nonnegative even when 3798 // interpreted as signed, assume there is no unsigned overflow. 3799 SDNodeFlags Flags; 3800 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3801 Flags.setNoUnsignedWrap(true); 3802 3803 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3804 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3805 } 3806 } else { 3807 // IdxSize is the width of the arithmetic according to IR semantics. 3808 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3809 // (and fix up the result later). 3810 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3811 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3812 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3813 // We intentionally mask away the high bits here; ElementSize may not 3814 // fit in IdxTy. 3815 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3816 bool ElementScalable = ElementSize.isScalable(); 3817 3818 // If this is a scalar constant or a splat vector of constants, 3819 // handle it quickly. 3820 const auto *C = dyn_cast<Constant>(Idx); 3821 if (C && isa<VectorType>(C->getType())) 3822 C = C->getSplatValue(); 3823 3824 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3825 if (CI && CI->isZero()) 3826 continue; 3827 if (CI && !ElementScalable) { 3828 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3829 LLVMContext &Context = *DAG.getContext(); 3830 SDValue OffsVal; 3831 if (IsVectorGEP) 3832 OffsVal = DAG.getConstant( 3833 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3834 else 3835 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3836 3837 // In an inbounds GEP with an offset that is nonnegative even when 3838 // interpreted as signed, assume there is no unsigned overflow. 3839 SDNodeFlags Flags; 3840 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3841 Flags.setNoUnsignedWrap(true); 3842 3843 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3844 3845 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3846 continue; 3847 } 3848 3849 // N = N + Idx * ElementMul; 3850 SDValue IdxN = getValue(Idx); 3851 3852 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3853 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3854 VectorElementCount); 3855 if (VectorElementCount.Scalable) 3856 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3857 else 3858 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3859 } 3860 3861 // If the index is smaller or larger than intptr_t, truncate or extend 3862 // it. 3863 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3864 3865 if (ElementScalable) { 3866 EVT VScaleTy = N.getValueType().getScalarType(); 3867 SDValue VScale = DAG.getNode( 3868 ISD::VSCALE, dl, VScaleTy, 3869 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3870 if (IsVectorGEP) 3871 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3872 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3873 } else { 3874 // If this is a multiply by a power of two, turn it into a shl 3875 // immediately. This is a very common case. 3876 if (ElementMul != 1) { 3877 if (ElementMul.isPowerOf2()) { 3878 unsigned Amt = ElementMul.logBase2(); 3879 IdxN = DAG.getNode(ISD::SHL, dl, 3880 N.getValueType(), IdxN, 3881 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3882 } else { 3883 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3884 IdxN.getValueType()); 3885 IdxN = DAG.getNode(ISD::MUL, dl, 3886 N.getValueType(), IdxN, Scale); 3887 } 3888 } 3889 } 3890 3891 N = DAG.getNode(ISD::ADD, dl, 3892 N.getValueType(), N, IdxN); 3893 } 3894 } 3895 3896 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3897 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3898 3899 setValue(&I, N); 3900 } 3901 3902 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3903 // If this is a fixed sized alloca in the entry block of the function, 3904 // allocate it statically on the stack. 3905 if (FuncInfo.StaticAllocaMap.count(&I)) 3906 return; // getValue will auto-populate this. 3907 3908 SDLoc dl = getCurSDLoc(); 3909 Type *Ty = I.getAllocatedType(); 3910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3911 auto &DL = DAG.getDataLayout(); 3912 uint64_t TySize = DL.getTypeAllocSize(Ty); 3913 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3914 3915 SDValue AllocSize = getValue(I.getArraySize()); 3916 3917 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3918 if (AllocSize.getValueType() != IntPtr) 3919 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3920 3921 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3922 AllocSize, 3923 DAG.getConstant(TySize, dl, IntPtr)); 3924 3925 // Handle alignment. If the requested alignment is less than or equal to 3926 // the stack alignment, ignore it. If the size is greater than or equal to 3927 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3928 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3929 if (*Alignment <= StackAlign) 3930 Alignment = None; 3931 3932 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3933 // Round the size of the allocation up to the stack alignment size 3934 // by add SA-1 to the size. This doesn't overflow because we're computing 3935 // an address inside an alloca. 3936 SDNodeFlags Flags; 3937 Flags.setNoUnsignedWrap(true); 3938 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3939 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3940 3941 // Mask out the low bits for alignment purposes. 3942 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3943 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3944 3945 SDValue Ops[] = { 3946 getRoot(), AllocSize, 3947 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3948 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3949 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3950 setValue(&I, DSA); 3951 DAG.setRoot(DSA.getValue(1)); 3952 3953 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3954 } 3955 3956 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3957 if (I.isAtomic()) 3958 return visitAtomicLoad(I); 3959 3960 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3961 const Value *SV = I.getOperand(0); 3962 if (TLI.supportSwiftError()) { 3963 // Swifterror values can come from either a function parameter with 3964 // swifterror attribute or an alloca with swifterror attribute. 3965 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3966 if (Arg->hasSwiftErrorAttr()) 3967 return visitLoadFromSwiftError(I); 3968 } 3969 3970 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3971 if (Alloca->isSwiftError()) 3972 return visitLoadFromSwiftError(I); 3973 } 3974 } 3975 3976 SDValue Ptr = getValue(SV); 3977 3978 Type *Ty = I.getType(); 3979 Align Alignment = I.getAlign(); 3980 3981 AAMDNodes AAInfo; 3982 I.getAAMetadata(AAInfo); 3983 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3984 3985 SmallVector<EVT, 4> ValueVTs, MemVTs; 3986 SmallVector<uint64_t, 4> Offsets; 3987 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3988 unsigned NumValues = ValueVTs.size(); 3989 if (NumValues == 0) 3990 return; 3991 3992 bool isVolatile = I.isVolatile(); 3993 3994 SDValue Root; 3995 bool ConstantMemory = false; 3996 if (isVolatile) 3997 // Serialize volatile loads with other side effects. 3998 Root = getRoot(); 3999 else if (NumValues > MaxParallelChains) 4000 Root = getMemoryRoot(); 4001 else if (AA && 4002 AA->pointsToConstantMemory(MemoryLocation( 4003 SV, 4004 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4005 AAInfo))) { 4006 // Do not serialize (non-volatile) loads of constant memory with anything. 4007 Root = DAG.getEntryNode(); 4008 ConstantMemory = true; 4009 } else { 4010 // Do not serialize non-volatile loads against each other. 4011 Root = DAG.getRoot(); 4012 } 4013 4014 SDLoc dl = getCurSDLoc(); 4015 4016 if (isVolatile) 4017 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4018 4019 // An aggregate load cannot wrap around the address space, so offsets to its 4020 // parts don't wrap either. 4021 SDNodeFlags Flags; 4022 Flags.setNoUnsignedWrap(true); 4023 4024 SmallVector<SDValue, 4> Values(NumValues); 4025 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4026 EVT PtrVT = Ptr.getValueType(); 4027 4028 MachineMemOperand::Flags MMOFlags 4029 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4030 4031 unsigned ChainI = 0; 4032 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4033 // Serializing loads here may result in excessive register pressure, and 4034 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4035 // could recover a bit by hoisting nodes upward in the chain by recognizing 4036 // they are side-effect free or do not alias. The optimizer should really 4037 // avoid this case by converting large object/array copies to llvm.memcpy 4038 // (MaxParallelChains should always remain as failsafe). 4039 if (ChainI == MaxParallelChains) { 4040 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4041 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4042 makeArrayRef(Chains.data(), ChainI)); 4043 Root = Chain; 4044 ChainI = 0; 4045 } 4046 SDValue A = DAG.getNode(ISD::ADD, dl, 4047 PtrVT, Ptr, 4048 DAG.getConstant(Offsets[i], dl, PtrVT), 4049 Flags); 4050 4051 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4052 MachinePointerInfo(SV, Offsets[i]), Alignment, 4053 MMOFlags, AAInfo, Ranges); 4054 Chains[ChainI] = L.getValue(1); 4055 4056 if (MemVTs[i] != ValueVTs[i]) 4057 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4058 4059 Values[i] = L; 4060 } 4061 4062 if (!ConstantMemory) { 4063 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4064 makeArrayRef(Chains.data(), ChainI)); 4065 if (isVolatile) 4066 DAG.setRoot(Chain); 4067 else 4068 PendingLoads.push_back(Chain); 4069 } 4070 4071 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4072 DAG.getVTList(ValueVTs), Values)); 4073 } 4074 4075 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4076 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4077 "call visitStoreToSwiftError when backend supports swifterror"); 4078 4079 SmallVector<EVT, 4> ValueVTs; 4080 SmallVector<uint64_t, 4> Offsets; 4081 const Value *SrcV = I.getOperand(0); 4082 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4083 SrcV->getType(), ValueVTs, &Offsets); 4084 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4085 "expect a single EVT for swifterror"); 4086 4087 SDValue Src = getValue(SrcV); 4088 // Create a virtual register, then update the virtual register. 4089 Register VReg = 4090 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4091 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4092 // Chain can be getRoot or getControlRoot. 4093 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4094 SDValue(Src.getNode(), Src.getResNo())); 4095 DAG.setRoot(CopyNode); 4096 } 4097 4098 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4099 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4100 "call visitLoadFromSwiftError when backend supports swifterror"); 4101 4102 assert(!I.isVolatile() && 4103 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4104 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4105 "Support volatile, non temporal, invariant for load_from_swift_error"); 4106 4107 const Value *SV = I.getOperand(0); 4108 Type *Ty = I.getType(); 4109 AAMDNodes AAInfo; 4110 I.getAAMetadata(AAInfo); 4111 assert( 4112 (!AA || 4113 !AA->pointsToConstantMemory(MemoryLocation( 4114 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4115 AAInfo))) && 4116 "load_from_swift_error should not be constant memory"); 4117 4118 SmallVector<EVT, 4> ValueVTs; 4119 SmallVector<uint64_t, 4> Offsets; 4120 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4121 ValueVTs, &Offsets); 4122 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4123 "expect a single EVT for swifterror"); 4124 4125 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4126 SDValue L = DAG.getCopyFromReg( 4127 getRoot(), getCurSDLoc(), 4128 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4129 4130 setValue(&I, L); 4131 } 4132 4133 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4134 if (I.isAtomic()) 4135 return visitAtomicStore(I); 4136 4137 const Value *SrcV = I.getOperand(0); 4138 const Value *PtrV = I.getOperand(1); 4139 4140 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4141 if (TLI.supportSwiftError()) { 4142 // Swifterror values can come from either a function parameter with 4143 // swifterror attribute or an alloca with swifterror attribute. 4144 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4145 if (Arg->hasSwiftErrorAttr()) 4146 return visitStoreToSwiftError(I); 4147 } 4148 4149 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4150 if (Alloca->isSwiftError()) 4151 return visitStoreToSwiftError(I); 4152 } 4153 } 4154 4155 SmallVector<EVT, 4> ValueVTs, MemVTs; 4156 SmallVector<uint64_t, 4> Offsets; 4157 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4158 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4159 unsigned NumValues = ValueVTs.size(); 4160 if (NumValues == 0) 4161 return; 4162 4163 // Get the lowered operands. Note that we do this after 4164 // checking if NumResults is zero, because with zero results 4165 // the operands won't have values in the map. 4166 SDValue Src = getValue(SrcV); 4167 SDValue Ptr = getValue(PtrV); 4168 4169 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4170 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4171 SDLoc dl = getCurSDLoc(); 4172 Align Alignment = I.getAlign(); 4173 AAMDNodes AAInfo; 4174 I.getAAMetadata(AAInfo); 4175 4176 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4177 4178 // An aggregate load cannot wrap around the address space, so offsets to its 4179 // parts don't wrap either. 4180 SDNodeFlags Flags; 4181 Flags.setNoUnsignedWrap(true); 4182 4183 unsigned ChainI = 0; 4184 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4185 // See visitLoad comments. 4186 if (ChainI == MaxParallelChains) { 4187 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4188 makeArrayRef(Chains.data(), ChainI)); 4189 Root = Chain; 4190 ChainI = 0; 4191 } 4192 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4193 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4194 if (MemVTs[i] != ValueVTs[i]) 4195 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4196 SDValue St = 4197 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4198 Alignment, MMOFlags, AAInfo); 4199 Chains[ChainI] = St; 4200 } 4201 4202 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4203 makeArrayRef(Chains.data(), ChainI)); 4204 DAG.setRoot(StoreNode); 4205 } 4206 4207 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4208 bool IsCompressing) { 4209 SDLoc sdl = getCurSDLoc(); 4210 4211 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4212 MaybeAlign &Alignment) { 4213 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4214 Src0 = I.getArgOperand(0); 4215 Ptr = I.getArgOperand(1); 4216 Alignment = 4217 MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4218 Mask = I.getArgOperand(3); 4219 }; 4220 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4221 MaybeAlign &Alignment) { 4222 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4223 Src0 = I.getArgOperand(0); 4224 Ptr = I.getArgOperand(1); 4225 Mask = I.getArgOperand(2); 4226 Alignment = None; 4227 }; 4228 4229 Value *PtrOperand, *MaskOperand, *Src0Operand; 4230 MaybeAlign Alignment; 4231 if (IsCompressing) 4232 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4233 else 4234 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4235 4236 SDValue Ptr = getValue(PtrOperand); 4237 SDValue Src0 = getValue(Src0Operand); 4238 SDValue Mask = getValue(MaskOperand); 4239 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4240 4241 EVT VT = Src0.getValueType(); 4242 if (!Alignment) 4243 Alignment = DAG.getEVTAlign(VT); 4244 4245 AAMDNodes AAInfo; 4246 I.getAAMetadata(AAInfo); 4247 4248 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4249 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4250 // TODO: Make MachineMemOperands aware of scalable 4251 // vectors. 4252 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4253 SDValue StoreNode = 4254 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4255 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4256 DAG.setRoot(StoreNode); 4257 setValue(&I, StoreNode); 4258 } 4259 4260 // Get a uniform base for the Gather/Scatter intrinsic. 4261 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4262 // We try to represent it as a base pointer + vector of indices. 4263 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4264 // The first operand of the GEP may be a single pointer or a vector of pointers 4265 // Example: 4266 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4267 // or 4268 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4269 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4270 // 4271 // When the first GEP operand is a single pointer - it is the uniform base we 4272 // are looking for. If first operand of the GEP is a splat vector - we 4273 // extract the splat value and use it as a uniform base. 4274 // In all other cases the function returns 'false'. 4275 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4276 ISD::MemIndexType &IndexType, SDValue &Scale, 4277 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4278 SelectionDAG& DAG = SDB->DAG; 4279 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4280 const DataLayout &DL = DAG.getDataLayout(); 4281 4282 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4283 4284 // Handle splat constant pointer. 4285 if (auto *C = dyn_cast<Constant>(Ptr)) { 4286 C = C->getSplatValue(); 4287 if (!C) 4288 return false; 4289 4290 Base = SDB->getValue(C); 4291 4292 unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements(); 4293 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4294 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4295 IndexType = ISD::SIGNED_SCALED; 4296 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4297 return true; 4298 } 4299 4300 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4301 if (!GEP || GEP->getParent() != CurBB) 4302 return false; 4303 4304 if (GEP->getNumOperands() != 2) 4305 return false; 4306 4307 const Value *BasePtr = GEP->getPointerOperand(); 4308 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4309 4310 // Make sure the base is scalar and the index is a vector. 4311 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4312 return false; 4313 4314 Base = SDB->getValue(BasePtr); 4315 Index = SDB->getValue(IndexVal); 4316 IndexType = ISD::SIGNED_SCALED; 4317 Scale = DAG.getTargetConstant( 4318 DL.getTypeAllocSize(GEP->getResultElementType()), 4319 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4320 return true; 4321 } 4322 4323 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4324 SDLoc sdl = getCurSDLoc(); 4325 4326 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4327 const Value *Ptr = I.getArgOperand(1); 4328 SDValue Src0 = getValue(I.getArgOperand(0)); 4329 SDValue Mask = getValue(I.getArgOperand(3)); 4330 EVT VT = Src0.getValueType(); 4331 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); 4332 if (!Alignment) 4333 Alignment = DAG.getEVTAlign(VT); 4334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4335 4336 AAMDNodes AAInfo; 4337 I.getAAMetadata(AAInfo); 4338 4339 SDValue Base; 4340 SDValue Index; 4341 ISD::MemIndexType IndexType; 4342 SDValue Scale; 4343 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4344 I.getParent()); 4345 4346 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4347 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4348 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4349 // TODO: Make MachineMemOperands aware of scalable 4350 // vectors. 4351 MemoryLocation::UnknownSize, *Alignment, AAInfo); 4352 if (!UniformBase) { 4353 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4354 Index = getValue(Ptr); 4355 IndexType = ISD::SIGNED_SCALED; 4356 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4357 } 4358 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4359 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4360 Ops, MMO, IndexType); 4361 DAG.setRoot(Scatter); 4362 setValue(&I, Scatter); 4363 } 4364 4365 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4366 SDLoc sdl = getCurSDLoc(); 4367 4368 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4369 MaybeAlign &Alignment) { 4370 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4371 Ptr = I.getArgOperand(0); 4372 Alignment = 4373 MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4374 Mask = I.getArgOperand(2); 4375 Src0 = I.getArgOperand(3); 4376 }; 4377 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4378 MaybeAlign &Alignment) { 4379 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4380 Ptr = I.getArgOperand(0); 4381 Alignment = None; 4382 Mask = I.getArgOperand(1); 4383 Src0 = I.getArgOperand(2); 4384 }; 4385 4386 Value *PtrOperand, *MaskOperand, *Src0Operand; 4387 MaybeAlign Alignment; 4388 if (IsExpanding) 4389 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4390 else 4391 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4392 4393 SDValue Ptr = getValue(PtrOperand); 4394 SDValue Src0 = getValue(Src0Operand); 4395 SDValue Mask = getValue(MaskOperand); 4396 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4397 4398 EVT VT = Src0.getValueType(); 4399 if (!Alignment) 4400 Alignment = DAG.getEVTAlign(VT); 4401 4402 AAMDNodes AAInfo; 4403 I.getAAMetadata(AAInfo); 4404 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4405 4406 // Do not serialize masked loads of constant memory with anything. 4407 MemoryLocation ML; 4408 if (VT.isScalableVector()) 4409 ML = MemoryLocation(PtrOperand); 4410 else 4411 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4412 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4413 AAInfo); 4414 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4415 4416 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4417 4418 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4419 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4420 // TODO: Make MachineMemOperands aware of scalable 4421 // vectors. 4422 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4423 4424 SDValue Load = 4425 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4426 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4427 if (AddToChain) 4428 PendingLoads.push_back(Load.getValue(1)); 4429 setValue(&I, Load); 4430 } 4431 4432 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4433 SDLoc sdl = getCurSDLoc(); 4434 4435 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4436 const Value *Ptr = I.getArgOperand(0); 4437 SDValue Src0 = getValue(I.getArgOperand(3)); 4438 SDValue Mask = getValue(I.getArgOperand(2)); 4439 4440 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4441 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4442 MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); 4443 if (!Alignment) 4444 Alignment = DAG.getEVTAlign(VT); 4445 4446 AAMDNodes AAInfo; 4447 I.getAAMetadata(AAInfo); 4448 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4449 4450 SDValue Root = DAG.getRoot(); 4451 SDValue Base; 4452 SDValue Index; 4453 ISD::MemIndexType IndexType; 4454 SDValue Scale; 4455 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4456 I.getParent()); 4457 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4458 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4459 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4460 // TODO: Make MachineMemOperands aware of scalable 4461 // vectors. 4462 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges); 4463 4464 if (!UniformBase) { 4465 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4466 Index = getValue(Ptr); 4467 IndexType = ISD::SIGNED_SCALED; 4468 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4469 } 4470 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4471 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4472 Ops, MMO, IndexType); 4473 4474 PendingLoads.push_back(Gather.getValue(1)); 4475 setValue(&I, Gather); 4476 } 4477 4478 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4479 SDLoc dl = getCurSDLoc(); 4480 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4481 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4482 SyncScope::ID SSID = I.getSyncScopeID(); 4483 4484 SDValue InChain = getRoot(); 4485 4486 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4487 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4488 4489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4490 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4491 4492 MachineFunction &MF = DAG.getMachineFunction(); 4493 MachineMemOperand *MMO = MF.getMachineMemOperand( 4494 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4495 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4496 FailureOrdering); 4497 4498 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4499 dl, MemVT, VTs, InChain, 4500 getValue(I.getPointerOperand()), 4501 getValue(I.getCompareOperand()), 4502 getValue(I.getNewValOperand()), MMO); 4503 4504 SDValue OutChain = L.getValue(2); 4505 4506 setValue(&I, L); 4507 DAG.setRoot(OutChain); 4508 } 4509 4510 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4511 SDLoc dl = getCurSDLoc(); 4512 ISD::NodeType NT; 4513 switch (I.getOperation()) { 4514 default: llvm_unreachable("Unknown atomicrmw operation"); 4515 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4516 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4517 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4518 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4519 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4520 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4521 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4522 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4523 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4524 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4525 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4526 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4527 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4528 } 4529 AtomicOrdering Ordering = I.getOrdering(); 4530 SyncScope::ID SSID = I.getSyncScopeID(); 4531 4532 SDValue InChain = getRoot(); 4533 4534 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4536 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4537 4538 MachineFunction &MF = DAG.getMachineFunction(); 4539 MachineMemOperand *MMO = MF.getMachineMemOperand( 4540 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4541 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4542 4543 SDValue L = 4544 DAG.getAtomic(NT, dl, MemVT, InChain, 4545 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4546 MMO); 4547 4548 SDValue OutChain = L.getValue(1); 4549 4550 setValue(&I, L); 4551 DAG.setRoot(OutChain); 4552 } 4553 4554 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4555 SDLoc dl = getCurSDLoc(); 4556 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4557 SDValue Ops[3]; 4558 Ops[0] = getRoot(); 4559 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4560 TLI.getFenceOperandTy(DAG.getDataLayout())); 4561 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4562 TLI.getFenceOperandTy(DAG.getDataLayout())); 4563 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4564 } 4565 4566 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4567 SDLoc dl = getCurSDLoc(); 4568 AtomicOrdering Order = I.getOrdering(); 4569 SyncScope::ID SSID = I.getSyncScopeID(); 4570 4571 SDValue InChain = getRoot(); 4572 4573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4574 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4575 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4576 4577 if (!TLI.supportsUnalignedAtomics() && 4578 I.getAlignment() < MemVT.getSizeInBits() / 8) 4579 report_fatal_error("Cannot generate unaligned atomic load"); 4580 4581 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4582 4583 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4584 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4585 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4586 4587 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4588 4589 SDValue Ptr = getValue(I.getPointerOperand()); 4590 4591 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4592 // TODO: Once this is better exercised by tests, it should be merged with 4593 // the normal path for loads to prevent future divergence. 4594 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4595 if (MemVT != VT) 4596 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4597 4598 setValue(&I, L); 4599 SDValue OutChain = L.getValue(1); 4600 if (!I.isUnordered()) 4601 DAG.setRoot(OutChain); 4602 else 4603 PendingLoads.push_back(OutChain); 4604 return; 4605 } 4606 4607 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4608 Ptr, MMO); 4609 4610 SDValue OutChain = L.getValue(1); 4611 if (MemVT != VT) 4612 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4613 4614 setValue(&I, L); 4615 DAG.setRoot(OutChain); 4616 } 4617 4618 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4619 SDLoc dl = getCurSDLoc(); 4620 4621 AtomicOrdering Ordering = I.getOrdering(); 4622 SyncScope::ID SSID = I.getSyncScopeID(); 4623 4624 SDValue InChain = getRoot(); 4625 4626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4627 EVT MemVT = 4628 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4629 4630 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4631 report_fatal_error("Cannot generate unaligned atomic store"); 4632 4633 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4634 4635 MachineFunction &MF = DAG.getMachineFunction(); 4636 MachineMemOperand *MMO = MF.getMachineMemOperand( 4637 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4638 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4639 4640 SDValue Val = getValue(I.getValueOperand()); 4641 if (Val.getValueType() != MemVT) 4642 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4643 SDValue Ptr = getValue(I.getPointerOperand()); 4644 4645 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4646 // TODO: Once this is better exercised by tests, it should be merged with 4647 // the normal path for stores to prevent future divergence. 4648 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4649 DAG.setRoot(S); 4650 return; 4651 } 4652 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4653 Ptr, Val, MMO); 4654 4655 4656 DAG.setRoot(OutChain); 4657 } 4658 4659 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4660 /// node. 4661 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4662 unsigned Intrinsic) { 4663 // Ignore the callsite's attributes. A specific call site may be marked with 4664 // readnone, but the lowering code will expect the chain based on the 4665 // definition. 4666 const Function *F = I.getCalledFunction(); 4667 bool HasChain = !F->doesNotAccessMemory(); 4668 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4669 4670 // Build the operand list. 4671 SmallVector<SDValue, 8> Ops; 4672 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4673 if (OnlyLoad) { 4674 // We don't need to serialize loads against other loads. 4675 Ops.push_back(DAG.getRoot()); 4676 } else { 4677 Ops.push_back(getRoot()); 4678 } 4679 } 4680 4681 // Info is set by getTgtMemInstrinsic 4682 TargetLowering::IntrinsicInfo Info; 4683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4684 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4685 DAG.getMachineFunction(), 4686 Intrinsic); 4687 4688 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4689 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4690 Info.opc == ISD::INTRINSIC_W_CHAIN) 4691 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4692 TLI.getPointerTy(DAG.getDataLayout()))); 4693 4694 // Add all operands of the call to the operand list. 4695 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4696 const Value *Arg = I.getArgOperand(i); 4697 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4698 Ops.push_back(getValue(Arg)); 4699 continue; 4700 } 4701 4702 // Use TargetConstant instead of a regular constant for immarg. 4703 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4704 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4705 assert(CI->getBitWidth() <= 64 && 4706 "large intrinsic immediates not handled"); 4707 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4708 } else { 4709 Ops.push_back( 4710 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4711 } 4712 } 4713 4714 SmallVector<EVT, 4> ValueVTs; 4715 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4716 4717 if (HasChain) 4718 ValueVTs.push_back(MVT::Other); 4719 4720 SDVTList VTs = DAG.getVTList(ValueVTs); 4721 4722 // Create the node. 4723 SDValue Result; 4724 if (IsTgtIntrinsic) { 4725 // This is target intrinsic that touches memory 4726 AAMDNodes AAInfo; 4727 I.getAAMetadata(AAInfo); 4728 Result = 4729 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4730 MachinePointerInfo(Info.ptrVal, Info.offset), 4731 Info.align, Info.flags, Info.size, AAInfo); 4732 } else if (!HasChain) { 4733 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4734 } else if (!I.getType()->isVoidTy()) { 4735 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4736 } else { 4737 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4738 } 4739 4740 if (HasChain) { 4741 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4742 if (OnlyLoad) 4743 PendingLoads.push_back(Chain); 4744 else 4745 DAG.setRoot(Chain); 4746 } 4747 4748 if (!I.getType()->isVoidTy()) { 4749 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4750 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4751 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4752 } else 4753 Result = lowerRangeToAssertZExt(DAG, I, Result); 4754 4755 MaybeAlign Alignment = I.getRetAlign(); 4756 if (!Alignment) 4757 Alignment = F->getAttributes().getRetAlignment(); 4758 // Insert `assertalign` node if there's an alignment. 4759 if (InsertAssertAlign && Alignment) { 4760 Result = 4761 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4762 } 4763 4764 setValue(&I, Result); 4765 } 4766 } 4767 4768 /// GetSignificand - Get the significand and build it into a floating-point 4769 /// number with exponent of 1: 4770 /// 4771 /// Op = (Op & 0x007fffff) | 0x3f800000; 4772 /// 4773 /// where Op is the hexadecimal representation of floating point value. 4774 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4775 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4776 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4777 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4778 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4779 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4780 } 4781 4782 /// GetExponent - Get the exponent: 4783 /// 4784 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4785 /// 4786 /// where Op is the hexadecimal representation of floating point value. 4787 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4788 const TargetLowering &TLI, const SDLoc &dl) { 4789 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4790 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4791 SDValue t1 = DAG.getNode( 4792 ISD::SRL, dl, MVT::i32, t0, 4793 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4794 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4795 DAG.getConstant(127, dl, MVT::i32)); 4796 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4797 } 4798 4799 /// getF32Constant - Get 32-bit floating point constant. 4800 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4801 const SDLoc &dl) { 4802 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4803 MVT::f32); 4804 } 4805 4806 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4807 SelectionDAG &DAG) { 4808 // TODO: What fast-math-flags should be set on the floating-point nodes? 4809 4810 // IntegerPartOfX = ((int32_t)(t0); 4811 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4812 4813 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4814 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4815 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4816 4817 // IntegerPartOfX <<= 23; 4818 IntegerPartOfX = DAG.getNode( 4819 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4820 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4821 DAG.getDataLayout()))); 4822 4823 SDValue TwoToFractionalPartOfX; 4824 if (LimitFloatPrecision <= 6) { 4825 // For floating-point precision of 6: 4826 // 4827 // TwoToFractionalPartOfX = 4828 // 0.997535578f + 4829 // (0.735607626f + 0.252464424f * x) * x; 4830 // 4831 // error 0.0144103317, which is 6 bits 4832 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4833 getF32Constant(DAG, 0x3e814304, dl)); 4834 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4835 getF32Constant(DAG, 0x3f3c50c8, dl)); 4836 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4837 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4838 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4839 } else if (LimitFloatPrecision <= 12) { 4840 // For floating-point precision of 12: 4841 // 4842 // TwoToFractionalPartOfX = 4843 // 0.999892986f + 4844 // (0.696457318f + 4845 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4846 // 4847 // error 0.000107046256, which is 13 to 14 bits 4848 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4849 getF32Constant(DAG, 0x3da235e3, dl)); 4850 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4851 getF32Constant(DAG, 0x3e65b8f3, dl)); 4852 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4853 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4854 getF32Constant(DAG, 0x3f324b07, dl)); 4855 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4856 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4857 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4858 } else { // LimitFloatPrecision <= 18 4859 // For floating-point precision of 18: 4860 // 4861 // TwoToFractionalPartOfX = 4862 // 0.999999982f + 4863 // (0.693148872f + 4864 // (0.240227044f + 4865 // (0.554906021e-1f + 4866 // (0.961591928e-2f + 4867 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4868 // error 2.47208000*10^(-7), which is better than 18 bits 4869 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4870 getF32Constant(DAG, 0x3924b03e, dl)); 4871 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4872 getF32Constant(DAG, 0x3ab24b87, dl)); 4873 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4874 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4875 getF32Constant(DAG, 0x3c1d8c17, dl)); 4876 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4877 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4878 getF32Constant(DAG, 0x3d634a1d, dl)); 4879 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4880 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4881 getF32Constant(DAG, 0x3e75fe14, dl)); 4882 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4883 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4884 getF32Constant(DAG, 0x3f317234, dl)); 4885 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4886 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4887 getF32Constant(DAG, 0x3f800000, dl)); 4888 } 4889 4890 // Add the exponent into the result in integer domain. 4891 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4892 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4893 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4894 } 4895 4896 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4897 /// limited-precision mode. 4898 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4899 const TargetLowering &TLI) { 4900 if (Op.getValueType() == MVT::f32 && 4901 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4902 4903 // Put the exponent in the right bit position for later addition to the 4904 // final result: 4905 // 4906 // t0 = Op * log2(e) 4907 4908 // TODO: What fast-math-flags should be set here? 4909 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4910 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4911 return getLimitedPrecisionExp2(t0, dl, DAG); 4912 } 4913 4914 // No special expansion. 4915 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4916 } 4917 4918 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4919 /// limited-precision mode. 4920 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4921 const TargetLowering &TLI) { 4922 // TODO: What fast-math-flags should be set on the floating-point nodes? 4923 4924 if (Op.getValueType() == MVT::f32 && 4925 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4926 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4927 4928 // Scale the exponent by log(2). 4929 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4930 SDValue LogOfExponent = 4931 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4932 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4933 4934 // Get the significand and build it into a floating-point number with 4935 // exponent of 1. 4936 SDValue X = GetSignificand(DAG, Op1, dl); 4937 4938 SDValue LogOfMantissa; 4939 if (LimitFloatPrecision <= 6) { 4940 // For floating-point precision of 6: 4941 // 4942 // LogofMantissa = 4943 // -1.1609546f + 4944 // (1.4034025f - 0.23903021f * x) * x; 4945 // 4946 // error 0.0034276066, which is better than 8 bits 4947 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4948 getF32Constant(DAG, 0xbe74c456, dl)); 4949 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4950 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4951 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4952 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4953 getF32Constant(DAG, 0x3f949a29, dl)); 4954 } else if (LimitFloatPrecision <= 12) { 4955 // For floating-point precision of 12: 4956 // 4957 // LogOfMantissa = 4958 // -1.7417939f + 4959 // (2.8212026f + 4960 // (-1.4699568f + 4961 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4962 // 4963 // error 0.000061011436, which is 14 bits 4964 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4965 getF32Constant(DAG, 0xbd67b6d6, dl)); 4966 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4967 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4968 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4969 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4970 getF32Constant(DAG, 0x3fbc278b, dl)); 4971 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4972 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4973 getF32Constant(DAG, 0x40348e95, dl)); 4974 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4975 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4976 getF32Constant(DAG, 0x3fdef31a, dl)); 4977 } else { // LimitFloatPrecision <= 18 4978 // For floating-point precision of 18: 4979 // 4980 // LogOfMantissa = 4981 // -2.1072184f + 4982 // (4.2372794f + 4983 // (-3.7029485f + 4984 // (2.2781945f + 4985 // (-0.87823314f + 4986 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4987 // 4988 // error 0.0000023660568, which is better than 18 bits 4989 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4990 getF32Constant(DAG, 0xbc91e5ac, dl)); 4991 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4992 getF32Constant(DAG, 0x3e4350aa, dl)); 4993 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4994 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4995 getF32Constant(DAG, 0x3f60d3e3, dl)); 4996 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4997 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4998 getF32Constant(DAG, 0x4011cdf0, dl)); 4999 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5000 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5001 getF32Constant(DAG, 0x406cfd1c, dl)); 5002 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5003 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5004 getF32Constant(DAG, 0x408797cb, dl)); 5005 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5006 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5007 getF32Constant(DAG, 0x4006dcab, dl)); 5008 } 5009 5010 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5011 } 5012 5013 // No special expansion. 5014 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5015 } 5016 5017 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5018 /// limited-precision mode. 5019 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5020 const TargetLowering &TLI) { 5021 // TODO: What fast-math-flags should be set on the floating-point nodes? 5022 5023 if (Op.getValueType() == MVT::f32 && 5024 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5025 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5026 5027 // Get the exponent. 5028 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5029 5030 // Get the significand and build it into a floating-point number with 5031 // exponent of 1. 5032 SDValue X = GetSignificand(DAG, Op1, dl); 5033 5034 // Different possible minimax approximations of significand in 5035 // floating-point for various degrees of accuracy over [1,2]. 5036 SDValue Log2ofMantissa; 5037 if (LimitFloatPrecision <= 6) { 5038 // For floating-point precision of 6: 5039 // 5040 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5041 // 5042 // error 0.0049451742, which is more than 7 bits 5043 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5044 getF32Constant(DAG, 0xbeb08fe0, dl)); 5045 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5046 getF32Constant(DAG, 0x40019463, dl)); 5047 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5048 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5049 getF32Constant(DAG, 0x3fd6633d, dl)); 5050 } else if (LimitFloatPrecision <= 12) { 5051 // For floating-point precision of 12: 5052 // 5053 // Log2ofMantissa = 5054 // -2.51285454f + 5055 // (4.07009056f + 5056 // (-2.12067489f + 5057 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5058 // 5059 // error 0.0000876136000, which is better than 13 bits 5060 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5061 getF32Constant(DAG, 0xbda7262e, dl)); 5062 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5063 getF32Constant(DAG, 0x3f25280b, dl)); 5064 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5065 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5066 getF32Constant(DAG, 0x4007b923, dl)); 5067 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5068 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5069 getF32Constant(DAG, 0x40823e2f, dl)); 5070 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5071 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5072 getF32Constant(DAG, 0x4020d29c, dl)); 5073 } else { // LimitFloatPrecision <= 18 5074 // For floating-point precision of 18: 5075 // 5076 // Log2ofMantissa = 5077 // -3.0400495f + 5078 // (6.1129976f + 5079 // (-5.3420409f + 5080 // (3.2865683f + 5081 // (-1.2669343f + 5082 // (0.27515199f - 5083 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5084 // 5085 // error 0.0000018516, which is better than 18 bits 5086 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5087 getF32Constant(DAG, 0xbcd2769e, dl)); 5088 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5089 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5090 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5091 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5092 getF32Constant(DAG, 0x3fa22ae7, dl)); 5093 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5094 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5095 getF32Constant(DAG, 0x40525723, dl)); 5096 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5097 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5098 getF32Constant(DAG, 0x40aaf200, dl)); 5099 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5100 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5101 getF32Constant(DAG, 0x40c39dad, dl)); 5102 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5103 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5104 getF32Constant(DAG, 0x4042902c, dl)); 5105 } 5106 5107 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5108 } 5109 5110 // No special expansion. 5111 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5112 } 5113 5114 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5115 /// limited-precision mode. 5116 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5117 const TargetLowering &TLI) { 5118 // TODO: What fast-math-flags should be set on the floating-point nodes? 5119 5120 if (Op.getValueType() == MVT::f32 && 5121 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5122 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5123 5124 // Scale the exponent by log10(2) [0.30102999f]. 5125 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5126 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5127 getF32Constant(DAG, 0x3e9a209a, dl)); 5128 5129 // Get the significand and build it into a floating-point number with 5130 // exponent of 1. 5131 SDValue X = GetSignificand(DAG, Op1, dl); 5132 5133 SDValue Log10ofMantissa; 5134 if (LimitFloatPrecision <= 6) { 5135 // For floating-point precision of 6: 5136 // 5137 // Log10ofMantissa = 5138 // -0.50419619f + 5139 // (0.60948995f - 0.10380950f * x) * x; 5140 // 5141 // error 0.0014886165, which is 6 bits 5142 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5143 getF32Constant(DAG, 0xbdd49a13, dl)); 5144 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5145 getF32Constant(DAG, 0x3f1c0789, dl)); 5146 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5147 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5148 getF32Constant(DAG, 0x3f011300, dl)); 5149 } else if (LimitFloatPrecision <= 12) { 5150 // For floating-point precision of 12: 5151 // 5152 // Log10ofMantissa = 5153 // -0.64831180f + 5154 // (0.91751397f + 5155 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5156 // 5157 // error 0.00019228036, which is better than 12 bits 5158 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5159 getF32Constant(DAG, 0x3d431f31, dl)); 5160 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5161 getF32Constant(DAG, 0x3ea21fb2, dl)); 5162 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5163 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5164 getF32Constant(DAG, 0x3f6ae232, dl)); 5165 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5166 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5167 getF32Constant(DAG, 0x3f25f7c3, dl)); 5168 } else { // LimitFloatPrecision <= 18 5169 // For floating-point precision of 18: 5170 // 5171 // Log10ofMantissa = 5172 // -0.84299375f + 5173 // (1.5327582f + 5174 // (-1.0688956f + 5175 // (0.49102474f + 5176 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5177 // 5178 // error 0.0000037995730, which is better than 18 bits 5179 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5180 getF32Constant(DAG, 0x3c5d51ce, dl)); 5181 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5182 getF32Constant(DAG, 0x3e00685a, dl)); 5183 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5184 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5185 getF32Constant(DAG, 0x3efb6798, dl)); 5186 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5187 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5188 getF32Constant(DAG, 0x3f88d192, dl)); 5189 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5190 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5191 getF32Constant(DAG, 0x3fc4316c, dl)); 5192 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5193 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5194 getF32Constant(DAG, 0x3f57ce70, dl)); 5195 } 5196 5197 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5198 } 5199 5200 // No special expansion. 5201 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5202 } 5203 5204 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5205 /// limited-precision mode. 5206 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5207 const TargetLowering &TLI) { 5208 if (Op.getValueType() == MVT::f32 && 5209 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5210 return getLimitedPrecisionExp2(Op, dl, DAG); 5211 5212 // No special expansion. 5213 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5214 } 5215 5216 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5217 /// limited-precision mode with x == 10.0f. 5218 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5219 SelectionDAG &DAG, const TargetLowering &TLI) { 5220 bool IsExp10 = false; 5221 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5222 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5223 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5224 APFloat Ten(10.0f); 5225 IsExp10 = LHSC->isExactlyValue(Ten); 5226 } 5227 } 5228 5229 // TODO: What fast-math-flags should be set on the FMUL node? 5230 if (IsExp10) { 5231 // Put the exponent in the right bit position for later addition to the 5232 // final result: 5233 // 5234 // #define LOG2OF10 3.3219281f 5235 // t0 = Op * LOG2OF10; 5236 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5237 getF32Constant(DAG, 0x40549a78, dl)); 5238 return getLimitedPrecisionExp2(t0, dl, DAG); 5239 } 5240 5241 // No special expansion. 5242 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5243 } 5244 5245 /// ExpandPowI - Expand a llvm.powi intrinsic. 5246 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5247 SelectionDAG &DAG) { 5248 // If RHS is a constant, we can expand this out to a multiplication tree, 5249 // otherwise we end up lowering to a call to __powidf2 (for example). When 5250 // optimizing for size, we only want to do this if the expansion would produce 5251 // a small number of multiplies, otherwise we do the full expansion. 5252 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5253 // Get the exponent as a positive value. 5254 unsigned Val = RHSC->getSExtValue(); 5255 if ((int)Val < 0) Val = -Val; 5256 5257 // powi(x, 0) -> 1.0 5258 if (Val == 0) 5259 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5260 5261 bool OptForSize = DAG.shouldOptForSize(); 5262 if (!OptForSize || 5263 // If optimizing for size, don't insert too many multiplies. 5264 // This inserts up to 5 multiplies. 5265 countPopulation(Val) + Log2_32(Val) < 7) { 5266 // We use the simple binary decomposition method to generate the multiply 5267 // sequence. There are more optimal ways to do this (for example, 5268 // powi(x,15) generates one more multiply than it should), but this has 5269 // the benefit of being both really simple and much better than a libcall. 5270 SDValue Res; // Logically starts equal to 1.0 5271 SDValue CurSquare = LHS; 5272 // TODO: Intrinsics should have fast-math-flags that propagate to these 5273 // nodes. 5274 while (Val) { 5275 if (Val & 1) { 5276 if (Res.getNode()) 5277 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5278 else 5279 Res = CurSquare; // 1.0*CurSquare. 5280 } 5281 5282 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5283 CurSquare, CurSquare); 5284 Val >>= 1; 5285 } 5286 5287 // If the original was negative, invert the result, producing 1/(x*x*x). 5288 if (RHSC->getSExtValue() < 0) 5289 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5290 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5291 return Res; 5292 } 5293 } 5294 5295 // Otherwise, expand to a libcall. 5296 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5297 } 5298 5299 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5300 SDValue LHS, SDValue RHS, SDValue Scale, 5301 SelectionDAG &DAG, const TargetLowering &TLI) { 5302 EVT VT = LHS.getValueType(); 5303 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5304 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5305 LLVMContext &Ctx = *DAG.getContext(); 5306 5307 // If the type is legal but the operation isn't, this node might survive all 5308 // the way to operation legalization. If we end up there and we do not have 5309 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5310 // node. 5311 5312 // Coax the legalizer into expanding the node during type legalization instead 5313 // by bumping the size by one bit. This will force it to Promote, enabling the 5314 // early expansion and avoiding the need to expand later. 5315 5316 // We don't have to do this if Scale is 0; that can always be expanded, unless 5317 // it's a saturating signed operation. Those can experience true integer 5318 // division overflow, a case which we must avoid. 5319 5320 // FIXME: We wouldn't have to do this (or any of the early 5321 // expansion/promotion) if it was possible to expand a libcall of an 5322 // illegal type during operation legalization. But it's not, so things 5323 // get a bit hacky. 5324 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5325 if ((ScaleInt > 0 || (Saturating && Signed)) && 5326 (TLI.isTypeLegal(VT) || 5327 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5328 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5329 Opcode, VT, ScaleInt); 5330 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5331 EVT PromVT; 5332 if (VT.isScalarInteger()) 5333 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5334 else if (VT.isVector()) { 5335 PromVT = VT.getVectorElementType(); 5336 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5337 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5338 } else 5339 llvm_unreachable("Wrong VT for DIVFIX?"); 5340 if (Signed) { 5341 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5342 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5343 } else { 5344 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5345 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5346 } 5347 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5348 // For saturating operations, we need to shift up the LHS to get the 5349 // proper saturation width, and then shift down again afterwards. 5350 if (Saturating) 5351 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5352 DAG.getConstant(1, DL, ShiftTy)); 5353 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5354 if (Saturating) 5355 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5356 DAG.getConstant(1, DL, ShiftTy)); 5357 return DAG.getZExtOrTrunc(Res, DL, VT); 5358 } 5359 } 5360 5361 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5362 } 5363 5364 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5365 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5366 static void 5367 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5368 const SDValue &N) { 5369 switch (N.getOpcode()) { 5370 case ISD::CopyFromReg: { 5371 SDValue Op = N.getOperand(1); 5372 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5373 Op.getValueType().getSizeInBits()); 5374 return; 5375 } 5376 case ISD::BITCAST: 5377 case ISD::AssertZext: 5378 case ISD::AssertSext: 5379 case ISD::TRUNCATE: 5380 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5381 return; 5382 case ISD::BUILD_PAIR: 5383 case ISD::BUILD_VECTOR: 5384 case ISD::CONCAT_VECTORS: 5385 for (SDValue Op : N->op_values()) 5386 getUnderlyingArgRegs(Regs, Op); 5387 return; 5388 default: 5389 return; 5390 } 5391 } 5392 5393 /// If the DbgValueInst is a dbg_value of a function argument, create the 5394 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5395 /// instruction selection, they will be inserted to the entry BB. 5396 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5397 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5398 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5399 const Argument *Arg = dyn_cast<Argument>(V); 5400 if (!Arg) 5401 return false; 5402 5403 if (!IsDbgDeclare) { 5404 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5405 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5406 // the entry block. 5407 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5408 if (!IsInEntryBlock) 5409 return false; 5410 5411 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5412 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5413 // variable that also is a param. 5414 // 5415 // Although, if we are at the top of the entry block already, we can still 5416 // emit using ArgDbgValue. This might catch some situations when the 5417 // dbg.value refers to an argument that isn't used in the entry block, so 5418 // any CopyToReg node would be optimized out and the only way to express 5419 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5420 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5421 // we should only emit as ArgDbgValue if the Variable is an argument to the 5422 // current function, and the dbg.value intrinsic is found in the entry 5423 // block. 5424 bool VariableIsFunctionInputArg = Variable->isParameter() && 5425 !DL->getInlinedAt(); 5426 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5427 if (!IsInPrologue && !VariableIsFunctionInputArg) 5428 return false; 5429 5430 // Here we assume that a function argument on IR level only can be used to 5431 // describe one input parameter on source level. If we for example have 5432 // source code like this 5433 // 5434 // struct A { long x, y; }; 5435 // void foo(struct A a, long b) { 5436 // ... 5437 // b = a.x; 5438 // ... 5439 // } 5440 // 5441 // and IR like this 5442 // 5443 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5444 // entry: 5445 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5446 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5447 // call void @llvm.dbg.value(metadata i32 %b, "b", 5448 // ... 5449 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5450 // ... 5451 // 5452 // then the last dbg.value is describing a parameter "b" using a value that 5453 // is an argument. But since we already has used %a1 to describe a parameter 5454 // we should not handle that last dbg.value here (that would result in an 5455 // incorrect hoisting of the DBG_VALUE to the function entry). 5456 // Notice that we allow one dbg.value per IR level argument, to accommodate 5457 // for the situation with fragments above. 5458 if (VariableIsFunctionInputArg) { 5459 unsigned ArgNo = Arg->getArgNo(); 5460 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5461 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5462 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5463 return false; 5464 FuncInfo.DescribedArgs.set(ArgNo); 5465 } 5466 } 5467 5468 MachineFunction &MF = DAG.getMachineFunction(); 5469 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5470 5471 bool IsIndirect = false; 5472 Optional<MachineOperand> Op; 5473 // Some arguments' frame index is recorded during argument lowering. 5474 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5475 if (FI != std::numeric_limits<int>::max()) 5476 Op = MachineOperand::CreateFI(FI); 5477 5478 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5479 if (!Op && N.getNode()) { 5480 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5481 Register Reg; 5482 if (ArgRegsAndSizes.size() == 1) 5483 Reg = ArgRegsAndSizes.front().first; 5484 5485 if (Reg && Reg.isVirtual()) { 5486 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5487 Register PR = RegInfo.getLiveInPhysReg(Reg); 5488 if (PR) 5489 Reg = PR; 5490 } 5491 if (Reg) { 5492 Op = MachineOperand::CreateReg(Reg, false); 5493 IsIndirect = IsDbgDeclare; 5494 } 5495 } 5496 5497 if (!Op && N.getNode()) { 5498 // Check if frame index is available. 5499 SDValue LCandidate = peekThroughBitcasts(N); 5500 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5501 if (FrameIndexSDNode *FINode = 5502 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5503 Op = MachineOperand::CreateFI(FINode->getIndex()); 5504 } 5505 5506 if (!Op) { 5507 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5508 auto splitMultiRegDbgValue 5509 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5510 unsigned Offset = 0; 5511 for (auto RegAndSize : SplitRegs) { 5512 // If the expression is already a fragment, the current register 5513 // offset+size might extend beyond the fragment. In this case, only 5514 // the register bits that are inside the fragment are relevant. 5515 int RegFragmentSizeInBits = RegAndSize.second; 5516 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5517 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5518 // The register is entirely outside the expression fragment, 5519 // so is irrelevant for debug info. 5520 if (Offset >= ExprFragmentSizeInBits) 5521 break; 5522 // The register is partially outside the expression fragment, only 5523 // the low bits within the fragment are relevant for debug info. 5524 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5525 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5526 } 5527 } 5528 5529 auto FragmentExpr = DIExpression::createFragmentExpression( 5530 Expr, Offset, RegFragmentSizeInBits); 5531 Offset += RegAndSize.second; 5532 // If a valid fragment expression cannot be created, the variable's 5533 // correct value cannot be determined and so it is set as Undef. 5534 if (!FragmentExpr) { 5535 SDDbgValue *SDV = DAG.getConstantDbgValue( 5536 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5537 DAG.AddDbgValue(SDV, nullptr, false); 5538 continue; 5539 } 5540 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5541 FuncInfo.ArgDbgValues.push_back( 5542 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5543 RegAndSize.first, Variable, *FragmentExpr)); 5544 } 5545 }; 5546 5547 // Check if ValueMap has reg number. 5548 DenseMap<const Value *, Register>::const_iterator 5549 VMI = FuncInfo.ValueMap.find(V); 5550 if (VMI != FuncInfo.ValueMap.end()) { 5551 const auto &TLI = DAG.getTargetLoweringInfo(); 5552 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5553 V->getType(), getABIRegCopyCC(V)); 5554 if (RFV.occupiesMultipleRegs()) { 5555 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5556 return true; 5557 } 5558 5559 Op = MachineOperand::CreateReg(VMI->second, false); 5560 IsIndirect = IsDbgDeclare; 5561 } else if (ArgRegsAndSizes.size() > 1) { 5562 // This was split due to the calling convention, and no virtual register 5563 // mapping exists for the value. 5564 splitMultiRegDbgValue(ArgRegsAndSizes); 5565 return true; 5566 } 5567 } 5568 5569 if (!Op) 5570 return false; 5571 5572 assert(Variable->isValidLocationForIntrinsic(DL) && 5573 "Expected inlined-at fields to agree"); 5574 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5575 FuncInfo.ArgDbgValues.push_back( 5576 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5577 *Op, Variable, Expr)); 5578 5579 return true; 5580 } 5581 5582 /// Return the appropriate SDDbgValue based on N. 5583 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5584 DILocalVariable *Variable, 5585 DIExpression *Expr, 5586 const DebugLoc &dl, 5587 unsigned DbgSDNodeOrder) { 5588 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5589 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5590 // stack slot locations. 5591 // 5592 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5593 // debug values here after optimization: 5594 // 5595 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5596 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5597 // 5598 // Both describe the direct values of their associated variables. 5599 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5600 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5601 } 5602 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5603 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5604 } 5605 5606 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5607 switch (Intrinsic) { 5608 case Intrinsic::smul_fix: 5609 return ISD::SMULFIX; 5610 case Intrinsic::umul_fix: 5611 return ISD::UMULFIX; 5612 case Intrinsic::smul_fix_sat: 5613 return ISD::SMULFIXSAT; 5614 case Intrinsic::umul_fix_sat: 5615 return ISD::UMULFIXSAT; 5616 case Intrinsic::sdiv_fix: 5617 return ISD::SDIVFIX; 5618 case Intrinsic::udiv_fix: 5619 return ISD::UDIVFIX; 5620 case Intrinsic::sdiv_fix_sat: 5621 return ISD::SDIVFIXSAT; 5622 case Intrinsic::udiv_fix_sat: 5623 return ISD::UDIVFIXSAT; 5624 default: 5625 llvm_unreachable("Unhandled fixed point intrinsic"); 5626 } 5627 } 5628 5629 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5630 const char *FunctionName) { 5631 assert(FunctionName && "FunctionName must not be nullptr"); 5632 SDValue Callee = DAG.getExternalSymbol( 5633 FunctionName, 5634 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5635 LowerCallTo(I, Callee, I.isTailCall()); 5636 } 5637 5638 /// Given a @llvm.call.preallocated.setup, return the corresponding 5639 /// preallocated call. 5640 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5641 assert(cast<CallBase>(PreallocatedSetup) 5642 ->getCalledFunction() 5643 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5644 "expected call_preallocated_setup Value"); 5645 for (auto *U : PreallocatedSetup->users()) { 5646 auto *UseCall = cast<CallBase>(U); 5647 const Function *Fn = UseCall->getCalledFunction(); 5648 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5649 return UseCall; 5650 } 5651 } 5652 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5653 } 5654 5655 /// Lower the call to the specified intrinsic function. 5656 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5657 unsigned Intrinsic) { 5658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5659 SDLoc sdl = getCurSDLoc(); 5660 DebugLoc dl = getCurDebugLoc(); 5661 SDValue Res; 5662 5663 switch (Intrinsic) { 5664 default: 5665 // By default, turn this into a target intrinsic node. 5666 visitTargetIntrinsic(I, Intrinsic); 5667 return; 5668 case Intrinsic::vscale: { 5669 match(&I, m_VScale(DAG.getDataLayout())); 5670 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5671 setValue(&I, 5672 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5673 return; 5674 } 5675 case Intrinsic::vastart: visitVAStart(I); return; 5676 case Intrinsic::vaend: visitVAEnd(I); return; 5677 case Intrinsic::vacopy: visitVACopy(I); return; 5678 case Intrinsic::returnaddress: 5679 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5680 TLI.getPointerTy(DAG.getDataLayout()), 5681 getValue(I.getArgOperand(0)))); 5682 return; 5683 case Intrinsic::addressofreturnaddress: 5684 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5685 TLI.getPointerTy(DAG.getDataLayout()))); 5686 return; 5687 case Intrinsic::sponentry: 5688 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5689 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5690 return; 5691 case Intrinsic::frameaddress: 5692 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5693 TLI.getFrameIndexTy(DAG.getDataLayout()), 5694 getValue(I.getArgOperand(0)))); 5695 return; 5696 case Intrinsic::read_register: { 5697 Value *Reg = I.getArgOperand(0); 5698 SDValue Chain = getRoot(); 5699 SDValue RegName = 5700 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5701 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5702 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5703 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5704 setValue(&I, Res); 5705 DAG.setRoot(Res.getValue(1)); 5706 return; 5707 } 5708 case Intrinsic::write_register: { 5709 Value *Reg = I.getArgOperand(0); 5710 Value *RegValue = I.getArgOperand(1); 5711 SDValue Chain = getRoot(); 5712 SDValue RegName = 5713 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5714 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5715 RegName, getValue(RegValue))); 5716 return; 5717 } 5718 case Intrinsic::memcpy: { 5719 const auto &MCI = cast<MemCpyInst>(I); 5720 SDValue Op1 = getValue(I.getArgOperand(0)); 5721 SDValue Op2 = getValue(I.getArgOperand(1)); 5722 SDValue Op3 = getValue(I.getArgOperand(2)); 5723 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5724 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5725 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5726 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5727 bool isVol = MCI.isVolatile(); 5728 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5729 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5730 // node. 5731 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5732 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5733 /* AlwaysInline */ false, isTC, 5734 MachinePointerInfo(I.getArgOperand(0)), 5735 MachinePointerInfo(I.getArgOperand(1))); 5736 updateDAGForMaybeTailCall(MC); 5737 return; 5738 } 5739 case Intrinsic::memcpy_inline: { 5740 const auto &MCI = cast<MemCpyInlineInst>(I); 5741 SDValue Dst = getValue(I.getArgOperand(0)); 5742 SDValue Src = getValue(I.getArgOperand(1)); 5743 SDValue Size = getValue(I.getArgOperand(2)); 5744 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5745 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5746 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5747 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5748 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5749 bool isVol = MCI.isVolatile(); 5750 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5751 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5752 // node. 5753 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5754 /* AlwaysInline */ true, isTC, 5755 MachinePointerInfo(I.getArgOperand(0)), 5756 MachinePointerInfo(I.getArgOperand(1))); 5757 updateDAGForMaybeTailCall(MC); 5758 return; 5759 } 5760 case Intrinsic::memset: { 5761 const auto &MSI = cast<MemSetInst>(I); 5762 SDValue Op1 = getValue(I.getArgOperand(0)); 5763 SDValue Op2 = getValue(I.getArgOperand(1)); 5764 SDValue Op3 = getValue(I.getArgOperand(2)); 5765 // @llvm.memset defines 0 and 1 to both mean no alignment. 5766 Align Alignment = MSI.getDestAlign().valueOrOne(); 5767 bool isVol = MSI.isVolatile(); 5768 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5769 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5770 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5771 MachinePointerInfo(I.getArgOperand(0))); 5772 updateDAGForMaybeTailCall(MS); 5773 return; 5774 } 5775 case Intrinsic::memmove: { 5776 const auto &MMI = cast<MemMoveInst>(I); 5777 SDValue Op1 = getValue(I.getArgOperand(0)); 5778 SDValue Op2 = getValue(I.getArgOperand(1)); 5779 SDValue Op3 = getValue(I.getArgOperand(2)); 5780 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5781 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5782 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5783 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5784 bool isVol = MMI.isVolatile(); 5785 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5786 // FIXME: Support passing different dest/src alignments to the memmove DAG 5787 // node. 5788 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5789 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5790 isTC, MachinePointerInfo(I.getArgOperand(0)), 5791 MachinePointerInfo(I.getArgOperand(1))); 5792 updateDAGForMaybeTailCall(MM); 5793 return; 5794 } 5795 case Intrinsic::memcpy_element_unordered_atomic: { 5796 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5797 SDValue Dst = getValue(MI.getRawDest()); 5798 SDValue Src = getValue(MI.getRawSource()); 5799 SDValue Length = getValue(MI.getLength()); 5800 5801 unsigned DstAlign = MI.getDestAlignment(); 5802 unsigned SrcAlign = MI.getSourceAlignment(); 5803 Type *LengthTy = MI.getLength()->getType(); 5804 unsigned ElemSz = MI.getElementSizeInBytes(); 5805 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5806 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5807 SrcAlign, Length, LengthTy, ElemSz, isTC, 5808 MachinePointerInfo(MI.getRawDest()), 5809 MachinePointerInfo(MI.getRawSource())); 5810 updateDAGForMaybeTailCall(MC); 5811 return; 5812 } 5813 case Intrinsic::memmove_element_unordered_atomic: { 5814 auto &MI = cast<AtomicMemMoveInst>(I); 5815 SDValue Dst = getValue(MI.getRawDest()); 5816 SDValue Src = getValue(MI.getRawSource()); 5817 SDValue Length = getValue(MI.getLength()); 5818 5819 unsigned DstAlign = MI.getDestAlignment(); 5820 unsigned SrcAlign = MI.getSourceAlignment(); 5821 Type *LengthTy = MI.getLength()->getType(); 5822 unsigned ElemSz = MI.getElementSizeInBytes(); 5823 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5824 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5825 SrcAlign, Length, LengthTy, ElemSz, isTC, 5826 MachinePointerInfo(MI.getRawDest()), 5827 MachinePointerInfo(MI.getRawSource())); 5828 updateDAGForMaybeTailCall(MC); 5829 return; 5830 } 5831 case Intrinsic::memset_element_unordered_atomic: { 5832 auto &MI = cast<AtomicMemSetInst>(I); 5833 SDValue Dst = getValue(MI.getRawDest()); 5834 SDValue Val = getValue(MI.getValue()); 5835 SDValue Length = getValue(MI.getLength()); 5836 5837 unsigned DstAlign = MI.getDestAlignment(); 5838 Type *LengthTy = MI.getLength()->getType(); 5839 unsigned ElemSz = MI.getElementSizeInBytes(); 5840 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5841 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5842 LengthTy, ElemSz, isTC, 5843 MachinePointerInfo(MI.getRawDest())); 5844 updateDAGForMaybeTailCall(MC); 5845 return; 5846 } 5847 case Intrinsic::call_preallocated_setup: { 5848 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5849 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5850 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5851 getRoot(), SrcValue); 5852 setValue(&I, Res); 5853 DAG.setRoot(Res); 5854 return; 5855 } 5856 case Intrinsic::call_preallocated_arg: { 5857 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5858 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5859 SDValue Ops[3]; 5860 Ops[0] = getRoot(); 5861 Ops[1] = SrcValue; 5862 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5863 MVT::i32); // arg index 5864 SDValue Res = DAG.getNode( 5865 ISD::PREALLOCATED_ARG, sdl, 5866 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5867 setValue(&I, Res); 5868 DAG.setRoot(Res.getValue(1)); 5869 return; 5870 } 5871 case Intrinsic::dbg_addr: 5872 case Intrinsic::dbg_declare: { 5873 const auto &DI = cast<DbgVariableIntrinsic>(I); 5874 DILocalVariable *Variable = DI.getVariable(); 5875 DIExpression *Expression = DI.getExpression(); 5876 dropDanglingDebugInfo(Variable, Expression); 5877 assert(Variable && "Missing variable"); 5878 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5879 << "\n"); 5880 // Check if address has undef value. 5881 const Value *Address = DI.getVariableLocation(); 5882 if (!Address || isa<UndefValue>(Address) || 5883 (Address->use_empty() && !isa<Argument>(Address))) { 5884 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5885 << " (bad/undef/unused-arg address)\n"); 5886 return; 5887 } 5888 5889 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5890 5891 // Check if this variable can be described by a frame index, typically 5892 // either as a static alloca or a byval parameter. 5893 int FI = std::numeric_limits<int>::max(); 5894 if (const auto *AI = 5895 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5896 if (AI->isStaticAlloca()) { 5897 auto I = FuncInfo.StaticAllocaMap.find(AI); 5898 if (I != FuncInfo.StaticAllocaMap.end()) 5899 FI = I->second; 5900 } 5901 } else if (const auto *Arg = dyn_cast<Argument>( 5902 Address->stripInBoundsConstantOffsets())) { 5903 FI = FuncInfo.getArgumentFrameIndex(Arg); 5904 } 5905 5906 // llvm.dbg.addr is control dependent and always generates indirect 5907 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5908 // the MachineFunction variable table. 5909 if (FI != std::numeric_limits<int>::max()) { 5910 if (Intrinsic == Intrinsic::dbg_addr) { 5911 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5912 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5913 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5914 } else { 5915 LLVM_DEBUG(dbgs() << "Skipping " << DI 5916 << " (variable info stashed in MF side table)\n"); 5917 } 5918 return; 5919 } 5920 5921 SDValue &N = NodeMap[Address]; 5922 if (!N.getNode() && isa<Argument>(Address)) 5923 // Check unused arguments map. 5924 N = UnusedArgNodeMap[Address]; 5925 SDDbgValue *SDV; 5926 if (N.getNode()) { 5927 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5928 Address = BCI->getOperand(0); 5929 // Parameters are handled specially. 5930 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5931 if (isParameter && FINode) { 5932 // Byval parameter. We have a frame index at this point. 5933 SDV = 5934 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5935 /*IsIndirect*/ true, dl, SDNodeOrder); 5936 } else if (isa<Argument>(Address)) { 5937 // Address is an argument, so try to emit its dbg value using 5938 // virtual register info from the FuncInfo.ValueMap. 5939 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5940 return; 5941 } else { 5942 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5943 true, dl, SDNodeOrder); 5944 } 5945 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5946 } else { 5947 // If Address is an argument then try to emit its dbg value using 5948 // virtual register info from the FuncInfo.ValueMap. 5949 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5950 N)) { 5951 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5952 << " (could not emit func-arg dbg_value)\n"); 5953 } 5954 } 5955 return; 5956 } 5957 case Intrinsic::dbg_label: { 5958 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5959 DILabel *Label = DI.getLabel(); 5960 assert(Label && "Missing label"); 5961 5962 SDDbgLabel *SDV; 5963 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5964 DAG.AddDbgLabel(SDV); 5965 return; 5966 } 5967 case Intrinsic::dbg_value: { 5968 const DbgValueInst &DI = cast<DbgValueInst>(I); 5969 assert(DI.getVariable() && "Missing variable"); 5970 5971 DILocalVariable *Variable = DI.getVariable(); 5972 DIExpression *Expression = DI.getExpression(); 5973 dropDanglingDebugInfo(Variable, Expression); 5974 const Value *V = DI.getValue(); 5975 if (!V) 5976 return; 5977 5978 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5979 SDNodeOrder)) 5980 return; 5981 5982 // TODO: Dangling debug info will eventually either be resolved or produce 5983 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5984 // between the original dbg.value location and its resolved DBG_VALUE, which 5985 // we should ideally fill with an extra Undef DBG_VALUE. 5986 5987 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5988 return; 5989 } 5990 5991 case Intrinsic::eh_typeid_for: { 5992 // Find the type id for the given typeinfo. 5993 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5994 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5995 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5996 setValue(&I, Res); 5997 return; 5998 } 5999 6000 case Intrinsic::eh_return_i32: 6001 case Intrinsic::eh_return_i64: 6002 DAG.getMachineFunction().setCallsEHReturn(true); 6003 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6004 MVT::Other, 6005 getControlRoot(), 6006 getValue(I.getArgOperand(0)), 6007 getValue(I.getArgOperand(1)))); 6008 return; 6009 case Intrinsic::eh_unwind_init: 6010 DAG.getMachineFunction().setCallsUnwindInit(true); 6011 return; 6012 case Intrinsic::eh_dwarf_cfa: 6013 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6014 TLI.getPointerTy(DAG.getDataLayout()), 6015 getValue(I.getArgOperand(0)))); 6016 return; 6017 case Intrinsic::eh_sjlj_callsite: { 6018 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6019 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6020 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6021 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6022 6023 MMI.setCurrentCallSite(CI->getZExtValue()); 6024 return; 6025 } 6026 case Intrinsic::eh_sjlj_functioncontext: { 6027 // Get and store the index of the function context. 6028 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6029 AllocaInst *FnCtx = 6030 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6031 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6032 MFI.setFunctionContextIndex(FI); 6033 return; 6034 } 6035 case Intrinsic::eh_sjlj_setjmp: { 6036 SDValue Ops[2]; 6037 Ops[0] = getRoot(); 6038 Ops[1] = getValue(I.getArgOperand(0)); 6039 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6040 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6041 setValue(&I, Op.getValue(0)); 6042 DAG.setRoot(Op.getValue(1)); 6043 return; 6044 } 6045 case Intrinsic::eh_sjlj_longjmp: 6046 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6047 getRoot(), getValue(I.getArgOperand(0)))); 6048 return; 6049 case Intrinsic::eh_sjlj_setup_dispatch: 6050 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6051 getRoot())); 6052 return; 6053 case Intrinsic::masked_gather: 6054 visitMaskedGather(I); 6055 return; 6056 case Intrinsic::masked_load: 6057 visitMaskedLoad(I); 6058 return; 6059 case Intrinsic::masked_scatter: 6060 visitMaskedScatter(I); 6061 return; 6062 case Intrinsic::masked_store: 6063 visitMaskedStore(I); 6064 return; 6065 case Intrinsic::masked_expandload: 6066 visitMaskedLoad(I, true /* IsExpanding */); 6067 return; 6068 case Intrinsic::masked_compressstore: 6069 visitMaskedStore(I, true /* IsCompressing */); 6070 return; 6071 case Intrinsic::powi: 6072 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6073 getValue(I.getArgOperand(1)), DAG)); 6074 return; 6075 case Intrinsic::log: 6076 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6077 return; 6078 case Intrinsic::log2: 6079 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6080 return; 6081 case Intrinsic::log10: 6082 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6083 return; 6084 case Intrinsic::exp: 6085 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6086 return; 6087 case Intrinsic::exp2: 6088 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6089 return; 6090 case Intrinsic::pow: 6091 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6092 getValue(I.getArgOperand(1)), DAG, TLI)); 6093 return; 6094 case Intrinsic::sqrt: 6095 case Intrinsic::fabs: 6096 case Intrinsic::sin: 6097 case Intrinsic::cos: 6098 case Intrinsic::floor: 6099 case Intrinsic::ceil: 6100 case Intrinsic::trunc: 6101 case Intrinsic::rint: 6102 case Intrinsic::nearbyint: 6103 case Intrinsic::round: 6104 case Intrinsic::roundeven: 6105 case Intrinsic::canonicalize: { 6106 unsigned Opcode; 6107 switch (Intrinsic) { 6108 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6109 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6110 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6111 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6112 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6113 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6114 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6115 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6116 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6117 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6118 case Intrinsic::round: Opcode = ISD::FROUND; break; 6119 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6120 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6121 } 6122 6123 setValue(&I, DAG.getNode(Opcode, sdl, 6124 getValue(I.getArgOperand(0)).getValueType(), 6125 getValue(I.getArgOperand(0)))); 6126 return; 6127 } 6128 case Intrinsic::lround: 6129 case Intrinsic::llround: 6130 case Intrinsic::lrint: 6131 case Intrinsic::llrint: { 6132 unsigned Opcode; 6133 switch (Intrinsic) { 6134 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6135 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6136 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6137 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6138 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6139 } 6140 6141 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6142 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6143 getValue(I.getArgOperand(0)))); 6144 return; 6145 } 6146 case Intrinsic::minnum: 6147 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6148 getValue(I.getArgOperand(0)).getValueType(), 6149 getValue(I.getArgOperand(0)), 6150 getValue(I.getArgOperand(1)))); 6151 return; 6152 case Intrinsic::maxnum: 6153 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6154 getValue(I.getArgOperand(0)).getValueType(), 6155 getValue(I.getArgOperand(0)), 6156 getValue(I.getArgOperand(1)))); 6157 return; 6158 case Intrinsic::minimum: 6159 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6160 getValue(I.getArgOperand(0)).getValueType(), 6161 getValue(I.getArgOperand(0)), 6162 getValue(I.getArgOperand(1)))); 6163 return; 6164 case Intrinsic::maximum: 6165 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6166 getValue(I.getArgOperand(0)).getValueType(), 6167 getValue(I.getArgOperand(0)), 6168 getValue(I.getArgOperand(1)))); 6169 return; 6170 case Intrinsic::copysign: 6171 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6172 getValue(I.getArgOperand(0)).getValueType(), 6173 getValue(I.getArgOperand(0)), 6174 getValue(I.getArgOperand(1)))); 6175 return; 6176 case Intrinsic::fma: 6177 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6178 getValue(I.getArgOperand(0)).getValueType(), 6179 getValue(I.getArgOperand(0)), 6180 getValue(I.getArgOperand(1)), 6181 getValue(I.getArgOperand(2)))); 6182 return; 6183 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6184 case Intrinsic::INTRINSIC: 6185 #include "llvm/IR/ConstrainedOps.def" 6186 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6187 return; 6188 case Intrinsic::fmuladd: { 6189 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6190 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6191 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6192 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6193 getValue(I.getArgOperand(0)).getValueType(), 6194 getValue(I.getArgOperand(0)), 6195 getValue(I.getArgOperand(1)), 6196 getValue(I.getArgOperand(2)))); 6197 } else { 6198 // TODO: Intrinsic calls should have fast-math-flags. 6199 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6200 getValue(I.getArgOperand(0)).getValueType(), 6201 getValue(I.getArgOperand(0)), 6202 getValue(I.getArgOperand(1))); 6203 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6204 getValue(I.getArgOperand(0)).getValueType(), 6205 Mul, 6206 getValue(I.getArgOperand(2))); 6207 setValue(&I, Add); 6208 } 6209 return; 6210 } 6211 case Intrinsic::convert_to_fp16: 6212 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6213 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6214 getValue(I.getArgOperand(0)), 6215 DAG.getTargetConstant(0, sdl, 6216 MVT::i32)))); 6217 return; 6218 case Intrinsic::convert_from_fp16: 6219 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6220 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6221 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6222 getValue(I.getArgOperand(0))))); 6223 return; 6224 case Intrinsic::pcmarker: { 6225 SDValue Tmp = getValue(I.getArgOperand(0)); 6226 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6227 return; 6228 } 6229 case Intrinsic::readcyclecounter: { 6230 SDValue Op = getRoot(); 6231 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6232 DAG.getVTList(MVT::i64, MVT::Other), Op); 6233 setValue(&I, Res); 6234 DAG.setRoot(Res.getValue(1)); 6235 return; 6236 } 6237 case Intrinsic::bitreverse: 6238 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6239 getValue(I.getArgOperand(0)).getValueType(), 6240 getValue(I.getArgOperand(0)))); 6241 return; 6242 case Intrinsic::bswap: 6243 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6244 getValue(I.getArgOperand(0)).getValueType(), 6245 getValue(I.getArgOperand(0)))); 6246 return; 6247 case Intrinsic::cttz: { 6248 SDValue Arg = getValue(I.getArgOperand(0)); 6249 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6250 EVT Ty = Arg.getValueType(); 6251 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6252 sdl, Ty, Arg)); 6253 return; 6254 } 6255 case Intrinsic::ctlz: { 6256 SDValue Arg = getValue(I.getArgOperand(0)); 6257 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6258 EVT Ty = Arg.getValueType(); 6259 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6260 sdl, Ty, Arg)); 6261 return; 6262 } 6263 case Intrinsic::ctpop: { 6264 SDValue Arg = getValue(I.getArgOperand(0)); 6265 EVT Ty = Arg.getValueType(); 6266 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6267 return; 6268 } 6269 case Intrinsic::fshl: 6270 case Intrinsic::fshr: { 6271 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6272 SDValue X = getValue(I.getArgOperand(0)); 6273 SDValue Y = getValue(I.getArgOperand(1)); 6274 SDValue Z = getValue(I.getArgOperand(2)); 6275 EVT VT = X.getValueType(); 6276 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6277 SDValue Zero = DAG.getConstant(0, sdl, VT); 6278 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6279 6280 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6281 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6282 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6283 return; 6284 } 6285 6286 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6287 // avoid the select that is necessary in the general case to filter out 6288 // the 0-shift possibility that leads to UB. 6289 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6290 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6291 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6292 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6293 return; 6294 } 6295 6296 // Some targets only rotate one way. Try the opposite direction. 6297 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6298 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6299 // Negate the shift amount because it is safe to ignore the high bits. 6300 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6301 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6302 return; 6303 } 6304 6305 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6306 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6307 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6308 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6309 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6310 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6311 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6312 return; 6313 } 6314 6315 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6316 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6317 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6318 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6319 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6320 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6321 6322 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6323 // and that is undefined. We must compare and select to avoid UB. 6324 EVT CCVT = MVT::i1; 6325 if (VT.isVector()) 6326 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6327 6328 // For fshl, 0-shift returns the 1st arg (X). 6329 // For fshr, 0-shift returns the 2nd arg (Y). 6330 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6331 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6332 return; 6333 } 6334 case Intrinsic::sadd_sat: { 6335 SDValue Op1 = getValue(I.getArgOperand(0)); 6336 SDValue Op2 = getValue(I.getArgOperand(1)); 6337 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6338 return; 6339 } 6340 case Intrinsic::uadd_sat: { 6341 SDValue Op1 = getValue(I.getArgOperand(0)); 6342 SDValue Op2 = getValue(I.getArgOperand(1)); 6343 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6344 return; 6345 } 6346 case Intrinsic::ssub_sat: { 6347 SDValue Op1 = getValue(I.getArgOperand(0)); 6348 SDValue Op2 = getValue(I.getArgOperand(1)); 6349 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6350 return; 6351 } 6352 case Intrinsic::usub_sat: { 6353 SDValue Op1 = getValue(I.getArgOperand(0)); 6354 SDValue Op2 = getValue(I.getArgOperand(1)); 6355 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6356 return; 6357 } 6358 case Intrinsic::smul_fix: 6359 case Intrinsic::umul_fix: 6360 case Intrinsic::smul_fix_sat: 6361 case Intrinsic::umul_fix_sat: { 6362 SDValue Op1 = getValue(I.getArgOperand(0)); 6363 SDValue Op2 = getValue(I.getArgOperand(1)); 6364 SDValue Op3 = getValue(I.getArgOperand(2)); 6365 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6366 Op1.getValueType(), Op1, Op2, Op3)); 6367 return; 6368 } 6369 case Intrinsic::sdiv_fix: 6370 case Intrinsic::udiv_fix: 6371 case Intrinsic::sdiv_fix_sat: 6372 case Intrinsic::udiv_fix_sat: { 6373 SDValue Op1 = getValue(I.getArgOperand(0)); 6374 SDValue Op2 = getValue(I.getArgOperand(1)); 6375 SDValue Op3 = getValue(I.getArgOperand(2)); 6376 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6377 Op1, Op2, Op3, DAG, TLI)); 6378 return; 6379 } 6380 case Intrinsic::stacksave: { 6381 SDValue Op = getRoot(); 6382 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6383 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6384 setValue(&I, Res); 6385 DAG.setRoot(Res.getValue(1)); 6386 return; 6387 } 6388 case Intrinsic::stackrestore: 6389 Res = getValue(I.getArgOperand(0)); 6390 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6391 return; 6392 case Intrinsic::get_dynamic_area_offset: { 6393 SDValue Op = getRoot(); 6394 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6395 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6396 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6397 // target. 6398 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6399 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6400 " intrinsic!"); 6401 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6402 Op); 6403 DAG.setRoot(Op); 6404 setValue(&I, Res); 6405 return; 6406 } 6407 case Intrinsic::stackguard: { 6408 MachineFunction &MF = DAG.getMachineFunction(); 6409 const Module &M = *MF.getFunction().getParent(); 6410 SDValue Chain = getRoot(); 6411 if (TLI.useLoadStackGuardNode()) { 6412 Res = getLoadStackGuard(DAG, sdl, Chain); 6413 } else { 6414 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6415 const Value *Global = TLI.getSDagStackGuard(M); 6416 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6417 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6418 MachinePointerInfo(Global, 0), Align, 6419 MachineMemOperand::MOVolatile); 6420 } 6421 if (TLI.useStackGuardXorFP()) 6422 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6423 DAG.setRoot(Chain); 6424 setValue(&I, Res); 6425 return; 6426 } 6427 case Intrinsic::stackprotector: { 6428 // Emit code into the DAG to store the stack guard onto the stack. 6429 MachineFunction &MF = DAG.getMachineFunction(); 6430 MachineFrameInfo &MFI = MF.getFrameInfo(); 6431 SDValue Src, Chain = getRoot(); 6432 6433 if (TLI.useLoadStackGuardNode()) 6434 Src = getLoadStackGuard(DAG, sdl, Chain); 6435 else 6436 Src = getValue(I.getArgOperand(0)); // The guard's value. 6437 6438 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6439 6440 int FI = FuncInfo.StaticAllocaMap[Slot]; 6441 MFI.setStackProtectorIndex(FI); 6442 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6443 6444 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6445 6446 // Store the stack protector onto the stack. 6447 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6448 DAG.getMachineFunction(), FI), 6449 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6450 setValue(&I, Res); 6451 DAG.setRoot(Res); 6452 return; 6453 } 6454 case Intrinsic::objectsize: 6455 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6456 6457 case Intrinsic::is_constant: 6458 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6459 6460 case Intrinsic::annotation: 6461 case Intrinsic::ptr_annotation: 6462 case Intrinsic::launder_invariant_group: 6463 case Intrinsic::strip_invariant_group: 6464 // Drop the intrinsic, but forward the value 6465 setValue(&I, getValue(I.getOperand(0))); 6466 return; 6467 case Intrinsic::assume: 6468 case Intrinsic::var_annotation: 6469 case Intrinsic::sideeffect: 6470 // Discard annotate attributes, assumptions, and artificial side-effects. 6471 return; 6472 6473 case Intrinsic::codeview_annotation: { 6474 // Emit a label associated with this metadata. 6475 MachineFunction &MF = DAG.getMachineFunction(); 6476 MCSymbol *Label = 6477 MF.getMMI().getContext().createTempSymbol("annotation", true); 6478 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6479 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6480 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6481 DAG.setRoot(Res); 6482 return; 6483 } 6484 6485 case Intrinsic::init_trampoline: { 6486 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6487 6488 SDValue Ops[6]; 6489 Ops[0] = getRoot(); 6490 Ops[1] = getValue(I.getArgOperand(0)); 6491 Ops[2] = getValue(I.getArgOperand(1)); 6492 Ops[3] = getValue(I.getArgOperand(2)); 6493 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6494 Ops[5] = DAG.getSrcValue(F); 6495 6496 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6497 6498 DAG.setRoot(Res); 6499 return; 6500 } 6501 case Intrinsic::adjust_trampoline: 6502 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6503 TLI.getPointerTy(DAG.getDataLayout()), 6504 getValue(I.getArgOperand(0)))); 6505 return; 6506 case Intrinsic::gcroot: { 6507 assert(DAG.getMachineFunction().getFunction().hasGC() && 6508 "only valid in functions with gc specified, enforced by Verifier"); 6509 assert(GFI && "implied by previous"); 6510 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6511 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6512 6513 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6514 GFI->addStackRoot(FI->getIndex(), TypeMap); 6515 return; 6516 } 6517 case Intrinsic::gcread: 6518 case Intrinsic::gcwrite: 6519 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6520 case Intrinsic::flt_rounds: 6521 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6522 setValue(&I, Res); 6523 DAG.setRoot(Res.getValue(1)); 6524 return; 6525 6526 case Intrinsic::expect: 6527 // Just replace __builtin_expect(exp, c) with EXP. 6528 setValue(&I, getValue(I.getArgOperand(0))); 6529 return; 6530 6531 case Intrinsic::debugtrap: 6532 case Intrinsic::trap: { 6533 StringRef TrapFuncName = 6534 I.getAttributes() 6535 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6536 .getValueAsString(); 6537 if (TrapFuncName.empty()) { 6538 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6539 ISD::TRAP : ISD::DEBUGTRAP; 6540 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6541 return; 6542 } 6543 TargetLowering::ArgListTy Args; 6544 6545 TargetLowering::CallLoweringInfo CLI(DAG); 6546 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6547 CallingConv::C, I.getType(), 6548 DAG.getExternalSymbol(TrapFuncName.data(), 6549 TLI.getPointerTy(DAG.getDataLayout())), 6550 std::move(Args)); 6551 6552 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6553 DAG.setRoot(Result.second); 6554 return; 6555 } 6556 6557 case Intrinsic::uadd_with_overflow: 6558 case Intrinsic::sadd_with_overflow: 6559 case Intrinsic::usub_with_overflow: 6560 case Intrinsic::ssub_with_overflow: 6561 case Intrinsic::umul_with_overflow: 6562 case Intrinsic::smul_with_overflow: { 6563 ISD::NodeType Op; 6564 switch (Intrinsic) { 6565 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6566 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6567 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6568 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6569 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6570 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6571 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6572 } 6573 SDValue Op1 = getValue(I.getArgOperand(0)); 6574 SDValue Op2 = getValue(I.getArgOperand(1)); 6575 6576 EVT ResultVT = Op1.getValueType(); 6577 EVT OverflowVT = MVT::i1; 6578 if (ResultVT.isVector()) 6579 OverflowVT = EVT::getVectorVT( 6580 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6581 6582 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6583 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6584 return; 6585 } 6586 case Intrinsic::prefetch: { 6587 SDValue Ops[5]; 6588 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6589 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6590 Ops[0] = DAG.getRoot(); 6591 Ops[1] = getValue(I.getArgOperand(0)); 6592 Ops[2] = getValue(I.getArgOperand(1)); 6593 Ops[3] = getValue(I.getArgOperand(2)); 6594 Ops[4] = getValue(I.getArgOperand(3)); 6595 SDValue Result = DAG.getMemIntrinsicNode( 6596 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6597 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6598 /* align */ None, Flags); 6599 6600 // Chain the prefetch in parallell with any pending loads, to stay out of 6601 // the way of later optimizations. 6602 PendingLoads.push_back(Result); 6603 Result = getRoot(); 6604 DAG.setRoot(Result); 6605 return; 6606 } 6607 case Intrinsic::lifetime_start: 6608 case Intrinsic::lifetime_end: { 6609 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6610 // Stack coloring is not enabled in O0, discard region information. 6611 if (TM.getOptLevel() == CodeGenOpt::None) 6612 return; 6613 6614 const int64_t ObjectSize = 6615 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6616 Value *const ObjectPtr = I.getArgOperand(1); 6617 SmallVector<const Value *, 4> Allocas; 6618 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6619 6620 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6621 E = Allocas.end(); Object != E; ++Object) { 6622 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6623 6624 // Could not find an Alloca. 6625 if (!LifetimeObject) 6626 continue; 6627 6628 // First check that the Alloca is static, otherwise it won't have a 6629 // valid frame index. 6630 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6631 if (SI == FuncInfo.StaticAllocaMap.end()) 6632 return; 6633 6634 const int FrameIndex = SI->second; 6635 int64_t Offset; 6636 if (GetPointerBaseWithConstantOffset( 6637 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6638 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6639 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6640 Offset); 6641 DAG.setRoot(Res); 6642 } 6643 return; 6644 } 6645 case Intrinsic::invariant_start: 6646 // Discard region information. 6647 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6648 return; 6649 case Intrinsic::invariant_end: 6650 // Discard region information. 6651 return; 6652 case Intrinsic::clear_cache: 6653 /// FunctionName may be null. 6654 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6655 lowerCallToExternalSymbol(I, FunctionName); 6656 return; 6657 case Intrinsic::donothing: 6658 // ignore 6659 return; 6660 case Intrinsic::experimental_stackmap: 6661 visitStackmap(I); 6662 return; 6663 case Intrinsic::experimental_patchpoint_void: 6664 case Intrinsic::experimental_patchpoint_i64: 6665 visitPatchpoint(I); 6666 return; 6667 case Intrinsic::experimental_gc_statepoint: 6668 LowerStatepoint(cast<GCStatepointInst>(I)); 6669 return; 6670 case Intrinsic::experimental_gc_result: 6671 visitGCResult(cast<GCResultInst>(I)); 6672 return; 6673 case Intrinsic::experimental_gc_relocate: 6674 visitGCRelocate(cast<GCRelocateInst>(I)); 6675 return; 6676 case Intrinsic::instrprof_increment: 6677 llvm_unreachable("instrprof failed to lower an increment"); 6678 case Intrinsic::instrprof_value_profile: 6679 llvm_unreachable("instrprof failed to lower a value profiling call"); 6680 case Intrinsic::localescape: { 6681 MachineFunction &MF = DAG.getMachineFunction(); 6682 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6683 6684 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6685 // is the same on all targets. 6686 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6687 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6688 if (isa<ConstantPointerNull>(Arg)) 6689 continue; // Skip null pointers. They represent a hole in index space. 6690 AllocaInst *Slot = cast<AllocaInst>(Arg); 6691 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6692 "can only escape static allocas"); 6693 int FI = FuncInfo.StaticAllocaMap[Slot]; 6694 MCSymbol *FrameAllocSym = 6695 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6696 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6697 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6698 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6699 .addSym(FrameAllocSym) 6700 .addFrameIndex(FI); 6701 } 6702 6703 return; 6704 } 6705 6706 case Intrinsic::localrecover: { 6707 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6708 MachineFunction &MF = DAG.getMachineFunction(); 6709 6710 // Get the symbol that defines the frame offset. 6711 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6712 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6713 unsigned IdxVal = 6714 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6715 MCSymbol *FrameAllocSym = 6716 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6717 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6718 6719 Value *FP = I.getArgOperand(1); 6720 SDValue FPVal = getValue(FP); 6721 EVT PtrVT = FPVal.getValueType(); 6722 6723 // Create a MCSymbol for the label to avoid any target lowering 6724 // that would make this PC relative. 6725 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6726 SDValue OffsetVal = 6727 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6728 6729 // Add the offset to the FP. 6730 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6731 setValue(&I, Add); 6732 6733 return; 6734 } 6735 6736 case Intrinsic::eh_exceptionpointer: 6737 case Intrinsic::eh_exceptioncode: { 6738 // Get the exception pointer vreg, copy from it, and resize it to fit. 6739 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6740 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6741 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6742 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6743 SDValue N = 6744 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6745 if (Intrinsic == Intrinsic::eh_exceptioncode) 6746 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6747 setValue(&I, N); 6748 return; 6749 } 6750 case Intrinsic::xray_customevent: { 6751 // Here we want to make sure that the intrinsic behaves as if it has a 6752 // specific calling convention, and only for x86_64. 6753 // FIXME: Support other platforms later. 6754 const auto &Triple = DAG.getTarget().getTargetTriple(); 6755 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6756 return; 6757 6758 SDLoc DL = getCurSDLoc(); 6759 SmallVector<SDValue, 8> Ops; 6760 6761 // We want to say that we always want the arguments in registers. 6762 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6763 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6764 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6765 SDValue Chain = getRoot(); 6766 Ops.push_back(LogEntryVal); 6767 Ops.push_back(StrSizeVal); 6768 Ops.push_back(Chain); 6769 6770 // We need to enforce the calling convention for the callsite, so that 6771 // argument ordering is enforced correctly, and that register allocation can 6772 // see that some registers may be assumed clobbered and have to preserve 6773 // them across calls to the intrinsic. 6774 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6775 DL, NodeTys, Ops); 6776 SDValue patchableNode = SDValue(MN, 0); 6777 DAG.setRoot(patchableNode); 6778 setValue(&I, patchableNode); 6779 return; 6780 } 6781 case Intrinsic::xray_typedevent: { 6782 // Here we want to make sure that the intrinsic behaves as if it has a 6783 // specific calling convention, and only for x86_64. 6784 // FIXME: Support other platforms later. 6785 const auto &Triple = DAG.getTarget().getTargetTriple(); 6786 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6787 return; 6788 6789 SDLoc DL = getCurSDLoc(); 6790 SmallVector<SDValue, 8> Ops; 6791 6792 // We want to say that we always want the arguments in registers. 6793 // It's unclear to me how manipulating the selection DAG here forces callers 6794 // to provide arguments in registers instead of on the stack. 6795 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6796 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6797 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6798 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6799 SDValue Chain = getRoot(); 6800 Ops.push_back(LogTypeId); 6801 Ops.push_back(LogEntryVal); 6802 Ops.push_back(StrSizeVal); 6803 Ops.push_back(Chain); 6804 6805 // We need to enforce the calling convention for the callsite, so that 6806 // argument ordering is enforced correctly, and that register allocation can 6807 // see that some registers may be assumed clobbered and have to preserve 6808 // them across calls to the intrinsic. 6809 MachineSDNode *MN = DAG.getMachineNode( 6810 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6811 SDValue patchableNode = SDValue(MN, 0); 6812 DAG.setRoot(patchableNode); 6813 setValue(&I, patchableNode); 6814 return; 6815 } 6816 case Intrinsic::experimental_deoptimize: 6817 LowerDeoptimizeCall(&I); 6818 return; 6819 6820 case Intrinsic::experimental_vector_reduce_v2_fadd: 6821 case Intrinsic::experimental_vector_reduce_v2_fmul: 6822 case Intrinsic::experimental_vector_reduce_add: 6823 case Intrinsic::experimental_vector_reduce_mul: 6824 case Intrinsic::experimental_vector_reduce_and: 6825 case Intrinsic::experimental_vector_reduce_or: 6826 case Intrinsic::experimental_vector_reduce_xor: 6827 case Intrinsic::experimental_vector_reduce_smax: 6828 case Intrinsic::experimental_vector_reduce_smin: 6829 case Intrinsic::experimental_vector_reduce_umax: 6830 case Intrinsic::experimental_vector_reduce_umin: 6831 case Intrinsic::experimental_vector_reduce_fmax: 6832 case Intrinsic::experimental_vector_reduce_fmin: 6833 visitVectorReduce(I, Intrinsic); 6834 return; 6835 6836 case Intrinsic::icall_branch_funnel: { 6837 SmallVector<SDValue, 16> Ops; 6838 Ops.push_back(getValue(I.getArgOperand(0))); 6839 6840 int64_t Offset; 6841 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6842 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6843 if (!Base) 6844 report_fatal_error( 6845 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6846 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6847 6848 struct BranchFunnelTarget { 6849 int64_t Offset; 6850 SDValue Target; 6851 }; 6852 SmallVector<BranchFunnelTarget, 8> Targets; 6853 6854 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6855 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6856 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6857 if (ElemBase != Base) 6858 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6859 "to the same GlobalValue"); 6860 6861 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6862 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6863 if (!GA) 6864 report_fatal_error( 6865 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6866 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6867 GA->getGlobal(), getCurSDLoc(), 6868 Val.getValueType(), GA->getOffset())}); 6869 } 6870 llvm::sort(Targets, 6871 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6872 return T1.Offset < T2.Offset; 6873 }); 6874 6875 for (auto &T : Targets) { 6876 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6877 Ops.push_back(T.Target); 6878 } 6879 6880 Ops.push_back(DAG.getRoot()); // Chain 6881 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6882 getCurSDLoc(), MVT::Other, Ops), 6883 0); 6884 DAG.setRoot(N); 6885 setValue(&I, N); 6886 HasTailCall = true; 6887 return; 6888 } 6889 6890 case Intrinsic::wasm_landingpad_index: 6891 // Information this intrinsic contained has been transferred to 6892 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6893 // delete it now. 6894 return; 6895 6896 case Intrinsic::aarch64_settag: 6897 case Intrinsic::aarch64_settag_zero: { 6898 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6899 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6900 SDValue Val = TSI.EmitTargetCodeForSetTag( 6901 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6902 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6903 ZeroMemory); 6904 DAG.setRoot(Val); 6905 setValue(&I, Val); 6906 return; 6907 } 6908 case Intrinsic::ptrmask: { 6909 SDValue Ptr = getValue(I.getOperand(0)); 6910 SDValue Const = getValue(I.getOperand(1)); 6911 6912 EVT PtrVT = Ptr.getValueType(); 6913 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 6914 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 6915 return; 6916 } 6917 case Intrinsic::get_active_lane_mask: { 6918 auto DL = getCurSDLoc(); 6919 SDValue Index = getValue(I.getOperand(0)); 6920 SDValue BTC = getValue(I.getOperand(1)); 6921 Type *ElementTy = I.getOperand(0)->getType(); 6922 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6923 unsigned VecWidth = VT.getVectorNumElements(); 6924 6925 SmallVector<SDValue, 16> OpsBTC; 6926 SmallVector<SDValue, 16> OpsIndex; 6927 SmallVector<SDValue, 16> OpsStepConstants; 6928 for (unsigned i = 0; i < VecWidth; i++) { 6929 OpsBTC.push_back(BTC); 6930 OpsIndex.push_back(Index); 6931 OpsStepConstants.push_back(DAG.getConstant(i, DL, MVT::getVT(ElementTy))); 6932 } 6933 6934 EVT CCVT = MVT::i1; 6935 CCVT = EVT::getVectorVT(I.getContext(), CCVT, VecWidth); 6936 6937 auto VecTy = MVT::getVT(FixedVectorType::get(ElementTy, VecWidth)); 6938 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 6939 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 6940 SDValue VectorInduction = DAG.getNode( 6941 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 6942 SDValue VectorBTC = DAG.getBuildVector(VecTy, DL, OpsBTC); 6943 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 6944 VectorBTC, ISD::CondCode::SETULE); 6945 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 6946 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 6947 SetCC)); 6948 return; 6949 } 6950 } 6951 } 6952 6953 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6954 const ConstrainedFPIntrinsic &FPI) { 6955 SDLoc sdl = getCurSDLoc(); 6956 6957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6958 SmallVector<EVT, 4> ValueVTs; 6959 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6960 ValueVTs.push_back(MVT::Other); // Out chain 6961 6962 // We do not need to serialize constrained FP intrinsics against 6963 // each other or against (nonvolatile) loads, so they can be 6964 // chained like loads. 6965 SDValue Chain = DAG.getRoot(); 6966 SmallVector<SDValue, 4> Opers; 6967 Opers.push_back(Chain); 6968 if (FPI.isUnaryOp()) { 6969 Opers.push_back(getValue(FPI.getArgOperand(0))); 6970 } else if (FPI.isTernaryOp()) { 6971 Opers.push_back(getValue(FPI.getArgOperand(0))); 6972 Opers.push_back(getValue(FPI.getArgOperand(1))); 6973 Opers.push_back(getValue(FPI.getArgOperand(2))); 6974 } else { 6975 Opers.push_back(getValue(FPI.getArgOperand(0))); 6976 Opers.push_back(getValue(FPI.getArgOperand(1))); 6977 } 6978 6979 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6980 assert(Result.getNode()->getNumValues() == 2); 6981 6982 // Push node to the appropriate list so that future instructions can be 6983 // chained up correctly. 6984 SDValue OutChain = Result.getValue(1); 6985 switch (EB) { 6986 case fp::ExceptionBehavior::ebIgnore: 6987 // The only reason why ebIgnore nodes still need to be chained is that 6988 // they might depend on the current rounding mode, and therefore must 6989 // not be moved across instruction that may change that mode. 6990 LLVM_FALLTHROUGH; 6991 case fp::ExceptionBehavior::ebMayTrap: 6992 // These must not be moved across calls or instructions that may change 6993 // floating-point exception masks. 6994 PendingConstrainedFP.push_back(OutChain); 6995 break; 6996 case fp::ExceptionBehavior::ebStrict: 6997 // These must not be moved across calls or instructions that may change 6998 // floating-point exception masks or read floating-point exception flags. 6999 // In addition, they cannot be optimized out even if unused. 7000 PendingConstrainedFPStrict.push_back(OutChain); 7001 break; 7002 } 7003 }; 7004 7005 SDVTList VTs = DAG.getVTList(ValueVTs); 7006 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7007 7008 SDNodeFlags Flags; 7009 if (EB == fp::ExceptionBehavior::ebIgnore) 7010 Flags.setNoFPExcept(true); 7011 7012 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7013 Flags.copyFMF(*FPOp); 7014 7015 unsigned Opcode; 7016 switch (FPI.getIntrinsicID()) { 7017 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7018 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7019 case Intrinsic::INTRINSIC: \ 7020 Opcode = ISD::STRICT_##DAGN; \ 7021 break; 7022 #include "llvm/IR/ConstrainedOps.def" 7023 case Intrinsic::experimental_constrained_fmuladd: { 7024 Opcode = ISD::STRICT_FMA; 7025 // Break fmuladd into fmul and fadd. 7026 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7027 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7028 ValueVTs[0])) { 7029 Opers.pop_back(); 7030 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7031 pushOutChain(Mul, EB); 7032 Opcode = ISD::STRICT_FADD; 7033 Opers.clear(); 7034 Opers.push_back(Mul.getValue(1)); 7035 Opers.push_back(Mul.getValue(0)); 7036 Opers.push_back(getValue(FPI.getArgOperand(2))); 7037 } 7038 break; 7039 } 7040 } 7041 7042 // A few strict DAG nodes carry additional operands that are not 7043 // set up by the default code above. 7044 switch (Opcode) { 7045 default: break; 7046 case ISD::STRICT_FP_ROUND: 7047 Opers.push_back( 7048 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7049 break; 7050 case ISD::STRICT_FSETCC: 7051 case ISD::STRICT_FSETCCS: { 7052 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7053 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7054 break; 7055 } 7056 } 7057 7058 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7059 pushOutChain(Result, EB); 7060 7061 SDValue FPResult = Result.getValue(0); 7062 setValue(&FPI, FPResult); 7063 } 7064 7065 std::pair<SDValue, SDValue> 7066 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7067 const BasicBlock *EHPadBB) { 7068 MachineFunction &MF = DAG.getMachineFunction(); 7069 MachineModuleInfo &MMI = MF.getMMI(); 7070 MCSymbol *BeginLabel = nullptr; 7071 7072 if (EHPadBB) { 7073 // Insert a label before the invoke call to mark the try range. This can be 7074 // used to detect deletion of the invoke via the MachineModuleInfo. 7075 BeginLabel = MMI.getContext().createTempSymbol(); 7076 7077 // For SjLj, keep track of which landing pads go with which invokes 7078 // so as to maintain the ordering of pads in the LSDA. 7079 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7080 if (CallSiteIndex) { 7081 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7082 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7083 7084 // Now that the call site is handled, stop tracking it. 7085 MMI.setCurrentCallSite(0); 7086 } 7087 7088 // Both PendingLoads and PendingExports must be flushed here; 7089 // this call might not return. 7090 (void)getRoot(); 7091 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7092 7093 CLI.setChain(getRoot()); 7094 } 7095 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7096 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7097 7098 assert((CLI.IsTailCall || Result.second.getNode()) && 7099 "Non-null chain expected with non-tail call!"); 7100 assert((Result.second.getNode() || !Result.first.getNode()) && 7101 "Null value expected with tail call!"); 7102 7103 if (!Result.second.getNode()) { 7104 // As a special case, a null chain means that a tail call has been emitted 7105 // and the DAG root is already updated. 7106 HasTailCall = true; 7107 7108 // Since there's no actual continuation from this block, nothing can be 7109 // relying on us setting vregs for them. 7110 PendingExports.clear(); 7111 } else { 7112 DAG.setRoot(Result.second); 7113 } 7114 7115 if (EHPadBB) { 7116 // Insert a label at the end of the invoke call to mark the try range. This 7117 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7118 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7119 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7120 7121 // Inform MachineModuleInfo of range. 7122 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7123 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7124 // actually use outlined funclets and their LSDA info style. 7125 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7126 assert(CLI.CB); 7127 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7128 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7129 } else if (!isScopedEHPersonality(Pers)) { 7130 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7131 } 7132 } 7133 7134 return Result; 7135 } 7136 7137 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7138 bool isTailCall, 7139 const BasicBlock *EHPadBB) { 7140 auto &DL = DAG.getDataLayout(); 7141 FunctionType *FTy = CB.getFunctionType(); 7142 Type *RetTy = CB.getType(); 7143 7144 TargetLowering::ArgListTy Args; 7145 Args.reserve(CB.arg_size()); 7146 7147 const Value *SwiftErrorVal = nullptr; 7148 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7149 7150 if (isTailCall) { 7151 // Avoid emitting tail calls in functions with the disable-tail-calls 7152 // attribute. 7153 auto *Caller = CB.getParent()->getParent(); 7154 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7155 "true") 7156 isTailCall = false; 7157 7158 // We can't tail call inside a function with a swifterror argument. Lowering 7159 // does not support this yet. It would have to move into the swifterror 7160 // register before the call. 7161 if (TLI.supportSwiftError() && 7162 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7163 isTailCall = false; 7164 } 7165 7166 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7167 TargetLowering::ArgListEntry Entry; 7168 const Value *V = *I; 7169 7170 // Skip empty types 7171 if (V->getType()->isEmptyTy()) 7172 continue; 7173 7174 SDValue ArgNode = getValue(V); 7175 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7176 7177 Entry.setAttributes(&CB, I - CB.arg_begin()); 7178 7179 // Use swifterror virtual register as input to the call. 7180 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7181 SwiftErrorVal = V; 7182 // We find the virtual register for the actual swifterror argument. 7183 // Instead of using the Value, we use the virtual register instead. 7184 Entry.Node = 7185 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7186 EVT(TLI.getPointerTy(DL))); 7187 } 7188 7189 Args.push_back(Entry); 7190 7191 // If we have an explicit sret argument that is an Instruction, (i.e., it 7192 // might point to function-local memory), we can't meaningfully tail-call. 7193 if (Entry.IsSRet && isa<Instruction>(V)) 7194 isTailCall = false; 7195 } 7196 7197 // If call site has a cfguardtarget operand bundle, create and add an 7198 // additional ArgListEntry. 7199 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7200 TargetLowering::ArgListEntry Entry; 7201 Value *V = Bundle->Inputs[0]; 7202 SDValue ArgNode = getValue(V); 7203 Entry.Node = ArgNode; 7204 Entry.Ty = V->getType(); 7205 Entry.IsCFGuardTarget = true; 7206 Args.push_back(Entry); 7207 } 7208 7209 // Check if target-independent constraints permit a tail call here. 7210 // Target-dependent constraints are checked within TLI->LowerCallTo. 7211 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7212 isTailCall = false; 7213 7214 // Disable tail calls if there is an swifterror argument. Targets have not 7215 // been updated to support tail calls. 7216 if (TLI.supportSwiftError() && SwiftErrorVal) 7217 isTailCall = false; 7218 7219 TargetLowering::CallLoweringInfo CLI(DAG); 7220 CLI.setDebugLoc(getCurSDLoc()) 7221 .setChain(getRoot()) 7222 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7223 .setTailCall(isTailCall) 7224 .setConvergent(CB.isConvergent()) 7225 .setIsPreallocated( 7226 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7227 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7228 7229 if (Result.first.getNode()) { 7230 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7231 setValue(&CB, Result.first); 7232 } 7233 7234 // The last element of CLI.InVals has the SDValue for swifterror return. 7235 // Here we copy it to a virtual register and update SwiftErrorMap for 7236 // book-keeping. 7237 if (SwiftErrorVal && TLI.supportSwiftError()) { 7238 // Get the last element of InVals. 7239 SDValue Src = CLI.InVals.back(); 7240 Register VReg = 7241 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7242 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7243 DAG.setRoot(CopyNode); 7244 } 7245 } 7246 7247 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7248 SelectionDAGBuilder &Builder) { 7249 // Check to see if this load can be trivially constant folded, e.g. if the 7250 // input is from a string literal. 7251 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7252 // Cast pointer to the type we really want to load. 7253 Type *LoadTy = 7254 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7255 if (LoadVT.isVector()) 7256 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7257 7258 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7259 PointerType::getUnqual(LoadTy)); 7260 7261 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7262 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7263 return Builder.getValue(LoadCst); 7264 } 7265 7266 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7267 // still constant memory, the input chain can be the entry node. 7268 SDValue Root; 7269 bool ConstantMemory = false; 7270 7271 // Do not serialize (non-volatile) loads of constant memory with anything. 7272 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7273 Root = Builder.DAG.getEntryNode(); 7274 ConstantMemory = true; 7275 } else { 7276 // Do not serialize non-volatile loads against each other. 7277 Root = Builder.DAG.getRoot(); 7278 } 7279 7280 SDValue Ptr = Builder.getValue(PtrVal); 7281 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7282 Ptr, MachinePointerInfo(PtrVal), 7283 /* Alignment = */ 1); 7284 7285 if (!ConstantMemory) 7286 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7287 return LoadVal; 7288 } 7289 7290 /// Record the value for an instruction that produces an integer result, 7291 /// converting the type where necessary. 7292 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7293 SDValue Value, 7294 bool IsSigned) { 7295 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7296 I.getType(), true); 7297 if (IsSigned) 7298 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7299 else 7300 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7301 setValue(&I, Value); 7302 } 7303 7304 /// See if we can lower a memcmp call into an optimized form. If so, return 7305 /// true and lower it. Otherwise return false, and it will be lowered like a 7306 /// normal call. 7307 /// The caller already checked that \p I calls the appropriate LibFunc with a 7308 /// correct prototype. 7309 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7310 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7311 const Value *Size = I.getArgOperand(2); 7312 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7313 if (CSize && CSize->getZExtValue() == 0) { 7314 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7315 I.getType(), true); 7316 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7317 return true; 7318 } 7319 7320 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7321 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7322 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7323 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7324 if (Res.first.getNode()) { 7325 processIntegerCallValue(I, Res.first, true); 7326 PendingLoads.push_back(Res.second); 7327 return true; 7328 } 7329 7330 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7331 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7332 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7333 return false; 7334 7335 // If the target has a fast compare for the given size, it will return a 7336 // preferred load type for that size. Require that the load VT is legal and 7337 // that the target supports unaligned loads of that type. Otherwise, return 7338 // INVALID. 7339 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7340 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7341 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7342 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7343 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7344 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7345 // TODO: Check alignment of src and dest ptrs. 7346 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7347 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7348 if (!TLI.isTypeLegal(LVT) || 7349 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7350 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7351 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7352 } 7353 7354 return LVT; 7355 }; 7356 7357 // This turns into unaligned loads. We only do this if the target natively 7358 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7359 // we'll only produce a small number of byte loads. 7360 MVT LoadVT; 7361 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7362 switch (NumBitsToCompare) { 7363 default: 7364 return false; 7365 case 16: 7366 LoadVT = MVT::i16; 7367 break; 7368 case 32: 7369 LoadVT = MVT::i32; 7370 break; 7371 case 64: 7372 case 128: 7373 case 256: 7374 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7375 break; 7376 } 7377 7378 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7379 return false; 7380 7381 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7382 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7383 7384 // Bitcast to a wide integer type if the loads are vectors. 7385 if (LoadVT.isVector()) { 7386 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7387 LoadL = DAG.getBitcast(CmpVT, LoadL); 7388 LoadR = DAG.getBitcast(CmpVT, LoadR); 7389 } 7390 7391 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7392 processIntegerCallValue(I, Cmp, false); 7393 return true; 7394 } 7395 7396 /// See if we can lower a memchr call into an optimized form. If so, return 7397 /// true and lower it. Otherwise return false, and it will be lowered like a 7398 /// normal call. 7399 /// The caller already checked that \p I calls the appropriate LibFunc with a 7400 /// correct prototype. 7401 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7402 const Value *Src = I.getArgOperand(0); 7403 const Value *Char = I.getArgOperand(1); 7404 const Value *Length = I.getArgOperand(2); 7405 7406 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7407 std::pair<SDValue, SDValue> Res = 7408 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7409 getValue(Src), getValue(Char), getValue(Length), 7410 MachinePointerInfo(Src)); 7411 if (Res.first.getNode()) { 7412 setValue(&I, Res.first); 7413 PendingLoads.push_back(Res.second); 7414 return true; 7415 } 7416 7417 return false; 7418 } 7419 7420 /// See if we can lower a mempcpy call into an optimized form. If so, return 7421 /// true and lower it. Otherwise return false, and it will be lowered like a 7422 /// normal call. 7423 /// The caller already checked that \p I calls the appropriate LibFunc with a 7424 /// correct prototype. 7425 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7426 SDValue Dst = getValue(I.getArgOperand(0)); 7427 SDValue Src = getValue(I.getArgOperand(1)); 7428 SDValue Size = getValue(I.getArgOperand(2)); 7429 7430 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7431 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7432 // DAG::getMemcpy needs Alignment to be defined. 7433 Align Alignment = std::min(DstAlign, SrcAlign); 7434 7435 bool isVol = false; 7436 SDLoc sdl = getCurSDLoc(); 7437 7438 // In the mempcpy context we need to pass in a false value for isTailCall 7439 // because the return pointer needs to be adjusted by the size of 7440 // the copied memory. 7441 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7442 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7443 /*isTailCall=*/false, 7444 MachinePointerInfo(I.getArgOperand(0)), 7445 MachinePointerInfo(I.getArgOperand(1))); 7446 assert(MC.getNode() != nullptr && 7447 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7448 DAG.setRoot(MC); 7449 7450 // Check if Size needs to be truncated or extended. 7451 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7452 7453 // Adjust return pointer to point just past the last dst byte. 7454 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7455 Dst, Size); 7456 setValue(&I, DstPlusSize); 7457 return true; 7458 } 7459 7460 /// See if we can lower a strcpy call into an optimized form. If so, return 7461 /// true and lower it, otherwise return false and it will be lowered like a 7462 /// normal call. 7463 /// The caller already checked that \p I calls the appropriate LibFunc with a 7464 /// correct prototype. 7465 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7466 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7467 7468 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7469 std::pair<SDValue, SDValue> Res = 7470 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7471 getValue(Arg0), getValue(Arg1), 7472 MachinePointerInfo(Arg0), 7473 MachinePointerInfo(Arg1), isStpcpy); 7474 if (Res.first.getNode()) { 7475 setValue(&I, Res.first); 7476 DAG.setRoot(Res.second); 7477 return true; 7478 } 7479 7480 return false; 7481 } 7482 7483 /// See if we can lower a strcmp call into an optimized form. If so, return 7484 /// true and lower it, otherwise return false and it will be lowered like a 7485 /// normal call. 7486 /// The caller already checked that \p I calls the appropriate LibFunc with a 7487 /// correct prototype. 7488 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7489 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7490 7491 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7492 std::pair<SDValue, SDValue> Res = 7493 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7494 getValue(Arg0), getValue(Arg1), 7495 MachinePointerInfo(Arg0), 7496 MachinePointerInfo(Arg1)); 7497 if (Res.first.getNode()) { 7498 processIntegerCallValue(I, Res.first, true); 7499 PendingLoads.push_back(Res.second); 7500 return true; 7501 } 7502 7503 return false; 7504 } 7505 7506 /// See if we can lower a strlen call into an optimized form. If so, return 7507 /// true and lower it, otherwise return false and it will be lowered like a 7508 /// normal call. 7509 /// The caller already checked that \p I calls the appropriate LibFunc with a 7510 /// correct prototype. 7511 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7512 const Value *Arg0 = I.getArgOperand(0); 7513 7514 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7515 std::pair<SDValue, SDValue> Res = 7516 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7517 getValue(Arg0), MachinePointerInfo(Arg0)); 7518 if (Res.first.getNode()) { 7519 processIntegerCallValue(I, Res.first, false); 7520 PendingLoads.push_back(Res.second); 7521 return true; 7522 } 7523 7524 return false; 7525 } 7526 7527 /// See if we can lower a strnlen call into an optimized form. If so, return 7528 /// true and lower it, otherwise return false and it will be lowered like a 7529 /// normal call. 7530 /// The caller already checked that \p I calls the appropriate LibFunc with a 7531 /// correct prototype. 7532 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7533 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7534 7535 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7536 std::pair<SDValue, SDValue> Res = 7537 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7538 getValue(Arg0), getValue(Arg1), 7539 MachinePointerInfo(Arg0)); 7540 if (Res.first.getNode()) { 7541 processIntegerCallValue(I, Res.first, false); 7542 PendingLoads.push_back(Res.second); 7543 return true; 7544 } 7545 7546 return false; 7547 } 7548 7549 /// See if we can lower a unary floating-point operation into an SDNode with 7550 /// the specified Opcode. If so, return true and lower it, otherwise return 7551 /// false and it will be lowered like a normal call. 7552 /// The caller already checked that \p I calls the appropriate LibFunc with a 7553 /// correct prototype. 7554 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7555 unsigned Opcode) { 7556 // We already checked this call's prototype; verify it doesn't modify errno. 7557 if (!I.onlyReadsMemory()) 7558 return false; 7559 7560 SDValue Tmp = getValue(I.getArgOperand(0)); 7561 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7562 return true; 7563 } 7564 7565 /// See if we can lower a binary floating-point operation into an SDNode with 7566 /// the specified Opcode. If so, return true and lower it. Otherwise return 7567 /// false, and it will be lowered like a normal call. 7568 /// The caller already checked that \p I calls the appropriate LibFunc with a 7569 /// correct prototype. 7570 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7571 unsigned Opcode) { 7572 // We already checked this call's prototype; verify it doesn't modify errno. 7573 if (!I.onlyReadsMemory()) 7574 return false; 7575 7576 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7577 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7578 EVT VT = Tmp0.getValueType(); 7579 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7580 return true; 7581 } 7582 7583 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7584 // Handle inline assembly differently. 7585 if (I.isInlineAsm()) { 7586 visitInlineAsm(I); 7587 return; 7588 } 7589 7590 if (Function *F = I.getCalledFunction()) { 7591 if (F->isDeclaration()) { 7592 // Is this an LLVM intrinsic or a target-specific intrinsic? 7593 unsigned IID = F->getIntrinsicID(); 7594 if (!IID) 7595 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7596 IID = II->getIntrinsicID(F); 7597 7598 if (IID) { 7599 visitIntrinsicCall(I, IID); 7600 return; 7601 } 7602 } 7603 7604 // Check for well-known libc/libm calls. If the function is internal, it 7605 // can't be a library call. Don't do the check if marked as nobuiltin for 7606 // some reason or the call site requires strict floating point semantics. 7607 LibFunc Func; 7608 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7609 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7610 LibInfo->hasOptimizedCodeGen(Func)) { 7611 switch (Func) { 7612 default: break; 7613 case LibFunc_copysign: 7614 case LibFunc_copysignf: 7615 case LibFunc_copysignl: 7616 // We already checked this call's prototype; verify it doesn't modify 7617 // errno. 7618 if (I.onlyReadsMemory()) { 7619 SDValue LHS = getValue(I.getArgOperand(0)); 7620 SDValue RHS = getValue(I.getArgOperand(1)); 7621 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7622 LHS.getValueType(), LHS, RHS)); 7623 return; 7624 } 7625 break; 7626 case LibFunc_fabs: 7627 case LibFunc_fabsf: 7628 case LibFunc_fabsl: 7629 if (visitUnaryFloatCall(I, ISD::FABS)) 7630 return; 7631 break; 7632 case LibFunc_fmin: 7633 case LibFunc_fminf: 7634 case LibFunc_fminl: 7635 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7636 return; 7637 break; 7638 case LibFunc_fmax: 7639 case LibFunc_fmaxf: 7640 case LibFunc_fmaxl: 7641 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7642 return; 7643 break; 7644 case LibFunc_sin: 7645 case LibFunc_sinf: 7646 case LibFunc_sinl: 7647 if (visitUnaryFloatCall(I, ISD::FSIN)) 7648 return; 7649 break; 7650 case LibFunc_cos: 7651 case LibFunc_cosf: 7652 case LibFunc_cosl: 7653 if (visitUnaryFloatCall(I, ISD::FCOS)) 7654 return; 7655 break; 7656 case LibFunc_sqrt: 7657 case LibFunc_sqrtf: 7658 case LibFunc_sqrtl: 7659 case LibFunc_sqrt_finite: 7660 case LibFunc_sqrtf_finite: 7661 case LibFunc_sqrtl_finite: 7662 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7663 return; 7664 break; 7665 case LibFunc_floor: 7666 case LibFunc_floorf: 7667 case LibFunc_floorl: 7668 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7669 return; 7670 break; 7671 case LibFunc_nearbyint: 7672 case LibFunc_nearbyintf: 7673 case LibFunc_nearbyintl: 7674 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7675 return; 7676 break; 7677 case LibFunc_ceil: 7678 case LibFunc_ceilf: 7679 case LibFunc_ceill: 7680 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7681 return; 7682 break; 7683 case LibFunc_rint: 7684 case LibFunc_rintf: 7685 case LibFunc_rintl: 7686 if (visitUnaryFloatCall(I, ISD::FRINT)) 7687 return; 7688 break; 7689 case LibFunc_round: 7690 case LibFunc_roundf: 7691 case LibFunc_roundl: 7692 if (visitUnaryFloatCall(I, ISD::FROUND)) 7693 return; 7694 break; 7695 case LibFunc_trunc: 7696 case LibFunc_truncf: 7697 case LibFunc_truncl: 7698 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7699 return; 7700 break; 7701 case LibFunc_log2: 7702 case LibFunc_log2f: 7703 case LibFunc_log2l: 7704 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7705 return; 7706 break; 7707 case LibFunc_exp2: 7708 case LibFunc_exp2f: 7709 case LibFunc_exp2l: 7710 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7711 return; 7712 break; 7713 case LibFunc_memcmp: 7714 if (visitMemCmpCall(I)) 7715 return; 7716 break; 7717 case LibFunc_mempcpy: 7718 if (visitMemPCpyCall(I)) 7719 return; 7720 break; 7721 case LibFunc_memchr: 7722 if (visitMemChrCall(I)) 7723 return; 7724 break; 7725 case LibFunc_strcpy: 7726 if (visitStrCpyCall(I, false)) 7727 return; 7728 break; 7729 case LibFunc_stpcpy: 7730 if (visitStrCpyCall(I, true)) 7731 return; 7732 break; 7733 case LibFunc_strcmp: 7734 if (visitStrCmpCall(I)) 7735 return; 7736 break; 7737 case LibFunc_strlen: 7738 if (visitStrLenCall(I)) 7739 return; 7740 break; 7741 case LibFunc_strnlen: 7742 if (visitStrNLenCall(I)) 7743 return; 7744 break; 7745 } 7746 } 7747 } 7748 7749 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7750 // have to do anything here to lower funclet bundles. 7751 // CFGuardTarget bundles are lowered in LowerCallTo. 7752 assert(!I.hasOperandBundlesOtherThan( 7753 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7754 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) && 7755 "Cannot lower calls with arbitrary operand bundles!"); 7756 7757 SDValue Callee = getValue(I.getCalledOperand()); 7758 7759 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7760 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7761 else 7762 // Check if we can potentially perform a tail call. More detailed checking 7763 // is be done within LowerCallTo, after more information about the call is 7764 // known. 7765 LowerCallTo(I, Callee, I.isTailCall()); 7766 } 7767 7768 namespace { 7769 7770 /// AsmOperandInfo - This contains information for each constraint that we are 7771 /// lowering. 7772 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7773 public: 7774 /// CallOperand - If this is the result output operand or a clobber 7775 /// this is null, otherwise it is the incoming operand to the CallInst. 7776 /// This gets modified as the asm is processed. 7777 SDValue CallOperand; 7778 7779 /// AssignedRegs - If this is a register or register class operand, this 7780 /// contains the set of register corresponding to the operand. 7781 RegsForValue AssignedRegs; 7782 7783 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7784 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7785 } 7786 7787 /// Whether or not this operand accesses memory 7788 bool hasMemory(const TargetLowering &TLI) const { 7789 // Indirect operand accesses access memory. 7790 if (isIndirect) 7791 return true; 7792 7793 for (const auto &Code : Codes) 7794 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7795 return true; 7796 7797 return false; 7798 } 7799 7800 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7801 /// corresponds to. If there is no Value* for this operand, it returns 7802 /// MVT::Other. 7803 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7804 const DataLayout &DL) const { 7805 if (!CallOperandVal) return MVT::Other; 7806 7807 if (isa<BasicBlock>(CallOperandVal)) 7808 return TLI.getProgramPointerTy(DL); 7809 7810 llvm::Type *OpTy = CallOperandVal->getType(); 7811 7812 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7813 // If this is an indirect operand, the operand is a pointer to the 7814 // accessed type. 7815 if (isIndirect) { 7816 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7817 if (!PtrTy) 7818 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7819 OpTy = PtrTy->getElementType(); 7820 } 7821 7822 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7823 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7824 if (STy->getNumElements() == 1) 7825 OpTy = STy->getElementType(0); 7826 7827 // If OpTy is not a single value, it may be a struct/union that we 7828 // can tile with integers. 7829 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7830 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7831 switch (BitSize) { 7832 default: break; 7833 case 1: 7834 case 8: 7835 case 16: 7836 case 32: 7837 case 64: 7838 case 128: 7839 OpTy = IntegerType::get(Context, BitSize); 7840 break; 7841 } 7842 } 7843 7844 return TLI.getValueType(DL, OpTy, true); 7845 } 7846 }; 7847 7848 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7849 7850 } // end anonymous namespace 7851 7852 /// Make sure that the output operand \p OpInfo and its corresponding input 7853 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7854 /// out). 7855 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7856 SDISelAsmOperandInfo &MatchingOpInfo, 7857 SelectionDAG &DAG) { 7858 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7859 return; 7860 7861 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7862 const auto &TLI = DAG.getTargetLoweringInfo(); 7863 7864 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7865 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7866 OpInfo.ConstraintVT); 7867 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7868 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7869 MatchingOpInfo.ConstraintVT); 7870 if ((OpInfo.ConstraintVT.isInteger() != 7871 MatchingOpInfo.ConstraintVT.isInteger()) || 7872 (MatchRC.second != InputRC.second)) { 7873 // FIXME: error out in a more elegant fashion 7874 report_fatal_error("Unsupported asm: input constraint" 7875 " with a matching output constraint of" 7876 " incompatible type!"); 7877 } 7878 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7879 } 7880 7881 /// Get a direct memory input to behave well as an indirect operand. 7882 /// This may introduce stores, hence the need for a \p Chain. 7883 /// \return The (possibly updated) chain. 7884 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7885 SDISelAsmOperandInfo &OpInfo, 7886 SelectionDAG &DAG) { 7887 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7888 7889 // If we don't have an indirect input, put it in the constpool if we can, 7890 // otherwise spill it to a stack slot. 7891 // TODO: This isn't quite right. We need to handle these according to 7892 // the addressing mode that the constraint wants. Also, this may take 7893 // an additional register for the computation and we don't want that 7894 // either. 7895 7896 // If the operand is a float, integer, or vector constant, spill to a 7897 // constant pool entry to get its address. 7898 const Value *OpVal = OpInfo.CallOperandVal; 7899 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7900 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7901 OpInfo.CallOperand = DAG.getConstantPool( 7902 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7903 return Chain; 7904 } 7905 7906 // Otherwise, create a stack slot and emit a store to it before the asm. 7907 Type *Ty = OpVal->getType(); 7908 auto &DL = DAG.getDataLayout(); 7909 uint64_t TySize = DL.getTypeAllocSize(Ty); 7910 MachineFunction &MF = DAG.getMachineFunction(); 7911 int SSFI = MF.getFrameInfo().CreateStackObject( 7912 TySize, DL.getPrefTypeAlign(Ty), false); 7913 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7914 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7915 MachinePointerInfo::getFixedStack(MF, SSFI), 7916 TLI.getMemValueType(DL, Ty)); 7917 OpInfo.CallOperand = StackSlot; 7918 7919 return Chain; 7920 } 7921 7922 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7923 /// specified operand. We prefer to assign virtual registers, to allow the 7924 /// register allocator to handle the assignment process. However, if the asm 7925 /// uses features that we can't model on machineinstrs, we have SDISel do the 7926 /// allocation. This produces generally horrible, but correct, code. 7927 /// 7928 /// OpInfo describes the operand 7929 /// RefOpInfo describes the matching operand if any, the operand otherwise 7930 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7931 SDISelAsmOperandInfo &OpInfo, 7932 SDISelAsmOperandInfo &RefOpInfo) { 7933 LLVMContext &Context = *DAG.getContext(); 7934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7935 7936 MachineFunction &MF = DAG.getMachineFunction(); 7937 SmallVector<unsigned, 4> Regs; 7938 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7939 7940 // No work to do for memory operations. 7941 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7942 return; 7943 7944 // If this is a constraint for a single physreg, or a constraint for a 7945 // register class, find it. 7946 unsigned AssignedReg; 7947 const TargetRegisterClass *RC; 7948 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7949 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7950 // RC is unset only on failure. Return immediately. 7951 if (!RC) 7952 return; 7953 7954 // Get the actual register value type. This is important, because the user 7955 // may have asked for (e.g.) the AX register in i32 type. We need to 7956 // remember that AX is actually i16 to get the right extension. 7957 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7958 7959 if (OpInfo.ConstraintVT != MVT::Other) { 7960 // If this is an FP operand in an integer register (or visa versa), or more 7961 // generally if the operand value disagrees with the register class we plan 7962 // to stick it in, fix the operand type. 7963 // 7964 // If this is an input value, the bitcast to the new type is done now. 7965 // Bitcast for output value is done at the end of visitInlineAsm(). 7966 if ((OpInfo.Type == InlineAsm::isOutput || 7967 OpInfo.Type == InlineAsm::isInput) && 7968 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7969 // Try to convert to the first EVT that the reg class contains. If the 7970 // types are identical size, use a bitcast to convert (e.g. two differing 7971 // vector types). Note: output bitcast is done at the end of 7972 // visitInlineAsm(). 7973 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7974 // Exclude indirect inputs while they are unsupported because the code 7975 // to perform the load is missing and thus OpInfo.CallOperand still 7976 // refers to the input address rather than the pointed-to value. 7977 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7978 OpInfo.CallOperand = 7979 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7980 OpInfo.ConstraintVT = RegVT; 7981 // If the operand is an FP value and we want it in integer registers, 7982 // use the corresponding integer type. This turns an f64 value into 7983 // i64, which can be passed with two i32 values on a 32-bit machine. 7984 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7985 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7986 if (OpInfo.Type == InlineAsm::isInput) 7987 OpInfo.CallOperand = 7988 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7989 OpInfo.ConstraintVT = VT; 7990 } 7991 } 7992 } 7993 7994 // No need to allocate a matching input constraint since the constraint it's 7995 // matching to has already been allocated. 7996 if (OpInfo.isMatchingInputConstraint()) 7997 return; 7998 7999 EVT ValueVT = OpInfo.ConstraintVT; 8000 if (OpInfo.ConstraintVT == MVT::Other) 8001 ValueVT = RegVT; 8002 8003 // Initialize NumRegs. 8004 unsigned NumRegs = 1; 8005 if (OpInfo.ConstraintVT != MVT::Other) 8006 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8007 8008 // If this is a constraint for a specific physical register, like {r17}, 8009 // assign it now. 8010 8011 // If this associated to a specific register, initialize iterator to correct 8012 // place. If virtual, make sure we have enough registers 8013 8014 // Initialize iterator if necessary 8015 TargetRegisterClass::iterator I = RC->begin(); 8016 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8017 8018 // Do not check for single registers. 8019 if (AssignedReg) { 8020 for (; *I != AssignedReg; ++I) 8021 assert(I != RC->end() && "AssignedReg should be member of RC"); 8022 } 8023 8024 for (; NumRegs; --NumRegs, ++I) { 8025 assert(I != RC->end() && "Ran out of registers to allocate!"); 8026 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8027 Regs.push_back(R); 8028 } 8029 8030 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8031 } 8032 8033 static unsigned 8034 findMatchingInlineAsmOperand(unsigned OperandNo, 8035 const std::vector<SDValue> &AsmNodeOperands) { 8036 // Scan until we find the definition we already emitted of this operand. 8037 unsigned CurOp = InlineAsm::Op_FirstOperand; 8038 for (; OperandNo; --OperandNo) { 8039 // Advance to the next operand. 8040 unsigned OpFlag = 8041 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8042 assert((InlineAsm::isRegDefKind(OpFlag) || 8043 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8044 InlineAsm::isMemKind(OpFlag)) && 8045 "Skipped past definitions?"); 8046 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8047 } 8048 return CurOp; 8049 } 8050 8051 namespace { 8052 8053 class ExtraFlags { 8054 unsigned Flags = 0; 8055 8056 public: 8057 explicit ExtraFlags(const CallBase &Call) { 8058 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8059 if (IA->hasSideEffects()) 8060 Flags |= InlineAsm::Extra_HasSideEffects; 8061 if (IA->isAlignStack()) 8062 Flags |= InlineAsm::Extra_IsAlignStack; 8063 if (Call.isConvergent()) 8064 Flags |= InlineAsm::Extra_IsConvergent; 8065 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8066 } 8067 8068 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8069 // Ideally, we would only check against memory constraints. However, the 8070 // meaning of an Other constraint can be target-specific and we can't easily 8071 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8072 // for Other constraints as well. 8073 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8074 OpInfo.ConstraintType == TargetLowering::C_Other) { 8075 if (OpInfo.Type == InlineAsm::isInput) 8076 Flags |= InlineAsm::Extra_MayLoad; 8077 else if (OpInfo.Type == InlineAsm::isOutput) 8078 Flags |= InlineAsm::Extra_MayStore; 8079 else if (OpInfo.Type == InlineAsm::isClobber) 8080 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8081 } 8082 } 8083 8084 unsigned get() const { return Flags; } 8085 }; 8086 8087 } // end anonymous namespace 8088 8089 /// visitInlineAsm - Handle a call to an InlineAsm object. 8090 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8091 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8092 8093 /// ConstraintOperands - Information about all of the constraints. 8094 SDISelAsmOperandInfoVector ConstraintOperands; 8095 8096 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8097 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8098 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8099 8100 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8101 // AsmDialect, MayLoad, MayStore). 8102 bool HasSideEffect = IA->hasSideEffects(); 8103 ExtraFlags ExtraInfo(Call); 8104 8105 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8106 unsigned ResNo = 0; // ResNo - The result number of the next output. 8107 unsigned NumMatchingOps = 0; 8108 for (auto &T : TargetConstraints) { 8109 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8110 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8111 8112 // Compute the value type for each operand. 8113 if (OpInfo.Type == InlineAsm::isInput || 8114 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8115 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8116 8117 // Process the call argument. BasicBlocks are labels, currently appearing 8118 // only in asm's. 8119 if (isa<CallBrInst>(Call) && 8120 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8121 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8122 NumMatchingOps) && 8123 (NumMatchingOps == 0 || 8124 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8125 NumMatchingOps))) { 8126 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8127 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8128 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8129 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8130 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8131 } else { 8132 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8133 } 8134 8135 OpInfo.ConstraintVT = 8136 OpInfo 8137 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8138 .getSimpleVT(); 8139 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8140 // The return value of the call is this value. As such, there is no 8141 // corresponding argument. 8142 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8143 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8144 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8145 DAG.getDataLayout(), STy->getElementType(ResNo)); 8146 } else { 8147 assert(ResNo == 0 && "Asm only has one result!"); 8148 OpInfo.ConstraintVT = 8149 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8150 } 8151 ++ResNo; 8152 } else { 8153 OpInfo.ConstraintVT = MVT::Other; 8154 } 8155 8156 if (OpInfo.hasMatchingInput()) 8157 ++NumMatchingOps; 8158 8159 if (!HasSideEffect) 8160 HasSideEffect = OpInfo.hasMemory(TLI); 8161 8162 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8163 // FIXME: Could we compute this on OpInfo rather than T? 8164 8165 // Compute the constraint code and ConstraintType to use. 8166 TLI.ComputeConstraintToUse(T, SDValue()); 8167 8168 if (T.ConstraintType == TargetLowering::C_Immediate && 8169 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8170 // We've delayed emitting a diagnostic like the "n" constraint because 8171 // inlining could cause an integer showing up. 8172 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8173 "' expects an integer constant " 8174 "expression"); 8175 8176 ExtraInfo.update(T); 8177 } 8178 8179 8180 // We won't need to flush pending loads if this asm doesn't touch 8181 // memory and is nonvolatile. 8182 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8183 8184 bool IsCallBr = isa<CallBrInst>(Call); 8185 if (IsCallBr) { 8186 // If this is a callbr we need to flush pending exports since inlineasm_br 8187 // is a terminator. We need to do this before nodes are glued to 8188 // the inlineasm_br node. 8189 Chain = getControlRoot(); 8190 } 8191 8192 // Second pass over the constraints: compute which constraint option to use. 8193 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8194 // If this is an output operand with a matching input operand, look up the 8195 // matching input. If their types mismatch, e.g. one is an integer, the 8196 // other is floating point, or their sizes are different, flag it as an 8197 // error. 8198 if (OpInfo.hasMatchingInput()) { 8199 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8200 patchMatchingInput(OpInfo, Input, DAG); 8201 } 8202 8203 // Compute the constraint code and ConstraintType to use. 8204 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8205 8206 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8207 OpInfo.Type == InlineAsm::isClobber) 8208 continue; 8209 8210 // If this is a memory input, and if the operand is not indirect, do what we 8211 // need to provide an address for the memory input. 8212 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8213 !OpInfo.isIndirect) { 8214 assert((OpInfo.isMultipleAlternative || 8215 (OpInfo.Type == InlineAsm::isInput)) && 8216 "Can only indirectify direct input operands!"); 8217 8218 // Memory operands really want the address of the value. 8219 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8220 8221 // There is no longer a Value* corresponding to this operand. 8222 OpInfo.CallOperandVal = nullptr; 8223 8224 // It is now an indirect operand. 8225 OpInfo.isIndirect = true; 8226 } 8227 8228 } 8229 8230 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8231 std::vector<SDValue> AsmNodeOperands; 8232 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8233 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8234 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8235 8236 // If we have a !srcloc metadata node associated with it, we want to attach 8237 // this to the ultimately generated inline asm machineinstr. To do this, we 8238 // pass in the third operand as this (potentially null) inline asm MDNode. 8239 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8240 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8241 8242 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8243 // bits as operand 3. 8244 AsmNodeOperands.push_back(DAG.getTargetConstant( 8245 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8246 8247 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8248 // this, assign virtual and physical registers for inputs and otput. 8249 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8250 // Assign Registers. 8251 SDISelAsmOperandInfo &RefOpInfo = 8252 OpInfo.isMatchingInputConstraint() 8253 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8254 : OpInfo; 8255 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8256 8257 auto DetectWriteToReservedRegister = [&]() { 8258 const MachineFunction &MF = DAG.getMachineFunction(); 8259 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8260 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8261 if (Register::isPhysicalRegister(Reg) && 8262 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8263 const char *RegName = TRI.getName(Reg); 8264 emitInlineAsmError(Call, "write to reserved register '" + 8265 Twine(RegName) + "'"); 8266 return true; 8267 } 8268 } 8269 return false; 8270 }; 8271 8272 switch (OpInfo.Type) { 8273 case InlineAsm::isOutput: 8274 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8275 unsigned ConstraintID = 8276 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8277 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8278 "Failed to convert memory constraint code to constraint id."); 8279 8280 // Add information to the INLINEASM node to know about this output. 8281 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8282 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8283 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8284 MVT::i32)); 8285 AsmNodeOperands.push_back(OpInfo.CallOperand); 8286 } else { 8287 // Otherwise, this outputs to a register (directly for C_Register / 8288 // C_RegisterClass, and a target-defined fashion for 8289 // C_Immediate/C_Other). Find a register that we can use. 8290 if (OpInfo.AssignedRegs.Regs.empty()) { 8291 emitInlineAsmError( 8292 Call, "couldn't allocate output register for constraint '" + 8293 Twine(OpInfo.ConstraintCode) + "'"); 8294 return; 8295 } 8296 8297 if (DetectWriteToReservedRegister()) 8298 return; 8299 8300 // Add information to the INLINEASM node to know that this register is 8301 // set. 8302 OpInfo.AssignedRegs.AddInlineAsmOperands( 8303 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8304 : InlineAsm::Kind_RegDef, 8305 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8306 } 8307 break; 8308 8309 case InlineAsm::isInput: { 8310 SDValue InOperandVal = OpInfo.CallOperand; 8311 8312 if (OpInfo.isMatchingInputConstraint()) { 8313 // If this is required to match an output register we have already set, 8314 // just use its register. 8315 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8316 AsmNodeOperands); 8317 unsigned OpFlag = 8318 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8319 if (InlineAsm::isRegDefKind(OpFlag) || 8320 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8321 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8322 if (OpInfo.isIndirect) { 8323 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8324 emitInlineAsmError(Call, "inline asm not supported yet: " 8325 "don't know how to handle tied " 8326 "indirect register inputs"); 8327 return; 8328 } 8329 8330 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8331 SmallVector<unsigned, 4> Regs; 8332 8333 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8334 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8335 MachineRegisterInfo &RegInfo = 8336 DAG.getMachineFunction().getRegInfo(); 8337 for (unsigned i = 0; i != NumRegs; ++i) 8338 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8339 } else { 8340 emitInlineAsmError(Call, 8341 "inline asm error: This value type register " 8342 "class is not natively supported!"); 8343 return; 8344 } 8345 8346 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8347 8348 SDLoc dl = getCurSDLoc(); 8349 // Use the produced MatchedRegs object to 8350 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8351 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8352 true, OpInfo.getMatchedOperand(), dl, 8353 DAG, AsmNodeOperands); 8354 break; 8355 } 8356 8357 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8358 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8359 "Unexpected number of operands"); 8360 // Add information to the INLINEASM node to know about this input. 8361 // See InlineAsm.h isUseOperandTiedToDef. 8362 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8363 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8364 OpInfo.getMatchedOperand()); 8365 AsmNodeOperands.push_back(DAG.getTargetConstant( 8366 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8367 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8368 break; 8369 } 8370 8371 // Treat indirect 'X' constraint as memory. 8372 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8373 OpInfo.isIndirect) 8374 OpInfo.ConstraintType = TargetLowering::C_Memory; 8375 8376 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8377 OpInfo.ConstraintType == TargetLowering::C_Other) { 8378 std::vector<SDValue> Ops; 8379 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8380 Ops, DAG); 8381 if (Ops.empty()) { 8382 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8383 if (isa<ConstantSDNode>(InOperandVal)) { 8384 emitInlineAsmError(Call, "value out of range for constraint '" + 8385 Twine(OpInfo.ConstraintCode) + "'"); 8386 return; 8387 } 8388 8389 emitInlineAsmError(Call, 8390 "invalid operand for inline asm constraint '" + 8391 Twine(OpInfo.ConstraintCode) + "'"); 8392 return; 8393 } 8394 8395 // Add information to the INLINEASM node to know about this input. 8396 unsigned ResOpType = 8397 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8398 AsmNodeOperands.push_back(DAG.getTargetConstant( 8399 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8400 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8401 break; 8402 } 8403 8404 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8405 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8406 assert(InOperandVal.getValueType() == 8407 TLI.getPointerTy(DAG.getDataLayout()) && 8408 "Memory operands expect pointer values"); 8409 8410 unsigned ConstraintID = 8411 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8412 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8413 "Failed to convert memory constraint code to constraint id."); 8414 8415 // Add information to the INLINEASM node to know about this input. 8416 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8417 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8418 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8419 getCurSDLoc(), 8420 MVT::i32)); 8421 AsmNodeOperands.push_back(InOperandVal); 8422 break; 8423 } 8424 8425 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8426 OpInfo.ConstraintType == TargetLowering::C_Register) && 8427 "Unknown constraint type!"); 8428 8429 // TODO: Support this. 8430 if (OpInfo.isIndirect) { 8431 emitInlineAsmError( 8432 Call, "Don't know how to handle indirect register inputs yet " 8433 "for constraint '" + 8434 Twine(OpInfo.ConstraintCode) + "'"); 8435 return; 8436 } 8437 8438 // Copy the input into the appropriate registers. 8439 if (OpInfo.AssignedRegs.Regs.empty()) { 8440 emitInlineAsmError(Call, 8441 "couldn't allocate input reg for constraint '" + 8442 Twine(OpInfo.ConstraintCode) + "'"); 8443 return; 8444 } 8445 8446 if (DetectWriteToReservedRegister()) 8447 return; 8448 8449 SDLoc dl = getCurSDLoc(); 8450 8451 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8452 &Call); 8453 8454 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8455 dl, DAG, AsmNodeOperands); 8456 break; 8457 } 8458 case InlineAsm::isClobber: 8459 // Add the clobbered value to the operand list, so that the register 8460 // allocator is aware that the physreg got clobbered. 8461 if (!OpInfo.AssignedRegs.Regs.empty()) 8462 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8463 false, 0, getCurSDLoc(), DAG, 8464 AsmNodeOperands); 8465 break; 8466 } 8467 } 8468 8469 // Finish up input operands. Set the input chain and add the flag last. 8470 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8471 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8472 8473 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8474 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8475 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8476 Flag = Chain.getValue(1); 8477 8478 // Do additional work to generate outputs. 8479 8480 SmallVector<EVT, 1> ResultVTs; 8481 SmallVector<SDValue, 1> ResultValues; 8482 SmallVector<SDValue, 8> OutChains; 8483 8484 llvm::Type *CallResultType = Call.getType(); 8485 ArrayRef<Type *> ResultTypes; 8486 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8487 ResultTypes = StructResult->elements(); 8488 else if (!CallResultType->isVoidTy()) 8489 ResultTypes = makeArrayRef(CallResultType); 8490 8491 auto CurResultType = ResultTypes.begin(); 8492 auto handleRegAssign = [&](SDValue V) { 8493 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8494 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8495 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8496 ++CurResultType; 8497 // If the type of the inline asm call site return value is different but has 8498 // same size as the type of the asm output bitcast it. One example of this 8499 // is for vectors with different width / number of elements. This can 8500 // happen for register classes that can contain multiple different value 8501 // types. The preg or vreg allocated may not have the same VT as was 8502 // expected. 8503 // 8504 // This can also happen for a return value that disagrees with the register 8505 // class it is put in, eg. a double in a general-purpose register on a 8506 // 32-bit machine. 8507 if (ResultVT != V.getValueType() && 8508 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8509 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8510 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8511 V.getValueType().isInteger()) { 8512 // If a result value was tied to an input value, the computed result 8513 // may have a wider width than the expected result. Extract the 8514 // relevant portion. 8515 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8516 } 8517 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8518 ResultVTs.push_back(ResultVT); 8519 ResultValues.push_back(V); 8520 }; 8521 8522 // Deal with output operands. 8523 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8524 if (OpInfo.Type == InlineAsm::isOutput) { 8525 SDValue Val; 8526 // Skip trivial output operands. 8527 if (OpInfo.AssignedRegs.Regs.empty()) 8528 continue; 8529 8530 switch (OpInfo.ConstraintType) { 8531 case TargetLowering::C_Register: 8532 case TargetLowering::C_RegisterClass: 8533 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8534 Chain, &Flag, &Call); 8535 break; 8536 case TargetLowering::C_Immediate: 8537 case TargetLowering::C_Other: 8538 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8539 OpInfo, DAG); 8540 break; 8541 case TargetLowering::C_Memory: 8542 break; // Already handled. 8543 case TargetLowering::C_Unknown: 8544 assert(false && "Unexpected unknown constraint"); 8545 } 8546 8547 // Indirect output manifest as stores. Record output chains. 8548 if (OpInfo.isIndirect) { 8549 const Value *Ptr = OpInfo.CallOperandVal; 8550 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8551 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8552 MachinePointerInfo(Ptr)); 8553 OutChains.push_back(Store); 8554 } else { 8555 // generate CopyFromRegs to associated registers. 8556 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8557 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8558 for (const SDValue &V : Val->op_values()) 8559 handleRegAssign(V); 8560 } else 8561 handleRegAssign(Val); 8562 } 8563 } 8564 } 8565 8566 // Set results. 8567 if (!ResultValues.empty()) { 8568 assert(CurResultType == ResultTypes.end() && 8569 "Mismatch in number of ResultTypes"); 8570 assert(ResultValues.size() == ResultTypes.size() && 8571 "Mismatch in number of output operands in asm result"); 8572 8573 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8574 DAG.getVTList(ResultVTs), ResultValues); 8575 setValue(&Call, V); 8576 } 8577 8578 // Collect store chains. 8579 if (!OutChains.empty()) 8580 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8581 8582 // Only Update Root if inline assembly has a memory effect. 8583 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8584 DAG.setRoot(Chain); 8585 } 8586 8587 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8588 const Twine &Message) { 8589 LLVMContext &Ctx = *DAG.getContext(); 8590 Ctx.emitError(&Call, Message); 8591 8592 // Make sure we leave the DAG in a valid state 8593 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8594 SmallVector<EVT, 1> ValueVTs; 8595 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8596 8597 if (ValueVTs.empty()) 8598 return; 8599 8600 SmallVector<SDValue, 1> Ops; 8601 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8602 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8603 8604 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8605 } 8606 8607 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8608 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8609 MVT::Other, getRoot(), 8610 getValue(I.getArgOperand(0)), 8611 DAG.getSrcValue(I.getArgOperand(0)))); 8612 } 8613 8614 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8615 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8616 const DataLayout &DL = DAG.getDataLayout(); 8617 SDValue V = DAG.getVAArg( 8618 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8619 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8620 DL.getABITypeAlign(I.getType()).value()); 8621 DAG.setRoot(V.getValue(1)); 8622 8623 if (I.getType()->isPointerTy()) 8624 V = DAG.getPtrExtOrTrunc( 8625 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8626 setValue(&I, V); 8627 } 8628 8629 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8630 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8631 MVT::Other, getRoot(), 8632 getValue(I.getArgOperand(0)), 8633 DAG.getSrcValue(I.getArgOperand(0)))); 8634 } 8635 8636 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8637 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8638 MVT::Other, getRoot(), 8639 getValue(I.getArgOperand(0)), 8640 getValue(I.getArgOperand(1)), 8641 DAG.getSrcValue(I.getArgOperand(0)), 8642 DAG.getSrcValue(I.getArgOperand(1)))); 8643 } 8644 8645 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8646 const Instruction &I, 8647 SDValue Op) { 8648 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8649 if (!Range) 8650 return Op; 8651 8652 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8653 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8654 return Op; 8655 8656 APInt Lo = CR.getUnsignedMin(); 8657 if (!Lo.isMinValue()) 8658 return Op; 8659 8660 APInt Hi = CR.getUnsignedMax(); 8661 unsigned Bits = std::max(Hi.getActiveBits(), 8662 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8663 8664 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8665 8666 SDLoc SL = getCurSDLoc(); 8667 8668 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8669 DAG.getValueType(SmallVT)); 8670 unsigned NumVals = Op.getNode()->getNumValues(); 8671 if (NumVals == 1) 8672 return ZExt; 8673 8674 SmallVector<SDValue, 4> Ops; 8675 8676 Ops.push_back(ZExt); 8677 for (unsigned I = 1; I != NumVals; ++I) 8678 Ops.push_back(Op.getValue(I)); 8679 8680 return DAG.getMergeValues(Ops, SL); 8681 } 8682 8683 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8684 /// the call being lowered. 8685 /// 8686 /// This is a helper for lowering intrinsics that follow a target calling 8687 /// convention or require stack pointer adjustment. Only a subset of the 8688 /// intrinsic's operands need to participate in the calling convention. 8689 void SelectionDAGBuilder::populateCallLoweringInfo( 8690 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8691 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8692 bool IsPatchPoint) { 8693 TargetLowering::ArgListTy Args; 8694 Args.reserve(NumArgs); 8695 8696 // Populate the argument list. 8697 // Attributes for args start at offset 1, after the return attribute. 8698 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8699 ArgI != ArgE; ++ArgI) { 8700 const Value *V = Call->getOperand(ArgI); 8701 8702 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8703 8704 TargetLowering::ArgListEntry Entry; 8705 Entry.Node = getValue(V); 8706 Entry.Ty = V->getType(); 8707 Entry.setAttributes(Call, ArgI); 8708 Args.push_back(Entry); 8709 } 8710 8711 CLI.setDebugLoc(getCurSDLoc()) 8712 .setChain(getRoot()) 8713 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8714 .setDiscardResult(Call->use_empty()) 8715 .setIsPatchPoint(IsPatchPoint) 8716 .setIsPreallocated( 8717 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8718 } 8719 8720 /// Add a stack map intrinsic call's live variable operands to a stackmap 8721 /// or patchpoint target node's operand list. 8722 /// 8723 /// Constants are converted to TargetConstants purely as an optimization to 8724 /// avoid constant materialization and register allocation. 8725 /// 8726 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8727 /// generate addess computation nodes, and so FinalizeISel can convert the 8728 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8729 /// address materialization and register allocation, but may also be required 8730 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8731 /// alloca in the entry block, then the runtime may assume that the alloca's 8732 /// StackMap location can be read immediately after compilation and that the 8733 /// location is valid at any point during execution (this is similar to the 8734 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8735 /// only available in a register, then the runtime would need to trap when 8736 /// execution reaches the StackMap in order to read the alloca's location. 8737 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8738 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8739 SelectionDAGBuilder &Builder) { 8740 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8741 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8742 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8743 Ops.push_back( 8744 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8745 Ops.push_back( 8746 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8747 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8748 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8749 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8750 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8751 } else 8752 Ops.push_back(OpVal); 8753 } 8754 } 8755 8756 /// Lower llvm.experimental.stackmap directly to its target opcode. 8757 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8758 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8759 // [live variables...]) 8760 8761 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8762 8763 SDValue Chain, InFlag, Callee, NullPtr; 8764 SmallVector<SDValue, 32> Ops; 8765 8766 SDLoc DL = getCurSDLoc(); 8767 Callee = getValue(CI.getCalledOperand()); 8768 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8769 8770 // The stackmap intrinsic only records the live variables (the arguments 8771 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8772 // intrinsic, this won't be lowered to a function call. This means we don't 8773 // have to worry about calling conventions and target specific lowering code. 8774 // Instead we perform the call lowering right here. 8775 // 8776 // chain, flag = CALLSEQ_START(chain, 0, 0) 8777 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8778 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8779 // 8780 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8781 InFlag = Chain.getValue(1); 8782 8783 // Add the <id> and <numBytes> constants. 8784 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8785 Ops.push_back(DAG.getTargetConstant( 8786 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8787 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8788 Ops.push_back(DAG.getTargetConstant( 8789 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8790 MVT::i32)); 8791 8792 // Push live variables for the stack map. 8793 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8794 8795 // We are not pushing any register mask info here on the operands list, 8796 // because the stackmap doesn't clobber anything. 8797 8798 // Push the chain and the glue flag. 8799 Ops.push_back(Chain); 8800 Ops.push_back(InFlag); 8801 8802 // Create the STACKMAP node. 8803 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8804 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8805 Chain = SDValue(SM, 0); 8806 InFlag = Chain.getValue(1); 8807 8808 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8809 8810 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8811 8812 // Set the root to the target-lowered call chain. 8813 DAG.setRoot(Chain); 8814 8815 // Inform the Frame Information that we have a stackmap in this function. 8816 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8817 } 8818 8819 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8820 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8821 const BasicBlock *EHPadBB) { 8822 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8823 // i32 <numBytes>, 8824 // i8* <target>, 8825 // i32 <numArgs>, 8826 // [Args...], 8827 // [live variables...]) 8828 8829 CallingConv::ID CC = CB.getCallingConv(); 8830 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8831 bool HasDef = !CB.getType()->isVoidTy(); 8832 SDLoc dl = getCurSDLoc(); 8833 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8834 8835 // Handle immediate and symbolic callees. 8836 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8837 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8838 /*isTarget=*/true); 8839 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8840 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8841 SDLoc(SymbolicCallee), 8842 SymbolicCallee->getValueType(0)); 8843 8844 // Get the real number of arguments participating in the call <numArgs> 8845 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8846 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8847 8848 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8849 // Intrinsics include all meta-operands up to but not including CC. 8850 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8851 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8852 "Not enough arguments provided to the patchpoint intrinsic"); 8853 8854 // For AnyRegCC the arguments are lowered later on manually. 8855 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8856 Type *ReturnTy = 8857 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8858 8859 TargetLowering::CallLoweringInfo CLI(DAG); 8860 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8861 ReturnTy, true); 8862 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8863 8864 SDNode *CallEnd = Result.second.getNode(); 8865 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8866 CallEnd = CallEnd->getOperand(0).getNode(); 8867 8868 /// Get a call instruction from the call sequence chain. 8869 /// Tail calls are not allowed. 8870 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8871 "Expected a callseq node."); 8872 SDNode *Call = CallEnd->getOperand(0).getNode(); 8873 bool HasGlue = Call->getGluedNode(); 8874 8875 // Replace the target specific call node with the patchable intrinsic. 8876 SmallVector<SDValue, 8> Ops; 8877 8878 // Add the <id> and <numBytes> constants. 8879 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8880 Ops.push_back(DAG.getTargetConstant( 8881 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8882 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8883 Ops.push_back(DAG.getTargetConstant( 8884 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8885 MVT::i32)); 8886 8887 // Add the callee. 8888 Ops.push_back(Callee); 8889 8890 // Adjust <numArgs> to account for any arguments that have been passed on the 8891 // stack instead. 8892 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8893 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8894 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8895 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8896 8897 // Add the calling convention 8898 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8899 8900 // Add the arguments we omitted previously. The register allocator should 8901 // place these in any free register. 8902 if (IsAnyRegCC) 8903 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8904 Ops.push_back(getValue(CB.getArgOperand(i))); 8905 8906 // Push the arguments from the call instruction up to the register mask. 8907 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8908 Ops.append(Call->op_begin() + 2, e); 8909 8910 // Push live variables for the stack map. 8911 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8912 8913 // Push the register mask info. 8914 if (HasGlue) 8915 Ops.push_back(*(Call->op_end()-2)); 8916 else 8917 Ops.push_back(*(Call->op_end()-1)); 8918 8919 // Push the chain (this is originally the first operand of the call, but 8920 // becomes now the last or second to last operand). 8921 Ops.push_back(*(Call->op_begin())); 8922 8923 // Push the glue flag (last operand). 8924 if (HasGlue) 8925 Ops.push_back(*(Call->op_end()-1)); 8926 8927 SDVTList NodeTys; 8928 if (IsAnyRegCC && HasDef) { 8929 // Create the return types based on the intrinsic definition 8930 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8931 SmallVector<EVT, 3> ValueVTs; 8932 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8933 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8934 8935 // There is always a chain and a glue type at the end 8936 ValueVTs.push_back(MVT::Other); 8937 ValueVTs.push_back(MVT::Glue); 8938 NodeTys = DAG.getVTList(ValueVTs); 8939 } else 8940 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8941 8942 // Replace the target specific call node with a PATCHPOINT node. 8943 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8944 dl, NodeTys, Ops); 8945 8946 // Update the NodeMap. 8947 if (HasDef) { 8948 if (IsAnyRegCC) 8949 setValue(&CB, SDValue(MN, 0)); 8950 else 8951 setValue(&CB, Result.first); 8952 } 8953 8954 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8955 // call sequence. Furthermore the location of the chain and glue can change 8956 // when the AnyReg calling convention is used and the intrinsic returns a 8957 // value. 8958 if (IsAnyRegCC && HasDef) { 8959 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8960 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8961 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8962 } else 8963 DAG.ReplaceAllUsesWith(Call, MN); 8964 DAG.DeleteNode(Call); 8965 8966 // Inform the Frame Information that we have a patchpoint in this function. 8967 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8968 } 8969 8970 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8971 unsigned Intrinsic) { 8972 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8973 SDValue Op1 = getValue(I.getArgOperand(0)); 8974 SDValue Op2; 8975 if (I.getNumArgOperands() > 1) 8976 Op2 = getValue(I.getArgOperand(1)); 8977 SDLoc dl = getCurSDLoc(); 8978 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8979 SDValue Res; 8980 FastMathFlags FMF; 8981 if (isa<FPMathOperator>(I)) 8982 FMF = I.getFastMathFlags(); 8983 8984 switch (Intrinsic) { 8985 case Intrinsic::experimental_vector_reduce_v2_fadd: 8986 if (FMF.allowReassoc()) 8987 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8988 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8989 else 8990 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8991 break; 8992 case Intrinsic::experimental_vector_reduce_v2_fmul: 8993 if (FMF.allowReassoc()) 8994 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8995 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8996 else 8997 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8998 break; 8999 case Intrinsic::experimental_vector_reduce_add: 9000 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9001 break; 9002 case Intrinsic::experimental_vector_reduce_mul: 9003 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9004 break; 9005 case Intrinsic::experimental_vector_reduce_and: 9006 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9007 break; 9008 case Intrinsic::experimental_vector_reduce_or: 9009 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9010 break; 9011 case Intrinsic::experimental_vector_reduce_xor: 9012 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9013 break; 9014 case Intrinsic::experimental_vector_reduce_smax: 9015 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9016 break; 9017 case Intrinsic::experimental_vector_reduce_smin: 9018 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9019 break; 9020 case Intrinsic::experimental_vector_reduce_umax: 9021 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9022 break; 9023 case Intrinsic::experimental_vector_reduce_umin: 9024 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9025 break; 9026 case Intrinsic::experimental_vector_reduce_fmax: 9027 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 9028 break; 9029 case Intrinsic::experimental_vector_reduce_fmin: 9030 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9031 break; 9032 default: 9033 llvm_unreachable("Unhandled vector reduce intrinsic"); 9034 } 9035 setValue(&I, Res); 9036 } 9037 9038 /// Returns an AttributeList representing the attributes applied to the return 9039 /// value of the given call. 9040 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9041 SmallVector<Attribute::AttrKind, 2> Attrs; 9042 if (CLI.RetSExt) 9043 Attrs.push_back(Attribute::SExt); 9044 if (CLI.RetZExt) 9045 Attrs.push_back(Attribute::ZExt); 9046 if (CLI.IsInReg) 9047 Attrs.push_back(Attribute::InReg); 9048 9049 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9050 Attrs); 9051 } 9052 9053 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9054 /// implementation, which just calls LowerCall. 9055 /// FIXME: When all targets are 9056 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9057 std::pair<SDValue, SDValue> 9058 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9059 // Handle the incoming return values from the call. 9060 CLI.Ins.clear(); 9061 Type *OrigRetTy = CLI.RetTy; 9062 SmallVector<EVT, 4> RetTys; 9063 SmallVector<uint64_t, 4> Offsets; 9064 auto &DL = CLI.DAG.getDataLayout(); 9065 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9066 9067 if (CLI.IsPostTypeLegalization) { 9068 // If we are lowering a libcall after legalization, split the return type. 9069 SmallVector<EVT, 4> OldRetTys; 9070 SmallVector<uint64_t, 4> OldOffsets; 9071 RetTys.swap(OldRetTys); 9072 Offsets.swap(OldOffsets); 9073 9074 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9075 EVT RetVT = OldRetTys[i]; 9076 uint64_t Offset = OldOffsets[i]; 9077 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9078 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9079 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9080 RetTys.append(NumRegs, RegisterVT); 9081 for (unsigned j = 0; j != NumRegs; ++j) 9082 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9083 } 9084 } 9085 9086 SmallVector<ISD::OutputArg, 4> Outs; 9087 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9088 9089 bool CanLowerReturn = 9090 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9091 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9092 9093 SDValue DemoteStackSlot; 9094 int DemoteStackIdx = -100; 9095 if (!CanLowerReturn) { 9096 // FIXME: equivalent assert? 9097 // assert(!CS.hasInAllocaArgument() && 9098 // "sret demotion is incompatible with inalloca"); 9099 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9100 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9101 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9102 DemoteStackIdx = 9103 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9104 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9105 DL.getAllocaAddrSpace()); 9106 9107 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9108 ArgListEntry Entry; 9109 Entry.Node = DemoteStackSlot; 9110 Entry.Ty = StackSlotPtrType; 9111 Entry.IsSExt = false; 9112 Entry.IsZExt = false; 9113 Entry.IsInReg = false; 9114 Entry.IsSRet = true; 9115 Entry.IsNest = false; 9116 Entry.IsByVal = false; 9117 Entry.IsReturned = false; 9118 Entry.IsSwiftSelf = false; 9119 Entry.IsSwiftError = false; 9120 Entry.IsCFGuardTarget = false; 9121 Entry.Alignment = Alignment; 9122 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9123 CLI.NumFixedArgs += 1; 9124 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9125 9126 // sret demotion isn't compatible with tail-calls, since the sret argument 9127 // points into the callers stack frame. 9128 CLI.IsTailCall = false; 9129 } else { 9130 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9131 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9132 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9133 ISD::ArgFlagsTy Flags; 9134 if (NeedsRegBlock) { 9135 Flags.setInConsecutiveRegs(); 9136 if (I == RetTys.size() - 1) 9137 Flags.setInConsecutiveRegsLast(); 9138 } 9139 EVT VT = RetTys[I]; 9140 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9141 CLI.CallConv, VT); 9142 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9143 CLI.CallConv, VT); 9144 for (unsigned i = 0; i != NumRegs; ++i) { 9145 ISD::InputArg MyFlags; 9146 MyFlags.Flags = Flags; 9147 MyFlags.VT = RegisterVT; 9148 MyFlags.ArgVT = VT; 9149 MyFlags.Used = CLI.IsReturnValueUsed; 9150 if (CLI.RetTy->isPointerTy()) { 9151 MyFlags.Flags.setPointer(); 9152 MyFlags.Flags.setPointerAddrSpace( 9153 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9154 } 9155 if (CLI.RetSExt) 9156 MyFlags.Flags.setSExt(); 9157 if (CLI.RetZExt) 9158 MyFlags.Flags.setZExt(); 9159 if (CLI.IsInReg) 9160 MyFlags.Flags.setInReg(); 9161 CLI.Ins.push_back(MyFlags); 9162 } 9163 } 9164 } 9165 9166 // We push in swifterror return as the last element of CLI.Ins. 9167 ArgListTy &Args = CLI.getArgs(); 9168 if (supportSwiftError()) { 9169 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9170 if (Args[i].IsSwiftError) { 9171 ISD::InputArg MyFlags; 9172 MyFlags.VT = getPointerTy(DL); 9173 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9174 MyFlags.Flags.setSwiftError(); 9175 CLI.Ins.push_back(MyFlags); 9176 } 9177 } 9178 } 9179 9180 // Handle all of the outgoing arguments. 9181 CLI.Outs.clear(); 9182 CLI.OutVals.clear(); 9183 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9184 SmallVector<EVT, 4> ValueVTs; 9185 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9186 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9187 Type *FinalType = Args[i].Ty; 9188 if (Args[i].IsByVal) 9189 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9190 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9191 FinalType, CLI.CallConv, CLI.IsVarArg); 9192 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9193 ++Value) { 9194 EVT VT = ValueVTs[Value]; 9195 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9196 SDValue Op = SDValue(Args[i].Node.getNode(), 9197 Args[i].Node.getResNo() + Value); 9198 ISD::ArgFlagsTy Flags; 9199 9200 // Certain targets (such as MIPS), may have a different ABI alignment 9201 // for a type depending on the context. Give the target a chance to 9202 // specify the alignment it wants. 9203 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9204 9205 if (Args[i].Ty->isPointerTy()) { 9206 Flags.setPointer(); 9207 Flags.setPointerAddrSpace( 9208 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9209 } 9210 if (Args[i].IsZExt) 9211 Flags.setZExt(); 9212 if (Args[i].IsSExt) 9213 Flags.setSExt(); 9214 if (Args[i].IsInReg) { 9215 // If we are using vectorcall calling convention, a structure that is 9216 // passed InReg - is surely an HVA 9217 if (CLI.CallConv == CallingConv::X86_VectorCall && 9218 isa<StructType>(FinalType)) { 9219 // The first value of a structure is marked 9220 if (0 == Value) 9221 Flags.setHvaStart(); 9222 Flags.setHva(); 9223 } 9224 // Set InReg Flag 9225 Flags.setInReg(); 9226 } 9227 if (Args[i].IsSRet) 9228 Flags.setSRet(); 9229 if (Args[i].IsSwiftSelf) 9230 Flags.setSwiftSelf(); 9231 if (Args[i].IsSwiftError) 9232 Flags.setSwiftError(); 9233 if (Args[i].IsCFGuardTarget) 9234 Flags.setCFGuardTarget(); 9235 if (Args[i].IsByVal) 9236 Flags.setByVal(); 9237 if (Args[i].IsPreallocated) { 9238 Flags.setPreallocated(); 9239 // Set the byval flag for CCAssignFn callbacks that don't know about 9240 // preallocated. This way we can know how many bytes we should've 9241 // allocated and how many bytes a callee cleanup function will pop. If 9242 // we port preallocated to more targets, we'll have to add custom 9243 // preallocated handling in the various CC lowering callbacks. 9244 Flags.setByVal(); 9245 } 9246 if (Args[i].IsInAlloca) { 9247 Flags.setInAlloca(); 9248 // Set the byval flag for CCAssignFn callbacks that don't know about 9249 // inalloca. This way we can know how many bytes we should've allocated 9250 // and how many bytes a callee cleanup function will pop. If we port 9251 // inalloca to more targets, we'll have to add custom inalloca handling 9252 // in the various CC lowering callbacks. 9253 Flags.setByVal(); 9254 } 9255 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9256 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9257 Type *ElementTy = Ty->getElementType(); 9258 9259 unsigned FrameSize = DL.getTypeAllocSize( 9260 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9261 Flags.setByValSize(FrameSize); 9262 9263 // info is not there but there are cases it cannot get right. 9264 Align FrameAlign; 9265 if (auto MA = Args[i].Alignment) 9266 FrameAlign = *MA; 9267 else 9268 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9269 Flags.setByValAlign(FrameAlign); 9270 } 9271 if (Args[i].IsNest) 9272 Flags.setNest(); 9273 if (NeedsRegBlock) 9274 Flags.setInConsecutiveRegs(); 9275 Flags.setOrigAlign(OriginalAlignment); 9276 9277 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9278 CLI.CallConv, VT); 9279 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9280 CLI.CallConv, VT); 9281 SmallVector<SDValue, 4> Parts(NumParts); 9282 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9283 9284 if (Args[i].IsSExt) 9285 ExtendKind = ISD::SIGN_EXTEND; 9286 else if (Args[i].IsZExt) 9287 ExtendKind = ISD::ZERO_EXTEND; 9288 9289 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9290 // for now. 9291 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9292 CanLowerReturn) { 9293 assert((CLI.RetTy == Args[i].Ty || 9294 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9295 CLI.RetTy->getPointerAddressSpace() == 9296 Args[i].Ty->getPointerAddressSpace())) && 9297 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9298 // Before passing 'returned' to the target lowering code, ensure that 9299 // either the register MVT and the actual EVT are the same size or that 9300 // the return value and argument are extended in the same way; in these 9301 // cases it's safe to pass the argument register value unchanged as the 9302 // return register value (although it's at the target's option whether 9303 // to do so) 9304 // TODO: allow code generation to take advantage of partially preserved 9305 // registers rather than clobbering the entire register when the 9306 // parameter extension method is not compatible with the return 9307 // extension method 9308 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9309 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9310 CLI.RetZExt == Args[i].IsZExt)) 9311 Flags.setReturned(); 9312 } 9313 9314 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9315 CLI.CallConv, ExtendKind); 9316 9317 for (unsigned j = 0; j != NumParts; ++j) { 9318 // if it isn't first piece, alignment must be 1 9319 // For scalable vectors the scalable part is currently handled 9320 // by individual targets, so we just use the known minimum size here. 9321 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9322 i < CLI.NumFixedArgs, i, 9323 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9324 if (NumParts > 1 && j == 0) 9325 MyFlags.Flags.setSplit(); 9326 else if (j != 0) { 9327 MyFlags.Flags.setOrigAlign(Align(1)); 9328 if (j == NumParts - 1) 9329 MyFlags.Flags.setSplitEnd(); 9330 } 9331 9332 CLI.Outs.push_back(MyFlags); 9333 CLI.OutVals.push_back(Parts[j]); 9334 } 9335 9336 if (NeedsRegBlock && Value == NumValues - 1) 9337 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9338 } 9339 } 9340 9341 SmallVector<SDValue, 4> InVals; 9342 CLI.Chain = LowerCall(CLI, InVals); 9343 9344 // Update CLI.InVals to use outside of this function. 9345 CLI.InVals = InVals; 9346 9347 // Verify that the target's LowerCall behaved as expected. 9348 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9349 "LowerCall didn't return a valid chain!"); 9350 assert((!CLI.IsTailCall || InVals.empty()) && 9351 "LowerCall emitted a return value for a tail call!"); 9352 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9353 "LowerCall didn't emit the correct number of values!"); 9354 9355 // For a tail call, the return value is merely live-out and there aren't 9356 // any nodes in the DAG representing it. Return a special value to 9357 // indicate that a tail call has been emitted and no more Instructions 9358 // should be processed in the current block. 9359 if (CLI.IsTailCall) { 9360 CLI.DAG.setRoot(CLI.Chain); 9361 return std::make_pair(SDValue(), SDValue()); 9362 } 9363 9364 #ifndef NDEBUG 9365 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9366 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9367 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9368 "LowerCall emitted a value with the wrong type!"); 9369 } 9370 #endif 9371 9372 SmallVector<SDValue, 4> ReturnValues; 9373 if (!CanLowerReturn) { 9374 // The instruction result is the result of loading from the 9375 // hidden sret parameter. 9376 SmallVector<EVT, 1> PVTs; 9377 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9378 9379 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9380 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9381 EVT PtrVT = PVTs[0]; 9382 9383 unsigned NumValues = RetTys.size(); 9384 ReturnValues.resize(NumValues); 9385 SmallVector<SDValue, 4> Chains(NumValues); 9386 9387 // An aggregate return value cannot wrap around the address space, so 9388 // offsets to its parts don't wrap either. 9389 SDNodeFlags Flags; 9390 Flags.setNoUnsignedWrap(true); 9391 9392 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9393 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9394 for (unsigned i = 0; i < NumValues; ++i) { 9395 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9396 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9397 PtrVT), Flags); 9398 SDValue L = CLI.DAG.getLoad( 9399 RetTys[i], CLI.DL, CLI.Chain, Add, 9400 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9401 DemoteStackIdx, Offsets[i]), 9402 HiddenSRetAlign); 9403 ReturnValues[i] = L; 9404 Chains[i] = L.getValue(1); 9405 } 9406 9407 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9408 } else { 9409 // Collect the legal value parts into potentially illegal values 9410 // that correspond to the original function's return values. 9411 Optional<ISD::NodeType> AssertOp; 9412 if (CLI.RetSExt) 9413 AssertOp = ISD::AssertSext; 9414 else if (CLI.RetZExt) 9415 AssertOp = ISD::AssertZext; 9416 unsigned CurReg = 0; 9417 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9418 EVT VT = RetTys[I]; 9419 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9420 CLI.CallConv, VT); 9421 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9422 CLI.CallConv, VT); 9423 9424 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9425 NumRegs, RegisterVT, VT, nullptr, 9426 CLI.CallConv, AssertOp)); 9427 CurReg += NumRegs; 9428 } 9429 9430 // For a function returning void, there is no return value. We can't create 9431 // such a node, so we just return a null return value in that case. In 9432 // that case, nothing will actually look at the value. 9433 if (ReturnValues.empty()) 9434 return std::make_pair(SDValue(), CLI.Chain); 9435 } 9436 9437 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9438 CLI.DAG.getVTList(RetTys), ReturnValues); 9439 return std::make_pair(Res, CLI.Chain); 9440 } 9441 9442 void TargetLowering::LowerOperationWrapper(SDNode *N, 9443 SmallVectorImpl<SDValue> &Results, 9444 SelectionDAG &DAG) const { 9445 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9446 Results.push_back(Res); 9447 } 9448 9449 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9450 llvm_unreachable("LowerOperation not implemented for this target!"); 9451 } 9452 9453 void 9454 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9455 SDValue Op = getNonRegisterValue(V); 9456 assert((Op.getOpcode() != ISD::CopyFromReg || 9457 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9458 "Copy from a reg to the same reg!"); 9459 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9460 9461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9462 // If this is an InlineAsm we have to match the registers required, not the 9463 // notional registers required by the type. 9464 9465 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9466 None); // This is not an ABI copy. 9467 SDValue Chain = DAG.getEntryNode(); 9468 9469 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9470 FuncInfo.PreferredExtendType.end()) 9471 ? ISD::ANY_EXTEND 9472 : FuncInfo.PreferredExtendType[V]; 9473 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9474 PendingExports.push_back(Chain); 9475 } 9476 9477 #include "llvm/CodeGen/SelectionDAGISel.h" 9478 9479 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9480 /// entry block, return true. This includes arguments used by switches, since 9481 /// the switch may expand into multiple basic blocks. 9482 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9483 // With FastISel active, we may be splitting blocks, so force creation 9484 // of virtual registers for all non-dead arguments. 9485 if (FastISel) 9486 return A->use_empty(); 9487 9488 const BasicBlock &Entry = A->getParent()->front(); 9489 for (const User *U : A->users()) 9490 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9491 return false; // Use not in entry block. 9492 9493 return true; 9494 } 9495 9496 using ArgCopyElisionMapTy = 9497 DenseMap<const Argument *, 9498 std::pair<const AllocaInst *, const StoreInst *>>; 9499 9500 /// Scan the entry block of the function in FuncInfo for arguments that look 9501 /// like copies into a local alloca. Record any copied arguments in 9502 /// ArgCopyElisionCandidates. 9503 static void 9504 findArgumentCopyElisionCandidates(const DataLayout &DL, 9505 FunctionLoweringInfo *FuncInfo, 9506 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9507 // Record the state of every static alloca used in the entry block. Argument 9508 // allocas are all used in the entry block, so we need approximately as many 9509 // entries as we have arguments. 9510 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9511 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9512 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9513 StaticAllocas.reserve(NumArgs * 2); 9514 9515 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9516 if (!V) 9517 return nullptr; 9518 V = V->stripPointerCasts(); 9519 const auto *AI = dyn_cast<AllocaInst>(V); 9520 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9521 return nullptr; 9522 auto Iter = StaticAllocas.insert({AI, Unknown}); 9523 return &Iter.first->second; 9524 }; 9525 9526 // Look for stores of arguments to static allocas. Look through bitcasts and 9527 // GEPs to handle type coercions, as long as the alloca is fully initialized 9528 // by the store. Any non-store use of an alloca escapes it and any subsequent 9529 // unanalyzed store might write it. 9530 // FIXME: Handle structs initialized with multiple stores. 9531 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9532 // Look for stores, and handle non-store uses conservatively. 9533 const auto *SI = dyn_cast<StoreInst>(&I); 9534 if (!SI) { 9535 // We will look through cast uses, so ignore them completely. 9536 if (I.isCast()) 9537 continue; 9538 // Ignore debug info intrinsics, they don't escape or store to allocas. 9539 if (isa<DbgInfoIntrinsic>(I)) 9540 continue; 9541 // This is an unknown instruction. Assume it escapes or writes to all 9542 // static alloca operands. 9543 for (const Use &U : I.operands()) { 9544 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9545 *Info = StaticAllocaInfo::Clobbered; 9546 } 9547 continue; 9548 } 9549 9550 // If the stored value is a static alloca, mark it as escaped. 9551 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9552 *Info = StaticAllocaInfo::Clobbered; 9553 9554 // Check if the destination is a static alloca. 9555 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9556 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9557 if (!Info) 9558 continue; 9559 const AllocaInst *AI = cast<AllocaInst>(Dst); 9560 9561 // Skip allocas that have been initialized or clobbered. 9562 if (*Info != StaticAllocaInfo::Unknown) 9563 continue; 9564 9565 // Check if the stored value is an argument, and that this store fully 9566 // initializes the alloca. Don't elide copies from the same argument twice. 9567 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9568 const auto *Arg = dyn_cast<Argument>(Val); 9569 if (!Arg || Arg->hasPassPointeeByValueAttr() || 9570 Arg->getType()->isEmptyTy() || 9571 DL.getTypeStoreSize(Arg->getType()) != 9572 DL.getTypeAllocSize(AI->getAllocatedType()) || 9573 ArgCopyElisionCandidates.count(Arg)) { 9574 *Info = StaticAllocaInfo::Clobbered; 9575 continue; 9576 } 9577 9578 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9579 << '\n'); 9580 9581 // Mark this alloca and store for argument copy elision. 9582 *Info = StaticAllocaInfo::Elidable; 9583 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9584 9585 // Stop scanning if we've seen all arguments. This will happen early in -O0 9586 // builds, which is useful, because -O0 builds have large entry blocks and 9587 // many allocas. 9588 if (ArgCopyElisionCandidates.size() == NumArgs) 9589 break; 9590 } 9591 } 9592 9593 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9594 /// ArgVal is a load from a suitable fixed stack object. 9595 static void tryToElideArgumentCopy( 9596 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9597 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9598 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9599 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9600 SDValue ArgVal, bool &ArgHasUses) { 9601 // Check if this is a load from a fixed stack object. 9602 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9603 if (!LNode) 9604 return; 9605 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9606 if (!FINode) 9607 return; 9608 9609 // Check that the fixed stack object is the right size and alignment. 9610 // Look at the alignment that the user wrote on the alloca instead of looking 9611 // at the stack object. 9612 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9613 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9614 const AllocaInst *AI = ArgCopyIter->second.first; 9615 int FixedIndex = FINode->getIndex(); 9616 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9617 int OldIndex = AllocaIndex; 9618 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9619 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9620 LLVM_DEBUG( 9621 dbgs() << " argument copy elision failed due to bad fixed stack " 9622 "object size\n"); 9623 return; 9624 } 9625 Align RequiredAlignment = AI->getAlign(); 9626 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9627 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9628 "greater than stack argument alignment (" 9629 << DebugStr(RequiredAlignment) << " vs " 9630 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9631 return; 9632 } 9633 9634 // Perform the elision. Delete the old stack object and replace its only use 9635 // in the variable info map. Mark the stack object as mutable. 9636 LLVM_DEBUG({ 9637 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9638 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9639 << '\n'; 9640 }); 9641 MFI.RemoveStackObject(OldIndex); 9642 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9643 AllocaIndex = FixedIndex; 9644 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9645 Chains.push_back(ArgVal.getValue(1)); 9646 9647 // Avoid emitting code for the store implementing the copy. 9648 const StoreInst *SI = ArgCopyIter->second.second; 9649 ElidedArgCopyInstrs.insert(SI); 9650 9651 // Check for uses of the argument again so that we can avoid exporting ArgVal 9652 // if it is't used by anything other than the store. 9653 for (const Value *U : Arg.users()) { 9654 if (U != SI) { 9655 ArgHasUses = true; 9656 break; 9657 } 9658 } 9659 } 9660 9661 void SelectionDAGISel::LowerArguments(const Function &F) { 9662 SelectionDAG &DAG = SDB->DAG; 9663 SDLoc dl = SDB->getCurSDLoc(); 9664 const DataLayout &DL = DAG.getDataLayout(); 9665 SmallVector<ISD::InputArg, 16> Ins; 9666 9667 // In Naked functions we aren't going to save any registers. 9668 if (F.hasFnAttribute(Attribute::Naked)) 9669 return; 9670 9671 if (!FuncInfo->CanLowerReturn) { 9672 // Put in an sret pointer parameter before all the other parameters. 9673 SmallVector<EVT, 1> ValueVTs; 9674 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9675 F.getReturnType()->getPointerTo( 9676 DAG.getDataLayout().getAllocaAddrSpace()), 9677 ValueVTs); 9678 9679 // NOTE: Assuming that a pointer will never break down to more than one VT 9680 // or one register. 9681 ISD::ArgFlagsTy Flags; 9682 Flags.setSRet(); 9683 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9684 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9685 ISD::InputArg::NoArgIndex, 0); 9686 Ins.push_back(RetArg); 9687 } 9688 9689 // Look for stores of arguments to static allocas. Mark such arguments with a 9690 // flag to ask the target to give us the memory location of that argument if 9691 // available. 9692 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9693 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9694 ArgCopyElisionCandidates); 9695 9696 // Set up the incoming argument description vector. 9697 for (const Argument &Arg : F.args()) { 9698 unsigned ArgNo = Arg.getArgNo(); 9699 SmallVector<EVT, 4> ValueVTs; 9700 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9701 bool isArgValueUsed = !Arg.use_empty(); 9702 unsigned PartBase = 0; 9703 Type *FinalType = Arg.getType(); 9704 if (Arg.hasAttribute(Attribute::ByVal)) 9705 FinalType = Arg.getParamByValType(); 9706 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9707 FinalType, F.getCallingConv(), F.isVarArg()); 9708 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9709 Value != NumValues; ++Value) { 9710 EVT VT = ValueVTs[Value]; 9711 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9712 ISD::ArgFlagsTy Flags; 9713 9714 // Certain targets (such as MIPS), may have a different ABI alignment 9715 // for a type depending on the context. Give the target a chance to 9716 // specify the alignment it wants. 9717 const Align OriginalAlignment( 9718 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9719 9720 if (Arg.getType()->isPointerTy()) { 9721 Flags.setPointer(); 9722 Flags.setPointerAddrSpace( 9723 cast<PointerType>(Arg.getType())->getAddressSpace()); 9724 } 9725 if (Arg.hasAttribute(Attribute::ZExt)) 9726 Flags.setZExt(); 9727 if (Arg.hasAttribute(Attribute::SExt)) 9728 Flags.setSExt(); 9729 if (Arg.hasAttribute(Attribute::InReg)) { 9730 // If we are using vectorcall calling convention, a structure that is 9731 // passed InReg - is surely an HVA 9732 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9733 isa<StructType>(Arg.getType())) { 9734 // The first value of a structure is marked 9735 if (0 == Value) 9736 Flags.setHvaStart(); 9737 Flags.setHva(); 9738 } 9739 // Set InReg Flag 9740 Flags.setInReg(); 9741 } 9742 if (Arg.hasAttribute(Attribute::StructRet)) 9743 Flags.setSRet(); 9744 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9745 Flags.setSwiftSelf(); 9746 if (Arg.hasAttribute(Attribute::SwiftError)) 9747 Flags.setSwiftError(); 9748 if (Arg.hasAttribute(Attribute::ByVal)) 9749 Flags.setByVal(); 9750 if (Arg.hasAttribute(Attribute::InAlloca)) { 9751 Flags.setInAlloca(); 9752 // Set the byval flag for CCAssignFn callbacks that don't know about 9753 // inalloca. This way we can know how many bytes we should've allocated 9754 // and how many bytes a callee cleanup function will pop. If we port 9755 // inalloca to more targets, we'll have to add custom inalloca handling 9756 // in the various CC lowering callbacks. 9757 Flags.setByVal(); 9758 } 9759 if (Arg.hasAttribute(Attribute::Preallocated)) { 9760 Flags.setPreallocated(); 9761 // Set the byval flag for CCAssignFn callbacks that don't know about 9762 // preallocated. This way we can know how many bytes we should've 9763 // allocated and how many bytes a callee cleanup function will pop. If 9764 // we port preallocated to more targets, we'll have to add custom 9765 // preallocated handling in the various CC lowering callbacks. 9766 Flags.setByVal(); 9767 } 9768 if (F.getCallingConv() == CallingConv::X86_INTR) { 9769 // IA Interrupt passes frame (1st parameter) by value in the stack. 9770 if (ArgNo == 0) 9771 Flags.setByVal(); 9772 } 9773 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) { 9774 Type *ElementTy = Arg.getParamByValType(); 9775 9776 // For ByVal, size and alignment should be passed from FE. BE will 9777 // guess if this info is not there but there are cases it cannot get 9778 // right. 9779 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9780 Flags.setByValSize(FrameSize); 9781 9782 unsigned FrameAlign; 9783 if (Arg.getParamAlignment()) 9784 FrameAlign = Arg.getParamAlignment(); 9785 else 9786 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9787 Flags.setByValAlign(Align(FrameAlign)); 9788 } 9789 if (Arg.hasAttribute(Attribute::Nest)) 9790 Flags.setNest(); 9791 if (NeedsRegBlock) 9792 Flags.setInConsecutiveRegs(); 9793 Flags.setOrigAlign(OriginalAlignment); 9794 if (ArgCopyElisionCandidates.count(&Arg)) 9795 Flags.setCopyElisionCandidate(); 9796 if (Arg.hasAttribute(Attribute::Returned)) 9797 Flags.setReturned(); 9798 9799 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9800 *CurDAG->getContext(), F.getCallingConv(), VT); 9801 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9802 *CurDAG->getContext(), F.getCallingConv(), VT); 9803 for (unsigned i = 0; i != NumRegs; ++i) { 9804 // For scalable vectors, use the minimum size; individual targets 9805 // are responsible for handling scalable vector arguments and 9806 // return values. 9807 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9808 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9809 if (NumRegs > 1 && i == 0) 9810 MyFlags.Flags.setSplit(); 9811 // if it isn't first piece, alignment must be 1 9812 else if (i > 0) { 9813 MyFlags.Flags.setOrigAlign(Align(1)); 9814 if (i == NumRegs - 1) 9815 MyFlags.Flags.setSplitEnd(); 9816 } 9817 Ins.push_back(MyFlags); 9818 } 9819 if (NeedsRegBlock && Value == NumValues - 1) 9820 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9821 PartBase += VT.getStoreSize().getKnownMinSize(); 9822 } 9823 } 9824 9825 // Call the target to set up the argument values. 9826 SmallVector<SDValue, 8> InVals; 9827 SDValue NewRoot = TLI->LowerFormalArguments( 9828 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9829 9830 // Verify that the target's LowerFormalArguments behaved as expected. 9831 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9832 "LowerFormalArguments didn't return a valid chain!"); 9833 assert(InVals.size() == Ins.size() && 9834 "LowerFormalArguments didn't emit the correct number of values!"); 9835 LLVM_DEBUG({ 9836 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9837 assert(InVals[i].getNode() && 9838 "LowerFormalArguments emitted a null value!"); 9839 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9840 "LowerFormalArguments emitted a value with the wrong type!"); 9841 } 9842 }); 9843 9844 // Update the DAG with the new chain value resulting from argument lowering. 9845 DAG.setRoot(NewRoot); 9846 9847 // Set up the argument values. 9848 unsigned i = 0; 9849 if (!FuncInfo->CanLowerReturn) { 9850 // Create a virtual register for the sret pointer, and put in a copy 9851 // from the sret argument into it. 9852 SmallVector<EVT, 1> ValueVTs; 9853 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9854 F.getReturnType()->getPointerTo( 9855 DAG.getDataLayout().getAllocaAddrSpace()), 9856 ValueVTs); 9857 MVT VT = ValueVTs[0].getSimpleVT(); 9858 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9859 Optional<ISD::NodeType> AssertOp = None; 9860 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9861 nullptr, F.getCallingConv(), AssertOp); 9862 9863 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9864 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9865 Register SRetReg = 9866 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9867 FuncInfo->DemoteRegister = SRetReg; 9868 NewRoot = 9869 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9870 DAG.setRoot(NewRoot); 9871 9872 // i indexes lowered arguments. Bump it past the hidden sret argument. 9873 ++i; 9874 } 9875 9876 SmallVector<SDValue, 4> Chains; 9877 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9878 for (const Argument &Arg : F.args()) { 9879 SmallVector<SDValue, 4> ArgValues; 9880 SmallVector<EVT, 4> ValueVTs; 9881 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9882 unsigned NumValues = ValueVTs.size(); 9883 if (NumValues == 0) 9884 continue; 9885 9886 bool ArgHasUses = !Arg.use_empty(); 9887 9888 // Elide the copying store if the target loaded this argument from a 9889 // suitable fixed stack object. 9890 if (Ins[i].Flags.isCopyElisionCandidate()) { 9891 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9892 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9893 InVals[i], ArgHasUses); 9894 } 9895 9896 // If this argument is unused then remember its value. It is used to generate 9897 // debugging information. 9898 bool isSwiftErrorArg = 9899 TLI->supportSwiftError() && 9900 Arg.hasAttribute(Attribute::SwiftError); 9901 if (!ArgHasUses && !isSwiftErrorArg) { 9902 SDB->setUnusedArgValue(&Arg, InVals[i]); 9903 9904 // Also remember any frame index for use in FastISel. 9905 if (FrameIndexSDNode *FI = 9906 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9907 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9908 } 9909 9910 for (unsigned Val = 0; Val != NumValues; ++Val) { 9911 EVT VT = ValueVTs[Val]; 9912 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9913 F.getCallingConv(), VT); 9914 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9915 *CurDAG->getContext(), F.getCallingConv(), VT); 9916 9917 // Even an apparent 'unused' swifterror argument needs to be returned. So 9918 // we do generate a copy for it that can be used on return from the 9919 // function. 9920 if (ArgHasUses || isSwiftErrorArg) { 9921 Optional<ISD::NodeType> AssertOp; 9922 if (Arg.hasAttribute(Attribute::SExt)) 9923 AssertOp = ISD::AssertSext; 9924 else if (Arg.hasAttribute(Attribute::ZExt)) 9925 AssertOp = ISD::AssertZext; 9926 9927 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9928 PartVT, VT, nullptr, 9929 F.getCallingConv(), AssertOp)); 9930 } 9931 9932 i += NumParts; 9933 } 9934 9935 // We don't need to do anything else for unused arguments. 9936 if (ArgValues.empty()) 9937 continue; 9938 9939 // Note down frame index. 9940 if (FrameIndexSDNode *FI = 9941 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9942 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9943 9944 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9945 SDB->getCurSDLoc()); 9946 9947 SDB->setValue(&Arg, Res); 9948 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9949 // We want to associate the argument with the frame index, among 9950 // involved operands, that correspond to the lowest address. The 9951 // getCopyFromParts function, called earlier, is swapping the order of 9952 // the operands to BUILD_PAIR depending on endianness. The result of 9953 // that swapping is that the least significant bits of the argument will 9954 // be in the first operand of the BUILD_PAIR node, and the most 9955 // significant bits will be in the second operand. 9956 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9957 if (LoadSDNode *LNode = 9958 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9959 if (FrameIndexSDNode *FI = 9960 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9961 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9962 } 9963 9964 // Analyses past this point are naive and don't expect an assertion. 9965 if (Res.getOpcode() == ISD::AssertZext) 9966 Res = Res.getOperand(0); 9967 9968 // Update the SwiftErrorVRegDefMap. 9969 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9970 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9971 if (Register::isVirtualRegister(Reg)) 9972 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9973 Reg); 9974 } 9975 9976 // If this argument is live outside of the entry block, insert a copy from 9977 // wherever we got it to the vreg that other BB's will reference it as. 9978 if (Res.getOpcode() == ISD::CopyFromReg) { 9979 // If we can, though, try to skip creating an unnecessary vreg. 9980 // FIXME: This isn't very clean... it would be nice to make this more 9981 // general. 9982 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9983 if (Register::isVirtualRegister(Reg)) { 9984 FuncInfo->ValueMap[&Arg] = Reg; 9985 continue; 9986 } 9987 } 9988 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9989 FuncInfo->InitializeRegForValue(&Arg); 9990 SDB->CopyToExportRegsIfNeeded(&Arg); 9991 } 9992 } 9993 9994 if (!Chains.empty()) { 9995 Chains.push_back(NewRoot); 9996 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9997 } 9998 9999 DAG.setRoot(NewRoot); 10000 10001 assert(i == InVals.size() && "Argument register count mismatch!"); 10002 10003 // If any argument copy elisions occurred and we have debug info, update the 10004 // stale frame indices used in the dbg.declare variable info table. 10005 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10006 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10007 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10008 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10009 if (I != ArgCopyElisionFrameIndexMap.end()) 10010 VI.Slot = I->second; 10011 } 10012 } 10013 10014 // Finally, if the target has anything special to do, allow it to do so. 10015 emitFunctionEntryCode(); 10016 } 10017 10018 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10019 /// ensure constants are generated when needed. Remember the virtual registers 10020 /// that need to be added to the Machine PHI nodes as input. We cannot just 10021 /// directly add them, because expansion might result in multiple MBB's for one 10022 /// BB. As such, the start of the BB might correspond to a different MBB than 10023 /// the end. 10024 void 10025 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10026 const Instruction *TI = LLVMBB->getTerminator(); 10027 10028 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10029 10030 // Check PHI nodes in successors that expect a value to be available from this 10031 // block. 10032 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10033 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10034 if (!isa<PHINode>(SuccBB->begin())) continue; 10035 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10036 10037 // If this terminator has multiple identical successors (common for 10038 // switches), only handle each succ once. 10039 if (!SuccsHandled.insert(SuccMBB).second) 10040 continue; 10041 10042 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10043 10044 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10045 // nodes and Machine PHI nodes, but the incoming operands have not been 10046 // emitted yet. 10047 for (const PHINode &PN : SuccBB->phis()) { 10048 // Ignore dead phi's. 10049 if (PN.use_empty()) 10050 continue; 10051 10052 // Skip empty types 10053 if (PN.getType()->isEmptyTy()) 10054 continue; 10055 10056 unsigned Reg; 10057 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10058 10059 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10060 unsigned &RegOut = ConstantsOut[C]; 10061 if (RegOut == 0) { 10062 RegOut = FuncInfo.CreateRegs(C); 10063 CopyValueToVirtualRegister(C, RegOut); 10064 } 10065 Reg = RegOut; 10066 } else { 10067 DenseMap<const Value *, Register>::iterator I = 10068 FuncInfo.ValueMap.find(PHIOp); 10069 if (I != FuncInfo.ValueMap.end()) 10070 Reg = I->second; 10071 else { 10072 assert(isa<AllocaInst>(PHIOp) && 10073 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10074 "Didn't codegen value into a register!??"); 10075 Reg = FuncInfo.CreateRegs(PHIOp); 10076 CopyValueToVirtualRegister(PHIOp, Reg); 10077 } 10078 } 10079 10080 // Remember that this register needs to added to the machine PHI node as 10081 // the input for this MBB. 10082 SmallVector<EVT, 4> ValueVTs; 10083 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10084 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10085 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10086 EVT VT = ValueVTs[vti]; 10087 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10088 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10089 FuncInfo.PHINodesToUpdate.push_back( 10090 std::make_pair(&*MBBI++, Reg + i)); 10091 Reg += NumRegisters; 10092 } 10093 } 10094 } 10095 10096 ConstantsOut.clear(); 10097 } 10098 10099 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10100 /// is 0. 10101 MachineBasicBlock * 10102 SelectionDAGBuilder::StackProtectorDescriptor:: 10103 AddSuccessorMBB(const BasicBlock *BB, 10104 MachineBasicBlock *ParentMBB, 10105 bool IsLikely, 10106 MachineBasicBlock *SuccMBB) { 10107 // If SuccBB has not been created yet, create it. 10108 if (!SuccMBB) { 10109 MachineFunction *MF = ParentMBB->getParent(); 10110 MachineFunction::iterator BBI(ParentMBB); 10111 SuccMBB = MF->CreateMachineBasicBlock(BB); 10112 MF->insert(++BBI, SuccMBB); 10113 } 10114 // Add it as a successor of ParentMBB. 10115 ParentMBB->addSuccessor( 10116 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10117 return SuccMBB; 10118 } 10119 10120 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10121 MachineFunction::iterator I(MBB); 10122 if (++I == FuncInfo.MF->end()) 10123 return nullptr; 10124 return &*I; 10125 } 10126 10127 /// During lowering new call nodes can be created (such as memset, etc.). 10128 /// Those will become new roots of the current DAG, but complications arise 10129 /// when they are tail calls. In such cases, the call lowering will update 10130 /// the root, but the builder still needs to know that a tail call has been 10131 /// lowered in order to avoid generating an additional return. 10132 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10133 // If the node is null, we do have a tail call. 10134 if (MaybeTC.getNode() != nullptr) 10135 DAG.setRoot(MaybeTC); 10136 else 10137 HasTailCall = true; 10138 } 10139 10140 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10141 MachineBasicBlock *SwitchMBB, 10142 MachineBasicBlock *DefaultMBB) { 10143 MachineFunction *CurMF = FuncInfo.MF; 10144 MachineBasicBlock *NextMBB = nullptr; 10145 MachineFunction::iterator BBI(W.MBB); 10146 if (++BBI != FuncInfo.MF->end()) 10147 NextMBB = &*BBI; 10148 10149 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10150 10151 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10152 10153 if (Size == 2 && W.MBB == SwitchMBB) { 10154 // If any two of the cases has the same destination, and if one value 10155 // is the same as the other, but has one bit unset that the other has set, 10156 // use bit manipulation to do two compares at once. For example: 10157 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10158 // TODO: This could be extended to merge any 2 cases in switches with 3 10159 // cases. 10160 // TODO: Handle cases where W.CaseBB != SwitchBB. 10161 CaseCluster &Small = *W.FirstCluster; 10162 CaseCluster &Big = *W.LastCluster; 10163 10164 if (Small.Low == Small.High && Big.Low == Big.High && 10165 Small.MBB == Big.MBB) { 10166 const APInt &SmallValue = Small.Low->getValue(); 10167 const APInt &BigValue = Big.Low->getValue(); 10168 10169 // Check that there is only one bit different. 10170 APInt CommonBit = BigValue ^ SmallValue; 10171 if (CommonBit.isPowerOf2()) { 10172 SDValue CondLHS = getValue(Cond); 10173 EVT VT = CondLHS.getValueType(); 10174 SDLoc DL = getCurSDLoc(); 10175 10176 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10177 DAG.getConstant(CommonBit, DL, VT)); 10178 SDValue Cond = DAG.getSetCC( 10179 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10180 ISD::SETEQ); 10181 10182 // Update successor info. 10183 // Both Small and Big will jump to Small.BB, so we sum up the 10184 // probabilities. 10185 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10186 if (BPI) 10187 addSuccessorWithProb( 10188 SwitchMBB, DefaultMBB, 10189 // The default destination is the first successor in IR. 10190 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10191 else 10192 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10193 10194 // Insert the true branch. 10195 SDValue BrCond = 10196 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10197 DAG.getBasicBlock(Small.MBB)); 10198 // Insert the false branch. 10199 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10200 DAG.getBasicBlock(DefaultMBB)); 10201 10202 DAG.setRoot(BrCond); 10203 return; 10204 } 10205 } 10206 } 10207 10208 if (TM.getOptLevel() != CodeGenOpt::None) { 10209 // Here, we order cases by probability so the most likely case will be 10210 // checked first. However, two clusters can have the same probability in 10211 // which case their relative ordering is non-deterministic. So we use Low 10212 // as a tie-breaker as clusters are guaranteed to never overlap. 10213 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10214 [](const CaseCluster &a, const CaseCluster &b) { 10215 return a.Prob != b.Prob ? 10216 a.Prob > b.Prob : 10217 a.Low->getValue().slt(b.Low->getValue()); 10218 }); 10219 10220 // Rearrange the case blocks so that the last one falls through if possible 10221 // without changing the order of probabilities. 10222 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10223 --I; 10224 if (I->Prob > W.LastCluster->Prob) 10225 break; 10226 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10227 std::swap(*I, *W.LastCluster); 10228 break; 10229 } 10230 } 10231 } 10232 10233 // Compute total probability. 10234 BranchProbability DefaultProb = W.DefaultProb; 10235 BranchProbability UnhandledProbs = DefaultProb; 10236 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10237 UnhandledProbs += I->Prob; 10238 10239 MachineBasicBlock *CurMBB = W.MBB; 10240 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10241 bool FallthroughUnreachable = false; 10242 MachineBasicBlock *Fallthrough; 10243 if (I == W.LastCluster) { 10244 // For the last cluster, fall through to the default destination. 10245 Fallthrough = DefaultMBB; 10246 FallthroughUnreachable = isa<UnreachableInst>( 10247 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10248 } else { 10249 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10250 CurMF->insert(BBI, Fallthrough); 10251 // Put Cond in a virtual register to make it available from the new blocks. 10252 ExportFromCurrentBlock(Cond); 10253 } 10254 UnhandledProbs -= I->Prob; 10255 10256 switch (I->Kind) { 10257 case CC_JumpTable: { 10258 // FIXME: Optimize away range check based on pivot comparisons. 10259 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10260 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10261 10262 // The jump block hasn't been inserted yet; insert it here. 10263 MachineBasicBlock *JumpMBB = JT->MBB; 10264 CurMF->insert(BBI, JumpMBB); 10265 10266 auto JumpProb = I->Prob; 10267 auto FallthroughProb = UnhandledProbs; 10268 10269 // If the default statement is a target of the jump table, we evenly 10270 // distribute the default probability to successors of CurMBB. Also 10271 // update the probability on the edge from JumpMBB to Fallthrough. 10272 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10273 SE = JumpMBB->succ_end(); 10274 SI != SE; ++SI) { 10275 if (*SI == DefaultMBB) { 10276 JumpProb += DefaultProb / 2; 10277 FallthroughProb -= DefaultProb / 2; 10278 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10279 JumpMBB->normalizeSuccProbs(); 10280 break; 10281 } 10282 } 10283 10284 if (FallthroughUnreachable) { 10285 // Skip the range check if the fallthrough block is unreachable. 10286 JTH->OmitRangeCheck = true; 10287 } 10288 10289 if (!JTH->OmitRangeCheck) 10290 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10291 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10292 CurMBB->normalizeSuccProbs(); 10293 10294 // The jump table header will be inserted in our current block, do the 10295 // range check, and fall through to our fallthrough block. 10296 JTH->HeaderBB = CurMBB; 10297 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10298 10299 // If we're in the right place, emit the jump table header right now. 10300 if (CurMBB == SwitchMBB) { 10301 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10302 JTH->Emitted = true; 10303 } 10304 break; 10305 } 10306 case CC_BitTests: { 10307 // FIXME: Optimize away range check based on pivot comparisons. 10308 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10309 10310 // The bit test blocks haven't been inserted yet; insert them here. 10311 for (BitTestCase &BTC : BTB->Cases) 10312 CurMF->insert(BBI, BTC.ThisBB); 10313 10314 // Fill in fields of the BitTestBlock. 10315 BTB->Parent = CurMBB; 10316 BTB->Default = Fallthrough; 10317 10318 BTB->DefaultProb = UnhandledProbs; 10319 // If the cases in bit test don't form a contiguous range, we evenly 10320 // distribute the probability on the edge to Fallthrough to two 10321 // successors of CurMBB. 10322 if (!BTB->ContiguousRange) { 10323 BTB->Prob += DefaultProb / 2; 10324 BTB->DefaultProb -= DefaultProb / 2; 10325 } 10326 10327 if (FallthroughUnreachable) { 10328 // Skip the range check if the fallthrough block is unreachable. 10329 BTB->OmitRangeCheck = true; 10330 } 10331 10332 // If we're in the right place, emit the bit test header right now. 10333 if (CurMBB == SwitchMBB) { 10334 visitBitTestHeader(*BTB, SwitchMBB); 10335 BTB->Emitted = true; 10336 } 10337 break; 10338 } 10339 case CC_Range: { 10340 const Value *RHS, *LHS, *MHS; 10341 ISD::CondCode CC; 10342 if (I->Low == I->High) { 10343 // Check Cond == I->Low. 10344 CC = ISD::SETEQ; 10345 LHS = Cond; 10346 RHS=I->Low; 10347 MHS = nullptr; 10348 } else { 10349 // Check I->Low <= Cond <= I->High. 10350 CC = ISD::SETLE; 10351 LHS = I->Low; 10352 MHS = Cond; 10353 RHS = I->High; 10354 } 10355 10356 // If Fallthrough is unreachable, fold away the comparison. 10357 if (FallthroughUnreachable) 10358 CC = ISD::SETTRUE; 10359 10360 // The false probability is the sum of all unhandled cases. 10361 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10362 getCurSDLoc(), I->Prob, UnhandledProbs); 10363 10364 if (CurMBB == SwitchMBB) 10365 visitSwitchCase(CB, SwitchMBB); 10366 else 10367 SL->SwitchCases.push_back(CB); 10368 10369 break; 10370 } 10371 } 10372 CurMBB = Fallthrough; 10373 } 10374 } 10375 10376 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10377 CaseClusterIt First, 10378 CaseClusterIt Last) { 10379 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10380 if (X.Prob != CC.Prob) 10381 return X.Prob > CC.Prob; 10382 10383 // Ties are broken by comparing the case value. 10384 return X.Low->getValue().slt(CC.Low->getValue()); 10385 }); 10386 } 10387 10388 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10389 const SwitchWorkListItem &W, 10390 Value *Cond, 10391 MachineBasicBlock *SwitchMBB) { 10392 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10393 "Clusters not sorted?"); 10394 10395 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10396 10397 // Balance the tree based on branch probabilities to create a near-optimal (in 10398 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10399 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10400 CaseClusterIt LastLeft = W.FirstCluster; 10401 CaseClusterIt FirstRight = W.LastCluster; 10402 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10403 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10404 10405 // Move LastLeft and FirstRight towards each other from opposite directions to 10406 // find a partitioning of the clusters which balances the probability on both 10407 // sides. If LeftProb and RightProb are equal, alternate which side is 10408 // taken to ensure 0-probability nodes are distributed evenly. 10409 unsigned I = 0; 10410 while (LastLeft + 1 < FirstRight) { 10411 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10412 LeftProb += (++LastLeft)->Prob; 10413 else 10414 RightProb += (--FirstRight)->Prob; 10415 I++; 10416 } 10417 10418 while (true) { 10419 // Our binary search tree differs from a typical BST in that ours can have up 10420 // to three values in each leaf. The pivot selection above doesn't take that 10421 // into account, which means the tree might require more nodes and be less 10422 // efficient. We compensate for this here. 10423 10424 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10425 unsigned NumRight = W.LastCluster - FirstRight + 1; 10426 10427 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10428 // If one side has less than 3 clusters, and the other has more than 3, 10429 // consider taking a cluster from the other side. 10430 10431 if (NumLeft < NumRight) { 10432 // Consider moving the first cluster on the right to the left side. 10433 CaseCluster &CC = *FirstRight; 10434 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10435 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10436 if (LeftSideRank <= RightSideRank) { 10437 // Moving the cluster to the left does not demote it. 10438 ++LastLeft; 10439 ++FirstRight; 10440 continue; 10441 } 10442 } else { 10443 assert(NumRight < NumLeft); 10444 // Consider moving the last element on the left to the right side. 10445 CaseCluster &CC = *LastLeft; 10446 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10447 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10448 if (RightSideRank <= LeftSideRank) { 10449 // Moving the cluster to the right does not demot it. 10450 --LastLeft; 10451 --FirstRight; 10452 continue; 10453 } 10454 } 10455 } 10456 break; 10457 } 10458 10459 assert(LastLeft + 1 == FirstRight); 10460 assert(LastLeft >= W.FirstCluster); 10461 assert(FirstRight <= W.LastCluster); 10462 10463 // Use the first element on the right as pivot since we will make less-than 10464 // comparisons against it. 10465 CaseClusterIt PivotCluster = FirstRight; 10466 assert(PivotCluster > W.FirstCluster); 10467 assert(PivotCluster <= W.LastCluster); 10468 10469 CaseClusterIt FirstLeft = W.FirstCluster; 10470 CaseClusterIt LastRight = W.LastCluster; 10471 10472 const ConstantInt *Pivot = PivotCluster->Low; 10473 10474 // New blocks will be inserted immediately after the current one. 10475 MachineFunction::iterator BBI(W.MBB); 10476 ++BBI; 10477 10478 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10479 // we can branch to its destination directly if it's squeezed exactly in 10480 // between the known lower bound and Pivot - 1. 10481 MachineBasicBlock *LeftMBB; 10482 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10483 FirstLeft->Low == W.GE && 10484 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10485 LeftMBB = FirstLeft->MBB; 10486 } else { 10487 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10488 FuncInfo.MF->insert(BBI, LeftMBB); 10489 WorkList.push_back( 10490 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10491 // Put Cond in a virtual register to make it available from the new blocks. 10492 ExportFromCurrentBlock(Cond); 10493 } 10494 10495 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10496 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10497 // directly if RHS.High equals the current upper bound. 10498 MachineBasicBlock *RightMBB; 10499 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10500 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10501 RightMBB = FirstRight->MBB; 10502 } else { 10503 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10504 FuncInfo.MF->insert(BBI, RightMBB); 10505 WorkList.push_back( 10506 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10507 // Put Cond in a virtual register to make it available from the new blocks. 10508 ExportFromCurrentBlock(Cond); 10509 } 10510 10511 // Create the CaseBlock record that will be used to lower the branch. 10512 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10513 getCurSDLoc(), LeftProb, RightProb); 10514 10515 if (W.MBB == SwitchMBB) 10516 visitSwitchCase(CB, SwitchMBB); 10517 else 10518 SL->SwitchCases.push_back(CB); 10519 } 10520 10521 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10522 // from the swith statement. 10523 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10524 BranchProbability PeeledCaseProb) { 10525 if (PeeledCaseProb == BranchProbability::getOne()) 10526 return BranchProbability::getZero(); 10527 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10528 10529 uint32_t Numerator = CaseProb.getNumerator(); 10530 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10531 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10532 } 10533 10534 // Try to peel the top probability case if it exceeds the threshold. 10535 // Return current MachineBasicBlock for the switch statement if the peeling 10536 // does not occur. 10537 // If the peeling is performed, return the newly created MachineBasicBlock 10538 // for the peeled switch statement. Also update Clusters to remove the peeled 10539 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10540 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10541 const SwitchInst &SI, CaseClusterVector &Clusters, 10542 BranchProbability &PeeledCaseProb) { 10543 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10544 // Don't perform if there is only one cluster or optimizing for size. 10545 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10546 TM.getOptLevel() == CodeGenOpt::None || 10547 SwitchMBB->getParent()->getFunction().hasMinSize()) 10548 return SwitchMBB; 10549 10550 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10551 unsigned PeeledCaseIndex = 0; 10552 bool SwitchPeeled = false; 10553 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10554 CaseCluster &CC = Clusters[Index]; 10555 if (CC.Prob < TopCaseProb) 10556 continue; 10557 TopCaseProb = CC.Prob; 10558 PeeledCaseIndex = Index; 10559 SwitchPeeled = true; 10560 } 10561 if (!SwitchPeeled) 10562 return SwitchMBB; 10563 10564 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10565 << TopCaseProb << "\n"); 10566 10567 // Record the MBB for the peeled switch statement. 10568 MachineFunction::iterator BBI(SwitchMBB); 10569 ++BBI; 10570 MachineBasicBlock *PeeledSwitchMBB = 10571 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10572 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10573 10574 ExportFromCurrentBlock(SI.getCondition()); 10575 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10576 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10577 nullptr, nullptr, TopCaseProb.getCompl()}; 10578 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10579 10580 Clusters.erase(PeeledCaseIt); 10581 for (CaseCluster &CC : Clusters) { 10582 LLVM_DEBUG( 10583 dbgs() << "Scale the probablity for one cluster, before scaling: " 10584 << CC.Prob << "\n"); 10585 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10586 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10587 } 10588 PeeledCaseProb = TopCaseProb; 10589 return PeeledSwitchMBB; 10590 } 10591 10592 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10593 // Extract cases from the switch. 10594 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10595 CaseClusterVector Clusters; 10596 Clusters.reserve(SI.getNumCases()); 10597 for (auto I : SI.cases()) { 10598 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10599 const ConstantInt *CaseVal = I.getCaseValue(); 10600 BranchProbability Prob = 10601 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10602 : BranchProbability(1, SI.getNumCases() + 1); 10603 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10604 } 10605 10606 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10607 10608 // Cluster adjacent cases with the same destination. We do this at all 10609 // optimization levels because it's cheap to do and will make codegen faster 10610 // if there are many clusters. 10611 sortAndRangeify(Clusters); 10612 10613 // The branch probablity of the peeled case. 10614 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10615 MachineBasicBlock *PeeledSwitchMBB = 10616 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10617 10618 // If there is only the default destination, jump there directly. 10619 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10620 if (Clusters.empty()) { 10621 assert(PeeledSwitchMBB == SwitchMBB); 10622 SwitchMBB->addSuccessor(DefaultMBB); 10623 if (DefaultMBB != NextBlock(SwitchMBB)) { 10624 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10625 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10626 } 10627 return; 10628 } 10629 10630 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10631 SL->findBitTestClusters(Clusters, &SI); 10632 10633 LLVM_DEBUG({ 10634 dbgs() << "Case clusters: "; 10635 for (const CaseCluster &C : Clusters) { 10636 if (C.Kind == CC_JumpTable) 10637 dbgs() << "JT:"; 10638 if (C.Kind == CC_BitTests) 10639 dbgs() << "BT:"; 10640 10641 C.Low->getValue().print(dbgs(), true); 10642 if (C.Low != C.High) { 10643 dbgs() << '-'; 10644 C.High->getValue().print(dbgs(), true); 10645 } 10646 dbgs() << ' '; 10647 } 10648 dbgs() << '\n'; 10649 }); 10650 10651 assert(!Clusters.empty()); 10652 SwitchWorkList WorkList; 10653 CaseClusterIt First = Clusters.begin(); 10654 CaseClusterIt Last = Clusters.end() - 1; 10655 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10656 // Scale the branchprobability for DefaultMBB if the peel occurs and 10657 // DefaultMBB is not replaced. 10658 if (PeeledCaseProb != BranchProbability::getZero() && 10659 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10660 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10661 WorkList.push_back( 10662 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10663 10664 while (!WorkList.empty()) { 10665 SwitchWorkListItem W = WorkList.back(); 10666 WorkList.pop_back(); 10667 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10668 10669 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10670 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10671 // For optimized builds, lower large range as a balanced binary tree. 10672 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10673 continue; 10674 } 10675 10676 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10677 } 10678 } 10679 10680 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10681 SmallVector<EVT, 4> ValueVTs; 10682 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10683 ValueVTs); 10684 unsigned NumValues = ValueVTs.size(); 10685 if (NumValues == 0) return; 10686 10687 SmallVector<SDValue, 4> Values(NumValues); 10688 SDValue Op = getValue(I.getOperand(0)); 10689 10690 for (unsigned i = 0; i != NumValues; ++i) 10691 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10692 SDValue(Op.getNode(), Op.getResNo() + i)); 10693 10694 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10695 DAG.getVTList(ValueVTs), Values)); 10696 } 10697