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.isFixedLengthVector()) 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.getVectorElementCount() == 707 ValueVT.getVectorElementCount()) { 708 709 // Promoted vector extract 710 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 711 } else { 712 if (ValueVT.getVectorNumElements() == 1) { 713 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 714 DAG.getVectorIdxConstant(0, DL)); 715 } else { 716 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 717 "lossy conversion of vector to scalar type"); 718 EVT IntermediateType = 719 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 720 Val = DAG.getBitcast(IntermediateType, Val); 721 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 722 } 723 } 724 725 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 726 Parts[0] = Val; 727 return; 728 } 729 730 // Handle a multi-element vector. 731 EVT IntermediateVT; 732 MVT RegisterVT; 733 unsigned NumIntermediates; 734 unsigned NumRegs; 735 if (IsABIRegCopy) { 736 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 737 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 738 NumIntermediates, RegisterVT); 739 } else { 740 NumRegs = 741 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 742 NumIntermediates, RegisterVT); 743 } 744 745 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 746 NumParts = NumRegs; // Silence a compiler warning. 747 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 748 749 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 750 "Mixing scalable and fixed vectors when copying in parts"); 751 752 ElementCount DestEltCnt; 753 754 if (IntermediateVT.isVector()) 755 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 756 else 757 DestEltCnt = ElementCount(NumIntermediates, false); 758 759 EVT BuiltVectorTy = EVT::getVectorVT( 760 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt); 761 if (ValueVT != BuiltVectorTy) { 762 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 763 Val = Widened; 764 765 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 766 } 767 768 // Split the vector into intermediate operands. 769 SmallVector<SDValue, 8> Ops(NumIntermediates); 770 for (unsigned i = 0; i != NumIntermediates; ++i) { 771 if (IntermediateVT.isVector()) { 772 // This does something sensible for scalable vectors - see the 773 // definition of EXTRACT_SUBVECTOR for further details. 774 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 775 Ops[i] = 776 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 777 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 778 } else { 779 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 780 DAG.getVectorIdxConstant(i, DL)); 781 } 782 } 783 784 // Split the intermediate operands into legal parts. 785 if (NumParts == NumIntermediates) { 786 // If the register was not expanded, promote or copy the value, 787 // as appropriate. 788 for (unsigned i = 0; i != NumParts; ++i) 789 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 790 } else if (NumParts > 0) { 791 // If the intermediate type was expanded, split each the value into 792 // legal parts. 793 assert(NumIntermediates != 0 && "division by zero"); 794 assert(NumParts % NumIntermediates == 0 && 795 "Must expand into a divisible number of parts!"); 796 unsigned Factor = NumParts / NumIntermediates; 797 for (unsigned i = 0; i != NumIntermediates; ++i) 798 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 799 CallConv); 800 } 801 } 802 803 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 804 EVT valuevt, Optional<CallingConv::ID> CC) 805 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 806 RegCount(1, regs.size()), CallConv(CC) {} 807 808 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 809 const DataLayout &DL, unsigned Reg, Type *Ty, 810 Optional<CallingConv::ID> CC) { 811 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 812 813 CallConv = CC; 814 815 for (EVT ValueVT : ValueVTs) { 816 unsigned NumRegs = 817 isABIMangled() 818 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 819 : TLI.getNumRegisters(Context, ValueVT); 820 MVT RegisterVT = 821 isABIMangled() 822 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 823 : TLI.getRegisterType(Context, ValueVT); 824 for (unsigned i = 0; i != NumRegs; ++i) 825 Regs.push_back(Reg + i); 826 RegVTs.push_back(RegisterVT); 827 RegCount.push_back(NumRegs); 828 Reg += NumRegs; 829 } 830 } 831 832 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 833 FunctionLoweringInfo &FuncInfo, 834 const SDLoc &dl, SDValue &Chain, 835 SDValue *Flag, const Value *V) const { 836 // A Value with type {} or [0 x %t] needs no registers. 837 if (ValueVTs.empty()) 838 return SDValue(); 839 840 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 841 842 // Assemble the legal parts into the final values. 843 SmallVector<SDValue, 4> Values(ValueVTs.size()); 844 SmallVector<SDValue, 8> Parts; 845 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 846 // Copy the legal parts from the registers. 847 EVT ValueVT = ValueVTs[Value]; 848 unsigned NumRegs = RegCount[Value]; 849 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 850 *DAG.getContext(), 851 CallConv.getValue(), RegVTs[Value]) 852 : RegVTs[Value]; 853 854 Parts.resize(NumRegs); 855 for (unsigned i = 0; i != NumRegs; ++i) { 856 SDValue P; 857 if (!Flag) { 858 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 859 } else { 860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 861 *Flag = P.getValue(2); 862 } 863 864 Chain = P.getValue(1); 865 Parts[i] = P; 866 867 // If the source register was virtual and if we know something about it, 868 // add an assert node. 869 if (!Register::isVirtualRegister(Regs[Part + i]) || 870 !RegisterVT.isInteger()) 871 continue; 872 873 const FunctionLoweringInfo::LiveOutInfo *LOI = 874 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 875 if (!LOI) 876 continue; 877 878 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 879 unsigned NumSignBits = LOI->NumSignBits; 880 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 881 882 if (NumZeroBits == RegSize) { 883 // The current value is a zero. 884 // Explicitly express that as it would be easier for 885 // optimizations to kick in. 886 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 887 continue; 888 } 889 890 // FIXME: We capture more information than the dag can represent. For 891 // now, just use the tightest assertzext/assertsext possible. 892 bool isSExt; 893 EVT FromVT(MVT::Other); 894 if (NumZeroBits) { 895 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 896 isSExt = false; 897 } else if (NumSignBits > 1) { 898 FromVT = 899 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 900 isSExt = true; 901 } else { 902 continue; 903 } 904 // Add an assertion node. 905 assert(FromVT != MVT::Other); 906 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 907 RegisterVT, P, DAG.getValueType(FromVT)); 908 } 909 910 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 911 RegisterVT, ValueVT, V, CallConv); 912 Part += NumRegs; 913 Parts.clear(); 914 } 915 916 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 917 } 918 919 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 920 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 921 const Value *V, 922 ISD::NodeType PreferredExtendType) const { 923 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 924 ISD::NodeType ExtendKind = PreferredExtendType; 925 926 // Get the list of the values's legal parts. 927 unsigned NumRegs = Regs.size(); 928 SmallVector<SDValue, 8> Parts(NumRegs); 929 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 930 unsigned NumParts = RegCount[Value]; 931 932 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 933 *DAG.getContext(), 934 CallConv.getValue(), RegVTs[Value]) 935 : RegVTs[Value]; 936 937 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 938 ExtendKind = ISD::ZERO_EXTEND; 939 940 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 941 NumParts, RegisterVT, V, CallConv, ExtendKind); 942 Part += NumParts; 943 } 944 945 // Copy the parts into the registers. 946 SmallVector<SDValue, 8> Chains(NumRegs); 947 for (unsigned i = 0; i != NumRegs; ++i) { 948 SDValue Part; 949 if (!Flag) { 950 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 951 } else { 952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 953 *Flag = Part.getValue(1); 954 } 955 956 Chains[i] = Part.getValue(0); 957 } 958 959 if (NumRegs == 1 || Flag) 960 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 961 // flagged to it. That is the CopyToReg nodes and the user are considered 962 // a single scheduling unit. If we create a TokenFactor and return it as 963 // chain, then the TokenFactor is both a predecessor (operand) of the 964 // user as well as a successor (the TF operands are flagged to the user). 965 // c1, f1 = CopyToReg 966 // c2, f2 = CopyToReg 967 // c3 = TokenFactor c1, c2 968 // ... 969 // = op c3, ..., f2 970 Chain = Chains[NumRegs-1]; 971 else 972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 973 } 974 975 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 976 unsigned MatchingIdx, const SDLoc &dl, 977 SelectionDAG &DAG, 978 std::vector<SDValue> &Ops) const { 979 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 980 981 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 982 if (HasMatching) 983 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 984 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 985 // Put the register class of the virtual registers in the flag word. That 986 // way, later passes can recompute register class constraints for inline 987 // assembly as well as normal instructions. 988 // Don't do this for tied operands that can use the regclass information 989 // from the def. 990 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 991 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 992 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 993 } 994 995 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 996 Ops.push_back(Res); 997 998 if (Code == InlineAsm::Kind_Clobber) { 999 // Clobbers should always have a 1:1 mapping with registers, and may 1000 // reference registers that have illegal (e.g. vector) types. Hence, we 1001 // shouldn't try to apply any sort of splitting logic to them. 1002 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 1003 "No 1:1 mapping from clobbers to regs?"); 1004 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 1005 (void)SP; 1006 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 1007 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 1008 assert( 1009 (Regs[I] != SP || 1010 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 1011 "If we clobbered the stack pointer, MFI should know about it."); 1012 } 1013 return; 1014 } 1015 1016 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 1017 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 1018 MVT RegisterVT = RegVTs[Value]; 1019 for (unsigned i = 0; i != NumRegs; ++i) { 1020 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1021 unsigned TheReg = Regs[Reg++]; 1022 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1023 } 1024 } 1025 } 1026 1027 SmallVector<std::pair<unsigned, unsigned>, 4> 1028 RegsForValue::getRegsAndSizes() const { 1029 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1030 unsigned I = 0; 1031 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1032 unsigned RegCount = std::get<0>(CountAndVT); 1033 MVT RegisterVT = std::get<1>(CountAndVT); 1034 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1035 for (unsigned E = I + RegCount; I != E; ++I) 1036 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1037 } 1038 return OutVec; 1039 } 1040 1041 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1042 const TargetLibraryInfo *li) { 1043 AA = aa; 1044 GFI = gfi; 1045 LibInfo = li; 1046 DL = &DAG.getDataLayout(); 1047 Context = DAG.getContext(); 1048 LPadToCallSiteMap.clear(); 1049 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1050 } 1051 1052 void SelectionDAGBuilder::clear() { 1053 NodeMap.clear(); 1054 UnusedArgNodeMap.clear(); 1055 PendingLoads.clear(); 1056 PendingExports.clear(); 1057 PendingConstrainedFP.clear(); 1058 PendingConstrainedFPStrict.clear(); 1059 CurInst = nullptr; 1060 HasTailCall = false; 1061 SDNodeOrder = LowestSDNodeOrder; 1062 StatepointLowering.clear(); 1063 } 1064 1065 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1066 DanglingDebugInfoMap.clear(); 1067 } 1068 1069 // Update DAG root to include dependencies on Pending chains. 1070 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1071 SDValue Root = DAG.getRoot(); 1072 1073 if (Pending.empty()) 1074 return Root; 1075 1076 // Add current root to PendingChains, unless we already indirectly 1077 // depend on it. 1078 if (Root.getOpcode() != ISD::EntryToken) { 1079 unsigned i = 0, e = Pending.size(); 1080 for (; i != e; ++i) { 1081 assert(Pending[i].getNode()->getNumOperands() > 1); 1082 if (Pending[i].getNode()->getOperand(0) == Root) 1083 break; // Don't add the root if we already indirectly depend on it. 1084 } 1085 1086 if (i == e) 1087 Pending.push_back(Root); 1088 } 1089 1090 if (Pending.size() == 1) 1091 Root = Pending[0]; 1092 else 1093 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1094 1095 DAG.setRoot(Root); 1096 Pending.clear(); 1097 return Root; 1098 } 1099 1100 SDValue SelectionDAGBuilder::getMemoryRoot() { 1101 return updateRoot(PendingLoads); 1102 } 1103 1104 SDValue SelectionDAGBuilder::getRoot() { 1105 // Chain up all pending constrained intrinsics together with all 1106 // pending loads, by simply appending them to PendingLoads and 1107 // then calling getMemoryRoot(). 1108 PendingLoads.reserve(PendingLoads.size() + 1109 PendingConstrainedFP.size() + 1110 PendingConstrainedFPStrict.size()); 1111 PendingLoads.append(PendingConstrainedFP.begin(), 1112 PendingConstrainedFP.end()); 1113 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1114 PendingConstrainedFPStrict.end()); 1115 PendingConstrainedFP.clear(); 1116 PendingConstrainedFPStrict.clear(); 1117 return getMemoryRoot(); 1118 } 1119 1120 SDValue SelectionDAGBuilder::getControlRoot() { 1121 // We need to emit pending fpexcept.strict constrained intrinsics, 1122 // so append them to the PendingExports list. 1123 PendingExports.append(PendingConstrainedFPStrict.begin(), 1124 PendingConstrainedFPStrict.end()); 1125 PendingConstrainedFPStrict.clear(); 1126 return updateRoot(PendingExports); 1127 } 1128 1129 void SelectionDAGBuilder::visit(const Instruction &I) { 1130 // Set up outgoing PHI node register values before emitting the terminator. 1131 if (I.isTerminator()) { 1132 HandlePHINodesInSuccessorBlocks(I.getParent()); 1133 } 1134 1135 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1136 if (!isa<DbgInfoIntrinsic>(I)) 1137 ++SDNodeOrder; 1138 1139 CurInst = &I; 1140 1141 visit(I.getOpcode(), I); 1142 1143 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1144 // ConstrainedFPIntrinsics handle their own FMF. 1145 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1146 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1147 // maps to this instruction. 1148 // TODO: We could handle all flags (nsw, etc) here. 1149 // TODO: If an IR instruction maps to >1 node, only the final node will have 1150 // flags set. 1151 if (SDNode *Node = getNodeForIRValue(&I)) { 1152 SDNodeFlags IncomingFlags; 1153 IncomingFlags.copyFMF(*FPMO); 1154 if (!Node->getFlags().isDefined()) 1155 Node->setFlags(IncomingFlags); 1156 else 1157 Node->intersectFlagsWith(IncomingFlags); 1158 } 1159 } 1160 } 1161 1162 if (!I.isTerminator() && !HasTailCall && 1163 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1164 CopyToExportRegsIfNeeded(&I); 1165 1166 CurInst = nullptr; 1167 } 1168 1169 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1170 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1171 } 1172 1173 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1174 // Note: this doesn't use InstVisitor, because it has to work with 1175 // ConstantExpr's in addition to instructions. 1176 switch (Opcode) { 1177 default: llvm_unreachable("Unknown instruction type encountered!"); 1178 // Build the switch statement using the Instruction.def file. 1179 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1180 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1181 #include "llvm/IR/Instruction.def" 1182 } 1183 } 1184 1185 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1186 const DIExpression *Expr) { 1187 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1188 const DbgValueInst *DI = DDI.getDI(); 1189 DIVariable *DanglingVariable = DI->getVariable(); 1190 DIExpression *DanglingExpr = DI->getExpression(); 1191 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1192 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1193 return true; 1194 } 1195 return false; 1196 }; 1197 1198 for (auto &DDIMI : DanglingDebugInfoMap) { 1199 DanglingDebugInfoVector &DDIV = DDIMI.second; 1200 1201 // If debug info is to be dropped, run it through final checks to see 1202 // whether it can be salvaged. 1203 for (auto &DDI : DDIV) 1204 if (isMatchingDbgValue(DDI)) 1205 salvageUnresolvedDbgValue(DDI); 1206 1207 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1208 } 1209 } 1210 1211 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1212 // generate the debug data structures now that we've seen its definition. 1213 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1214 SDValue Val) { 1215 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1216 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1217 return; 1218 1219 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1220 for (auto &DDI : DDIV) { 1221 const DbgValueInst *DI = DDI.getDI(); 1222 assert(DI && "Ill-formed DanglingDebugInfo"); 1223 DebugLoc dl = DDI.getdl(); 1224 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1225 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1226 DILocalVariable *Variable = DI->getVariable(); 1227 DIExpression *Expr = DI->getExpression(); 1228 assert(Variable->isValidLocationForIntrinsic(dl) && 1229 "Expected inlined-at fields to agree"); 1230 SDDbgValue *SDV; 1231 if (Val.getNode()) { 1232 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1233 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1234 // we couldn't resolve it directly when examining the DbgValue intrinsic 1235 // in the first place we should not be more successful here). Unless we 1236 // have some test case that prove this to be correct we should avoid 1237 // calling EmitFuncArgumentDbgValue here. 1238 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1239 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1240 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1241 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1242 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1243 // inserted after the definition of Val when emitting the instructions 1244 // after ISel. An alternative could be to teach 1245 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1246 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1247 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1248 << ValSDNodeOrder << "\n"); 1249 SDV = getDbgValue(Val, Variable, Expr, dl, 1250 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1251 DAG.AddDbgValue(SDV, Val.getNode(), false); 1252 } else 1253 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1254 << "in EmitFuncArgumentDbgValue\n"); 1255 } else { 1256 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1257 auto Undef = 1258 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1259 auto SDV = 1260 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1261 DAG.AddDbgValue(SDV, nullptr, false); 1262 } 1263 } 1264 DDIV.clear(); 1265 } 1266 1267 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1268 Value *V = DDI.getDI()->getValue(); 1269 DILocalVariable *Var = DDI.getDI()->getVariable(); 1270 DIExpression *Expr = DDI.getDI()->getExpression(); 1271 DebugLoc DL = DDI.getdl(); 1272 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1273 unsigned SDOrder = DDI.getSDNodeOrder(); 1274 1275 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1276 // that DW_OP_stack_value is desired. 1277 assert(isa<DbgValueInst>(DDI.getDI())); 1278 bool StackValue = true; 1279 1280 // Can this Value can be encoded without any further work? 1281 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1282 return; 1283 1284 // Attempt to salvage back through as many instructions as possible. Bail if 1285 // a non-instruction is seen, such as a constant expression or global 1286 // variable. FIXME: Further work could recover those too. 1287 while (isa<Instruction>(V)) { 1288 Instruction &VAsInst = *cast<Instruction>(V); 1289 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1290 1291 // If we cannot salvage any further, and haven't yet found a suitable debug 1292 // expression, bail out. 1293 if (!NewExpr) 1294 break; 1295 1296 // New value and expr now represent this debuginfo. 1297 V = VAsInst.getOperand(0); 1298 Expr = NewExpr; 1299 1300 // Some kind of simplification occurred: check whether the operand of the 1301 // salvaged debug expression can be encoded in this DAG. 1302 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1303 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1304 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1305 return; 1306 } 1307 } 1308 1309 // This was the final opportunity to salvage this debug information, and it 1310 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1311 // any earlier variable location. 1312 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1313 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1314 DAG.AddDbgValue(SDV, nullptr, false); 1315 1316 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1317 << "\n"); 1318 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1319 << "\n"); 1320 } 1321 1322 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1323 DIExpression *Expr, DebugLoc dl, 1324 DebugLoc InstDL, unsigned Order) { 1325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1326 SDDbgValue *SDV; 1327 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1328 isa<ConstantPointerNull>(V)) { 1329 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1330 DAG.AddDbgValue(SDV, nullptr, false); 1331 return true; 1332 } 1333 1334 // If the Value is a frame index, we can create a FrameIndex debug value 1335 // without relying on the DAG at all. 1336 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1337 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1338 if (SI != FuncInfo.StaticAllocaMap.end()) { 1339 auto SDV = 1340 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1341 /*IsIndirect*/ false, dl, SDNodeOrder); 1342 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1343 // is still available even if the SDNode gets optimized out. 1344 DAG.AddDbgValue(SDV, nullptr, false); 1345 return true; 1346 } 1347 } 1348 1349 // Do not use getValue() in here; we don't want to generate code at 1350 // this point if it hasn't been done yet. 1351 SDValue N = NodeMap[V]; 1352 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1353 N = UnusedArgNodeMap[V]; 1354 if (N.getNode()) { 1355 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1356 return true; 1357 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1358 DAG.AddDbgValue(SDV, N.getNode(), false); 1359 return true; 1360 } 1361 1362 // Special rules apply for the first dbg.values of parameter variables in a 1363 // function. Identify them by the fact they reference Argument Values, that 1364 // they're parameters, and they are parameters of the current function. We 1365 // need to let them dangle until they get an SDNode. 1366 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1367 !InstDL.getInlinedAt(); 1368 if (!IsParamOfFunc) { 1369 // The value is not used in this block yet (or it would have an SDNode). 1370 // We still want the value to appear for the user if possible -- if it has 1371 // an associated VReg, we can refer to that instead. 1372 auto VMI = FuncInfo.ValueMap.find(V); 1373 if (VMI != FuncInfo.ValueMap.end()) { 1374 unsigned Reg = VMI->second; 1375 // If this is a PHI node, it may be split up into several MI PHI nodes 1376 // (in FunctionLoweringInfo::set). 1377 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1378 V->getType(), None); 1379 if (RFV.occupiesMultipleRegs()) { 1380 unsigned Offset = 0; 1381 unsigned BitsToDescribe = 0; 1382 if (auto VarSize = Var->getSizeInBits()) 1383 BitsToDescribe = *VarSize; 1384 if (auto Fragment = Expr->getFragmentInfo()) 1385 BitsToDescribe = Fragment->SizeInBits; 1386 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1387 unsigned RegisterSize = RegAndSize.second; 1388 // Bail out if all bits are described already. 1389 if (Offset >= BitsToDescribe) 1390 break; 1391 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1392 ? BitsToDescribe - Offset 1393 : RegisterSize; 1394 auto FragmentExpr = DIExpression::createFragmentExpression( 1395 Expr, Offset, FragmentSize); 1396 if (!FragmentExpr) 1397 continue; 1398 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1399 false, dl, SDNodeOrder); 1400 DAG.AddDbgValue(SDV, nullptr, false); 1401 Offset += RegisterSize; 1402 } 1403 } else { 1404 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1405 DAG.AddDbgValue(SDV, nullptr, false); 1406 } 1407 return true; 1408 } 1409 } 1410 1411 return false; 1412 } 1413 1414 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1415 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1416 for (auto &Pair : DanglingDebugInfoMap) 1417 for (auto &DDI : Pair.second) 1418 salvageUnresolvedDbgValue(DDI); 1419 clearDanglingDebugInfo(); 1420 } 1421 1422 /// getCopyFromRegs - If there was virtual register allocated for the value V 1423 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1424 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1425 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1426 SDValue Result; 1427 1428 if (It != FuncInfo.ValueMap.end()) { 1429 Register InReg = It->second; 1430 1431 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1432 DAG.getDataLayout(), InReg, Ty, 1433 None); // This is not an ABI copy. 1434 SDValue Chain = DAG.getEntryNode(); 1435 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1436 V); 1437 resolveDanglingDebugInfo(V, Result); 1438 } 1439 1440 return Result; 1441 } 1442 1443 /// getValue - Return an SDValue for the given Value. 1444 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1445 // If we already have an SDValue for this value, use it. It's important 1446 // to do this first, so that we don't create a CopyFromReg if we already 1447 // have a regular SDValue. 1448 SDValue &N = NodeMap[V]; 1449 if (N.getNode()) return N; 1450 1451 // If there's a virtual register allocated and initialized for this 1452 // value, use it. 1453 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1454 return copyFromReg; 1455 1456 // Otherwise create a new SDValue and remember it. 1457 SDValue Val = getValueImpl(V); 1458 NodeMap[V] = Val; 1459 resolveDanglingDebugInfo(V, Val); 1460 return Val; 1461 } 1462 1463 /// getNonRegisterValue - Return an SDValue for the given Value, but 1464 /// don't look in FuncInfo.ValueMap for a virtual register. 1465 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1466 // If we already have an SDValue for this value, use it. 1467 SDValue &N = NodeMap[V]; 1468 if (N.getNode()) { 1469 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1470 // Remove the debug location from the node as the node is about to be used 1471 // in a location which may differ from the original debug location. This 1472 // is relevant to Constant and ConstantFP nodes because they can appear 1473 // as constant expressions inside PHI nodes. 1474 N->setDebugLoc(DebugLoc()); 1475 } 1476 return N; 1477 } 1478 1479 // Otherwise create a new SDValue and remember it. 1480 SDValue Val = getValueImpl(V); 1481 NodeMap[V] = Val; 1482 resolveDanglingDebugInfo(V, Val); 1483 return Val; 1484 } 1485 1486 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1487 /// Create an SDValue for the given value. 1488 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1490 1491 if (const Constant *C = dyn_cast<Constant>(V)) { 1492 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1493 1494 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1495 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1496 1497 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1498 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1499 1500 if (isa<ConstantPointerNull>(C)) { 1501 unsigned AS = V->getType()->getPointerAddressSpace(); 1502 return DAG.getConstant(0, getCurSDLoc(), 1503 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1504 } 1505 1506 if (match(C, m_VScale(DAG.getDataLayout()))) 1507 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1508 1509 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1510 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1511 1512 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1513 return DAG.getUNDEF(VT); 1514 1515 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1516 visit(CE->getOpcode(), *CE); 1517 SDValue N1 = NodeMap[V]; 1518 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1519 return N1; 1520 } 1521 1522 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1523 SmallVector<SDValue, 4> Constants; 1524 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1525 OI != OE; ++OI) { 1526 SDNode *Val = getValue(*OI).getNode(); 1527 // If the operand is an empty aggregate, there are no values. 1528 if (!Val) continue; 1529 // Add each leaf value from the operand to the Constants list 1530 // to form a flattened list of all the values. 1531 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1532 Constants.push_back(SDValue(Val, i)); 1533 } 1534 1535 return DAG.getMergeValues(Constants, getCurSDLoc()); 1536 } 1537 1538 if (const ConstantDataSequential *CDS = 1539 dyn_cast<ConstantDataSequential>(C)) { 1540 SmallVector<SDValue, 4> Ops; 1541 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1542 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1543 // Add each leaf value from the operand to the Constants list 1544 // to form a flattened list of all the values. 1545 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1546 Ops.push_back(SDValue(Val, i)); 1547 } 1548 1549 if (isa<ArrayType>(CDS->getType())) 1550 return DAG.getMergeValues(Ops, getCurSDLoc()); 1551 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1552 } 1553 1554 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1555 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1556 "Unknown struct or array constant!"); 1557 1558 SmallVector<EVT, 4> ValueVTs; 1559 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1560 unsigned NumElts = ValueVTs.size(); 1561 if (NumElts == 0) 1562 return SDValue(); // empty struct 1563 SmallVector<SDValue, 4> Constants(NumElts); 1564 for (unsigned i = 0; i != NumElts; ++i) { 1565 EVT EltVT = ValueVTs[i]; 1566 if (isa<UndefValue>(C)) 1567 Constants[i] = DAG.getUNDEF(EltVT); 1568 else if (EltVT.isFloatingPoint()) 1569 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1570 else 1571 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1572 } 1573 1574 return DAG.getMergeValues(Constants, getCurSDLoc()); 1575 } 1576 1577 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1578 return DAG.getBlockAddress(BA, VT); 1579 1580 VectorType *VecTy = cast<VectorType>(V->getType()); 1581 1582 // Now that we know the number and type of the elements, get that number of 1583 // elements into the Ops array based on what kind of constant it is. 1584 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1585 SmallVector<SDValue, 16> Ops; 1586 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1587 for (unsigned i = 0; i != NumElements; ++i) 1588 Ops.push_back(getValue(CV->getOperand(i))); 1589 1590 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1591 } else if (isa<ConstantAggregateZero>(C)) { 1592 EVT EltVT = 1593 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1594 1595 SDValue Op; 1596 if (EltVT.isFloatingPoint()) 1597 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1598 else 1599 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1600 1601 if (isa<ScalableVectorType>(VecTy)) 1602 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1603 else { 1604 SmallVector<SDValue, 16> Ops; 1605 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1606 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1607 } 1608 } 1609 llvm_unreachable("Unknown vector constant"); 1610 } 1611 1612 // If this is a static alloca, generate it as the frameindex instead of 1613 // computation. 1614 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1615 DenseMap<const AllocaInst*, int>::iterator SI = 1616 FuncInfo.StaticAllocaMap.find(AI); 1617 if (SI != FuncInfo.StaticAllocaMap.end()) 1618 return DAG.getFrameIndex(SI->second, 1619 TLI.getFrameIndexTy(DAG.getDataLayout())); 1620 } 1621 1622 // If this is an instruction which fast-isel has deferred, select it now. 1623 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1624 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1625 1626 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1627 Inst->getType(), getABIRegCopyCC(V)); 1628 SDValue Chain = DAG.getEntryNode(); 1629 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1630 } 1631 1632 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1633 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1634 } 1635 llvm_unreachable("Can't get register for value!"); 1636 } 1637 1638 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1639 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1640 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1641 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1642 bool IsSEH = isAsynchronousEHPersonality(Pers); 1643 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1644 if (!IsSEH) 1645 CatchPadMBB->setIsEHScopeEntry(); 1646 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1647 if (IsMSVCCXX || IsCoreCLR) 1648 CatchPadMBB->setIsEHFuncletEntry(); 1649 } 1650 1651 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1652 // Update machine-CFG edge. 1653 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1654 FuncInfo.MBB->addSuccessor(TargetMBB); 1655 1656 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1657 bool IsSEH = isAsynchronousEHPersonality(Pers); 1658 if (IsSEH) { 1659 // If this is not a fall-through branch or optimizations are switched off, 1660 // emit the branch. 1661 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1662 TM.getOptLevel() == CodeGenOpt::None) 1663 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1664 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1665 return; 1666 } 1667 1668 // Figure out the funclet membership for the catchret's successor. 1669 // This will be used by the FuncletLayout pass to determine how to order the 1670 // BB's. 1671 // A 'catchret' returns to the outer scope's color. 1672 Value *ParentPad = I.getCatchSwitchParentPad(); 1673 const BasicBlock *SuccessorColor; 1674 if (isa<ConstantTokenNone>(ParentPad)) 1675 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1676 else 1677 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1678 assert(SuccessorColor && "No parent funclet for catchret!"); 1679 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1680 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1681 1682 // Create the terminator node. 1683 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1684 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1685 DAG.getBasicBlock(SuccessorColorMBB)); 1686 DAG.setRoot(Ret); 1687 } 1688 1689 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1690 // Don't emit any special code for the cleanuppad instruction. It just marks 1691 // the start of an EH scope/funclet. 1692 FuncInfo.MBB->setIsEHScopeEntry(); 1693 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1694 if (Pers != EHPersonality::Wasm_CXX) { 1695 FuncInfo.MBB->setIsEHFuncletEntry(); 1696 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1697 } 1698 } 1699 1700 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1701 // the control flow always stops at the single catch pad, as it does for a 1702 // cleanup pad. In case the exception caught is not of the types the catch pad 1703 // catches, it will be rethrown by a rethrow. 1704 static void findWasmUnwindDestinations( 1705 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1706 BranchProbability Prob, 1707 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1708 &UnwindDests) { 1709 while (EHPadBB) { 1710 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1711 if (isa<CleanupPadInst>(Pad)) { 1712 // Stop on cleanup pads. 1713 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1714 UnwindDests.back().first->setIsEHScopeEntry(); 1715 break; 1716 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1717 // Add the catchpad handlers to the possible destinations. We don't 1718 // continue to the unwind destination of the catchswitch for wasm. 1719 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1720 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1721 UnwindDests.back().first->setIsEHScopeEntry(); 1722 } 1723 break; 1724 } else { 1725 continue; 1726 } 1727 } 1728 } 1729 1730 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1731 /// many places it could ultimately go. In the IR, we have a single unwind 1732 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1733 /// This function skips over imaginary basic blocks that hold catchswitch 1734 /// instructions, and finds all the "real" machine 1735 /// basic block destinations. As those destinations may not be successors of 1736 /// EHPadBB, here we also calculate the edge probability to those destinations. 1737 /// The passed-in Prob is the edge probability to EHPadBB. 1738 static void findUnwindDestinations( 1739 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1740 BranchProbability Prob, 1741 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1742 &UnwindDests) { 1743 EHPersonality Personality = 1744 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1745 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1746 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1747 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1748 bool IsSEH = isAsynchronousEHPersonality(Personality); 1749 1750 if (IsWasmCXX) { 1751 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1752 assert(UnwindDests.size() <= 1 && 1753 "There should be at most one unwind destination for wasm"); 1754 return; 1755 } 1756 1757 while (EHPadBB) { 1758 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1759 BasicBlock *NewEHPadBB = nullptr; 1760 if (isa<LandingPadInst>(Pad)) { 1761 // Stop on landingpads. They are not funclets. 1762 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1763 break; 1764 } else if (isa<CleanupPadInst>(Pad)) { 1765 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1766 // personalities. 1767 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1768 UnwindDests.back().first->setIsEHScopeEntry(); 1769 UnwindDests.back().first->setIsEHFuncletEntry(); 1770 break; 1771 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1772 // Add the catchpad handlers to the possible destinations. 1773 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1774 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1775 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1776 if (IsMSVCCXX || IsCoreCLR) 1777 UnwindDests.back().first->setIsEHFuncletEntry(); 1778 if (!IsSEH) 1779 UnwindDests.back().first->setIsEHScopeEntry(); 1780 } 1781 NewEHPadBB = CatchSwitch->getUnwindDest(); 1782 } else { 1783 continue; 1784 } 1785 1786 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1787 if (BPI && NewEHPadBB) 1788 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1789 EHPadBB = NewEHPadBB; 1790 } 1791 } 1792 1793 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1794 // Update successor info. 1795 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1796 auto UnwindDest = I.getUnwindDest(); 1797 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1798 BranchProbability UnwindDestProb = 1799 (BPI && UnwindDest) 1800 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1801 : BranchProbability::getZero(); 1802 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1803 for (auto &UnwindDest : UnwindDests) { 1804 UnwindDest.first->setIsEHPad(); 1805 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1806 } 1807 FuncInfo.MBB->normalizeSuccProbs(); 1808 1809 // Create the terminator node. 1810 SDValue Ret = 1811 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1812 DAG.setRoot(Ret); 1813 } 1814 1815 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1816 report_fatal_error("visitCatchSwitch not yet implemented!"); 1817 } 1818 1819 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1821 auto &DL = DAG.getDataLayout(); 1822 SDValue Chain = getControlRoot(); 1823 SmallVector<ISD::OutputArg, 8> Outs; 1824 SmallVector<SDValue, 8> OutVals; 1825 1826 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1827 // lower 1828 // 1829 // %val = call <ty> @llvm.experimental.deoptimize() 1830 // ret <ty> %val 1831 // 1832 // differently. 1833 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1834 LowerDeoptimizingReturn(); 1835 return; 1836 } 1837 1838 if (!FuncInfo.CanLowerReturn) { 1839 unsigned DemoteReg = FuncInfo.DemoteRegister; 1840 const Function *F = I.getParent()->getParent(); 1841 1842 // Emit a store of the return value through the virtual register. 1843 // Leave Outs empty so that LowerReturn won't try to load return 1844 // registers the usual way. 1845 SmallVector<EVT, 1> PtrValueVTs; 1846 ComputeValueVTs(TLI, DL, 1847 F->getReturnType()->getPointerTo( 1848 DAG.getDataLayout().getAllocaAddrSpace()), 1849 PtrValueVTs); 1850 1851 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1852 DemoteReg, PtrValueVTs[0]); 1853 SDValue RetOp = getValue(I.getOperand(0)); 1854 1855 SmallVector<EVT, 4> ValueVTs, MemVTs; 1856 SmallVector<uint64_t, 4> Offsets; 1857 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1858 &Offsets); 1859 unsigned NumValues = ValueVTs.size(); 1860 1861 SmallVector<SDValue, 4> Chains(NumValues); 1862 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1863 for (unsigned i = 0; i != NumValues; ++i) { 1864 // An aggregate return value cannot wrap around the address space, so 1865 // offsets to its parts don't wrap either. 1866 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1867 1868 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1869 if (MemVTs[i] != ValueVTs[i]) 1870 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1871 Chains[i] = DAG.getStore( 1872 Chain, getCurSDLoc(), Val, 1873 // FIXME: better loc info would be nice. 1874 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1875 commonAlignment(BaseAlign, Offsets[i])); 1876 } 1877 1878 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1879 MVT::Other, Chains); 1880 } else if (I.getNumOperands() != 0) { 1881 SmallVector<EVT, 4> ValueVTs; 1882 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1883 unsigned NumValues = ValueVTs.size(); 1884 if (NumValues) { 1885 SDValue RetOp = getValue(I.getOperand(0)); 1886 1887 const Function *F = I.getParent()->getParent(); 1888 1889 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1890 I.getOperand(0)->getType(), F->getCallingConv(), 1891 /*IsVarArg*/ false); 1892 1893 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1894 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1895 Attribute::SExt)) 1896 ExtendKind = ISD::SIGN_EXTEND; 1897 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1898 Attribute::ZExt)) 1899 ExtendKind = ISD::ZERO_EXTEND; 1900 1901 LLVMContext &Context = F->getContext(); 1902 bool RetInReg = F->getAttributes().hasAttribute( 1903 AttributeList::ReturnIndex, Attribute::InReg); 1904 1905 for (unsigned j = 0; j != NumValues; ++j) { 1906 EVT VT = ValueVTs[j]; 1907 1908 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1909 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1910 1911 CallingConv::ID CC = F->getCallingConv(); 1912 1913 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1914 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1915 SmallVector<SDValue, 4> Parts(NumParts); 1916 getCopyToParts(DAG, getCurSDLoc(), 1917 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1918 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1919 1920 // 'inreg' on function refers to return value 1921 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1922 if (RetInReg) 1923 Flags.setInReg(); 1924 1925 if (I.getOperand(0)->getType()->isPointerTy()) { 1926 Flags.setPointer(); 1927 Flags.setPointerAddrSpace( 1928 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1929 } 1930 1931 if (NeedsRegBlock) { 1932 Flags.setInConsecutiveRegs(); 1933 if (j == NumValues - 1) 1934 Flags.setInConsecutiveRegsLast(); 1935 } 1936 1937 // Propagate extension type if any 1938 if (ExtendKind == ISD::SIGN_EXTEND) 1939 Flags.setSExt(); 1940 else if (ExtendKind == ISD::ZERO_EXTEND) 1941 Flags.setZExt(); 1942 1943 for (unsigned i = 0; i < NumParts; ++i) { 1944 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1945 VT, /*isfixed=*/true, 0, 0)); 1946 OutVals.push_back(Parts[i]); 1947 } 1948 } 1949 } 1950 } 1951 1952 // Push in swifterror virtual register as the last element of Outs. This makes 1953 // sure swifterror virtual register will be returned in the swifterror 1954 // physical register. 1955 const Function *F = I.getParent()->getParent(); 1956 if (TLI.supportSwiftError() && 1957 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1958 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1959 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1960 Flags.setSwiftError(); 1961 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1962 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1963 true /*isfixed*/, 1 /*origidx*/, 1964 0 /*partOffs*/)); 1965 // Create SDNode for the swifterror virtual register. 1966 OutVals.push_back( 1967 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1968 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1969 EVT(TLI.getPointerTy(DL)))); 1970 } 1971 1972 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1973 CallingConv::ID CallConv = 1974 DAG.getMachineFunction().getFunction().getCallingConv(); 1975 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1976 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1977 1978 // Verify that the target's LowerReturn behaved as expected. 1979 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1980 "LowerReturn didn't return a valid chain!"); 1981 1982 // Update the DAG with the new chain value resulting from return lowering. 1983 DAG.setRoot(Chain); 1984 } 1985 1986 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1987 /// created for it, emit nodes to copy the value into the virtual 1988 /// registers. 1989 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1990 // Skip empty types 1991 if (V->getType()->isEmptyTy()) 1992 return; 1993 1994 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1995 if (VMI != FuncInfo.ValueMap.end()) { 1996 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1997 CopyValueToVirtualRegister(V, VMI->second); 1998 } 1999 } 2000 2001 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 2002 /// the current basic block, add it to ValueMap now so that we'll get a 2003 /// CopyTo/FromReg. 2004 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 2005 // No need to export constants. 2006 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 2007 2008 // Already exported? 2009 if (FuncInfo.isExportedInst(V)) return; 2010 2011 unsigned Reg = FuncInfo.InitializeRegForValue(V); 2012 CopyValueToVirtualRegister(V, Reg); 2013 } 2014 2015 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 2016 const BasicBlock *FromBB) { 2017 // The operands of the setcc have to be in this block. We don't know 2018 // how to export them from some other block. 2019 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2020 // Can export from current BB. 2021 if (VI->getParent() == FromBB) 2022 return true; 2023 2024 // Is already exported, noop. 2025 return FuncInfo.isExportedInst(V); 2026 } 2027 2028 // If this is an argument, we can export it if the BB is the entry block or 2029 // if it is already exported. 2030 if (isa<Argument>(V)) { 2031 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2032 return true; 2033 2034 // Otherwise, can only export this if it is already exported. 2035 return FuncInfo.isExportedInst(V); 2036 } 2037 2038 // Otherwise, constants can always be exported. 2039 return true; 2040 } 2041 2042 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2043 BranchProbability 2044 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2045 const MachineBasicBlock *Dst) const { 2046 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2047 const BasicBlock *SrcBB = Src->getBasicBlock(); 2048 const BasicBlock *DstBB = Dst->getBasicBlock(); 2049 if (!BPI) { 2050 // If BPI is not available, set the default probability as 1 / N, where N is 2051 // the number of successors. 2052 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2053 return BranchProbability(1, SuccSize); 2054 } 2055 return BPI->getEdgeProbability(SrcBB, DstBB); 2056 } 2057 2058 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2059 MachineBasicBlock *Dst, 2060 BranchProbability Prob) { 2061 if (!FuncInfo.BPI) 2062 Src->addSuccessorWithoutProb(Dst); 2063 else { 2064 if (Prob.isUnknown()) 2065 Prob = getEdgeProbability(Src, Dst); 2066 Src->addSuccessor(Dst, Prob); 2067 } 2068 } 2069 2070 static bool InBlock(const Value *V, const BasicBlock *BB) { 2071 if (const Instruction *I = dyn_cast<Instruction>(V)) 2072 return I->getParent() == BB; 2073 return true; 2074 } 2075 2076 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2077 /// This function emits a branch and is used at the leaves of an OR or an 2078 /// AND operator tree. 2079 void 2080 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2081 MachineBasicBlock *TBB, 2082 MachineBasicBlock *FBB, 2083 MachineBasicBlock *CurBB, 2084 MachineBasicBlock *SwitchBB, 2085 BranchProbability TProb, 2086 BranchProbability FProb, 2087 bool InvertCond) { 2088 const BasicBlock *BB = CurBB->getBasicBlock(); 2089 2090 // If the leaf of the tree is a comparison, merge the condition into 2091 // the caseblock. 2092 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2093 // The operands of the cmp have to be in this block. We don't know 2094 // how to export them from some other block. If this is the first block 2095 // of the sequence, no exporting is needed. 2096 if (CurBB == SwitchBB || 2097 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2098 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2099 ISD::CondCode Condition; 2100 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2101 ICmpInst::Predicate Pred = 2102 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2103 Condition = getICmpCondCode(Pred); 2104 } else { 2105 const FCmpInst *FC = cast<FCmpInst>(Cond); 2106 FCmpInst::Predicate Pred = 2107 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2108 Condition = getFCmpCondCode(Pred); 2109 if (TM.Options.NoNaNsFPMath) 2110 Condition = getFCmpCodeWithoutNaN(Condition); 2111 } 2112 2113 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2114 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2115 SL->SwitchCases.push_back(CB); 2116 return; 2117 } 2118 } 2119 2120 // Create a CaseBlock record representing this branch. 2121 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2122 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2123 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2124 SL->SwitchCases.push_back(CB); 2125 } 2126 2127 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2128 MachineBasicBlock *TBB, 2129 MachineBasicBlock *FBB, 2130 MachineBasicBlock *CurBB, 2131 MachineBasicBlock *SwitchBB, 2132 Instruction::BinaryOps Opc, 2133 BranchProbability TProb, 2134 BranchProbability FProb, 2135 bool InvertCond) { 2136 // Skip over not part of the tree and remember to invert op and operands at 2137 // next level. 2138 Value *NotCond; 2139 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2140 InBlock(NotCond, CurBB->getBasicBlock())) { 2141 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2142 !InvertCond); 2143 return; 2144 } 2145 2146 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2147 // Compute the effective opcode for Cond, taking into account whether it needs 2148 // to be inverted, e.g. 2149 // and (not (or A, B)), C 2150 // gets lowered as 2151 // and (and (not A, not B), C) 2152 unsigned BOpc = 0; 2153 if (BOp) { 2154 BOpc = BOp->getOpcode(); 2155 if (InvertCond) { 2156 if (BOpc == Instruction::And) 2157 BOpc = Instruction::Or; 2158 else if (BOpc == Instruction::Or) 2159 BOpc = Instruction::And; 2160 } 2161 } 2162 2163 // If this node is not part of the or/and tree, emit it as a branch. 2164 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2165 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2166 BOp->getParent() != CurBB->getBasicBlock() || 2167 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2168 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2169 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2170 TProb, FProb, InvertCond); 2171 return; 2172 } 2173 2174 // Create TmpBB after CurBB. 2175 MachineFunction::iterator BBI(CurBB); 2176 MachineFunction &MF = DAG.getMachineFunction(); 2177 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2178 CurBB->getParent()->insert(++BBI, TmpBB); 2179 2180 if (Opc == Instruction::Or) { 2181 // Codegen X | Y as: 2182 // BB1: 2183 // jmp_if_X TBB 2184 // jmp TmpBB 2185 // TmpBB: 2186 // jmp_if_Y TBB 2187 // jmp FBB 2188 // 2189 2190 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2191 // The requirement is that 2192 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2193 // = TrueProb for original BB. 2194 // Assuming the original probabilities are A and B, one choice is to set 2195 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2196 // A/(1+B) and 2B/(1+B). This choice assumes that 2197 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2198 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2199 // TmpBB, but the math is more complicated. 2200 2201 auto NewTrueProb = TProb / 2; 2202 auto NewFalseProb = TProb / 2 + FProb; 2203 // Emit the LHS condition. 2204 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2205 NewTrueProb, NewFalseProb, InvertCond); 2206 2207 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2208 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2209 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2210 // Emit the RHS condition into TmpBB. 2211 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2212 Probs[0], Probs[1], InvertCond); 2213 } else { 2214 assert(Opc == Instruction::And && "Unknown merge op!"); 2215 // Codegen X & Y as: 2216 // BB1: 2217 // jmp_if_X TmpBB 2218 // jmp FBB 2219 // TmpBB: 2220 // jmp_if_Y TBB 2221 // jmp FBB 2222 // 2223 // This requires creation of TmpBB after CurBB. 2224 2225 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2226 // The requirement is that 2227 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2228 // = FalseProb for original BB. 2229 // Assuming the original probabilities are A and B, one choice is to set 2230 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2231 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2232 // TrueProb for BB1 * FalseProb for TmpBB. 2233 2234 auto NewTrueProb = TProb + FProb / 2; 2235 auto NewFalseProb = FProb / 2; 2236 // Emit the LHS condition. 2237 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2238 NewTrueProb, NewFalseProb, InvertCond); 2239 2240 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2241 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2242 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2243 // Emit the RHS condition into TmpBB. 2244 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2245 Probs[0], Probs[1], InvertCond); 2246 } 2247 } 2248 2249 /// If the set of cases should be emitted as a series of branches, return true. 2250 /// If we should emit this as a bunch of and/or'd together conditions, return 2251 /// false. 2252 bool 2253 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2254 if (Cases.size() != 2) return true; 2255 2256 // If this is two comparisons of the same values or'd or and'd together, they 2257 // will get folded into a single comparison, so don't emit two blocks. 2258 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2259 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2260 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2261 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2262 return false; 2263 } 2264 2265 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2266 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2267 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2268 Cases[0].CC == Cases[1].CC && 2269 isa<Constant>(Cases[0].CmpRHS) && 2270 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2271 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2272 return false; 2273 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2274 return false; 2275 } 2276 2277 return true; 2278 } 2279 2280 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2281 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2282 2283 // Update machine-CFG edges. 2284 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2285 2286 if (I.isUnconditional()) { 2287 // Update machine-CFG edges. 2288 BrMBB->addSuccessor(Succ0MBB); 2289 2290 // If this is not a fall-through branch or optimizations are switched off, 2291 // emit the branch. 2292 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2293 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2294 MVT::Other, getControlRoot(), 2295 DAG.getBasicBlock(Succ0MBB))); 2296 2297 return; 2298 } 2299 2300 // If this condition is one of the special cases we handle, do special stuff 2301 // now. 2302 const Value *CondVal = I.getCondition(); 2303 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2304 2305 // If this is a series of conditions that are or'd or and'd together, emit 2306 // this as a sequence of branches instead of setcc's with and/or operations. 2307 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2308 // unpredictable branches, and vector extracts because those jumps are likely 2309 // expensive for any target), this should improve performance. 2310 // For example, instead of something like: 2311 // cmp A, B 2312 // C = seteq 2313 // cmp D, E 2314 // F = setle 2315 // or C, F 2316 // jnz foo 2317 // Emit: 2318 // cmp A, B 2319 // je foo 2320 // cmp D, E 2321 // jle foo 2322 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2323 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2324 Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1); 2325 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2326 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2327 (Opcode == Instruction::And || Opcode == Instruction::Or) && 2328 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2329 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2330 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2331 Opcode, 2332 getEdgeProbability(BrMBB, Succ0MBB), 2333 getEdgeProbability(BrMBB, Succ1MBB), 2334 /*InvertCond=*/false); 2335 // If the compares in later blocks need to use values not currently 2336 // exported from this block, export them now. This block should always 2337 // be the first entry. 2338 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2339 2340 // Allow some cases to be rejected. 2341 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2342 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2343 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2344 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2345 } 2346 2347 // Emit the branch for this block. 2348 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2349 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2350 return; 2351 } 2352 2353 // Okay, we decided not to do this, remove any inserted MBB's and clear 2354 // SwitchCases. 2355 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2356 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2357 2358 SL->SwitchCases.clear(); 2359 } 2360 } 2361 2362 // Create a CaseBlock record representing this branch. 2363 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2364 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2365 2366 // Use visitSwitchCase to actually insert the fast branch sequence for this 2367 // cond branch. 2368 visitSwitchCase(CB, BrMBB); 2369 } 2370 2371 /// visitSwitchCase - Emits the necessary code to represent a single node in 2372 /// the binary search tree resulting from lowering a switch instruction. 2373 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2374 MachineBasicBlock *SwitchBB) { 2375 SDValue Cond; 2376 SDValue CondLHS = getValue(CB.CmpLHS); 2377 SDLoc dl = CB.DL; 2378 2379 if (CB.CC == ISD::SETTRUE) { 2380 // Branch or fall through to TrueBB. 2381 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2382 SwitchBB->normalizeSuccProbs(); 2383 if (CB.TrueBB != NextBlock(SwitchBB)) { 2384 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2385 DAG.getBasicBlock(CB.TrueBB))); 2386 } 2387 return; 2388 } 2389 2390 auto &TLI = DAG.getTargetLoweringInfo(); 2391 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2392 2393 // Build the setcc now. 2394 if (!CB.CmpMHS) { 2395 // Fold "(X == true)" to X and "(X == false)" to !X to 2396 // handle common cases produced by branch lowering. 2397 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2398 CB.CC == ISD::SETEQ) 2399 Cond = CondLHS; 2400 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2401 CB.CC == ISD::SETEQ) { 2402 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2403 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2404 } else { 2405 SDValue CondRHS = getValue(CB.CmpRHS); 2406 2407 // If a pointer's DAG type is larger than its memory type then the DAG 2408 // values are zero-extended. This breaks signed comparisons so truncate 2409 // back to the underlying type before doing the compare. 2410 if (CondLHS.getValueType() != MemVT) { 2411 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2412 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2413 } 2414 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2415 } 2416 } else { 2417 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2418 2419 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2420 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2421 2422 SDValue CmpOp = getValue(CB.CmpMHS); 2423 EVT VT = CmpOp.getValueType(); 2424 2425 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2426 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2427 ISD::SETLE); 2428 } else { 2429 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2430 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2431 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2432 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2433 } 2434 } 2435 2436 // Update successor info 2437 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2438 // TrueBB and FalseBB are always different unless the incoming IR is 2439 // degenerate. This only happens when running llc on weird IR. 2440 if (CB.TrueBB != CB.FalseBB) 2441 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2442 SwitchBB->normalizeSuccProbs(); 2443 2444 // If the lhs block is the next block, invert the condition so that we can 2445 // fall through to the lhs instead of the rhs block. 2446 if (CB.TrueBB == NextBlock(SwitchBB)) { 2447 std::swap(CB.TrueBB, CB.FalseBB); 2448 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2449 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2450 } 2451 2452 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2453 MVT::Other, getControlRoot(), Cond, 2454 DAG.getBasicBlock(CB.TrueBB)); 2455 2456 // Insert the false branch. Do this even if it's a fall through branch, 2457 // this makes it easier to do DAG optimizations which require inverting 2458 // the branch condition. 2459 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2460 DAG.getBasicBlock(CB.FalseBB)); 2461 2462 DAG.setRoot(BrCond); 2463 } 2464 2465 /// visitJumpTable - Emit JumpTable node in the current MBB 2466 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2467 // Emit the code for the jump table 2468 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2469 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2470 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2471 JT.Reg, PTy); 2472 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2473 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2474 MVT::Other, Index.getValue(1), 2475 Table, Index); 2476 DAG.setRoot(BrJumpTable); 2477 } 2478 2479 /// visitJumpTableHeader - This function emits necessary code to produce index 2480 /// in the JumpTable from switch case. 2481 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2482 JumpTableHeader &JTH, 2483 MachineBasicBlock *SwitchBB) { 2484 SDLoc dl = getCurSDLoc(); 2485 2486 // Subtract the lowest switch case value from the value being switched on. 2487 SDValue SwitchOp = getValue(JTH.SValue); 2488 EVT VT = SwitchOp.getValueType(); 2489 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2490 DAG.getConstant(JTH.First, dl, VT)); 2491 2492 // The SDNode we just created, which holds the value being switched on minus 2493 // the smallest case value, needs to be copied to a virtual register so it 2494 // can be used as an index into the jump table in a subsequent basic block. 2495 // This value may be smaller or larger than the target's pointer type, and 2496 // therefore require extension or truncating. 2497 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2498 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2499 2500 unsigned JumpTableReg = 2501 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2502 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2503 JumpTableReg, SwitchOp); 2504 JT.Reg = JumpTableReg; 2505 2506 if (!JTH.OmitRangeCheck) { 2507 // Emit the range check for the jump table, and branch to the default block 2508 // for the switch statement if the value being switched on exceeds the 2509 // largest case in the switch. 2510 SDValue CMP = DAG.getSetCC( 2511 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2512 Sub.getValueType()), 2513 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2514 2515 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2516 MVT::Other, CopyTo, CMP, 2517 DAG.getBasicBlock(JT.Default)); 2518 2519 // Avoid emitting unnecessary branches to the next block. 2520 if (JT.MBB != NextBlock(SwitchBB)) 2521 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2522 DAG.getBasicBlock(JT.MBB)); 2523 2524 DAG.setRoot(BrCond); 2525 } else { 2526 // Avoid emitting unnecessary branches to the next block. 2527 if (JT.MBB != NextBlock(SwitchBB)) 2528 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2529 DAG.getBasicBlock(JT.MBB))); 2530 else 2531 DAG.setRoot(CopyTo); 2532 } 2533 } 2534 2535 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2536 /// variable if there exists one. 2537 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2538 SDValue &Chain) { 2539 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2540 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2541 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2542 MachineFunction &MF = DAG.getMachineFunction(); 2543 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2544 MachineSDNode *Node = 2545 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2546 if (Global) { 2547 MachinePointerInfo MPInfo(Global); 2548 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2549 MachineMemOperand::MODereferenceable; 2550 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2551 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2552 DAG.setNodeMemRefs(Node, {MemRef}); 2553 } 2554 if (PtrTy != PtrMemTy) 2555 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2556 return SDValue(Node, 0); 2557 } 2558 2559 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2560 /// tail spliced into a stack protector check success bb. 2561 /// 2562 /// For a high level explanation of how this fits into the stack protector 2563 /// generation see the comment on the declaration of class 2564 /// StackProtectorDescriptor. 2565 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2566 MachineBasicBlock *ParentBB) { 2567 2568 // First create the loads to the guard/stack slot for the comparison. 2569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2570 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2571 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2572 2573 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2574 int FI = MFI.getStackProtectorIndex(); 2575 2576 SDValue Guard; 2577 SDLoc dl = getCurSDLoc(); 2578 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2579 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2580 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2581 2582 // Generate code to load the content of the guard slot. 2583 SDValue GuardVal = DAG.getLoad( 2584 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2585 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2586 MachineMemOperand::MOVolatile); 2587 2588 if (TLI.useStackGuardXorFP()) 2589 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2590 2591 // Retrieve guard check function, nullptr if instrumentation is inlined. 2592 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2593 // The target provides a guard check function to validate the guard value. 2594 // Generate a call to that function with the content of the guard slot as 2595 // argument. 2596 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2597 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2598 2599 TargetLowering::ArgListTy Args; 2600 TargetLowering::ArgListEntry Entry; 2601 Entry.Node = GuardVal; 2602 Entry.Ty = FnTy->getParamType(0); 2603 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2604 Entry.IsInReg = true; 2605 Args.push_back(Entry); 2606 2607 TargetLowering::CallLoweringInfo CLI(DAG); 2608 CLI.setDebugLoc(getCurSDLoc()) 2609 .setChain(DAG.getEntryNode()) 2610 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2611 getValue(GuardCheckFn), std::move(Args)); 2612 2613 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2614 DAG.setRoot(Result.second); 2615 return; 2616 } 2617 2618 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2619 // Otherwise, emit a volatile load to retrieve the stack guard value. 2620 SDValue Chain = DAG.getEntryNode(); 2621 if (TLI.useLoadStackGuardNode()) { 2622 Guard = getLoadStackGuard(DAG, dl, Chain); 2623 } else { 2624 const Value *IRGuard = TLI.getSDagStackGuard(M); 2625 SDValue GuardPtr = getValue(IRGuard); 2626 2627 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2628 MachinePointerInfo(IRGuard, 0), Align, 2629 MachineMemOperand::MOVolatile); 2630 } 2631 2632 // Perform the comparison via a getsetcc. 2633 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2634 *DAG.getContext(), 2635 Guard.getValueType()), 2636 Guard, GuardVal, ISD::SETNE); 2637 2638 // If the guard/stackslot do not equal, branch to failure MBB. 2639 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2640 MVT::Other, GuardVal.getOperand(0), 2641 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2642 // Otherwise branch to success MBB. 2643 SDValue Br = DAG.getNode(ISD::BR, dl, 2644 MVT::Other, BrCond, 2645 DAG.getBasicBlock(SPD.getSuccessMBB())); 2646 2647 DAG.setRoot(Br); 2648 } 2649 2650 /// Codegen the failure basic block for a stack protector check. 2651 /// 2652 /// A failure stack protector machine basic block consists simply of a call to 2653 /// __stack_chk_fail(). 2654 /// 2655 /// For a high level explanation of how this fits into the stack protector 2656 /// generation see the comment on the declaration of class 2657 /// StackProtectorDescriptor. 2658 void 2659 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2660 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2661 TargetLowering::MakeLibCallOptions CallOptions; 2662 CallOptions.setDiscardResult(true); 2663 SDValue Chain = 2664 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2665 None, CallOptions, getCurSDLoc()).second; 2666 // On PS4, the "return address" must still be within the calling function, 2667 // even if it's at the very end, so emit an explicit TRAP here. 2668 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2669 if (TM.getTargetTriple().isPS4CPU()) 2670 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2671 2672 DAG.setRoot(Chain); 2673 } 2674 2675 /// visitBitTestHeader - This function emits necessary code to produce value 2676 /// suitable for "bit tests" 2677 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2678 MachineBasicBlock *SwitchBB) { 2679 SDLoc dl = getCurSDLoc(); 2680 2681 // Subtract the minimum value. 2682 SDValue SwitchOp = getValue(B.SValue); 2683 EVT VT = SwitchOp.getValueType(); 2684 SDValue RangeSub = 2685 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2686 2687 // Determine the type of the test operands. 2688 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2689 bool UsePtrType = false; 2690 if (!TLI.isTypeLegal(VT)) { 2691 UsePtrType = true; 2692 } else { 2693 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2694 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2695 // Switch table case range are encoded into series of masks. 2696 // Just use pointer type, it's guaranteed to fit. 2697 UsePtrType = true; 2698 break; 2699 } 2700 } 2701 SDValue Sub = RangeSub; 2702 if (UsePtrType) { 2703 VT = TLI.getPointerTy(DAG.getDataLayout()); 2704 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2705 } 2706 2707 B.RegVT = VT.getSimpleVT(); 2708 B.Reg = FuncInfo.CreateReg(B.RegVT); 2709 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2710 2711 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2712 2713 if (!B.OmitRangeCheck) 2714 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2715 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2716 SwitchBB->normalizeSuccProbs(); 2717 2718 SDValue Root = CopyTo; 2719 if (!B.OmitRangeCheck) { 2720 // Conditional branch to the default block. 2721 SDValue RangeCmp = DAG.getSetCC(dl, 2722 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2723 RangeSub.getValueType()), 2724 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2725 ISD::SETUGT); 2726 2727 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2728 DAG.getBasicBlock(B.Default)); 2729 } 2730 2731 // Avoid emitting unnecessary branches to the next block. 2732 if (MBB != NextBlock(SwitchBB)) 2733 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2734 2735 DAG.setRoot(Root); 2736 } 2737 2738 /// visitBitTestCase - this function produces one "bit test" 2739 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2740 MachineBasicBlock* NextMBB, 2741 BranchProbability BranchProbToNext, 2742 unsigned Reg, 2743 BitTestCase &B, 2744 MachineBasicBlock *SwitchBB) { 2745 SDLoc dl = getCurSDLoc(); 2746 MVT VT = BB.RegVT; 2747 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2748 SDValue Cmp; 2749 unsigned PopCount = countPopulation(B.Mask); 2750 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2751 if (PopCount == 1) { 2752 // Testing for a single bit; just compare the shift count with what it 2753 // would need to be to shift a 1 bit in that position. 2754 Cmp = DAG.getSetCC( 2755 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2756 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2757 ISD::SETEQ); 2758 } else if (PopCount == BB.Range) { 2759 // There is only one zero bit in the range, test for it directly. 2760 Cmp = DAG.getSetCC( 2761 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2762 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2763 ISD::SETNE); 2764 } else { 2765 // Make desired shift 2766 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2767 DAG.getConstant(1, dl, VT), ShiftOp); 2768 2769 // Emit bit tests and jumps 2770 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2771 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2772 Cmp = DAG.getSetCC( 2773 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2774 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2775 } 2776 2777 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2778 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2779 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2780 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2781 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2782 // one as they are relative probabilities (and thus work more like weights), 2783 // and hence we need to normalize them to let the sum of them become one. 2784 SwitchBB->normalizeSuccProbs(); 2785 2786 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2787 MVT::Other, getControlRoot(), 2788 Cmp, DAG.getBasicBlock(B.TargetBB)); 2789 2790 // Avoid emitting unnecessary branches to the next block. 2791 if (NextMBB != NextBlock(SwitchBB)) 2792 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2793 DAG.getBasicBlock(NextMBB)); 2794 2795 DAG.setRoot(BrAnd); 2796 } 2797 2798 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2799 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2800 2801 // Retrieve successors. Look through artificial IR level blocks like 2802 // catchswitch for successors. 2803 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2804 const BasicBlock *EHPadBB = I.getSuccessor(1); 2805 2806 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2807 // have to do anything here to lower funclet bundles. 2808 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2809 LLVMContext::OB_gc_transition, 2810 LLVMContext::OB_gc_live, 2811 LLVMContext::OB_funclet, 2812 LLVMContext::OB_cfguardtarget}) && 2813 "Cannot lower invokes with arbitrary operand bundles yet!"); 2814 2815 const Value *Callee(I.getCalledOperand()); 2816 const Function *Fn = dyn_cast<Function>(Callee); 2817 if (isa<InlineAsm>(Callee)) 2818 visitInlineAsm(I); 2819 else if (Fn && Fn->isIntrinsic()) { 2820 switch (Fn->getIntrinsicID()) { 2821 default: 2822 llvm_unreachable("Cannot invoke this intrinsic"); 2823 case Intrinsic::donothing: 2824 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2825 break; 2826 case Intrinsic::experimental_patchpoint_void: 2827 case Intrinsic::experimental_patchpoint_i64: 2828 visitPatchpoint(I, EHPadBB); 2829 break; 2830 case Intrinsic::experimental_gc_statepoint: 2831 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2832 break; 2833 case Intrinsic::wasm_rethrow_in_catch: { 2834 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2835 // special because it can be invoked, so we manually lower it to a DAG 2836 // node here. 2837 SmallVector<SDValue, 8> Ops; 2838 Ops.push_back(getRoot()); // inchain 2839 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2840 Ops.push_back( 2841 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2842 TLI.getPointerTy(DAG.getDataLayout()))); 2843 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2844 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2845 break; 2846 } 2847 } 2848 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2849 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2850 // Eventually we will support lowering the @llvm.experimental.deoptimize 2851 // intrinsic, and right now there are no plans to support other intrinsics 2852 // with deopt state. 2853 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2854 } else { 2855 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2856 } 2857 2858 // If the value of the invoke is used outside of its defining block, make it 2859 // available as a virtual register. 2860 // We already took care of the exported value for the statepoint instruction 2861 // during call to the LowerStatepoint. 2862 if (!isa<GCStatepointInst>(I)) { 2863 CopyToExportRegsIfNeeded(&I); 2864 } 2865 2866 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2867 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2868 BranchProbability EHPadBBProb = 2869 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2870 : BranchProbability::getZero(); 2871 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2872 2873 // Update successor info. 2874 addSuccessorWithProb(InvokeMBB, Return); 2875 for (auto &UnwindDest : UnwindDests) { 2876 UnwindDest.first->setIsEHPad(); 2877 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2878 } 2879 InvokeMBB->normalizeSuccProbs(); 2880 2881 // Drop into normal successor. 2882 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2883 DAG.getBasicBlock(Return))); 2884 } 2885 2886 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2887 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2888 2889 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2890 // have to do anything here to lower funclet bundles. 2891 assert(!I.hasOperandBundlesOtherThan( 2892 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2893 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2894 2895 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2896 visitInlineAsm(I); 2897 CopyToExportRegsIfNeeded(&I); 2898 2899 // Retrieve successors. 2900 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2901 2902 // Update successor info. 2903 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2904 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2905 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2906 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2907 Target->setIsInlineAsmBrIndirectTarget(); 2908 } 2909 CallBrMBB->normalizeSuccProbs(); 2910 2911 // Drop into default successor. 2912 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2913 MVT::Other, getControlRoot(), 2914 DAG.getBasicBlock(Return))); 2915 } 2916 2917 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2918 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2919 } 2920 2921 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2922 assert(FuncInfo.MBB->isEHPad() && 2923 "Call to landingpad not in landing pad!"); 2924 2925 // If there aren't registers to copy the values into (e.g., during SjLj 2926 // exceptions), then don't bother to create these DAG nodes. 2927 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2928 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2929 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2930 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2931 return; 2932 2933 // If landingpad's return type is token type, we don't create DAG nodes 2934 // for its exception pointer and selector value. The extraction of exception 2935 // pointer or selector value from token type landingpads is not currently 2936 // supported. 2937 if (LP.getType()->isTokenTy()) 2938 return; 2939 2940 SmallVector<EVT, 2> ValueVTs; 2941 SDLoc dl = getCurSDLoc(); 2942 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2943 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2944 2945 // Get the two live-in registers as SDValues. The physregs have already been 2946 // copied into virtual registers. 2947 SDValue Ops[2]; 2948 if (FuncInfo.ExceptionPointerVirtReg) { 2949 Ops[0] = DAG.getZExtOrTrunc( 2950 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2951 FuncInfo.ExceptionPointerVirtReg, 2952 TLI.getPointerTy(DAG.getDataLayout())), 2953 dl, ValueVTs[0]); 2954 } else { 2955 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2956 } 2957 Ops[1] = DAG.getZExtOrTrunc( 2958 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2959 FuncInfo.ExceptionSelectorVirtReg, 2960 TLI.getPointerTy(DAG.getDataLayout())), 2961 dl, ValueVTs[1]); 2962 2963 // Merge into one. 2964 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2965 DAG.getVTList(ValueVTs), Ops); 2966 setValue(&LP, Res); 2967 } 2968 2969 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2970 MachineBasicBlock *Last) { 2971 // Update JTCases. 2972 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2973 if (SL->JTCases[i].first.HeaderBB == First) 2974 SL->JTCases[i].first.HeaderBB = Last; 2975 2976 // Update BitTestCases. 2977 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2978 if (SL->BitTestCases[i].Parent == First) 2979 SL->BitTestCases[i].Parent = Last; 2980 } 2981 2982 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2983 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2984 2985 // Update machine-CFG edges with unique successors. 2986 SmallSet<BasicBlock*, 32> Done; 2987 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2988 BasicBlock *BB = I.getSuccessor(i); 2989 bool Inserted = Done.insert(BB).second; 2990 if (!Inserted) 2991 continue; 2992 2993 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2994 addSuccessorWithProb(IndirectBrMBB, Succ); 2995 } 2996 IndirectBrMBB->normalizeSuccProbs(); 2997 2998 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2999 MVT::Other, getControlRoot(), 3000 getValue(I.getAddress()))); 3001 } 3002 3003 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 3004 if (!DAG.getTarget().Options.TrapUnreachable) 3005 return; 3006 3007 // We may be able to ignore unreachable behind a noreturn call. 3008 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 3009 const BasicBlock &BB = *I.getParent(); 3010 if (&I != &BB.front()) { 3011 BasicBlock::const_iterator PredI = 3012 std::prev(BasicBlock::const_iterator(&I)); 3013 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 3014 if (Call->doesNotReturn()) 3015 return; 3016 } 3017 } 3018 } 3019 3020 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3021 } 3022 3023 void SelectionDAGBuilder::visitFSub(const User &I) { 3024 // -0.0 - X --> fneg 3025 Type *Ty = I.getType(); 3026 if (isa<Constant>(I.getOperand(0)) && 3027 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 3028 SDValue Op2 = getValue(I.getOperand(1)); 3029 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 3030 Op2.getValueType(), Op2)); 3031 return; 3032 } 3033 3034 visitBinary(I, ISD::FSUB); 3035 } 3036 3037 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3038 SDNodeFlags Flags; 3039 3040 SDValue Op = getValue(I.getOperand(0)); 3041 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3042 Op, Flags); 3043 setValue(&I, UnNodeValue); 3044 } 3045 3046 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3047 SDNodeFlags Flags; 3048 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3049 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3050 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3051 } 3052 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3053 Flags.setExact(ExactOp->isExact()); 3054 } 3055 3056 SDValue Op1 = getValue(I.getOperand(0)); 3057 SDValue Op2 = getValue(I.getOperand(1)); 3058 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3059 Op1, Op2, Flags); 3060 setValue(&I, BinNodeValue); 3061 } 3062 3063 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3064 SDValue Op1 = getValue(I.getOperand(0)); 3065 SDValue Op2 = getValue(I.getOperand(1)); 3066 3067 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3068 Op1.getValueType(), DAG.getDataLayout()); 3069 3070 // Coerce the shift amount to the right type if we can. 3071 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3072 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3073 unsigned Op2Size = Op2.getValueSizeInBits(); 3074 SDLoc DL = getCurSDLoc(); 3075 3076 // If the operand is smaller than the shift count type, promote it. 3077 if (ShiftSize > Op2Size) 3078 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3079 3080 // If the operand is larger than the shift count type but the shift 3081 // count type has enough bits to represent any shift value, truncate 3082 // it now. This is a common case and it exposes the truncate to 3083 // optimization early. 3084 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3085 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3086 // Otherwise we'll need to temporarily settle for some other convenient 3087 // type. Type legalization will make adjustments once the shiftee is split. 3088 else 3089 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3090 } 3091 3092 bool nuw = false; 3093 bool nsw = false; 3094 bool exact = false; 3095 3096 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3097 3098 if (const OverflowingBinaryOperator *OFBinOp = 3099 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3100 nuw = OFBinOp->hasNoUnsignedWrap(); 3101 nsw = OFBinOp->hasNoSignedWrap(); 3102 } 3103 if (const PossiblyExactOperator *ExactOp = 3104 dyn_cast<const PossiblyExactOperator>(&I)) 3105 exact = ExactOp->isExact(); 3106 } 3107 SDNodeFlags Flags; 3108 Flags.setExact(exact); 3109 Flags.setNoSignedWrap(nsw); 3110 Flags.setNoUnsignedWrap(nuw); 3111 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3112 Flags); 3113 setValue(&I, Res); 3114 } 3115 3116 void SelectionDAGBuilder::visitSDiv(const User &I) { 3117 SDValue Op1 = getValue(I.getOperand(0)); 3118 SDValue Op2 = getValue(I.getOperand(1)); 3119 3120 SDNodeFlags Flags; 3121 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3122 cast<PossiblyExactOperator>(&I)->isExact()); 3123 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3124 Op2, Flags)); 3125 } 3126 3127 void SelectionDAGBuilder::visitICmp(const User &I) { 3128 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3129 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3130 predicate = IC->getPredicate(); 3131 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3132 predicate = ICmpInst::Predicate(IC->getPredicate()); 3133 SDValue Op1 = getValue(I.getOperand(0)); 3134 SDValue Op2 = getValue(I.getOperand(1)); 3135 ISD::CondCode Opcode = getICmpCondCode(predicate); 3136 3137 auto &TLI = DAG.getTargetLoweringInfo(); 3138 EVT MemVT = 3139 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3140 3141 // If a pointer's DAG type is larger than its memory type then the DAG values 3142 // are zero-extended. This breaks signed comparisons so truncate back to the 3143 // underlying type before doing the compare. 3144 if (Op1.getValueType() != MemVT) { 3145 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3146 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3147 } 3148 3149 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3150 I.getType()); 3151 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3152 } 3153 3154 void SelectionDAGBuilder::visitFCmp(const User &I) { 3155 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3156 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3157 predicate = FC->getPredicate(); 3158 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3159 predicate = FCmpInst::Predicate(FC->getPredicate()); 3160 SDValue Op1 = getValue(I.getOperand(0)); 3161 SDValue Op2 = getValue(I.getOperand(1)); 3162 3163 ISD::CondCode Condition = getFCmpCondCode(predicate); 3164 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3165 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3166 Condition = getFCmpCodeWithoutNaN(Condition); 3167 3168 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3169 I.getType()); 3170 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3171 } 3172 3173 // Check if the condition of the select has one use or two users that are both 3174 // selects with the same condition. 3175 static bool hasOnlySelectUsers(const Value *Cond) { 3176 return llvm::all_of(Cond->users(), [](const Value *V) { 3177 return isa<SelectInst>(V); 3178 }); 3179 } 3180 3181 void SelectionDAGBuilder::visitSelect(const User &I) { 3182 SmallVector<EVT, 4> ValueVTs; 3183 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3184 ValueVTs); 3185 unsigned NumValues = ValueVTs.size(); 3186 if (NumValues == 0) return; 3187 3188 SmallVector<SDValue, 4> Values(NumValues); 3189 SDValue Cond = getValue(I.getOperand(0)); 3190 SDValue LHSVal = getValue(I.getOperand(1)); 3191 SDValue RHSVal = getValue(I.getOperand(2)); 3192 SmallVector<SDValue, 1> BaseOps(1, Cond); 3193 ISD::NodeType OpCode = 3194 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3195 3196 bool IsUnaryAbs = false; 3197 3198 // Min/max matching is only viable if all output VTs are the same. 3199 if (is_splat(ValueVTs)) { 3200 EVT VT = ValueVTs[0]; 3201 LLVMContext &Ctx = *DAG.getContext(); 3202 auto &TLI = DAG.getTargetLoweringInfo(); 3203 3204 // We care about the legality of the operation after it has been type 3205 // legalized. 3206 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3207 VT = TLI.getTypeToTransformTo(Ctx, VT); 3208 3209 // If the vselect is legal, assume we want to leave this as a vector setcc + 3210 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3211 // min/max is legal on the scalar type. 3212 bool UseScalarMinMax = VT.isVector() && 3213 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3214 3215 Value *LHS, *RHS; 3216 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3217 ISD::NodeType Opc = ISD::DELETED_NODE; 3218 switch (SPR.Flavor) { 3219 case SPF_UMAX: Opc = ISD::UMAX; break; 3220 case SPF_UMIN: Opc = ISD::UMIN; break; 3221 case SPF_SMAX: Opc = ISD::SMAX; break; 3222 case SPF_SMIN: Opc = ISD::SMIN; break; 3223 case SPF_FMINNUM: 3224 switch (SPR.NaNBehavior) { 3225 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3226 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3227 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3228 case SPNB_RETURNS_ANY: { 3229 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3230 Opc = ISD::FMINNUM; 3231 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3232 Opc = ISD::FMINIMUM; 3233 else if (UseScalarMinMax) 3234 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3235 ISD::FMINNUM : ISD::FMINIMUM; 3236 break; 3237 } 3238 } 3239 break; 3240 case SPF_FMAXNUM: 3241 switch (SPR.NaNBehavior) { 3242 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3243 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3244 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3245 case SPNB_RETURNS_ANY: 3246 3247 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3248 Opc = ISD::FMAXNUM; 3249 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3250 Opc = ISD::FMAXIMUM; 3251 else if (UseScalarMinMax) 3252 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3253 ISD::FMAXNUM : ISD::FMAXIMUM; 3254 break; 3255 } 3256 break; 3257 case SPF_ABS: 3258 IsUnaryAbs = true; 3259 Opc = ISD::ABS; 3260 break; 3261 case SPF_NABS: 3262 // TODO: we need to produce sub(0, abs(X)). 3263 default: break; 3264 } 3265 3266 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3267 (TLI.isOperationLegalOrCustom(Opc, VT) || 3268 (UseScalarMinMax && 3269 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3270 // If the underlying comparison instruction is used by any other 3271 // instruction, the consumed instructions won't be destroyed, so it is 3272 // not profitable to convert to a min/max. 3273 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3274 OpCode = Opc; 3275 LHSVal = getValue(LHS); 3276 RHSVal = getValue(RHS); 3277 BaseOps.clear(); 3278 } 3279 3280 if (IsUnaryAbs) { 3281 OpCode = Opc; 3282 LHSVal = getValue(LHS); 3283 BaseOps.clear(); 3284 } 3285 } 3286 3287 if (IsUnaryAbs) { 3288 for (unsigned i = 0; i != NumValues; ++i) { 3289 Values[i] = 3290 DAG.getNode(OpCode, getCurSDLoc(), 3291 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3292 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3293 } 3294 } else { 3295 for (unsigned i = 0; i != NumValues; ++i) { 3296 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3297 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3298 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3299 Values[i] = DAG.getNode( 3300 OpCode, getCurSDLoc(), 3301 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3302 } 3303 } 3304 3305 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3306 DAG.getVTList(ValueVTs), Values)); 3307 } 3308 3309 void SelectionDAGBuilder::visitTrunc(const User &I) { 3310 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3311 SDValue N = getValue(I.getOperand(0)); 3312 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3313 I.getType()); 3314 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3315 } 3316 3317 void SelectionDAGBuilder::visitZExt(const User &I) { 3318 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3319 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3320 SDValue N = getValue(I.getOperand(0)); 3321 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3322 I.getType()); 3323 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3324 } 3325 3326 void SelectionDAGBuilder::visitSExt(const User &I) { 3327 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3328 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3329 SDValue N = getValue(I.getOperand(0)); 3330 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3331 I.getType()); 3332 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3333 } 3334 3335 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3336 // FPTrunc is never a no-op cast, no need to check 3337 SDValue N = getValue(I.getOperand(0)); 3338 SDLoc dl = getCurSDLoc(); 3339 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3340 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3341 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3342 DAG.getTargetConstant( 3343 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3344 } 3345 3346 void SelectionDAGBuilder::visitFPExt(const User &I) { 3347 // FPExt is never a no-op cast, no need to check 3348 SDValue N = getValue(I.getOperand(0)); 3349 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3350 I.getType()); 3351 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3352 } 3353 3354 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3355 // FPToUI is never a no-op cast, no need to check 3356 SDValue N = getValue(I.getOperand(0)); 3357 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3358 I.getType()); 3359 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3360 } 3361 3362 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3363 // FPToSI is never a no-op cast, no need to check 3364 SDValue N = getValue(I.getOperand(0)); 3365 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3366 I.getType()); 3367 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3368 } 3369 3370 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3371 // UIToFP is never a no-op cast, no need to check 3372 SDValue N = getValue(I.getOperand(0)); 3373 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3374 I.getType()); 3375 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3376 } 3377 3378 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3379 // SIToFP is never a no-op cast, no need to check 3380 SDValue N = getValue(I.getOperand(0)); 3381 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3382 I.getType()); 3383 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3384 } 3385 3386 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3387 // What to do depends on the size of the integer and the size of the pointer. 3388 // We can either truncate, zero extend, or no-op, accordingly. 3389 SDValue N = getValue(I.getOperand(0)); 3390 auto &TLI = DAG.getTargetLoweringInfo(); 3391 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3392 I.getType()); 3393 EVT PtrMemVT = 3394 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3395 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3396 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3397 setValue(&I, N); 3398 } 3399 3400 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3401 // What to do depends on the size of the integer and the size of the pointer. 3402 // We can either truncate, zero extend, or no-op, accordingly. 3403 SDValue N = getValue(I.getOperand(0)); 3404 auto &TLI = DAG.getTargetLoweringInfo(); 3405 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3406 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3407 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3408 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3409 setValue(&I, N); 3410 } 3411 3412 void SelectionDAGBuilder::visitBitCast(const User &I) { 3413 SDValue N = getValue(I.getOperand(0)); 3414 SDLoc dl = getCurSDLoc(); 3415 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3416 I.getType()); 3417 3418 // BitCast assures us that source and destination are the same size so this is 3419 // either a BITCAST or a no-op. 3420 if (DestVT != N.getValueType()) 3421 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3422 DestVT, N)); // convert types. 3423 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3424 // might fold any kind of constant expression to an integer constant and that 3425 // is not what we are looking for. Only recognize a bitcast of a genuine 3426 // constant integer as an opaque constant. 3427 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3428 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3429 /*isOpaque*/true)); 3430 else 3431 setValue(&I, N); // noop cast. 3432 } 3433 3434 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3435 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3436 const Value *SV = I.getOperand(0); 3437 SDValue N = getValue(SV); 3438 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3439 3440 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3441 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3442 3443 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3444 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3445 3446 setValue(&I, N); 3447 } 3448 3449 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3450 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3451 SDValue InVec = getValue(I.getOperand(0)); 3452 SDValue InVal = getValue(I.getOperand(1)); 3453 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3454 TLI.getVectorIdxTy(DAG.getDataLayout())); 3455 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3456 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3457 InVec, InVal, InIdx)); 3458 } 3459 3460 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3462 SDValue InVec = getValue(I.getOperand(0)); 3463 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3464 TLI.getVectorIdxTy(DAG.getDataLayout())); 3465 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3466 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3467 InVec, InIdx)); 3468 } 3469 3470 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3471 SDValue Src1 = getValue(I.getOperand(0)); 3472 SDValue Src2 = getValue(I.getOperand(1)); 3473 ArrayRef<int> Mask; 3474 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3475 Mask = SVI->getShuffleMask(); 3476 else 3477 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3478 SDLoc DL = getCurSDLoc(); 3479 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3480 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3481 EVT SrcVT = Src1.getValueType(); 3482 3483 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3484 VT.isScalableVector()) { 3485 // Canonical splat form of first element of first input vector. 3486 SDValue FirstElt = 3487 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3488 DAG.getVectorIdxConstant(0, DL)); 3489 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3490 return; 3491 } 3492 3493 // For now, we only handle splats for scalable vectors. 3494 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3495 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3496 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3497 3498 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3499 unsigned MaskNumElts = Mask.size(); 3500 3501 if (SrcNumElts == MaskNumElts) { 3502 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3503 return; 3504 } 3505 3506 // Normalize the shuffle vector since mask and vector length don't match. 3507 if (SrcNumElts < MaskNumElts) { 3508 // Mask is longer than the source vectors. We can use concatenate vector to 3509 // make the mask and vectors lengths match. 3510 3511 if (MaskNumElts % SrcNumElts == 0) { 3512 // Mask length is a multiple of the source vector length. 3513 // Check if the shuffle is some kind of concatenation of the input 3514 // vectors. 3515 unsigned NumConcat = MaskNumElts / SrcNumElts; 3516 bool IsConcat = true; 3517 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3518 for (unsigned i = 0; i != MaskNumElts; ++i) { 3519 int Idx = Mask[i]; 3520 if (Idx < 0) 3521 continue; 3522 // Ensure the indices in each SrcVT sized piece are sequential and that 3523 // the same source is used for the whole piece. 3524 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3525 (ConcatSrcs[i / SrcNumElts] >= 0 && 3526 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3527 IsConcat = false; 3528 break; 3529 } 3530 // Remember which source this index came from. 3531 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3532 } 3533 3534 // The shuffle is concatenating multiple vectors together. Just emit 3535 // a CONCAT_VECTORS operation. 3536 if (IsConcat) { 3537 SmallVector<SDValue, 8> ConcatOps; 3538 for (auto Src : ConcatSrcs) { 3539 if (Src < 0) 3540 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3541 else if (Src == 0) 3542 ConcatOps.push_back(Src1); 3543 else 3544 ConcatOps.push_back(Src2); 3545 } 3546 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3547 return; 3548 } 3549 } 3550 3551 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3552 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3553 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3554 PaddedMaskNumElts); 3555 3556 // Pad both vectors with undefs to make them the same length as the mask. 3557 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3558 3559 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3560 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3561 MOps1[0] = Src1; 3562 MOps2[0] = Src2; 3563 3564 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3565 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3566 3567 // Readjust mask for new input vector length. 3568 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3569 for (unsigned i = 0; i != MaskNumElts; ++i) { 3570 int Idx = Mask[i]; 3571 if (Idx >= (int)SrcNumElts) 3572 Idx -= SrcNumElts - PaddedMaskNumElts; 3573 MappedOps[i] = Idx; 3574 } 3575 3576 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3577 3578 // If the concatenated vector was padded, extract a subvector with the 3579 // correct number of elements. 3580 if (MaskNumElts != PaddedMaskNumElts) 3581 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3582 DAG.getVectorIdxConstant(0, DL)); 3583 3584 setValue(&I, Result); 3585 return; 3586 } 3587 3588 if (SrcNumElts > MaskNumElts) { 3589 // Analyze the access pattern of the vector to see if we can extract 3590 // two subvectors and do the shuffle. 3591 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3592 bool CanExtract = true; 3593 for (int Idx : Mask) { 3594 unsigned Input = 0; 3595 if (Idx < 0) 3596 continue; 3597 3598 if (Idx >= (int)SrcNumElts) { 3599 Input = 1; 3600 Idx -= SrcNumElts; 3601 } 3602 3603 // If all the indices come from the same MaskNumElts sized portion of 3604 // the sources we can use extract. Also make sure the extract wouldn't 3605 // extract past the end of the source. 3606 int NewStartIdx = alignDown(Idx, MaskNumElts); 3607 if (NewStartIdx + MaskNumElts > SrcNumElts || 3608 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3609 CanExtract = false; 3610 // Make sure we always update StartIdx as we use it to track if all 3611 // elements are undef. 3612 StartIdx[Input] = NewStartIdx; 3613 } 3614 3615 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3616 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3617 return; 3618 } 3619 if (CanExtract) { 3620 // Extract appropriate subvector and generate a vector shuffle 3621 for (unsigned Input = 0; Input < 2; ++Input) { 3622 SDValue &Src = Input == 0 ? Src1 : Src2; 3623 if (StartIdx[Input] < 0) 3624 Src = DAG.getUNDEF(VT); 3625 else { 3626 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3627 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3628 } 3629 } 3630 3631 // Calculate new mask. 3632 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3633 for (int &Idx : MappedOps) { 3634 if (Idx >= (int)SrcNumElts) 3635 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3636 else if (Idx >= 0) 3637 Idx -= StartIdx[0]; 3638 } 3639 3640 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3641 return; 3642 } 3643 } 3644 3645 // We can't use either concat vectors or extract subvectors so fall back to 3646 // replacing the shuffle with extract and build vector. 3647 // to insert and build vector. 3648 EVT EltVT = VT.getVectorElementType(); 3649 SmallVector<SDValue,8> Ops; 3650 for (int Idx : Mask) { 3651 SDValue Res; 3652 3653 if (Idx < 0) { 3654 Res = DAG.getUNDEF(EltVT); 3655 } else { 3656 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3657 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3658 3659 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3660 DAG.getVectorIdxConstant(Idx, DL)); 3661 } 3662 3663 Ops.push_back(Res); 3664 } 3665 3666 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3667 } 3668 3669 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3670 ArrayRef<unsigned> Indices; 3671 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3672 Indices = IV->getIndices(); 3673 else 3674 Indices = cast<ConstantExpr>(&I)->getIndices(); 3675 3676 const Value *Op0 = I.getOperand(0); 3677 const Value *Op1 = I.getOperand(1); 3678 Type *AggTy = I.getType(); 3679 Type *ValTy = Op1->getType(); 3680 bool IntoUndef = isa<UndefValue>(Op0); 3681 bool FromUndef = isa<UndefValue>(Op1); 3682 3683 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3684 3685 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3686 SmallVector<EVT, 4> AggValueVTs; 3687 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3688 SmallVector<EVT, 4> ValValueVTs; 3689 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3690 3691 unsigned NumAggValues = AggValueVTs.size(); 3692 unsigned NumValValues = ValValueVTs.size(); 3693 SmallVector<SDValue, 4> Values(NumAggValues); 3694 3695 // Ignore an insertvalue that produces an empty object 3696 if (!NumAggValues) { 3697 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3698 return; 3699 } 3700 3701 SDValue Agg = getValue(Op0); 3702 unsigned i = 0; 3703 // Copy the beginning value(s) from the original aggregate. 3704 for (; i != LinearIndex; ++i) 3705 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3706 SDValue(Agg.getNode(), Agg.getResNo() + i); 3707 // Copy values from the inserted value(s). 3708 if (NumValValues) { 3709 SDValue Val = getValue(Op1); 3710 for (; i != LinearIndex + NumValValues; ++i) 3711 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3712 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3713 } 3714 // Copy remaining value(s) from the original aggregate. 3715 for (; i != NumAggValues; ++i) 3716 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3717 SDValue(Agg.getNode(), Agg.getResNo() + i); 3718 3719 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3720 DAG.getVTList(AggValueVTs), Values)); 3721 } 3722 3723 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3724 ArrayRef<unsigned> Indices; 3725 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3726 Indices = EV->getIndices(); 3727 else 3728 Indices = cast<ConstantExpr>(&I)->getIndices(); 3729 3730 const Value *Op0 = I.getOperand(0); 3731 Type *AggTy = Op0->getType(); 3732 Type *ValTy = I.getType(); 3733 bool OutOfUndef = isa<UndefValue>(Op0); 3734 3735 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3736 3737 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3738 SmallVector<EVT, 4> ValValueVTs; 3739 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3740 3741 unsigned NumValValues = ValValueVTs.size(); 3742 3743 // Ignore a extractvalue that produces an empty object 3744 if (!NumValValues) { 3745 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3746 return; 3747 } 3748 3749 SmallVector<SDValue, 4> Values(NumValValues); 3750 3751 SDValue Agg = getValue(Op0); 3752 // Copy out the selected value(s). 3753 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3754 Values[i - LinearIndex] = 3755 OutOfUndef ? 3756 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3757 SDValue(Agg.getNode(), Agg.getResNo() + i); 3758 3759 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3760 DAG.getVTList(ValValueVTs), Values)); 3761 } 3762 3763 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3764 Value *Op0 = I.getOperand(0); 3765 // Note that the pointer operand may be a vector of pointers. Take the scalar 3766 // element which holds a pointer. 3767 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3768 SDValue N = getValue(Op0); 3769 SDLoc dl = getCurSDLoc(); 3770 auto &TLI = DAG.getTargetLoweringInfo(); 3771 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3772 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3773 3774 // Normalize Vector GEP - all scalar operands should be converted to the 3775 // splat vector. 3776 bool IsVectorGEP = I.getType()->isVectorTy(); 3777 ElementCount VectorElementCount = 3778 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3779 : ElementCount(0, false); 3780 3781 if (IsVectorGEP && !N.getValueType().isVector()) { 3782 LLVMContext &Context = *DAG.getContext(); 3783 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3784 if (VectorElementCount.Scalable) 3785 N = DAG.getSplatVector(VT, dl, N); 3786 else 3787 N = DAG.getSplatBuildVector(VT, dl, N); 3788 } 3789 3790 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3791 GTI != E; ++GTI) { 3792 const Value *Idx = GTI.getOperand(); 3793 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3794 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3795 if (Field) { 3796 // N = N + Offset 3797 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3798 3799 // In an inbounds GEP with an offset that is nonnegative even when 3800 // interpreted as signed, assume there is no unsigned overflow. 3801 SDNodeFlags Flags; 3802 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3803 Flags.setNoUnsignedWrap(true); 3804 3805 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3806 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3807 } 3808 } else { 3809 // IdxSize is the width of the arithmetic according to IR semantics. 3810 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3811 // (and fix up the result later). 3812 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3813 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3814 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3815 // We intentionally mask away the high bits here; ElementSize may not 3816 // fit in IdxTy. 3817 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3818 bool ElementScalable = ElementSize.isScalable(); 3819 3820 // If this is a scalar constant or a splat vector of constants, 3821 // handle it quickly. 3822 const auto *C = dyn_cast<Constant>(Idx); 3823 if (C && isa<VectorType>(C->getType())) 3824 C = C->getSplatValue(); 3825 3826 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3827 if (CI && CI->isZero()) 3828 continue; 3829 if (CI && !ElementScalable) { 3830 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3831 LLVMContext &Context = *DAG.getContext(); 3832 SDValue OffsVal; 3833 if (IsVectorGEP) 3834 OffsVal = DAG.getConstant( 3835 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3836 else 3837 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3838 3839 // In an inbounds GEP with an offset that is nonnegative even when 3840 // interpreted as signed, assume there is no unsigned overflow. 3841 SDNodeFlags Flags; 3842 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3843 Flags.setNoUnsignedWrap(true); 3844 3845 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3846 3847 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3848 continue; 3849 } 3850 3851 // N = N + Idx * ElementMul; 3852 SDValue IdxN = getValue(Idx); 3853 3854 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3855 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3856 VectorElementCount); 3857 if (VectorElementCount.Scalable) 3858 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3859 else 3860 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3861 } 3862 3863 // If the index is smaller or larger than intptr_t, truncate or extend 3864 // it. 3865 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3866 3867 if (ElementScalable) { 3868 EVT VScaleTy = N.getValueType().getScalarType(); 3869 SDValue VScale = DAG.getNode( 3870 ISD::VSCALE, dl, VScaleTy, 3871 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3872 if (IsVectorGEP) 3873 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3874 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3875 } else { 3876 // If this is a multiply by a power of two, turn it into a shl 3877 // immediately. This is a very common case. 3878 if (ElementMul != 1) { 3879 if (ElementMul.isPowerOf2()) { 3880 unsigned Amt = ElementMul.logBase2(); 3881 IdxN = DAG.getNode(ISD::SHL, dl, 3882 N.getValueType(), IdxN, 3883 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3884 } else { 3885 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3886 IdxN.getValueType()); 3887 IdxN = DAG.getNode(ISD::MUL, dl, 3888 N.getValueType(), IdxN, Scale); 3889 } 3890 } 3891 } 3892 3893 N = DAG.getNode(ISD::ADD, dl, 3894 N.getValueType(), N, IdxN); 3895 } 3896 } 3897 3898 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3899 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3900 3901 setValue(&I, N); 3902 } 3903 3904 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3905 // If this is a fixed sized alloca in the entry block of the function, 3906 // allocate it statically on the stack. 3907 if (FuncInfo.StaticAllocaMap.count(&I)) 3908 return; // getValue will auto-populate this. 3909 3910 SDLoc dl = getCurSDLoc(); 3911 Type *Ty = I.getAllocatedType(); 3912 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3913 auto &DL = DAG.getDataLayout(); 3914 uint64_t TySize = DL.getTypeAllocSize(Ty); 3915 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3916 3917 SDValue AllocSize = getValue(I.getArraySize()); 3918 3919 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3920 if (AllocSize.getValueType() != IntPtr) 3921 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3922 3923 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3924 AllocSize, 3925 DAG.getConstant(TySize, dl, IntPtr)); 3926 3927 // Handle alignment. If the requested alignment is less than or equal to 3928 // the stack alignment, ignore it. If the size is greater than or equal to 3929 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3930 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3931 if (*Alignment <= StackAlign) 3932 Alignment = None; 3933 3934 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3935 // Round the size of the allocation up to the stack alignment size 3936 // by add SA-1 to the size. This doesn't overflow because we're computing 3937 // an address inside an alloca. 3938 SDNodeFlags Flags; 3939 Flags.setNoUnsignedWrap(true); 3940 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3941 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3942 3943 // Mask out the low bits for alignment purposes. 3944 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3945 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3946 3947 SDValue Ops[] = { 3948 getRoot(), AllocSize, 3949 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3950 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3951 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3952 setValue(&I, DSA); 3953 DAG.setRoot(DSA.getValue(1)); 3954 3955 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3956 } 3957 3958 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3959 if (I.isAtomic()) 3960 return visitAtomicLoad(I); 3961 3962 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3963 const Value *SV = I.getOperand(0); 3964 if (TLI.supportSwiftError()) { 3965 // Swifterror values can come from either a function parameter with 3966 // swifterror attribute or an alloca with swifterror attribute. 3967 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3968 if (Arg->hasSwiftErrorAttr()) 3969 return visitLoadFromSwiftError(I); 3970 } 3971 3972 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3973 if (Alloca->isSwiftError()) 3974 return visitLoadFromSwiftError(I); 3975 } 3976 } 3977 3978 SDValue Ptr = getValue(SV); 3979 3980 Type *Ty = I.getType(); 3981 Align Alignment = I.getAlign(); 3982 3983 AAMDNodes AAInfo; 3984 I.getAAMetadata(AAInfo); 3985 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3986 3987 SmallVector<EVT, 4> ValueVTs, MemVTs; 3988 SmallVector<uint64_t, 4> Offsets; 3989 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3990 unsigned NumValues = ValueVTs.size(); 3991 if (NumValues == 0) 3992 return; 3993 3994 bool isVolatile = I.isVolatile(); 3995 3996 SDValue Root; 3997 bool ConstantMemory = false; 3998 if (isVolatile) 3999 // Serialize volatile loads with other side effects. 4000 Root = getRoot(); 4001 else if (NumValues > MaxParallelChains) 4002 Root = getMemoryRoot(); 4003 else if (AA && 4004 AA->pointsToConstantMemory(MemoryLocation( 4005 SV, 4006 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4007 AAInfo))) { 4008 // Do not serialize (non-volatile) loads of constant memory with anything. 4009 Root = DAG.getEntryNode(); 4010 ConstantMemory = true; 4011 } else { 4012 // Do not serialize non-volatile loads against each other. 4013 Root = DAG.getRoot(); 4014 } 4015 4016 SDLoc dl = getCurSDLoc(); 4017 4018 if (isVolatile) 4019 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4020 4021 // An aggregate load cannot wrap around the address space, so offsets to its 4022 // parts don't wrap either. 4023 SDNodeFlags Flags; 4024 Flags.setNoUnsignedWrap(true); 4025 4026 SmallVector<SDValue, 4> Values(NumValues); 4027 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4028 EVT PtrVT = Ptr.getValueType(); 4029 4030 MachineMemOperand::Flags MMOFlags 4031 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4032 4033 unsigned ChainI = 0; 4034 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4035 // Serializing loads here may result in excessive register pressure, and 4036 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4037 // could recover a bit by hoisting nodes upward in the chain by recognizing 4038 // they are side-effect free or do not alias. The optimizer should really 4039 // avoid this case by converting large object/array copies to llvm.memcpy 4040 // (MaxParallelChains should always remain as failsafe). 4041 if (ChainI == MaxParallelChains) { 4042 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4043 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4044 makeArrayRef(Chains.data(), ChainI)); 4045 Root = Chain; 4046 ChainI = 0; 4047 } 4048 SDValue A = DAG.getNode(ISD::ADD, dl, 4049 PtrVT, Ptr, 4050 DAG.getConstant(Offsets[i], dl, PtrVT), 4051 Flags); 4052 4053 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4054 MachinePointerInfo(SV, Offsets[i]), Alignment, 4055 MMOFlags, AAInfo, Ranges); 4056 Chains[ChainI] = L.getValue(1); 4057 4058 if (MemVTs[i] != ValueVTs[i]) 4059 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4060 4061 Values[i] = L; 4062 } 4063 4064 if (!ConstantMemory) { 4065 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4066 makeArrayRef(Chains.data(), ChainI)); 4067 if (isVolatile) 4068 DAG.setRoot(Chain); 4069 else 4070 PendingLoads.push_back(Chain); 4071 } 4072 4073 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4074 DAG.getVTList(ValueVTs), Values)); 4075 } 4076 4077 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4078 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4079 "call visitStoreToSwiftError when backend supports swifterror"); 4080 4081 SmallVector<EVT, 4> ValueVTs; 4082 SmallVector<uint64_t, 4> Offsets; 4083 const Value *SrcV = I.getOperand(0); 4084 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4085 SrcV->getType(), ValueVTs, &Offsets); 4086 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4087 "expect a single EVT for swifterror"); 4088 4089 SDValue Src = getValue(SrcV); 4090 // Create a virtual register, then update the virtual register. 4091 Register VReg = 4092 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4093 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4094 // Chain can be getRoot or getControlRoot. 4095 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4096 SDValue(Src.getNode(), Src.getResNo())); 4097 DAG.setRoot(CopyNode); 4098 } 4099 4100 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4101 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4102 "call visitLoadFromSwiftError when backend supports swifterror"); 4103 4104 assert(!I.isVolatile() && 4105 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4106 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4107 "Support volatile, non temporal, invariant for load_from_swift_error"); 4108 4109 const Value *SV = I.getOperand(0); 4110 Type *Ty = I.getType(); 4111 AAMDNodes AAInfo; 4112 I.getAAMetadata(AAInfo); 4113 assert( 4114 (!AA || 4115 !AA->pointsToConstantMemory(MemoryLocation( 4116 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4117 AAInfo))) && 4118 "load_from_swift_error should not be constant memory"); 4119 4120 SmallVector<EVT, 4> ValueVTs; 4121 SmallVector<uint64_t, 4> Offsets; 4122 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4123 ValueVTs, &Offsets); 4124 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4125 "expect a single EVT for swifterror"); 4126 4127 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4128 SDValue L = DAG.getCopyFromReg( 4129 getRoot(), getCurSDLoc(), 4130 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4131 4132 setValue(&I, L); 4133 } 4134 4135 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4136 if (I.isAtomic()) 4137 return visitAtomicStore(I); 4138 4139 const Value *SrcV = I.getOperand(0); 4140 const Value *PtrV = I.getOperand(1); 4141 4142 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4143 if (TLI.supportSwiftError()) { 4144 // Swifterror values can come from either a function parameter with 4145 // swifterror attribute or an alloca with swifterror attribute. 4146 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4147 if (Arg->hasSwiftErrorAttr()) 4148 return visitStoreToSwiftError(I); 4149 } 4150 4151 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4152 if (Alloca->isSwiftError()) 4153 return visitStoreToSwiftError(I); 4154 } 4155 } 4156 4157 SmallVector<EVT, 4> ValueVTs, MemVTs; 4158 SmallVector<uint64_t, 4> Offsets; 4159 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4160 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4161 unsigned NumValues = ValueVTs.size(); 4162 if (NumValues == 0) 4163 return; 4164 4165 // Get the lowered operands. Note that we do this after 4166 // checking if NumResults is zero, because with zero results 4167 // the operands won't have values in the map. 4168 SDValue Src = getValue(SrcV); 4169 SDValue Ptr = getValue(PtrV); 4170 4171 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4172 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4173 SDLoc dl = getCurSDLoc(); 4174 Align Alignment = I.getAlign(); 4175 AAMDNodes AAInfo; 4176 I.getAAMetadata(AAInfo); 4177 4178 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4179 4180 // An aggregate load cannot wrap around the address space, so offsets to its 4181 // parts don't wrap either. 4182 SDNodeFlags Flags; 4183 Flags.setNoUnsignedWrap(true); 4184 4185 unsigned ChainI = 0; 4186 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4187 // See visitLoad comments. 4188 if (ChainI == MaxParallelChains) { 4189 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4190 makeArrayRef(Chains.data(), ChainI)); 4191 Root = Chain; 4192 ChainI = 0; 4193 } 4194 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4195 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4196 if (MemVTs[i] != ValueVTs[i]) 4197 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4198 SDValue St = 4199 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4200 Alignment, MMOFlags, AAInfo); 4201 Chains[ChainI] = St; 4202 } 4203 4204 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4205 makeArrayRef(Chains.data(), ChainI)); 4206 DAG.setRoot(StoreNode); 4207 } 4208 4209 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4210 bool IsCompressing) { 4211 SDLoc sdl = getCurSDLoc(); 4212 4213 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4214 MaybeAlign &Alignment) { 4215 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4216 Src0 = I.getArgOperand(0); 4217 Ptr = I.getArgOperand(1); 4218 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4219 Mask = I.getArgOperand(3); 4220 }; 4221 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4222 MaybeAlign &Alignment) { 4223 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4224 Src0 = I.getArgOperand(0); 4225 Ptr = I.getArgOperand(1); 4226 Mask = I.getArgOperand(2); 4227 Alignment = None; 4228 }; 4229 4230 Value *PtrOperand, *MaskOperand, *Src0Operand; 4231 MaybeAlign Alignment; 4232 if (IsCompressing) 4233 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4234 else 4235 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4236 4237 SDValue Ptr = getValue(PtrOperand); 4238 SDValue Src0 = getValue(Src0Operand); 4239 SDValue Mask = getValue(MaskOperand); 4240 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4241 4242 EVT VT = Src0.getValueType(); 4243 if (!Alignment) 4244 Alignment = DAG.getEVTAlign(VT); 4245 4246 AAMDNodes AAInfo; 4247 I.getAAMetadata(AAInfo); 4248 4249 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4250 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4251 // TODO: Make MachineMemOperands aware of scalable 4252 // vectors. 4253 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4254 SDValue StoreNode = 4255 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4256 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4257 DAG.setRoot(StoreNode); 4258 setValue(&I, StoreNode); 4259 } 4260 4261 // Get a uniform base for the Gather/Scatter intrinsic. 4262 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4263 // We try to represent it as a base pointer + vector of indices. 4264 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4265 // The first operand of the GEP may be a single pointer or a vector of pointers 4266 // Example: 4267 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4268 // or 4269 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4270 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4271 // 4272 // When the first GEP operand is a single pointer - it is the uniform base we 4273 // are looking for. If first operand of the GEP is a splat vector - we 4274 // extract the splat value and use it as a uniform base. 4275 // In all other cases the function returns 'false'. 4276 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4277 ISD::MemIndexType &IndexType, SDValue &Scale, 4278 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4279 SelectionDAG& DAG = SDB->DAG; 4280 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4281 const DataLayout &DL = DAG.getDataLayout(); 4282 4283 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4284 4285 // Handle splat constant pointer. 4286 if (auto *C = dyn_cast<Constant>(Ptr)) { 4287 C = C->getSplatValue(); 4288 if (!C) 4289 return false; 4290 4291 Base = SDB->getValue(C); 4292 4293 unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements(); 4294 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4295 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4296 IndexType = ISD::SIGNED_SCALED; 4297 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4298 return true; 4299 } 4300 4301 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4302 if (!GEP || GEP->getParent() != CurBB) 4303 return false; 4304 4305 if (GEP->getNumOperands() != 2) 4306 return false; 4307 4308 const Value *BasePtr = GEP->getPointerOperand(); 4309 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4310 4311 // Make sure the base is scalar and the index is a vector. 4312 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4313 return false; 4314 4315 Base = SDB->getValue(BasePtr); 4316 Index = SDB->getValue(IndexVal); 4317 IndexType = ISD::SIGNED_SCALED; 4318 Scale = DAG.getTargetConstant( 4319 DL.getTypeAllocSize(GEP->getResultElementType()), 4320 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4321 return true; 4322 } 4323 4324 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4325 SDLoc sdl = getCurSDLoc(); 4326 4327 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4328 const Value *Ptr = I.getArgOperand(1); 4329 SDValue Src0 = getValue(I.getArgOperand(0)); 4330 SDValue Mask = getValue(I.getArgOperand(3)); 4331 EVT VT = Src0.getValueType(); 4332 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4333 ->getMaybeAlignValue() 4334 .getValueOr(DAG.getEVTAlign(VT)); 4335 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4336 4337 AAMDNodes AAInfo; 4338 I.getAAMetadata(AAInfo); 4339 4340 SDValue Base; 4341 SDValue Index; 4342 ISD::MemIndexType IndexType; 4343 SDValue Scale; 4344 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4345 I.getParent()); 4346 4347 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4348 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4349 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4350 // TODO: Make MachineMemOperands aware of scalable 4351 // vectors. 4352 MemoryLocation::UnknownSize, Alignment, AAInfo); 4353 if (!UniformBase) { 4354 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4355 Index = getValue(Ptr); 4356 IndexType = ISD::SIGNED_SCALED; 4357 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4358 } 4359 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4360 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4361 Ops, MMO, IndexType); 4362 DAG.setRoot(Scatter); 4363 setValue(&I, Scatter); 4364 } 4365 4366 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4367 SDLoc sdl = getCurSDLoc(); 4368 4369 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4370 MaybeAlign &Alignment) { 4371 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4372 Ptr = I.getArgOperand(0); 4373 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 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 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4443 ->getMaybeAlignValue() 4444 .getValueOr(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 7849 } // end anonymous namespace 7850 7851 /// Make sure that the output operand \p OpInfo and its corresponding input 7852 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7853 /// out). 7854 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7855 SDISelAsmOperandInfo &MatchingOpInfo, 7856 SelectionDAG &DAG) { 7857 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7858 return; 7859 7860 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7861 const auto &TLI = DAG.getTargetLoweringInfo(); 7862 7863 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7864 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7865 OpInfo.ConstraintVT); 7866 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7867 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7868 MatchingOpInfo.ConstraintVT); 7869 if ((OpInfo.ConstraintVT.isInteger() != 7870 MatchingOpInfo.ConstraintVT.isInteger()) || 7871 (MatchRC.second != InputRC.second)) { 7872 // FIXME: error out in a more elegant fashion 7873 report_fatal_error("Unsupported asm: input constraint" 7874 " with a matching output constraint of" 7875 " incompatible type!"); 7876 } 7877 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7878 } 7879 7880 /// Get a direct memory input to behave well as an indirect operand. 7881 /// This may introduce stores, hence the need for a \p Chain. 7882 /// \return The (possibly updated) chain. 7883 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7884 SDISelAsmOperandInfo &OpInfo, 7885 SelectionDAG &DAG) { 7886 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7887 7888 // If we don't have an indirect input, put it in the constpool if we can, 7889 // otherwise spill it to a stack slot. 7890 // TODO: This isn't quite right. We need to handle these according to 7891 // the addressing mode that the constraint wants. Also, this may take 7892 // an additional register for the computation and we don't want that 7893 // either. 7894 7895 // If the operand is a float, integer, or vector constant, spill to a 7896 // constant pool entry to get its address. 7897 const Value *OpVal = OpInfo.CallOperandVal; 7898 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7899 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7900 OpInfo.CallOperand = DAG.getConstantPool( 7901 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7902 return Chain; 7903 } 7904 7905 // Otherwise, create a stack slot and emit a store to it before the asm. 7906 Type *Ty = OpVal->getType(); 7907 auto &DL = DAG.getDataLayout(); 7908 uint64_t TySize = DL.getTypeAllocSize(Ty); 7909 MachineFunction &MF = DAG.getMachineFunction(); 7910 int SSFI = MF.getFrameInfo().CreateStackObject( 7911 TySize, DL.getPrefTypeAlign(Ty), false); 7912 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7913 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7914 MachinePointerInfo::getFixedStack(MF, SSFI), 7915 TLI.getMemValueType(DL, Ty)); 7916 OpInfo.CallOperand = StackSlot; 7917 7918 return Chain; 7919 } 7920 7921 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7922 /// specified operand. We prefer to assign virtual registers, to allow the 7923 /// register allocator to handle the assignment process. However, if the asm 7924 /// uses features that we can't model on machineinstrs, we have SDISel do the 7925 /// allocation. This produces generally horrible, but correct, code. 7926 /// 7927 /// OpInfo describes the operand 7928 /// RefOpInfo describes the matching operand if any, the operand otherwise 7929 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7930 SDISelAsmOperandInfo &OpInfo, 7931 SDISelAsmOperandInfo &RefOpInfo) { 7932 LLVMContext &Context = *DAG.getContext(); 7933 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7934 7935 MachineFunction &MF = DAG.getMachineFunction(); 7936 SmallVector<unsigned, 4> Regs; 7937 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7938 7939 // No work to do for memory operations. 7940 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7941 return; 7942 7943 // If this is a constraint for a single physreg, or a constraint for a 7944 // register class, find it. 7945 unsigned AssignedReg; 7946 const TargetRegisterClass *RC; 7947 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7948 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7949 // RC is unset only on failure. Return immediately. 7950 if (!RC) 7951 return; 7952 7953 // Get the actual register value type. This is important, because the user 7954 // may have asked for (e.g.) the AX register in i32 type. We need to 7955 // remember that AX is actually i16 to get the right extension. 7956 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7957 7958 if (OpInfo.ConstraintVT != MVT::Other) { 7959 // If this is an FP operand in an integer register (or visa versa), or more 7960 // generally if the operand value disagrees with the register class we plan 7961 // to stick it in, fix the operand type. 7962 // 7963 // If this is an input value, the bitcast to the new type is done now. 7964 // Bitcast for output value is done at the end of visitInlineAsm(). 7965 if ((OpInfo.Type == InlineAsm::isOutput || 7966 OpInfo.Type == InlineAsm::isInput) && 7967 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7968 // Try to convert to the first EVT that the reg class contains. If the 7969 // types are identical size, use a bitcast to convert (e.g. two differing 7970 // vector types). Note: output bitcast is done at the end of 7971 // visitInlineAsm(). 7972 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7973 // Exclude indirect inputs while they are unsupported because the code 7974 // to perform the load is missing and thus OpInfo.CallOperand still 7975 // refers to the input address rather than the pointed-to value. 7976 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7977 OpInfo.CallOperand = 7978 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7979 OpInfo.ConstraintVT = RegVT; 7980 // If the operand is an FP value and we want it in integer registers, 7981 // use the corresponding integer type. This turns an f64 value into 7982 // i64, which can be passed with two i32 values on a 32-bit machine. 7983 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7984 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7985 if (OpInfo.Type == InlineAsm::isInput) 7986 OpInfo.CallOperand = 7987 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7988 OpInfo.ConstraintVT = VT; 7989 } 7990 } 7991 } 7992 7993 // No need to allocate a matching input constraint since the constraint it's 7994 // matching to has already been allocated. 7995 if (OpInfo.isMatchingInputConstraint()) 7996 return; 7997 7998 EVT ValueVT = OpInfo.ConstraintVT; 7999 if (OpInfo.ConstraintVT == MVT::Other) 8000 ValueVT = RegVT; 8001 8002 // Initialize NumRegs. 8003 unsigned NumRegs = 1; 8004 if (OpInfo.ConstraintVT != MVT::Other) 8005 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8006 8007 // If this is a constraint for a specific physical register, like {r17}, 8008 // assign it now. 8009 8010 // If this associated to a specific register, initialize iterator to correct 8011 // place. If virtual, make sure we have enough registers 8012 8013 // Initialize iterator if necessary 8014 TargetRegisterClass::iterator I = RC->begin(); 8015 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8016 8017 // Do not check for single registers. 8018 if (AssignedReg) { 8019 for (; *I != AssignedReg; ++I) 8020 assert(I != RC->end() && "AssignedReg should be member of RC"); 8021 } 8022 8023 for (; NumRegs; --NumRegs, ++I) { 8024 assert(I != RC->end() && "Ran out of registers to allocate!"); 8025 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8026 Regs.push_back(R); 8027 } 8028 8029 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8030 } 8031 8032 static unsigned 8033 findMatchingInlineAsmOperand(unsigned OperandNo, 8034 const std::vector<SDValue> &AsmNodeOperands) { 8035 // Scan until we find the definition we already emitted of this operand. 8036 unsigned CurOp = InlineAsm::Op_FirstOperand; 8037 for (; OperandNo; --OperandNo) { 8038 // Advance to the next operand. 8039 unsigned OpFlag = 8040 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8041 assert((InlineAsm::isRegDefKind(OpFlag) || 8042 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8043 InlineAsm::isMemKind(OpFlag)) && 8044 "Skipped past definitions?"); 8045 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8046 } 8047 return CurOp; 8048 } 8049 8050 namespace { 8051 8052 class ExtraFlags { 8053 unsigned Flags = 0; 8054 8055 public: 8056 explicit ExtraFlags(const CallBase &Call) { 8057 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8058 if (IA->hasSideEffects()) 8059 Flags |= InlineAsm::Extra_HasSideEffects; 8060 if (IA->isAlignStack()) 8061 Flags |= InlineAsm::Extra_IsAlignStack; 8062 if (Call.isConvergent()) 8063 Flags |= InlineAsm::Extra_IsConvergent; 8064 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8065 } 8066 8067 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8068 // Ideally, we would only check against memory constraints. However, the 8069 // meaning of an Other constraint can be target-specific and we can't easily 8070 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8071 // for Other constraints as well. 8072 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8073 OpInfo.ConstraintType == TargetLowering::C_Other) { 8074 if (OpInfo.Type == InlineAsm::isInput) 8075 Flags |= InlineAsm::Extra_MayLoad; 8076 else if (OpInfo.Type == InlineAsm::isOutput) 8077 Flags |= InlineAsm::Extra_MayStore; 8078 else if (OpInfo.Type == InlineAsm::isClobber) 8079 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8080 } 8081 } 8082 8083 unsigned get() const { return Flags; } 8084 }; 8085 8086 } // end anonymous namespace 8087 8088 /// visitInlineAsm - Handle a call to an InlineAsm object. 8089 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8090 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8091 8092 /// ConstraintOperands - Information about all of the constraints. 8093 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8094 8095 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8096 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8097 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8098 8099 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8100 // AsmDialect, MayLoad, MayStore). 8101 bool HasSideEffect = IA->hasSideEffects(); 8102 ExtraFlags ExtraInfo(Call); 8103 8104 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8105 unsigned ResNo = 0; // ResNo - The result number of the next output. 8106 unsigned NumMatchingOps = 0; 8107 for (auto &T : TargetConstraints) { 8108 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8109 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8110 8111 // Compute the value type for each operand. 8112 if (OpInfo.Type == InlineAsm::isInput || 8113 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8114 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8115 8116 // Process the call argument. BasicBlocks are labels, currently appearing 8117 // only in asm's. 8118 if (isa<CallBrInst>(Call) && 8119 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8120 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8121 NumMatchingOps) && 8122 (NumMatchingOps == 0 || 8123 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8124 NumMatchingOps))) { 8125 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8126 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8127 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8128 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8129 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8130 } else { 8131 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8132 } 8133 8134 OpInfo.ConstraintVT = 8135 OpInfo 8136 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8137 .getSimpleVT(); 8138 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8139 // The return value of the call is this value. As such, there is no 8140 // corresponding argument. 8141 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8142 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8143 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8144 DAG.getDataLayout(), STy->getElementType(ResNo)); 8145 } else { 8146 assert(ResNo == 0 && "Asm only has one result!"); 8147 OpInfo.ConstraintVT = 8148 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8149 } 8150 ++ResNo; 8151 } else { 8152 OpInfo.ConstraintVT = MVT::Other; 8153 } 8154 8155 if (OpInfo.hasMatchingInput()) 8156 ++NumMatchingOps; 8157 8158 if (!HasSideEffect) 8159 HasSideEffect = OpInfo.hasMemory(TLI); 8160 8161 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8162 // FIXME: Could we compute this on OpInfo rather than T? 8163 8164 // Compute the constraint code and ConstraintType to use. 8165 TLI.ComputeConstraintToUse(T, SDValue()); 8166 8167 if (T.ConstraintType == TargetLowering::C_Immediate && 8168 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8169 // We've delayed emitting a diagnostic like the "n" constraint because 8170 // inlining could cause an integer showing up. 8171 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8172 "' expects an integer constant " 8173 "expression"); 8174 8175 ExtraInfo.update(T); 8176 } 8177 8178 8179 // We won't need to flush pending loads if this asm doesn't touch 8180 // memory and is nonvolatile. 8181 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8182 8183 bool IsCallBr = isa<CallBrInst>(Call); 8184 if (IsCallBr) { 8185 // If this is a callbr we need to flush pending exports since inlineasm_br 8186 // is a terminator. We need to do this before nodes are glued to 8187 // the inlineasm_br node. 8188 Chain = getControlRoot(); 8189 } 8190 8191 // Second pass over the constraints: compute which constraint option to use. 8192 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8193 // If this is an output operand with a matching input operand, look up the 8194 // matching input. If their types mismatch, e.g. one is an integer, the 8195 // other is floating point, or their sizes are different, flag it as an 8196 // error. 8197 if (OpInfo.hasMatchingInput()) { 8198 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8199 patchMatchingInput(OpInfo, Input, DAG); 8200 } 8201 8202 // Compute the constraint code and ConstraintType to use. 8203 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8204 8205 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8206 OpInfo.Type == InlineAsm::isClobber) 8207 continue; 8208 8209 // If this is a memory input, and if the operand is not indirect, do what we 8210 // need to provide an address for the memory input. 8211 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8212 !OpInfo.isIndirect) { 8213 assert((OpInfo.isMultipleAlternative || 8214 (OpInfo.Type == InlineAsm::isInput)) && 8215 "Can only indirectify direct input operands!"); 8216 8217 // Memory operands really want the address of the value. 8218 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8219 8220 // There is no longer a Value* corresponding to this operand. 8221 OpInfo.CallOperandVal = nullptr; 8222 8223 // It is now an indirect operand. 8224 OpInfo.isIndirect = true; 8225 } 8226 8227 } 8228 8229 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8230 std::vector<SDValue> AsmNodeOperands; 8231 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8232 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8233 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8234 8235 // If we have a !srcloc metadata node associated with it, we want to attach 8236 // this to the ultimately generated inline asm machineinstr. To do this, we 8237 // pass in the third operand as this (potentially null) inline asm MDNode. 8238 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8239 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8240 8241 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8242 // bits as operand 3. 8243 AsmNodeOperands.push_back(DAG.getTargetConstant( 8244 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8245 8246 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8247 // this, assign virtual and physical registers for inputs and otput. 8248 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8249 // Assign Registers. 8250 SDISelAsmOperandInfo &RefOpInfo = 8251 OpInfo.isMatchingInputConstraint() 8252 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8253 : OpInfo; 8254 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8255 8256 auto DetectWriteToReservedRegister = [&]() { 8257 const MachineFunction &MF = DAG.getMachineFunction(); 8258 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8259 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8260 if (Register::isPhysicalRegister(Reg) && 8261 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8262 const char *RegName = TRI.getName(Reg); 8263 emitInlineAsmError(Call, "write to reserved register '" + 8264 Twine(RegName) + "'"); 8265 return true; 8266 } 8267 } 8268 return false; 8269 }; 8270 8271 switch (OpInfo.Type) { 8272 case InlineAsm::isOutput: 8273 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8274 unsigned ConstraintID = 8275 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8276 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8277 "Failed to convert memory constraint code to constraint id."); 8278 8279 // Add information to the INLINEASM node to know about this output. 8280 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8281 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8282 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8283 MVT::i32)); 8284 AsmNodeOperands.push_back(OpInfo.CallOperand); 8285 } else { 8286 // Otherwise, this outputs to a register (directly for C_Register / 8287 // C_RegisterClass, and a target-defined fashion for 8288 // C_Immediate/C_Other). Find a register that we can use. 8289 if (OpInfo.AssignedRegs.Regs.empty()) { 8290 emitInlineAsmError( 8291 Call, "couldn't allocate output register for constraint '" + 8292 Twine(OpInfo.ConstraintCode) + "'"); 8293 return; 8294 } 8295 8296 if (DetectWriteToReservedRegister()) 8297 return; 8298 8299 // Add information to the INLINEASM node to know that this register is 8300 // set. 8301 OpInfo.AssignedRegs.AddInlineAsmOperands( 8302 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8303 : InlineAsm::Kind_RegDef, 8304 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8305 } 8306 break; 8307 8308 case InlineAsm::isInput: { 8309 SDValue InOperandVal = OpInfo.CallOperand; 8310 8311 if (OpInfo.isMatchingInputConstraint()) { 8312 // If this is required to match an output register we have already set, 8313 // just use its register. 8314 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8315 AsmNodeOperands); 8316 unsigned OpFlag = 8317 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8318 if (InlineAsm::isRegDefKind(OpFlag) || 8319 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8320 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8321 if (OpInfo.isIndirect) { 8322 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8323 emitInlineAsmError(Call, "inline asm not supported yet: " 8324 "don't know how to handle tied " 8325 "indirect register inputs"); 8326 return; 8327 } 8328 8329 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8330 SmallVector<unsigned, 4> Regs; 8331 8332 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8333 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8334 MachineRegisterInfo &RegInfo = 8335 DAG.getMachineFunction().getRegInfo(); 8336 for (unsigned i = 0; i != NumRegs; ++i) 8337 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8338 } else { 8339 emitInlineAsmError(Call, 8340 "inline asm error: This value type register " 8341 "class is not natively supported!"); 8342 return; 8343 } 8344 8345 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8346 8347 SDLoc dl = getCurSDLoc(); 8348 // Use the produced MatchedRegs object to 8349 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8350 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8351 true, OpInfo.getMatchedOperand(), dl, 8352 DAG, AsmNodeOperands); 8353 break; 8354 } 8355 8356 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8357 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8358 "Unexpected number of operands"); 8359 // Add information to the INLINEASM node to know about this input. 8360 // See InlineAsm.h isUseOperandTiedToDef. 8361 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8362 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8363 OpInfo.getMatchedOperand()); 8364 AsmNodeOperands.push_back(DAG.getTargetConstant( 8365 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8366 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8367 break; 8368 } 8369 8370 // Treat indirect 'X' constraint as memory. 8371 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8372 OpInfo.isIndirect) 8373 OpInfo.ConstraintType = TargetLowering::C_Memory; 8374 8375 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8376 OpInfo.ConstraintType == TargetLowering::C_Other) { 8377 std::vector<SDValue> Ops; 8378 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8379 Ops, DAG); 8380 if (Ops.empty()) { 8381 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8382 if (isa<ConstantSDNode>(InOperandVal)) { 8383 emitInlineAsmError(Call, "value out of range for constraint '" + 8384 Twine(OpInfo.ConstraintCode) + "'"); 8385 return; 8386 } 8387 8388 emitInlineAsmError(Call, 8389 "invalid operand for inline asm constraint '" + 8390 Twine(OpInfo.ConstraintCode) + "'"); 8391 return; 8392 } 8393 8394 // Add information to the INLINEASM node to know about this input. 8395 unsigned ResOpType = 8396 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8397 AsmNodeOperands.push_back(DAG.getTargetConstant( 8398 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8399 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8400 break; 8401 } 8402 8403 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8404 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8405 assert(InOperandVal.getValueType() == 8406 TLI.getPointerTy(DAG.getDataLayout()) && 8407 "Memory operands expect pointer values"); 8408 8409 unsigned ConstraintID = 8410 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8411 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8412 "Failed to convert memory constraint code to constraint id."); 8413 8414 // Add information to the INLINEASM node to know about this input. 8415 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8416 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8417 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8418 getCurSDLoc(), 8419 MVT::i32)); 8420 AsmNodeOperands.push_back(InOperandVal); 8421 break; 8422 } 8423 8424 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8425 OpInfo.ConstraintType == TargetLowering::C_Register) && 8426 "Unknown constraint type!"); 8427 8428 // TODO: Support this. 8429 if (OpInfo.isIndirect) { 8430 emitInlineAsmError( 8431 Call, "Don't know how to handle indirect register inputs yet " 8432 "for constraint '" + 8433 Twine(OpInfo.ConstraintCode) + "'"); 8434 return; 8435 } 8436 8437 // Copy the input into the appropriate registers. 8438 if (OpInfo.AssignedRegs.Regs.empty()) { 8439 emitInlineAsmError(Call, 8440 "couldn't allocate input reg for constraint '" + 8441 Twine(OpInfo.ConstraintCode) + "'"); 8442 return; 8443 } 8444 8445 if (DetectWriteToReservedRegister()) 8446 return; 8447 8448 SDLoc dl = getCurSDLoc(); 8449 8450 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8451 &Call); 8452 8453 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8454 dl, DAG, AsmNodeOperands); 8455 break; 8456 } 8457 case InlineAsm::isClobber: 8458 // Add the clobbered value to the operand list, so that the register 8459 // allocator is aware that the physreg got clobbered. 8460 if (!OpInfo.AssignedRegs.Regs.empty()) 8461 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8462 false, 0, getCurSDLoc(), DAG, 8463 AsmNodeOperands); 8464 break; 8465 } 8466 } 8467 8468 // Finish up input operands. Set the input chain and add the flag last. 8469 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8470 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8471 8472 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8473 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8474 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8475 Flag = Chain.getValue(1); 8476 8477 // Do additional work to generate outputs. 8478 8479 SmallVector<EVT, 1> ResultVTs; 8480 SmallVector<SDValue, 1> ResultValues; 8481 SmallVector<SDValue, 8> OutChains; 8482 8483 llvm::Type *CallResultType = Call.getType(); 8484 ArrayRef<Type *> ResultTypes; 8485 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8486 ResultTypes = StructResult->elements(); 8487 else if (!CallResultType->isVoidTy()) 8488 ResultTypes = makeArrayRef(CallResultType); 8489 8490 auto CurResultType = ResultTypes.begin(); 8491 auto handleRegAssign = [&](SDValue V) { 8492 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8493 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8494 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8495 ++CurResultType; 8496 // If the type of the inline asm call site return value is different but has 8497 // same size as the type of the asm output bitcast it. One example of this 8498 // is for vectors with different width / number of elements. This can 8499 // happen for register classes that can contain multiple different value 8500 // types. The preg or vreg allocated may not have the same VT as was 8501 // expected. 8502 // 8503 // This can also happen for a return value that disagrees with the register 8504 // class it is put in, eg. a double in a general-purpose register on a 8505 // 32-bit machine. 8506 if (ResultVT != V.getValueType() && 8507 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8508 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8509 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8510 V.getValueType().isInteger()) { 8511 // If a result value was tied to an input value, the computed result 8512 // may have a wider width than the expected result. Extract the 8513 // relevant portion. 8514 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8515 } 8516 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8517 ResultVTs.push_back(ResultVT); 8518 ResultValues.push_back(V); 8519 }; 8520 8521 // Deal with output operands. 8522 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8523 if (OpInfo.Type == InlineAsm::isOutput) { 8524 SDValue Val; 8525 // Skip trivial output operands. 8526 if (OpInfo.AssignedRegs.Regs.empty()) 8527 continue; 8528 8529 switch (OpInfo.ConstraintType) { 8530 case TargetLowering::C_Register: 8531 case TargetLowering::C_RegisterClass: 8532 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8533 Chain, &Flag, &Call); 8534 break; 8535 case TargetLowering::C_Immediate: 8536 case TargetLowering::C_Other: 8537 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8538 OpInfo, DAG); 8539 break; 8540 case TargetLowering::C_Memory: 8541 break; // Already handled. 8542 case TargetLowering::C_Unknown: 8543 assert(false && "Unexpected unknown constraint"); 8544 } 8545 8546 // Indirect output manifest as stores. Record output chains. 8547 if (OpInfo.isIndirect) { 8548 const Value *Ptr = OpInfo.CallOperandVal; 8549 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8550 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8551 MachinePointerInfo(Ptr)); 8552 OutChains.push_back(Store); 8553 } else { 8554 // generate CopyFromRegs to associated registers. 8555 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8556 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8557 for (const SDValue &V : Val->op_values()) 8558 handleRegAssign(V); 8559 } else 8560 handleRegAssign(Val); 8561 } 8562 } 8563 } 8564 8565 // Set results. 8566 if (!ResultValues.empty()) { 8567 assert(CurResultType == ResultTypes.end() && 8568 "Mismatch in number of ResultTypes"); 8569 assert(ResultValues.size() == ResultTypes.size() && 8570 "Mismatch in number of output operands in asm result"); 8571 8572 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8573 DAG.getVTList(ResultVTs), ResultValues); 8574 setValue(&Call, V); 8575 } 8576 8577 // Collect store chains. 8578 if (!OutChains.empty()) 8579 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8580 8581 // Only Update Root if inline assembly has a memory effect. 8582 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8583 DAG.setRoot(Chain); 8584 } 8585 8586 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8587 const Twine &Message) { 8588 LLVMContext &Ctx = *DAG.getContext(); 8589 Ctx.emitError(&Call, Message); 8590 8591 // Make sure we leave the DAG in a valid state 8592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8593 SmallVector<EVT, 1> ValueVTs; 8594 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8595 8596 if (ValueVTs.empty()) 8597 return; 8598 8599 SmallVector<SDValue, 1> Ops; 8600 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8601 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8602 8603 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8604 } 8605 8606 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8607 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8608 MVT::Other, getRoot(), 8609 getValue(I.getArgOperand(0)), 8610 DAG.getSrcValue(I.getArgOperand(0)))); 8611 } 8612 8613 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8614 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8615 const DataLayout &DL = DAG.getDataLayout(); 8616 SDValue V = DAG.getVAArg( 8617 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8618 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8619 DL.getABITypeAlign(I.getType()).value()); 8620 DAG.setRoot(V.getValue(1)); 8621 8622 if (I.getType()->isPointerTy()) 8623 V = DAG.getPtrExtOrTrunc( 8624 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8625 setValue(&I, V); 8626 } 8627 8628 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8629 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8630 MVT::Other, getRoot(), 8631 getValue(I.getArgOperand(0)), 8632 DAG.getSrcValue(I.getArgOperand(0)))); 8633 } 8634 8635 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8636 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8637 MVT::Other, getRoot(), 8638 getValue(I.getArgOperand(0)), 8639 getValue(I.getArgOperand(1)), 8640 DAG.getSrcValue(I.getArgOperand(0)), 8641 DAG.getSrcValue(I.getArgOperand(1)))); 8642 } 8643 8644 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8645 const Instruction &I, 8646 SDValue Op) { 8647 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8648 if (!Range) 8649 return Op; 8650 8651 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8652 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8653 return Op; 8654 8655 APInt Lo = CR.getUnsignedMin(); 8656 if (!Lo.isMinValue()) 8657 return Op; 8658 8659 APInt Hi = CR.getUnsignedMax(); 8660 unsigned Bits = std::max(Hi.getActiveBits(), 8661 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8662 8663 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8664 8665 SDLoc SL = getCurSDLoc(); 8666 8667 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8668 DAG.getValueType(SmallVT)); 8669 unsigned NumVals = Op.getNode()->getNumValues(); 8670 if (NumVals == 1) 8671 return ZExt; 8672 8673 SmallVector<SDValue, 4> Ops; 8674 8675 Ops.push_back(ZExt); 8676 for (unsigned I = 1; I != NumVals; ++I) 8677 Ops.push_back(Op.getValue(I)); 8678 8679 return DAG.getMergeValues(Ops, SL); 8680 } 8681 8682 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8683 /// the call being lowered. 8684 /// 8685 /// This is a helper for lowering intrinsics that follow a target calling 8686 /// convention or require stack pointer adjustment. Only a subset of the 8687 /// intrinsic's operands need to participate in the calling convention. 8688 void SelectionDAGBuilder::populateCallLoweringInfo( 8689 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8690 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8691 bool IsPatchPoint) { 8692 TargetLowering::ArgListTy Args; 8693 Args.reserve(NumArgs); 8694 8695 // Populate the argument list. 8696 // Attributes for args start at offset 1, after the return attribute. 8697 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8698 ArgI != ArgE; ++ArgI) { 8699 const Value *V = Call->getOperand(ArgI); 8700 8701 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8702 8703 TargetLowering::ArgListEntry Entry; 8704 Entry.Node = getValue(V); 8705 Entry.Ty = V->getType(); 8706 Entry.setAttributes(Call, ArgI); 8707 Args.push_back(Entry); 8708 } 8709 8710 CLI.setDebugLoc(getCurSDLoc()) 8711 .setChain(getRoot()) 8712 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8713 .setDiscardResult(Call->use_empty()) 8714 .setIsPatchPoint(IsPatchPoint) 8715 .setIsPreallocated( 8716 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8717 } 8718 8719 /// Add a stack map intrinsic call's live variable operands to a stackmap 8720 /// or patchpoint target node's operand list. 8721 /// 8722 /// Constants are converted to TargetConstants purely as an optimization to 8723 /// avoid constant materialization and register allocation. 8724 /// 8725 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8726 /// generate addess computation nodes, and so FinalizeISel can convert the 8727 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8728 /// address materialization and register allocation, but may also be required 8729 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8730 /// alloca in the entry block, then the runtime may assume that the alloca's 8731 /// StackMap location can be read immediately after compilation and that the 8732 /// location is valid at any point during execution (this is similar to the 8733 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8734 /// only available in a register, then the runtime would need to trap when 8735 /// execution reaches the StackMap in order to read the alloca's location. 8736 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8737 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8738 SelectionDAGBuilder &Builder) { 8739 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8740 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8742 Ops.push_back( 8743 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8744 Ops.push_back( 8745 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8746 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8747 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8748 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8749 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8750 } else 8751 Ops.push_back(OpVal); 8752 } 8753 } 8754 8755 /// Lower llvm.experimental.stackmap directly to its target opcode. 8756 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8757 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8758 // [live variables...]) 8759 8760 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8761 8762 SDValue Chain, InFlag, Callee, NullPtr; 8763 SmallVector<SDValue, 32> Ops; 8764 8765 SDLoc DL = getCurSDLoc(); 8766 Callee = getValue(CI.getCalledOperand()); 8767 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8768 8769 // The stackmap intrinsic only records the live variables (the arguments 8770 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8771 // intrinsic, this won't be lowered to a function call. This means we don't 8772 // have to worry about calling conventions and target specific lowering code. 8773 // Instead we perform the call lowering right here. 8774 // 8775 // chain, flag = CALLSEQ_START(chain, 0, 0) 8776 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8777 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8778 // 8779 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8780 InFlag = Chain.getValue(1); 8781 8782 // Add the <id> and <numBytes> constants. 8783 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8784 Ops.push_back(DAG.getTargetConstant( 8785 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8786 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8787 Ops.push_back(DAG.getTargetConstant( 8788 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8789 MVT::i32)); 8790 8791 // Push live variables for the stack map. 8792 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8793 8794 // We are not pushing any register mask info here on the operands list, 8795 // because the stackmap doesn't clobber anything. 8796 8797 // Push the chain and the glue flag. 8798 Ops.push_back(Chain); 8799 Ops.push_back(InFlag); 8800 8801 // Create the STACKMAP node. 8802 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8803 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8804 Chain = SDValue(SM, 0); 8805 InFlag = Chain.getValue(1); 8806 8807 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8808 8809 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8810 8811 // Set the root to the target-lowered call chain. 8812 DAG.setRoot(Chain); 8813 8814 // Inform the Frame Information that we have a stackmap in this function. 8815 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8816 } 8817 8818 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8819 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8820 const BasicBlock *EHPadBB) { 8821 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8822 // i32 <numBytes>, 8823 // i8* <target>, 8824 // i32 <numArgs>, 8825 // [Args...], 8826 // [live variables...]) 8827 8828 CallingConv::ID CC = CB.getCallingConv(); 8829 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8830 bool HasDef = !CB.getType()->isVoidTy(); 8831 SDLoc dl = getCurSDLoc(); 8832 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8833 8834 // Handle immediate and symbolic callees. 8835 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8836 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8837 /*isTarget=*/true); 8838 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8839 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8840 SDLoc(SymbolicCallee), 8841 SymbolicCallee->getValueType(0)); 8842 8843 // Get the real number of arguments participating in the call <numArgs> 8844 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8845 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8846 8847 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8848 // Intrinsics include all meta-operands up to but not including CC. 8849 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8850 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8851 "Not enough arguments provided to the patchpoint intrinsic"); 8852 8853 // For AnyRegCC the arguments are lowered later on manually. 8854 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8855 Type *ReturnTy = 8856 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8857 8858 TargetLowering::CallLoweringInfo CLI(DAG); 8859 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8860 ReturnTy, true); 8861 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8862 8863 SDNode *CallEnd = Result.second.getNode(); 8864 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8865 CallEnd = CallEnd->getOperand(0).getNode(); 8866 8867 /// Get a call instruction from the call sequence chain. 8868 /// Tail calls are not allowed. 8869 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8870 "Expected a callseq node."); 8871 SDNode *Call = CallEnd->getOperand(0).getNode(); 8872 bool HasGlue = Call->getGluedNode(); 8873 8874 // Replace the target specific call node with the patchable intrinsic. 8875 SmallVector<SDValue, 8> Ops; 8876 8877 // Add the <id> and <numBytes> constants. 8878 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8879 Ops.push_back(DAG.getTargetConstant( 8880 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8881 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8882 Ops.push_back(DAG.getTargetConstant( 8883 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8884 MVT::i32)); 8885 8886 // Add the callee. 8887 Ops.push_back(Callee); 8888 8889 // Adjust <numArgs> to account for any arguments that have been passed on the 8890 // stack instead. 8891 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8892 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8893 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8894 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8895 8896 // Add the calling convention 8897 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8898 8899 // Add the arguments we omitted previously. The register allocator should 8900 // place these in any free register. 8901 if (IsAnyRegCC) 8902 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8903 Ops.push_back(getValue(CB.getArgOperand(i))); 8904 8905 // Push the arguments from the call instruction up to the register mask. 8906 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8907 Ops.append(Call->op_begin() + 2, e); 8908 8909 // Push live variables for the stack map. 8910 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8911 8912 // Push the register mask info. 8913 if (HasGlue) 8914 Ops.push_back(*(Call->op_end()-2)); 8915 else 8916 Ops.push_back(*(Call->op_end()-1)); 8917 8918 // Push the chain (this is originally the first operand of the call, but 8919 // becomes now the last or second to last operand). 8920 Ops.push_back(*(Call->op_begin())); 8921 8922 // Push the glue flag (last operand). 8923 if (HasGlue) 8924 Ops.push_back(*(Call->op_end()-1)); 8925 8926 SDVTList NodeTys; 8927 if (IsAnyRegCC && HasDef) { 8928 // Create the return types based on the intrinsic definition 8929 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8930 SmallVector<EVT, 3> ValueVTs; 8931 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8932 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8933 8934 // There is always a chain and a glue type at the end 8935 ValueVTs.push_back(MVT::Other); 8936 ValueVTs.push_back(MVT::Glue); 8937 NodeTys = DAG.getVTList(ValueVTs); 8938 } else 8939 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8940 8941 // Replace the target specific call node with a PATCHPOINT node. 8942 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8943 dl, NodeTys, Ops); 8944 8945 // Update the NodeMap. 8946 if (HasDef) { 8947 if (IsAnyRegCC) 8948 setValue(&CB, SDValue(MN, 0)); 8949 else 8950 setValue(&CB, Result.first); 8951 } 8952 8953 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8954 // call sequence. Furthermore the location of the chain and glue can change 8955 // when the AnyReg calling convention is used and the intrinsic returns a 8956 // value. 8957 if (IsAnyRegCC && HasDef) { 8958 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8959 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8960 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8961 } else 8962 DAG.ReplaceAllUsesWith(Call, MN); 8963 DAG.DeleteNode(Call); 8964 8965 // Inform the Frame Information that we have a patchpoint in this function. 8966 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8967 } 8968 8969 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8970 unsigned Intrinsic) { 8971 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8972 SDValue Op1 = getValue(I.getArgOperand(0)); 8973 SDValue Op2; 8974 if (I.getNumArgOperands() > 1) 8975 Op2 = getValue(I.getArgOperand(1)); 8976 SDLoc dl = getCurSDLoc(); 8977 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8978 SDValue Res; 8979 FastMathFlags FMF; 8980 if (isa<FPMathOperator>(I)) 8981 FMF = I.getFastMathFlags(); 8982 8983 switch (Intrinsic) { 8984 case Intrinsic::experimental_vector_reduce_v2_fadd: 8985 if (FMF.allowReassoc()) 8986 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8987 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8988 else 8989 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8990 break; 8991 case Intrinsic::experimental_vector_reduce_v2_fmul: 8992 if (FMF.allowReassoc()) 8993 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8994 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8995 else 8996 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8997 break; 8998 case Intrinsic::experimental_vector_reduce_add: 8999 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9000 break; 9001 case Intrinsic::experimental_vector_reduce_mul: 9002 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9003 break; 9004 case Intrinsic::experimental_vector_reduce_and: 9005 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9006 break; 9007 case Intrinsic::experimental_vector_reduce_or: 9008 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9009 break; 9010 case Intrinsic::experimental_vector_reduce_xor: 9011 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9012 break; 9013 case Intrinsic::experimental_vector_reduce_smax: 9014 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9015 break; 9016 case Intrinsic::experimental_vector_reduce_smin: 9017 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9018 break; 9019 case Intrinsic::experimental_vector_reduce_umax: 9020 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9021 break; 9022 case Intrinsic::experimental_vector_reduce_umin: 9023 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9024 break; 9025 case Intrinsic::experimental_vector_reduce_fmax: 9026 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 9027 break; 9028 case Intrinsic::experimental_vector_reduce_fmin: 9029 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9030 break; 9031 default: 9032 llvm_unreachable("Unhandled vector reduce intrinsic"); 9033 } 9034 setValue(&I, Res); 9035 } 9036 9037 /// Returns an AttributeList representing the attributes applied to the return 9038 /// value of the given call. 9039 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9040 SmallVector<Attribute::AttrKind, 2> Attrs; 9041 if (CLI.RetSExt) 9042 Attrs.push_back(Attribute::SExt); 9043 if (CLI.RetZExt) 9044 Attrs.push_back(Attribute::ZExt); 9045 if (CLI.IsInReg) 9046 Attrs.push_back(Attribute::InReg); 9047 9048 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9049 Attrs); 9050 } 9051 9052 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9053 /// implementation, which just calls LowerCall. 9054 /// FIXME: When all targets are 9055 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9056 std::pair<SDValue, SDValue> 9057 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9058 // Handle the incoming return values from the call. 9059 CLI.Ins.clear(); 9060 Type *OrigRetTy = CLI.RetTy; 9061 SmallVector<EVT, 4> RetTys; 9062 SmallVector<uint64_t, 4> Offsets; 9063 auto &DL = CLI.DAG.getDataLayout(); 9064 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9065 9066 if (CLI.IsPostTypeLegalization) { 9067 // If we are lowering a libcall after legalization, split the return type. 9068 SmallVector<EVT, 4> OldRetTys; 9069 SmallVector<uint64_t, 4> OldOffsets; 9070 RetTys.swap(OldRetTys); 9071 Offsets.swap(OldOffsets); 9072 9073 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9074 EVT RetVT = OldRetTys[i]; 9075 uint64_t Offset = OldOffsets[i]; 9076 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9077 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9078 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9079 RetTys.append(NumRegs, RegisterVT); 9080 for (unsigned j = 0; j != NumRegs; ++j) 9081 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9082 } 9083 } 9084 9085 SmallVector<ISD::OutputArg, 4> Outs; 9086 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9087 9088 bool CanLowerReturn = 9089 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9090 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9091 9092 SDValue DemoteStackSlot; 9093 int DemoteStackIdx = -100; 9094 if (!CanLowerReturn) { 9095 // FIXME: equivalent assert? 9096 // assert(!CS.hasInAllocaArgument() && 9097 // "sret demotion is incompatible with inalloca"); 9098 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9099 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9100 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9101 DemoteStackIdx = 9102 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9103 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9104 DL.getAllocaAddrSpace()); 9105 9106 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9107 ArgListEntry Entry; 9108 Entry.Node = DemoteStackSlot; 9109 Entry.Ty = StackSlotPtrType; 9110 Entry.IsSExt = false; 9111 Entry.IsZExt = false; 9112 Entry.IsInReg = false; 9113 Entry.IsSRet = true; 9114 Entry.IsNest = false; 9115 Entry.IsByVal = false; 9116 Entry.IsReturned = false; 9117 Entry.IsSwiftSelf = false; 9118 Entry.IsSwiftError = false; 9119 Entry.IsCFGuardTarget = false; 9120 Entry.Alignment = Alignment; 9121 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9122 CLI.NumFixedArgs += 1; 9123 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9124 9125 // sret demotion isn't compatible with tail-calls, since the sret argument 9126 // points into the callers stack frame. 9127 CLI.IsTailCall = false; 9128 } else { 9129 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9130 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9131 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9132 ISD::ArgFlagsTy Flags; 9133 if (NeedsRegBlock) { 9134 Flags.setInConsecutiveRegs(); 9135 if (I == RetTys.size() - 1) 9136 Flags.setInConsecutiveRegsLast(); 9137 } 9138 EVT VT = RetTys[I]; 9139 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9140 CLI.CallConv, VT); 9141 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9142 CLI.CallConv, VT); 9143 for (unsigned i = 0; i != NumRegs; ++i) { 9144 ISD::InputArg MyFlags; 9145 MyFlags.Flags = Flags; 9146 MyFlags.VT = RegisterVT; 9147 MyFlags.ArgVT = VT; 9148 MyFlags.Used = CLI.IsReturnValueUsed; 9149 if (CLI.RetTy->isPointerTy()) { 9150 MyFlags.Flags.setPointer(); 9151 MyFlags.Flags.setPointerAddrSpace( 9152 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9153 } 9154 if (CLI.RetSExt) 9155 MyFlags.Flags.setSExt(); 9156 if (CLI.RetZExt) 9157 MyFlags.Flags.setZExt(); 9158 if (CLI.IsInReg) 9159 MyFlags.Flags.setInReg(); 9160 CLI.Ins.push_back(MyFlags); 9161 } 9162 } 9163 } 9164 9165 // We push in swifterror return as the last element of CLI.Ins. 9166 ArgListTy &Args = CLI.getArgs(); 9167 if (supportSwiftError()) { 9168 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9169 if (Args[i].IsSwiftError) { 9170 ISD::InputArg MyFlags; 9171 MyFlags.VT = getPointerTy(DL); 9172 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9173 MyFlags.Flags.setSwiftError(); 9174 CLI.Ins.push_back(MyFlags); 9175 } 9176 } 9177 } 9178 9179 // Handle all of the outgoing arguments. 9180 CLI.Outs.clear(); 9181 CLI.OutVals.clear(); 9182 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9183 SmallVector<EVT, 4> ValueVTs; 9184 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9185 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9186 Type *FinalType = Args[i].Ty; 9187 if (Args[i].IsByVal) 9188 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9189 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9190 FinalType, CLI.CallConv, CLI.IsVarArg); 9191 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9192 ++Value) { 9193 EVT VT = ValueVTs[Value]; 9194 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9195 SDValue Op = SDValue(Args[i].Node.getNode(), 9196 Args[i].Node.getResNo() + Value); 9197 ISD::ArgFlagsTy Flags; 9198 9199 // Certain targets (such as MIPS), may have a different ABI alignment 9200 // for a type depending on the context. Give the target a chance to 9201 // specify the alignment it wants. 9202 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9203 9204 if (Args[i].Ty->isPointerTy()) { 9205 Flags.setPointer(); 9206 Flags.setPointerAddrSpace( 9207 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9208 } 9209 if (Args[i].IsZExt) 9210 Flags.setZExt(); 9211 if (Args[i].IsSExt) 9212 Flags.setSExt(); 9213 if (Args[i].IsInReg) { 9214 // If we are using vectorcall calling convention, a structure that is 9215 // passed InReg - is surely an HVA 9216 if (CLI.CallConv == CallingConv::X86_VectorCall && 9217 isa<StructType>(FinalType)) { 9218 // The first value of a structure is marked 9219 if (0 == Value) 9220 Flags.setHvaStart(); 9221 Flags.setHva(); 9222 } 9223 // Set InReg Flag 9224 Flags.setInReg(); 9225 } 9226 if (Args[i].IsSRet) 9227 Flags.setSRet(); 9228 if (Args[i].IsSwiftSelf) 9229 Flags.setSwiftSelf(); 9230 if (Args[i].IsSwiftError) 9231 Flags.setSwiftError(); 9232 if (Args[i].IsCFGuardTarget) 9233 Flags.setCFGuardTarget(); 9234 if (Args[i].IsByVal) 9235 Flags.setByVal(); 9236 if (Args[i].IsPreallocated) { 9237 Flags.setPreallocated(); 9238 // Set the byval flag for CCAssignFn callbacks that don't know about 9239 // preallocated. This way we can know how many bytes we should've 9240 // allocated and how many bytes a callee cleanup function will pop. If 9241 // we port preallocated to more targets, we'll have to add custom 9242 // preallocated handling in the various CC lowering callbacks. 9243 Flags.setByVal(); 9244 } 9245 if (Args[i].IsInAlloca) { 9246 Flags.setInAlloca(); 9247 // Set the byval flag for CCAssignFn callbacks that don't know about 9248 // inalloca. This way we can know how many bytes we should've allocated 9249 // and how many bytes a callee cleanup function will pop. If we port 9250 // inalloca to more targets, we'll have to add custom inalloca handling 9251 // in the various CC lowering callbacks. 9252 Flags.setByVal(); 9253 } 9254 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9255 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9256 Type *ElementTy = Ty->getElementType(); 9257 9258 unsigned FrameSize = DL.getTypeAllocSize( 9259 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9260 Flags.setByValSize(FrameSize); 9261 9262 // info is not there but there are cases it cannot get right. 9263 Align FrameAlign; 9264 if (auto MA = Args[i].Alignment) 9265 FrameAlign = *MA; 9266 else 9267 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9268 Flags.setByValAlign(FrameAlign); 9269 } 9270 if (Args[i].IsNest) 9271 Flags.setNest(); 9272 if (NeedsRegBlock) 9273 Flags.setInConsecutiveRegs(); 9274 Flags.setOrigAlign(OriginalAlignment); 9275 9276 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9277 CLI.CallConv, VT); 9278 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9279 CLI.CallConv, VT); 9280 SmallVector<SDValue, 4> Parts(NumParts); 9281 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9282 9283 if (Args[i].IsSExt) 9284 ExtendKind = ISD::SIGN_EXTEND; 9285 else if (Args[i].IsZExt) 9286 ExtendKind = ISD::ZERO_EXTEND; 9287 9288 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9289 // for now. 9290 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9291 CanLowerReturn) { 9292 assert((CLI.RetTy == Args[i].Ty || 9293 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9294 CLI.RetTy->getPointerAddressSpace() == 9295 Args[i].Ty->getPointerAddressSpace())) && 9296 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9297 // Before passing 'returned' to the target lowering code, ensure that 9298 // either the register MVT and the actual EVT are the same size or that 9299 // the return value and argument are extended in the same way; in these 9300 // cases it's safe to pass the argument register value unchanged as the 9301 // return register value (although it's at the target's option whether 9302 // to do so) 9303 // TODO: allow code generation to take advantage of partially preserved 9304 // registers rather than clobbering the entire register when the 9305 // parameter extension method is not compatible with the return 9306 // extension method 9307 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9308 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9309 CLI.RetZExt == Args[i].IsZExt)) 9310 Flags.setReturned(); 9311 } 9312 9313 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9314 CLI.CallConv, ExtendKind); 9315 9316 for (unsigned j = 0; j != NumParts; ++j) { 9317 // if it isn't first piece, alignment must be 1 9318 // For scalable vectors the scalable part is currently handled 9319 // by individual targets, so we just use the known minimum size here. 9320 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9321 i < CLI.NumFixedArgs, i, 9322 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9323 if (NumParts > 1 && j == 0) 9324 MyFlags.Flags.setSplit(); 9325 else if (j != 0) { 9326 MyFlags.Flags.setOrigAlign(Align(1)); 9327 if (j == NumParts - 1) 9328 MyFlags.Flags.setSplitEnd(); 9329 } 9330 9331 CLI.Outs.push_back(MyFlags); 9332 CLI.OutVals.push_back(Parts[j]); 9333 } 9334 9335 if (NeedsRegBlock && Value == NumValues - 1) 9336 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9337 } 9338 } 9339 9340 SmallVector<SDValue, 4> InVals; 9341 CLI.Chain = LowerCall(CLI, InVals); 9342 9343 // Update CLI.InVals to use outside of this function. 9344 CLI.InVals = InVals; 9345 9346 // Verify that the target's LowerCall behaved as expected. 9347 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9348 "LowerCall didn't return a valid chain!"); 9349 assert((!CLI.IsTailCall || InVals.empty()) && 9350 "LowerCall emitted a return value for a tail call!"); 9351 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9352 "LowerCall didn't emit the correct number of values!"); 9353 9354 // For a tail call, the return value is merely live-out and there aren't 9355 // any nodes in the DAG representing it. Return a special value to 9356 // indicate that a tail call has been emitted and no more Instructions 9357 // should be processed in the current block. 9358 if (CLI.IsTailCall) { 9359 CLI.DAG.setRoot(CLI.Chain); 9360 return std::make_pair(SDValue(), SDValue()); 9361 } 9362 9363 #ifndef NDEBUG 9364 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9365 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9366 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9367 "LowerCall emitted a value with the wrong type!"); 9368 } 9369 #endif 9370 9371 SmallVector<SDValue, 4> ReturnValues; 9372 if (!CanLowerReturn) { 9373 // The instruction result is the result of loading from the 9374 // hidden sret parameter. 9375 SmallVector<EVT, 1> PVTs; 9376 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9377 9378 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9379 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9380 EVT PtrVT = PVTs[0]; 9381 9382 unsigned NumValues = RetTys.size(); 9383 ReturnValues.resize(NumValues); 9384 SmallVector<SDValue, 4> Chains(NumValues); 9385 9386 // An aggregate return value cannot wrap around the address space, so 9387 // offsets to its parts don't wrap either. 9388 SDNodeFlags Flags; 9389 Flags.setNoUnsignedWrap(true); 9390 9391 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9392 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9393 for (unsigned i = 0; i < NumValues; ++i) { 9394 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9395 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9396 PtrVT), Flags); 9397 SDValue L = CLI.DAG.getLoad( 9398 RetTys[i], CLI.DL, CLI.Chain, Add, 9399 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9400 DemoteStackIdx, Offsets[i]), 9401 HiddenSRetAlign); 9402 ReturnValues[i] = L; 9403 Chains[i] = L.getValue(1); 9404 } 9405 9406 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9407 } else { 9408 // Collect the legal value parts into potentially illegal values 9409 // that correspond to the original function's return values. 9410 Optional<ISD::NodeType> AssertOp; 9411 if (CLI.RetSExt) 9412 AssertOp = ISD::AssertSext; 9413 else if (CLI.RetZExt) 9414 AssertOp = ISD::AssertZext; 9415 unsigned CurReg = 0; 9416 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9417 EVT VT = RetTys[I]; 9418 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9419 CLI.CallConv, VT); 9420 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9421 CLI.CallConv, VT); 9422 9423 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9424 NumRegs, RegisterVT, VT, nullptr, 9425 CLI.CallConv, AssertOp)); 9426 CurReg += NumRegs; 9427 } 9428 9429 // For a function returning void, there is no return value. We can't create 9430 // such a node, so we just return a null return value in that case. In 9431 // that case, nothing will actually look at the value. 9432 if (ReturnValues.empty()) 9433 return std::make_pair(SDValue(), CLI.Chain); 9434 } 9435 9436 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9437 CLI.DAG.getVTList(RetTys), ReturnValues); 9438 return std::make_pair(Res, CLI.Chain); 9439 } 9440 9441 void TargetLowering::LowerOperationWrapper(SDNode *N, 9442 SmallVectorImpl<SDValue> &Results, 9443 SelectionDAG &DAG) const { 9444 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9445 Results.push_back(Res); 9446 } 9447 9448 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9449 llvm_unreachable("LowerOperation not implemented for this target!"); 9450 } 9451 9452 void 9453 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9454 SDValue Op = getNonRegisterValue(V); 9455 assert((Op.getOpcode() != ISD::CopyFromReg || 9456 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9457 "Copy from a reg to the same reg!"); 9458 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9459 9460 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9461 // If this is an InlineAsm we have to match the registers required, not the 9462 // notional registers required by the type. 9463 9464 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9465 None); // This is not an ABI copy. 9466 SDValue Chain = DAG.getEntryNode(); 9467 9468 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9469 FuncInfo.PreferredExtendType.end()) 9470 ? ISD::ANY_EXTEND 9471 : FuncInfo.PreferredExtendType[V]; 9472 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9473 PendingExports.push_back(Chain); 9474 } 9475 9476 #include "llvm/CodeGen/SelectionDAGISel.h" 9477 9478 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9479 /// entry block, return true. This includes arguments used by switches, since 9480 /// the switch may expand into multiple basic blocks. 9481 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9482 // With FastISel active, we may be splitting blocks, so force creation 9483 // of virtual registers for all non-dead arguments. 9484 if (FastISel) 9485 return A->use_empty(); 9486 9487 const BasicBlock &Entry = A->getParent()->front(); 9488 for (const User *U : A->users()) 9489 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9490 return false; // Use not in entry block. 9491 9492 return true; 9493 } 9494 9495 using ArgCopyElisionMapTy = 9496 DenseMap<const Argument *, 9497 std::pair<const AllocaInst *, const StoreInst *>>; 9498 9499 /// Scan the entry block of the function in FuncInfo for arguments that look 9500 /// like copies into a local alloca. Record any copied arguments in 9501 /// ArgCopyElisionCandidates. 9502 static void 9503 findArgumentCopyElisionCandidates(const DataLayout &DL, 9504 FunctionLoweringInfo *FuncInfo, 9505 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9506 // Record the state of every static alloca used in the entry block. Argument 9507 // allocas are all used in the entry block, so we need approximately as many 9508 // entries as we have arguments. 9509 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9510 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9511 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9512 StaticAllocas.reserve(NumArgs * 2); 9513 9514 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9515 if (!V) 9516 return nullptr; 9517 V = V->stripPointerCasts(); 9518 const auto *AI = dyn_cast<AllocaInst>(V); 9519 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9520 return nullptr; 9521 auto Iter = StaticAllocas.insert({AI, Unknown}); 9522 return &Iter.first->second; 9523 }; 9524 9525 // Look for stores of arguments to static allocas. Look through bitcasts and 9526 // GEPs to handle type coercions, as long as the alloca is fully initialized 9527 // by the store. Any non-store use of an alloca escapes it and any subsequent 9528 // unanalyzed store might write it. 9529 // FIXME: Handle structs initialized with multiple stores. 9530 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9531 // Look for stores, and handle non-store uses conservatively. 9532 const auto *SI = dyn_cast<StoreInst>(&I); 9533 if (!SI) { 9534 // We will look through cast uses, so ignore them completely. 9535 if (I.isCast()) 9536 continue; 9537 // Ignore debug info intrinsics, they don't escape or store to allocas. 9538 if (isa<DbgInfoIntrinsic>(I)) 9539 continue; 9540 // This is an unknown instruction. Assume it escapes or writes to all 9541 // static alloca operands. 9542 for (const Use &U : I.operands()) { 9543 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9544 *Info = StaticAllocaInfo::Clobbered; 9545 } 9546 continue; 9547 } 9548 9549 // If the stored value is a static alloca, mark it as escaped. 9550 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9551 *Info = StaticAllocaInfo::Clobbered; 9552 9553 // Check if the destination is a static alloca. 9554 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9555 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9556 if (!Info) 9557 continue; 9558 const AllocaInst *AI = cast<AllocaInst>(Dst); 9559 9560 // Skip allocas that have been initialized or clobbered. 9561 if (*Info != StaticAllocaInfo::Unknown) 9562 continue; 9563 9564 // Check if the stored value is an argument, and that this store fully 9565 // initializes the alloca. Don't elide copies from the same argument twice. 9566 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9567 const auto *Arg = dyn_cast<Argument>(Val); 9568 if (!Arg || Arg->hasPassPointeeByValueAttr() || 9569 Arg->getType()->isEmptyTy() || 9570 DL.getTypeStoreSize(Arg->getType()) != 9571 DL.getTypeAllocSize(AI->getAllocatedType()) || 9572 ArgCopyElisionCandidates.count(Arg)) { 9573 *Info = StaticAllocaInfo::Clobbered; 9574 continue; 9575 } 9576 9577 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9578 << '\n'); 9579 9580 // Mark this alloca and store for argument copy elision. 9581 *Info = StaticAllocaInfo::Elidable; 9582 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9583 9584 // Stop scanning if we've seen all arguments. This will happen early in -O0 9585 // builds, which is useful, because -O0 builds have large entry blocks and 9586 // many allocas. 9587 if (ArgCopyElisionCandidates.size() == NumArgs) 9588 break; 9589 } 9590 } 9591 9592 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9593 /// ArgVal is a load from a suitable fixed stack object. 9594 static void tryToElideArgumentCopy( 9595 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9596 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9597 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9598 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9599 SDValue ArgVal, bool &ArgHasUses) { 9600 // Check if this is a load from a fixed stack object. 9601 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9602 if (!LNode) 9603 return; 9604 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9605 if (!FINode) 9606 return; 9607 9608 // Check that the fixed stack object is the right size and alignment. 9609 // Look at the alignment that the user wrote on the alloca instead of looking 9610 // at the stack object. 9611 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9612 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9613 const AllocaInst *AI = ArgCopyIter->second.first; 9614 int FixedIndex = FINode->getIndex(); 9615 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9616 int OldIndex = AllocaIndex; 9617 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9618 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9619 LLVM_DEBUG( 9620 dbgs() << " argument copy elision failed due to bad fixed stack " 9621 "object size\n"); 9622 return; 9623 } 9624 Align RequiredAlignment = AI->getAlign(); 9625 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9626 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9627 "greater than stack argument alignment (" 9628 << DebugStr(RequiredAlignment) << " vs " 9629 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9630 return; 9631 } 9632 9633 // Perform the elision. Delete the old stack object and replace its only use 9634 // in the variable info map. Mark the stack object as mutable. 9635 LLVM_DEBUG({ 9636 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9637 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9638 << '\n'; 9639 }); 9640 MFI.RemoveStackObject(OldIndex); 9641 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9642 AllocaIndex = FixedIndex; 9643 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9644 Chains.push_back(ArgVal.getValue(1)); 9645 9646 // Avoid emitting code for the store implementing the copy. 9647 const StoreInst *SI = ArgCopyIter->second.second; 9648 ElidedArgCopyInstrs.insert(SI); 9649 9650 // Check for uses of the argument again so that we can avoid exporting ArgVal 9651 // if it is't used by anything other than the store. 9652 for (const Value *U : Arg.users()) { 9653 if (U != SI) { 9654 ArgHasUses = true; 9655 break; 9656 } 9657 } 9658 } 9659 9660 void SelectionDAGISel::LowerArguments(const Function &F) { 9661 SelectionDAG &DAG = SDB->DAG; 9662 SDLoc dl = SDB->getCurSDLoc(); 9663 const DataLayout &DL = DAG.getDataLayout(); 9664 SmallVector<ISD::InputArg, 16> Ins; 9665 9666 // In Naked functions we aren't going to save any registers. 9667 if (F.hasFnAttribute(Attribute::Naked)) 9668 return; 9669 9670 if (!FuncInfo->CanLowerReturn) { 9671 // Put in an sret pointer parameter before all the other parameters. 9672 SmallVector<EVT, 1> ValueVTs; 9673 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9674 F.getReturnType()->getPointerTo( 9675 DAG.getDataLayout().getAllocaAddrSpace()), 9676 ValueVTs); 9677 9678 // NOTE: Assuming that a pointer will never break down to more than one VT 9679 // or one register. 9680 ISD::ArgFlagsTy Flags; 9681 Flags.setSRet(); 9682 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9683 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9684 ISD::InputArg::NoArgIndex, 0); 9685 Ins.push_back(RetArg); 9686 } 9687 9688 // Look for stores of arguments to static allocas. Mark such arguments with a 9689 // flag to ask the target to give us the memory location of that argument if 9690 // available. 9691 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9692 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9693 ArgCopyElisionCandidates); 9694 9695 // Set up the incoming argument description vector. 9696 for (const Argument &Arg : F.args()) { 9697 unsigned ArgNo = Arg.getArgNo(); 9698 SmallVector<EVT, 4> ValueVTs; 9699 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9700 bool isArgValueUsed = !Arg.use_empty(); 9701 unsigned PartBase = 0; 9702 Type *FinalType = Arg.getType(); 9703 if (Arg.hasAttribute(Attribute::ByVal)) 9704 FinalType = Arg.getParamByValType(); 9705 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9706 FinalType, F.getCallingConv(), F.isVarArg()); 9707 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9708 Value != NumValues; ++Value) { 9709 EVT VT = ValueVTs[Value]; 9710 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9711 ISD::ArgFlagsTy Flags; 9712 9713 // Certain targets (such as MIPS), may have a different ABI alignment 9714 // for a type depending on the context. Give the target a chance to 9715 // specify the alignment it wants. 9716 const Align OriginalAlignment( 9717 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9718 9719 if (Arg.getType()->isPointerTy()) { 9720 Flags.setPointer(); 9721 Flags.setPointerAddrSpace( 9722 cast<PointerType>(Arg.getType())->getAddressSpace()); 9723 } 9724 if (Arg.hasAttribute(Attribute::ZExt)) 9725 Flags.setZExt(); 9726 if (Arg.hasAttribute(Attribute::SExt)) 9727 Flags.setSExt(); 9728 if (Arg.hasAttribute(Attribute::InReg)) { 9729 // If we are using vectorcall calling convention, a structure that is 9730 // passed InReg - is surely an HVA 9731 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9732 isa<StructType>(Arg.getType())) { 9733 // The first value of a structure is marked 9734 if (0 == Value) 9735 Flags.setHvaStart(); 9736 Flags.setHva(); 9737 } 9738 // Set InReg Flag 9739 Flags.setInReg(); 9740 } 9741 if (Arg.hasAttribute(Attribute::StructRet)) 9742 Flags.setSRet(); 9743 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9744 Flags.setSwiftSelf(); 9745 if (Arg.hasAttribute(Attribute::SwiftError)) 9746 Flags.setSwiftError(); 9747 if (Arg.hasAttribute(Attribute::ByVal)) 9748 Flags.setByVal(); 9749 if (Arg.hasAttribute(Attribute::InAlloca)) { 9750 Flags.setInAlloca(); 9751 // Set the byval flag for CCAssignFn callbacks that don't know about 9752 // inalloca. This way we can know how many bytes we should've allocated 9753 // and how many bytes a callee cleanup function will pop. If we port 9754 // inalloca to more targets, we'll have to add custom inalloca handling 9755 // in the various CC lowering callbacks. 9756 Flags.setByVal(); 9757 } 9758 if (Arg.hasAttribute(Attribute::Preallocated)) { 9759 Flags.setPreallocated(); 9760 // Set the byval flag for CCAssignFn callbacks that don't know about 9761 // preallocated. This way we can know how many bytes we should've 9762 // allocated and how many bytes a callee cleanup function will pop. If 9763 // we port preallocated to more targets, we'll have to add custom 9764 // preallocated handling in the various CC lowering callbacks. 9765 Flags.setByVal(); 9766 } 9767 if (F.getCallingConv() == CallingConv::X86_INTR) { 9768 // IA Interrupt passes frame (1st parameter) by value in the stack. 9769 if (ArgNo == 0) 9770 Flags.setByVal(); 9771 } 9772 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) { 9773 Type *ElementTy = Arg.getParamByValType(); 9774 9775 // For ByVal, size and alignment should be passed from FE. BE will 9776 // guess if this info is not there but there are cases it cannot get 9777 // right. 9778 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9779 Flags.setByValSize(FrameSize); 9780 9781 unsigned FrameAlign; 9782 if (Arg.getParamAlignment()) 9783 FrameAlign = Arg.getParamAlignment(); 9784 else 9785 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9786 Flags.setByValAlign(Align(FrameAlign)); 9787 } 9788 if (Arg.hasAttribute(Attribute::Nest)) 9789 Flags.setNest(); 9790 if (NeedsRegBlock) 9791 Flags.setInConsecutiveRegs(); 9792 Flags.setOrigAlign(OriginalAlignment); 9793 if (ArgCopyElisionCandidates.count(&Arg)) 9794 Flags.setCopyElisionCandidate(); 9795 if (Arg.hasAttribute(Attribute::Returned)) 9796 Flags.setReturned(); 9797 9798 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9799 *CurDAG->getContext(), F.getCallingConv(), VT); 9800 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9801 *CurDAG->getContext(), F.getCallingConv(), VT); 9802 for (unsigned i = 0; i != NumRegs; ++i) { 9803 // For scalable vectors, use the minimum size; individual targets 9804 // are responsible for handling scalable vector arguments and 9805 // return values. 9806 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9807 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9808 if (NumRegs > 1 && i == 0) 9809 MyFlags.Flags.setSplit(); 9810 // if it isn't first piece, alignment must be 1 9811 else if (i > 0) { 9812 MyFlags.Flags.setOrigAlign(Align(1)); 9813 if (i == NumRegs - 1) 9814 MyFlags.Flags.setSplitEnd(); 9815 } 9816 Ins.push_back(MyFlags); 9817 } 9818 if (NeedsRegBlock && Value == NumValues - 1) 9819 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9820 PartBase += VT.getStoreSize().getKnownMinSize(); 9821 } 9822 } 9823 9824 // Call the target to set up the argument values. 9825 SmallVector<SDValue, 8> InVals; 9826 SDValue NewRoot = TLI->LowerFormalArguments( 9827 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9828 9829 // Verify that the target's LowerFormalArguments behaved as expected. 9830 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9831 "LowerFormalArguments didn't return a valid chain!"); 9832 assert(InVals.size() == Ins.size() && 9833 "LowerFormalArguments didn't emit the correct number of values!"); 9834 LLVM_DEBUG({ 9835 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9836 assert(InVals[i].getNode() && 9837 "LowerFormalArguments emitted a null value!"); 9838 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9839 "LowerFormalArguments emitted a value with the wrong type!"); 9840 } 9841 }); 9842 9843 // Update the DAG with the new chain value resulting from argument lowering. 9844 DAG.setRoot(NewRoot); 9845 9846 // Set up the argument values. 9847 unsigned i = 0; 9848 if (!FuncInfo->CanLowerReturn) { 9849 // Create a virtual register for the sret pointer, and put in a copy 9850 // from the sret argument into it. 9851 SmallVector<EVT, 1> ValueVTs; 9852 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9853 F.getReturnType()->getPointerTo( 9854 DAG.getDataLayout().getAllocaAddrSpace()), 9855 ValueVTs); 9856 MVT VT = ValueVTs[0].getSimpleVT(); 9857 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9858 Optional<ISD::NodeType> AssertOp = None; 9859 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9860 nullptr, F.getCallingConv(), AssertOp); 9861 9862 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9863 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9864 Register SRetReg = 9865 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9866 FuncInfo->DemoteRegister = SRetReg; 9867 NewRoot = 9868 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9869 DAG.setRoot(NewRoot); 9870 9871 // i indexes lowered arguments. Bump it past the hidden sret argument. 9872 ++i; 9873 } 9874 9875 SmallVector<SDValue, 4> Chains; 9876 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9877 for (const Argument &Arg : F.args()) { 9878 SmallVector<SDValue, 4> ArgValues; 9879 SmallVector<EVT, 4> ValueVTs; 9880 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9881 unsigned NumValues = ValueVTs.size(); 9882 if (NumValues == 0) 9883 continue; 9884 9885 bool ArgHasUses = !Arg.use_empty(); 9886 9887 // Elide the copying store if the target loaded this argument from a 9888 // suitable fixed stack object. 9889 if (Ins[i].Flags.isCopyElisionCandidate()) { 9890 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9891 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9892 InVals[i], ArgHasUses); 9893 } 9894 9895 // If this argument is unused then remember its value. It is used to generate 9896 // debugging information. 9897 bool isSwiftErrorArg = 9898 TLI->supportSwiftError() && 9899 Arg.hasAttribute(Attribute::SwiftError); 9900 if (!ArgHasUses && !isSwiftErrorArg) { 9901 SDB->setUnusedArgValue(&Arg, InVals[i]); 9902 9903 // Also remember any frame index for use in FastISel. 9904 if (FrameIndexSDNode *FI = 9905 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9906 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9907 } 9908 9909 for (unsigned Val = 0; Val != NumValues; ++Val) { 9910 EVT VT = ValueVTs[Val]; 9911 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9912 F.getCallingConv(), VT); 9913 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9914 *CurDAG->getContext(), F.getCallingConv(), VT); 9915 9916 // Even an apparent 'unused' swifterror argument needs to be returned. So 9917 // we do generate a copy for it that can be used on return from the 9918 // function. 9919 if (ArgHasUses || isSwiftErrorArg) { 9920 Optional<ISD::NodeType> AssertOp; 9921 if (Arg.hasAttribute(Attribute::SExt)) 9922 AssertOp = ISD::AssertSext; 9923 else if (Arg.hasAttribute(Attribute::ZExt)) 9924 AssertOp = ISD::AssertZext; 9925 9926 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9927 PartVT, VT, nullptr, 9928 F.getCallingConv(), AssertOp)); 9929 } 9930 9931 i += NumParts; 9932 } 9933 9934 // We don't need to do anything else for unused arguments. 9935 if (ArgValues.empty()) 9936 continue; 9937 9938 // Note down frame index. 9939 if (FrameIndexSDNode *FI = 9940 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9941 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9942 9943 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9944 SDB->getCurSDLoc()); 9945 9946 SDB->setValue(&Arg, Res); 9947 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9948 // We want to associate the argument with the frame index, among 9949 // involved operands, that correspond to the lowest address. The 9950 // getCopyFromParts function, called earlier, is swapping the order of 9951 // the operands to BUILD_PAIR depending on endianness. The result of 9952 // that swapping is that the least significant bits of the argument will 9953 // be in the first operand of the BUILD_PAIR node, and the most 9954 // significant bits will be in the second operand. 9955 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9956 if (LoadSDNode *LNode = 9957 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9958 if (FrameIndexSDNode *FI = 9959 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9960 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9961 } 9962 9963 // Analyses past this point are naive and don't expect an assertion. 9964 if (Res.getOpcode() == ISD::AssertZext) 9965 Res = Res.getOperand(0); 9966 9967 // Update the SwiftErrorVRegDefMap. 9968 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9969 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9970 if (Register::isVirtualRegister(Reg)) 9971 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9972 Reg); 9973 } 9974 9975 // If this argument is live outside of the entry block, insert a copy from 9976 // wherever we got it to the vreg that other BB's will reference it as. 9977 if (Res.getOpcode() == ISD::CopyFromReg) { 9978 // If we can, though, try to skip creating an unnecessary vreg. 9979 // FIXME: This isn't very clean... it would be nice to make this more 9980 // general. 9981 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9982 if (Register::isVirtualRegister(Reg)) { 9983 FuncInfo->ValueMap[&Arg] = Reg; 9984 continue; 9985 } 9986 } 9987 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9988 FuncInfo->InitializeRegForValue(&Arg); 9989 SDB->CopyToExportRegsIfNeeded(&Arg); 9990 } 9991 } 9992 9993 if (!Chains.empty()) { 9994 Chains.push_back(NewRoot); 9995 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9996 } 9997 9998 DAG.setRoot(NewRoot); 9999 10000 assert(i == InVals.size() && "Argument register count mismatch!"); 10001 10002 // If any argument copy elisions occurred and we have debug info, update the 10003 // stale frame indices used in the dbg.declare variable info table. 10004 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10005 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10006 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10007 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10008 if (I != ArgCopyElisionFrameIndexMap.end()) 10009 VI.Slot = I->second; 10010 } 10011 } 10012 10013 // Finally, if the target has anything special to do, allow it to do so. 10014 emitFunctionEntryCode(); 10015 } 10016 10017 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10018 /// ensure constants are generated when needed. Remember the virtual registers 10019 /// that need to be added to the Machine PHI nodes as input. We cannot just 10020 /// directly add them, because expansion might result in multiple MBB's for one 10021 /// BB. As such, the start of the BB might correspond to a different MBB than 10022 /// the end. 10023 void 10024 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10025 const Instruction *TI = LLVMBB->getTerminator(); 10026 10027 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10028 10029 // Check PHI nodes in successors that expect a value to be available from this 10030 // block. 10031 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10032 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10033 if (!isa<PHINode>(SuccBB->begin())) continue; 10034 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10035 10036 // If this terminator has multiple identical successors (common for 10037 // switches), only handle each succ once. 10038 if (!SuccsHandled.insert(SuccMBB).second) 10039 continue; 10040 10041 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10042 10043 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10044 // nodes and Machine PHI nodes, but the incoming operands have not been 10045 // emitted yet. 10046 for (const PHINode &PN : SuccBB->phis()) { 10047 // Ignore dead phi's. 10048 if (PN.use_empty()) 10049 continue; 10050 10051 // Skip empty types 10052 if (PN.getType()->isEmptyTy()) 10053 continue; 10054 10055 unsigned Reg; 10056 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10057 10058 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10059 unsigned &RegOut = ConstantsOut[C]; 10060 if (RegOut == 0) { 10061 RegOut = FuncInfo.CreateRegs(C); 10062 CopyValueToVirtualRegister(C, RegOut); 10063 } 10064 Reg = RegOut; 10065 } else { 10066 DenseMap<const Value *, Register>::iterator I = 10067 FuncInfo.ValueMap.find(PHIOp); 10068 if (I != FuncInfo.ValueMap.end()) 10069 Reg = I->second; 10070 else { 10071 assert(isa<AllocaInst>(PHIOp) && 10072 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10073 "Didn't codegen value into a register!??"); 10074 Reg = FuncInfo.CreateRegs(PHIOp); 10075 CopyValueToVirtualRegister(PHIOp, Reg); 10076 } 10077 } 10078 10079 // Remember that this register needs to added to the machine PHI node as 10080 // the input for this MBB. 10081 SmallVector<EVT, 4> ValueVTs; 10082 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10083 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10084 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10085 EVT VT = ValueVTs[vti]; 10086 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10087 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10088 FuncInfo.PHINodesToUpdate.push_back( 10089 std::make_pair(&*MBBI++, Reg + i)); 10090 Reg += NumRegisters; 10091 } 10092 } 10093 } 10094 10095 ConstantsOut.clear(); 10096 } 10097 10098 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10099 /// is 0. 10100 MachineBasicBlock * 10101 SelectionDAGBuilder::StackProtectorDescriptor:: 10102 AddSuccessorMBB(const BasicBlock *BB, 10103 MachineBasicBlock *ParentMBB, 10104 bool IsLikely, 10105 MachineBasicBlock *SuccMBB) { 10106 // If SuccBB has not been created yet, create it. 10107 if (!SuccMBB) { 10108 MachineFunction *MF = ParentMBB->getParent(); 10109 MachineFunction::iterator BBI(ParentMBB); 10110 SuccMBB = MF->CreateMachineBasicBlock(BB); 10111 MF->insert(++BBI, SuccMBB); 10112 } 10113 // Add it as a successor of ParentMBB. 10114 ParentMBB->addSuccessor( 10115 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10116 return SuccMBB; 10117 } 10118 10119 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10120 MachineFunction::iterator I(MBB); 10121 if (++I == FuncInfo.MF->end()) 10122 return nullptr; 10123 return &*I; 10124 } 10125 10126 /// During lowering new call nodes can be created (such as memset, etc.). 10127 /// Those will become new roots of the current DAG, but complications arise 10128 /// when they are tail calls. In such cases, the call lowering will update 10129 /// the root, but the builder still needs to know that a tail call has been 10130 /// lowered in order to avoid generating an additional return. 10131 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10132 // If the node is null, we do have a tail call. 10133 if (MaybeTC.getNode() != nullptr) 10134 DAG.setRoot(MaybeTC); 10135 else 10136 HasTailCall = true; 10137 } 10138 10139 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10140 MachineBasicBlock *SwitchMBB, 10141 MachineBasicBlock *DefaultMBB) { 10142 MachineFunction *CurMF = FuncInfo.MF; 10143 MachineBasicBlock *NextMBB = nullptr; 10144 MachineFunction::iterator BBI(W.MBB); 10145 if (++BBI != FuncInfo.MF->end()) 10146 NextMBB = &*BBI; 10147 10148 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10149 10150 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10151 10152 if (Size == 2 && W.MBB == SwitchMBB) { 10153 // If any two of the cases has the same destination, and if one value 10154 // is the same as the other, but has one bit unset that the other has set, 10155 // use bit manipulation to do two compares at once. For example: 10156 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10157 // TODO: This could be extended to merge any 2 cases in switches with 3 10158 // cases. 10159 // TODO: Handle cases where W.CaseBB != SwitchBB. 10160 CaseCluster &Small = *W.FirstCluster; 10161 CaseCluster &Big = *W.LastCluster; 10162 10163 if (Small.Low == Small.High && Big.Low == Big.High && 10164 Small.MBB == Big.MBB) { 10165 const APInt &SmallValue = Small.Low->getValue(); 10166 const APInt &BigValue = Big.Low->getValue(); 10167 10168 // Check that there is only one bit different. 10169 APInt CommonBit = BigValue ^ SmallValue; 10170 if (CommonBit.isPowerOf2()) { 10171 SDValue CondLHS = getValue(Cond); 10172 EVT VT = CondLHS.getValueType(); 10173 SDLoc DL = getCurSDLoc(); 10174 10175 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10176 DAG.getConstant(CommonBit, DL, VT)); 10177 SDValue Cond = DAG.getSetCC( 10178 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10179 ISD::SETEQ); 10180 10181 // Update successor info. 10182 // Both Small and Big will jump to Small.BB, so we sum up the 10183 // probabilities. 10184 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10185 if (BPI) 10186 addSuccessorWithProb( 10187 SwitchMBB, DefaultMBB, 10188 // The default destination is the first successor in IR. 10189 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10190 else 10191 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10192 10193 // Insert the true branch. 10194 SDValue BrCond = 10195 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10196 DAG.getBasicBlock(Small.MBB)); 10197 // Insert the false branch. 10198 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10199 DAG.getBasicBlock(DefaultMBB)); 10200 10201 DAG.setRoot(BrCond); 10202 return; 10203 } 10204 } 10205 } 10206 10207 if (TM.getOptLevel() != CodeGenOpt::None) { 10208 // Here, we order cases by probability so the most likely case will be 10209 // checked first. However, two clusters can have the same probability in 10210 // which case their relative ordering is non-deterministic. So we use Low 10211 // as a tie-breaker as clusters are guaranteed to never overlap. 10212 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10213 [](const CaseCluster &a, const CaseCluster &b) { 10214 return a.Prob != b.Prob ? 10215 a.Prob > b.Prob : 10216 a.Low->getValue().slt(b.Low->getValue()); 10217 }); 10218 10219 // Rearrange the case blocks so that the last one falls through if possible 10220 // without changing the order of probabilities. 10221 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10222 --I; 10223 if (I->Prob > W.LastCluster->Prob) 10224 break; 10225 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10226 std::swap(*I, *W.LastCluster); 10227 break; 10228 } 10229 } 10230 } 10231 10232 // Compute total probability. 10233 BranchProbability DefaultProb = W.DefaultProb; 10234 BranchProbability UnhandledProbs = DefaultProb; 10235 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10236 UnhandledProbs += I->Prob; 10237 10238 MachineBasicBlock *CurMBB = W.MBB; 10239 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10240 bool FallthroughUnreachable = false; 10241 MachineBasicBlock *Fallthrough; 10242 if (I == W.LastCluster) { 10243 // For the last cluster, fall through to the default destination. 10244 Fallthrough = DefaultMBB; 10245 FallthroughUnreachable = isa<UnreachableInst>( 10246 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10247 } else { 10248 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10249 CurMF->insert(BBI, Fallthrough); 10250 // Put Cond in a virtual register to make it available from the new blocks. 10251 ExportFromCurrentBlock(Cond); 10252 } 10253 UnhandledProbs -= I->Prob; 10254 10255 switch (I->Kind) { 10256 case CC_JumpTable: { 10257 // FIXME: Optimize away range check based on pivot comparisons. 10258 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10259 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10260 10261 // The jump block hasn't been inserted yet; insert it here. 10262 MachineBasicBlock *JumpMBB = JT->MBB; 10263 CurMF->insert(BBI, JumpMBB); 10264 10265 auto JumpProb = I->Prob; 10266 auto FallthroughProb = UnhandledProbs; 10267 10268 // If the default statement is a target of the jump table, we evenly 10269 // distribute the default probability to successors of CurMBB. Also 10270 // update the probability on the edge from JumpMBB to Fallthrough. 10271 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10272 SE = JumpMBB->succ_end(); 10273 SI != SE; ++SI) { 10274 if (*SI == DefaultMBB) { 10275 JumpProb += DefaultProb / 2; 10276 FallthroughProb -= DefaultProb / 2; 10277 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10278 JumpMBB->normalizeSuccProbs(); 10279 break; 10280 } 10281 } 10282 10283 if (FallthroughUnreachable) { 10284 // Skip the range check if the fallthrough block is unreachable. 10285 JTH->OmitRangeCheck = true; 10286 } 10287 10288 if (!JTH->OmitRangeCheck) 10289 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10290 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10291 CurMBB->normalizeSuccProbs(); 10292 10293 // The jump table header will be inserted in our current block, do the 10294 // range check, and fall through to our fallthrough block. 10295 JTH->HeaderBB = CurMBB; 10296 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10297 10298 // If we're in the right place, emit the jump table header right now. 10299 if (CurMBB == SwitchMBB) { 10300 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10301 JTH->Emitted = true; 10302 } 10303 break; 10304 } 10305 case CC_BitTests: { 10306 // FIXME: Optimize away range check based on pivot comparisons. 10307 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10308 10309 // The bit test blocks haven't been inserted yet; insert them here. 10310 for (BitTestCase &BTC : BTB->Cases) 10311 CurMF->insert(BBI, BTC.ThisBB); 10312 10313 // Fill in fields of the BitTestBlock. 10314 BTB->Parent = CurMBB; 10315 BTB->Default = Fallthrough; 10316 10317 BTB->DefaultProb = UnhandledProbs; 10318 // If the cases in bit test don't form a contiguous range, we evenly 10319 // distribute the probability on the edge to Fallthrough to two 10320 // successors of CurMBB. 10321 if (!BTB->ContiguousRange) { 10322 BTB->Prob += DefaultProb / 2; 10323 BTB->DefaultProb -= DefaultProb / 2; 10324 } 10325 10326 if (FallthroughUnreachable) { 10327 // Skip the range check if the fallthrough block is unreachable. 10328 BTB->OmitRangeCheck = true; 10329 } 10330 10331 // If we're in the right place, emit the bit test header right now. 10332 if (CurMBB == SwitchMBB) { 10333 visitBitTestHeader(*BTB, SwitchMBB); 10334 BTB->Emitted = true; 10335 } 10336 break; 10337 } 10338 case CC_Range: { 10339 const Value *RHS, *LHS, *MHS; 10340 ISD::CondCode CC; 10341 if (I->Low == I->High) { 10342 // Check Cond == I->Low. 10343 CC = ISD::SETEQ; 10344 LHS = Cond; 10345 RHS=I->Low; 10346 MHS = nullptr; 10347 } else { 10348 // Check I->Low <= Cond <= I->High. 10349 CC = ISD::SETLE; 10350 LHS = I->Low; 10351 MHS = Cond; 10352 RHS = I->High; 10353 } 10354 10355 // If Fallthrough is unreachable, fold away the comparison. 10356 if (FallthroughUnreachable) 10357 CC = ISD::SETTRUE; 10358 10359 // The false probability is the sum of all unhandled cases. 10360 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10361 getCurSDLoc(), I->Prob, UnhandledProbs); 10362 10363 if (CurMBB == SwitchMBB) 10364 visitSwitchCase(CB, SwitchMBB); 10365 else 10366 SL->SwitchCases.push_back(CB); 10367 10368 break; 10369 } 10370 } 10371 CurMBB = Fallthrough; 10372 } 10373 } 10374 10375 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10376 CaseClusterIt First, 10377 CaseClusterIt Last) { 10378 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10379 if (X.Prob != CC.Prob) 10380 return X.Prob > CC.Prob; 10381 10382 // Ties are broken by comparing the case value. 10383 return X.Low->getValue().slt(CC.Low->getValue()); 10384 }); 10385 } 10386 10387 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10388 const SwitchWorkListItem &W, 10389 Value *Cond, 10390 MachineBasicBlock *SwitchMBB) { 10391 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10392 "Clusters not sorted?"); 10393 10394 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10395 10396 // Balance the tree based on branch probabilities to create a near-optimal (in 10397 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10398 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10399 CaseClusterIt LastLeft = W.FirstCluster; 10400 CaseClusterIt FirstRight = W.LastCluster; 10401 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10402 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10403 10404 // Move LastLeft and FirstRight towards each other from opposite directions to 10405 // find a partitioning of the clusters which balances the probability on both 10406 // sides. If LeftProb and RightProb are equal, alternate which side is 10407 // taken to ensure 0-probability nodes are distributed evenly. 10408 unsigned I = 0; 10409 while (LastLeft + 1 < FirstRight) { 10410 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10411 LeftProb += (++LastLeft)->Prob; 10412 else 10413 RightProb += (--FirstRight)->Prob; 10414 I++; 10415 } 10416 10417 while (true) { 10418 // Our binary search tree differs from a typical BST in that ours can have up 10419 // to three values in each leaf. The pivot selection above doesn't take that 10420 // into account, which means the tree might require more nodes and be less 10421 // efficient. We compensate for this here. 10422 10423 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10424 unsigned NumRight = W.LastCluster - FirstRight + 1; 10425 10426 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10427 // If one side has less than 3 clusters, and the other has more than 3, 10428 // consider taking a cluster from the other side. 10429 10430 if (NumLeft < NumRight) { 10431 // Consider moving the first cluster on the right to the left side. 10432 CaseCluster &CC = *FirstRight; 10433 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10434 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10435 if (LeftSideRank <= RightSideRank) { 10436 // Moving the cluster to the left does not demote it. 10437 ++LastLeft; 10438 ++FirstRight; 10439 continue; 10440 } 10441 } else { 10442 assert(NumRight < NumLeft); 10443 // Consider moving the last element on the left to the right side. 10444 CaseCluster &CC = *LastLeft; 10445 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10446 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10447 if (RightSideRank <= LeftSideRank) { 10448 // Moving the cluster to the right does not demot it. 10449 --LastLeft; 10450 --FirstRight; 10451 continue; 10452 } 10453 } 10454 } 10455 break; 10456 } 10457 10458 assert(LastLeft + 1 == FirstRight); 10459 assert(LastLeft >= W.FirstCluster); 10460 assert(FirstRight <= W.LastCluster); 10461 10462 // Use the first element on the right as pivot since we will make less-than 10463 // comparisons against it. 10464 CaseClusterIt PivotCluster = FirstRight; 10465 assert(PivotCluster > W.FirstCluster); 10466 assert(PivotCluster <= W.LastCluster); 10467 10468 CaseClusterIt FirstLeft = W.FirstCluster; 10469 CaseClusterIt LastRight = W.LastCluster; 10470 10471 const ConstantInt *Pivot = PivotCluster->Low; 10472 10473 // New blocks will be inserted immediately after the current one. 10474 MachineFunction::iterator BBI(W.MBB); 10475 ++BBI; 10476 10477 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10478 // we can branch to its destination directly if it's squeezed exactly in 10479 // between the known lower bound and Pivot - 1. 10480 MachineBasicBlock *LeftMBB; 10481 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10482 FirstLeft->Low == W.GE && 10483 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10484 LeftMBB = FirstLeft->MBB; 10485 } else { 10486 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10487 FuncInfo.MF->insert(BBI, LeftMBB); 10488 WorkList.push_back( 10489 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10490 // Put Cond in a virtual register to make it available from the new blocks. 10491 ExportFromCurrentBlock(Cond); 10492 } 10493 10494 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10495 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10496 // directly if RHS.High equals the current upper bound. 10497 MachineBasicBlock *RightMBB; 10498 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10499 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10500 RightMBB = FirstRight->MBB; 10501 } else { 10502 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10503 FuncInfo.MF->insert(BBI, RightMBB); 10504 WorkList.push_back( 10505 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10506 // Put Cond in a virtual register to make it available from the new blocks. 10507 ExportFromCurrentBlock(Cond); 10508 } 10509 10510 // Create the CaseBlock record that will be used to lower the branch. 10511 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10512 getCurSDLoc(), LeftProb, RightProb); 10513 10514 if (W.MBB == SwitchMBB) 10515 visitSwitchCase(CB, SwitchMBB); 10516 else 10517 SL->SwitchCases.push_back(CB); 10518 } 10519 10520 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10521 // from the swith statement. 10522 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10523 BranchProbability PeeledCaseProb) { 10524 if (PeeledCaseProb == BranchProbability::getOne()) 10525 return BranchProbability::getZero(); 10526 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10527 10528 uint32_t Numerator = CaseProb.getNumerator(); 10529 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10530 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10531 } 10532 10533 // Try to peel the top probability case if it exceeds the threshold. 10534 // Return current MachineBasicBlock for the switch statement if the peeling 10535 // does not occur. 10536 // If the peeling is performed, return the newly created MachineBasicBlock 10537 // for the peeled switch statement. Also update Clusters to remove the peeled 10538 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10539 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10540 const SwitchInst &SI, CaseClusterVector &Clusters, 10541 BranchProbability &PeeledCaseProb) { 10542 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10543 // Don't perform if there is only one cluster or optimizing for size. 10544 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10545 TM.getOptLevel() == CodeGenOpt::None || 10546 SwitchMBB->getParent()->getFunction().hasMinSize()) 10547 return SwitchMBB; 10548 10549 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10550 unsigned PeeledCaseIndex = 0; 10551 bool SwitchPeeled = false; 10552 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10553 CaseCluster &CC = Clusters[Index]; 10554 if (CC.Prob < TopCaseProb) 10555 continue; 10556 TopCaseProb = CC.Prob; 10557 PeeledCaseIndex = Index; 10558 SwitchPeeled = true; 10559 } 10560 if (!SwitchPeeled) 10561 return SwitchMBB; 10562 10563 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10564 << TopCaseProb << "\n"); 10565 10566 // Record the MBB for the peeled switch statement. 10567 MachineFunction::iterator BBI(SwitchMBB); 10568 ++BBI; 10569 MachineBasicBlock *PeeledSwitchMBB = 10570 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10571 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10572 10573 ExportFromCurrentBlock(SI.getCondition()); 10574 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10575 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10576 nullptr, nullptr, TopCaseProb.getCompl()}; 10577 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10578 10579 Clusters.erase(PeeledCaseIt); 10580 for (CaseCluster &CC : Clusters) { 10581 LLVM_DEBUG( 10582 dbgs() << "Scale the probablity for one cluster, before scaling: " 10583 << CC.Prob << "\n"); 10584 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10585 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10586 } 10587 PeeledCaseProb = TopCaseProb; 10588 return PeeledSwitchMBB; 10589 } 10590 10591 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10592 // Extract cases from the switch. 10593 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10594 CaseClusterVector Clusters; 10595 Clusters.reserve(SI.getNumCases()); 10596 for (auto I : SI.cases()) { 10597 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10598 const ConstantInt *CaseVal = I.getCaseValue(); 10599 BranchProbability Prob = 10600 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10601 : BranchProbability(1, SI.getNumCases() + 1); 10602 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10603 } 10604 10605 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10606 10607 // Cluster adjacent cases with the same destination. We do this at all 10608 // optimization levels because it's cheap to do and will make codegen faster 10609 // if there are many clusters. 10610 sortAndRangeify(Clusters); 10611 10612 // The branch probablity of the peeled case. 10613 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10614 MachineBasicBlock *PeeledSwitchMBB = 10615 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10616 10617 // If there is only the default destination, jump there directly. 10618 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10619 if (Clusters.empty()) { 10620 assert(PeeledSwitchMBB == SwitchMBB); 10621 SwitchMBB->addSuccessor(DefaultMBB); 10622 if (DefaultMBB != NextBlock(SwitchMBB)) { 10623 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10624 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10625 } 10626 return; 10627 } 10628 10629 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10630 SL->findBitTestClusters(Clusters, &SI); 10631 10632 LLVM_DEBUG({ 10633 dbgs() << "Case clusters: "; 10634 for (const CaseCluster &C : Clusters) { 10635 if (C.Kind == CC_JumpTable) 10636 dbgs() << "JT:"; 10637 if (C.Kind == CC_BitTests) 10638 dbgs() << "BT:"; 10639 10640 C.Low->getValue().print(dbgs(), true); 10641 if (C.Low != C.High) { 10642 dbgs() << '-'; 10643 C.High->getValue().print(dbgs(), true); 10644 } 10645 dbgs() << ' '; 10646 } 10647 dbgs() << '\n'; 10648 }); 10649 10650 assert(!Clusters.empty()); 10651 SwitchWorkList WorkList; 10652 CaseClusterIt First = Clusters.begin(); 10653 CaseClusterIt Last = Clusters.end() - 1; 10654 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10655 // Scale the branchprobability for DefaultMBB if the peel occurs and 10656 // DefaultMBB is not replaced. 10657 if (PeeledCaseProb != BranchProbability::getZero() && 10658 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10659 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10660 WorkList.push_back( 10661 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10662 10663 while (!WorkList.empty()) { 10664 SwitchWorkListItem W = WorkList.back(); 10665 WorkList.pop_back(); 10666 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10667 10668 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10669 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10670 // For optimized builds, lower large range as a balanced binary tree. 10671 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10672 continue; 10673 } 10674 10675 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10676 } 10677 } 10678 10679 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10680 SmallVector<EVT, 4> ValueVTs; 10681 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10682 ValueVTs); 10683 unsigned NumValues = ValueVTs.size(); 10684 if (NumValues == 0) return; 10685 10686 SmallVector<SDValue, 4> Values(NumValues); 10687 SDValue Op = getValue(I.getOperand(0)); 10688 10689 for (unsigned i = 0; i != NumValues; ++i) 10690 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10691 SDValue(Op.getNode(), Op.getResNo() + i)); 10692 10693 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10694 DAG.getVTList(ValueVTs), Values)); 10695 } 10696