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/BitVector.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/StringRef.h" 24 #include "llvm/ADT/Triple.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/BlockFrequencyInfo.h" 27 #include "llvm/Analysis/BranchProbabilityInfo.h" 28 #include "llvm/Analysis/ConstantFolding.h" 29 #include "llvm/Analysis/EHPersonalities.h" 30 #include "llvm/Analysis/Loads.h" 31 #include "llvm/Analysis/MemoryLocation.h" 32 #include "llvm/Analysis/ProfileSummaryInfo.h" 33 #include "llvm/Analysis/TargetLibraryInfo.h" 34 #include "llvm/Analysis/ValueTracking.h" 35 #include "llvm/Analysis/VectorUtils.h" 36 #include "llvm/CodeGen/Analysis.h" 37 #include "llvm/CodeGen/FunctionLoweringInfo.h" 38 #include "llvm/CodeGen/GCMetadata.h" 39 #include "llvm/CodeGen/MachineBasicBlock.h" 40 #include "llvm/CodeGen/MachineFrameInfo.h" 41 #include "llvm/CodeGen/MachineFunction.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineMemOperand.h" 46 #include "llvm/CodeGen/MachineModuleInfo.h" 47 #include "llvm/CodeGen/MachineOperand.h" 48 #include "llvm/CodeGen/MachineRegisterInfo.h" 49 #include "llvm/CodeGen/RuntimeLibcalls.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 52 #include "llvm/CodeGen/StackMaps.h" 53 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 54 #include "llvm/CodeGen/TargetFrameLowering.h" 55 #include "llvm/CodeGen/TargetInstrInfo.h" 56 #include "llvm/CodeGen/TargetOpcodes.h" 57 #include "llvm/CodeGen/TargetRegisterInfo.h" 58 #include "llvm/CodeGen/TargetSubtargetInfo.h" 59 #include "llvm/CodeGen/WinEHFuncInfo.h" 60 #include "llvm/IR/Argument.h" 61 #include "llvm/IR/Attributes.h" 62 #include "llvm/IR/BasicBlock.h" 63 #include "llvm/IR/CFG.h" 64 #include "llvm/IR/CallingConv.h" 65 #include "llvm/IR/Constant.h" 66 #include "llvm/IR/ConstantRange.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DebugInfoMetadata.h" 70 #include "llvm/IR/DerivedTypes.h" 71 #include "llvm/IR/Function.h" 72 #include "llvm/IR/GetElementPtrTypeIterator.h" 73 #include "llvm/IR/InlineAsm.h" 74 #include "llvm/IR/InstrTypes.h" 75 #include "llvm/IR/Instructions.h" 76 #include "llvm/IR/IntrinsicInst.h" 77 #include "llvm/IR/Intrinsics.h" 78 #include "llvm/IR/IntrinsicsAArch64.h" 79 #include "llvm/IR/IntrinsicsWebAssembly.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/Metadata.h" 82 #include "llvm/IR/Module.h" 83 #include "llvm/IR/Operator.h" 84 #include "llvm/IR/PatternMatch.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/User.h" 87 #include "llvm/IR/Value.h" 88 #include "llvm/MC/MCContext.h" 89 #include "llvm/MC/MCSymbol.h" 90 #include "llvm/Support/AtomicOrdering.h" 91 #include "llvm/Support/Casting.h" 92 #include "llvm/Support/CommandLine.h" 93 #include "llvm/Support/Compiler.h" 94 #include "llvm/Support/Debug.h" 95 #include "llvm/Support/MathExtras.h" 96 #include "llvm/Support/raw_ostream.h" 97 #include "llvm/Target/TargetIntrinsicInfo.h" 98 #include "llvm/Target/TargetMachine.h" 99 #include "llvm/Target/TargetOptions.h" 100 #include "llvm/Transforms/Utils/Local.h" 101 #include <cstddef> 102 #include <cstring> 103 #include <iterator> 104 #include <limits> 105 #include <numeric> 106 #include <tuple> 107 108 using namespace llvm; 109 using namespace PatternMatch; 110 using namespace SwitchCG; 111 112 #define DEBUG_TYPE "isel" 113 114 /// LimitFloatPrecision - Generate low-precision inline sequences for 115 /// some float libcalls (6, 8 or 12 bits). 116 static unsigned LimitFloatPrecision; 117 118 static cl::opt<bool> 119 InsertAssertAlign("insert-assert-align", cl::init(true), 120 cl::desc("Insert the experimental `assertalign` node."), 121 cl::ReallyHidden); 122 123 static cl::opt<unsigned, true> 124 LimitFPPrecision("limit-float-precision", 125 cl::desc("Generate low-precision inline sequences " 126 "for some float libcalls"), 127 cl::location(LimitFloatPrecision), cl::Hidden, 128 cl::init(0)); 129 130 static cl::opt<unsigned> SwitchPeelThreshold( 131 "switch-peel-threshold", cl::Hidden, cl::init(66), 132 cl::desc("Set the case probability threshold for peeling the case from a " 133 "switch statement. A value greater than 100 will void this " 134 "optimization")); 135 136 // Limit the width of DAG chains. This is important in general to prevent 137 // DAG-based analysis from blowing up. For example, alias analysis and 138 // load clustering may not complete in reasonable time. It is difficult to 139 // recognize and avoid this situation within each individual analysis, and 140 // future analyses are likely to have the same behavior. Limiting DAG width is 141 // the safe approach and will be especially important with global DAGs. 142 // 143 // MaxParallelChains default is arbitrarily high to avoid affecting 144 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 145 // sequence over this should have been converted to llvm.memcpy by the 146 // frontend. It is easy to induce this behavior with .ll code such as: 147 // %buffer = alloca [4096 x i8] 148 // %data = load [4096 x i8]* %argPtr 149 // store [4096 x i8] %data, [4096 x i8]* %buffer 150 static const unsigned MaxParallelChains = 64; 151 152 // Return the calling convention if the Value passed requires ABI mangling as it 153 // is a parameter to a function or a return value from a function which is not 154 // an intrinsic. 155 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 156 if (auto *R = dyn_cast<ReturnInst>(V)) 157 return R->getParent()->getParent()->getCallingConv(); 158 159 if (auto *CI = dyn_cast<CallInst>(V)) { 160 const bool IsInlineAsm = CI->isInlineAsm(); 161 const bool IsIndirectFunctionCall = 162 !IsInlineAsm && !CI->getCalledFunction(); 163 164 // It is possible that the call instruction is an inline asm statement or an 165 // indirect function call in which case the return value of 166 // getCalledFunction() would be nullptr. 167 const bool IsInstrinsicCall = 168 !IsInlineAsm && !IsIndirectFunctionCall && 169 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 170 171 if (!IsInlineAsm && !IsInstrinsicCall) 172 return CI->getCallingConv(); 173 } 174 175 return None; 176 } 177 178 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 179 const SDValue *Parts, unsigned NumParts, 180 MVT PartVT, EVT ValueVT, const Value *V, 181 Optional<CallingConv::ID> CC); 182 183 /// getCopyFromParts - Create a value that contains the specified legal parts 184 /// combined into the value they represent. If the parts combine to a type 185 /// larger than ValueVT then AssertOp can be used to specify whether the extra 186 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 187 /// (ISD::AssertSext). 188 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 189 const SDValue *Parts, unsigned NumParts, 190 MVT PartVT, EVT ValueVT, const Value *V, 191 Optional<CallingConv::ID> CC = None, 192 Optional<ISD::NodeType> AssertOp = None) { 193 // Let the target assemble the parts if it wants to 194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 195 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 196 PartVT, ValueVT, CC)) 197 return Val; 198 199 if (ValueVT.isVector()) 200 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 201 CC); 202 203 assert(NumParts > 0 && "No parts to assemble!"); 204 SDValue Val = Parts[0]; 205 206 if (NumParts > 1) { 207 // Assemble the value from multiple parts. 208 if (ValueVT.isInteger()) { 209 unsigned PartBits = PartVT.getSizeInBits(); 210 unsigned ValueBits = ValueVT.getSizeInBits(); 211 212 // Assemble the power of 2 part. 213 unsigned RoundParts = 214 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 215 unsigned RoundBits = PartBits * RoundParts; 216 EVT RoundVT = RoundBits == ValueBits ? 217 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 218 SDValue Lo, Hi; 219 220 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 221 222 if (RoundParts > 2) { 223 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 224 PartVT, HalfVT, V); 225 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 226 RoundParts / 2, PartVT, HalfVT, V); 227 } else { 228 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 229 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 230 } 231 232 if (DAG.getDataLayout().isBigEndian()) 233 std::swap(Lo, Hi); 234 235 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 236 237 if (RoundParts < NumParts) { 238 // Assemble the trailing non-power-of-2 part. 239 unsigned OddParts = NumParts - RoundParts; 240 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 241 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 242 OddVT, V, CC); 243 244 // Combine the round and odd parts. 245 Lo = Val; 246 if (DAG.getDataLayout().isBigEndian()) 247 std::swap(Lo, Hi); 248 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 249 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 250 Hi = 251 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 252 DAG.getConstant(Lo.getValueSizeInBits(), DL, 253 TLI.getPointerTy(DAG.getDataLayout()))); 254 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 255 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 256 } 257 } else if (PartVT.isFloatingPoint()) { 258 // FP split into multiple FP parts (for ppcf128) 259 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 260 "Unexpected split"); 261 SDValue Lo, Hi; 262 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 263 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 264 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 265 std::swap(Lo, Hi); 266 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 267 } else { 268 // FP split into integer parts (soft fp) 269 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 270 !PartVT.isVector() && "Unexpected split"); 271 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 272 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 273 } 274 } 275 276 // There is now one part, held in Val. Correct it to match ValueVT. 277 // PartEVT is the type of the register class that holds the value. 278 // ValueVT is the type of the inline asm operation. 279 EVT PartEVT = Val.getValueType(); 280 281 if (PartEVT == ValueVT) 282 return Val; 283 284 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 285 ValueVT.bitsLT(PartEVT)) { 286 // For an FP value in an integer part, we need to truncate to the right 287 // width first. 288 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 289 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 290 } 291 292 // Handle types that have the same size. 293 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 294 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 295 296 // Handle types with different sizes. 297 if (PartEVT.isInteger() && ValueVT.isInteger()) { 298 if (ValueVT.bitsLT(PartEVT)) { 299 // For a truncate, see if we have any information to 300 // indicate whether the truncated bits will always be 301 // zero or sign-extension. 302 if (AssertOp.hasValue()) 303 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 304 DAG.getValueType(ValueVT)); 305 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 306 } 307 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 308 } 309 310 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 311 // FP_ROUND's are always exact here. 312 if (ValueVT.bitsLT(Val.getValueType())) 313 return DAG.getNode( 314 ISD::FP_ROUND, DL, ValueVT, Val, 315 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 316 317 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 318 } 319 320 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 321 // then truncating. 322 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 323 ValueVT.bitsLT(PartEVT)) { 324 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 325 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 326 } 327 328 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 329 } 330 331 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 332 const Twine &ErrMsg) { 333 const Instruction *I = dyn_cast_or_null<Instruction>(V); 334 if (!V) 335 return Ctx.emitError(ErrMsg); 336 337 const char *AsmError = ", possible invalid constraint for vector type"; 338 if (const CallInst *CI = dyn_cast<CallInst>(I)) 339 if (CI->isInlineAsm()) 340 return Ctx.emitError(I, ErrMsg + AsmError); 341 342 return Ctx.emitError(I, ErrMsg); 343 } 344 345 /// getCopyFromPartsVector - Create a value that contains the specified legal 346 /// parts combined into the value they represent. If the parts combine to a 347 /// type larger than ValueVT then AssertOp can be used to specify whether the 348 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 349 /// ValueVT (ISD::AssertSext). 350 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 351 const SDValue *Parts, unsigned NumParts, 352 MVT PartVT, EVT ValueVT, const Value *V, 353 Optional<CallingConv::ID> CallConv) { 354 assert(ValueVT.isVector() && "Not a vector value"); 355 assert(NumParts > 0 && "No parts to assemble!"); 356 const bool IsABIRegCopy = CallConv.hasValue(); 357 358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 359 SDValue Val = Parts[0]; 360 361 // Handle a multi-element vector. 362 if (NumParts > 1) { 363 EVT IntermediateVT; 364 MVT RegisterVT; 365 unsigned NumIntermediates; 366 unsigned NumRegs; 367 368 if (IsABIRegCopy) { 369 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 370 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 371 NumIntermediates, RegisterVT); 372 } else { 373 NumRegs = 374 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 375 NumIntermediates, RegisterVT); 376 } 377 378 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 379 NumParts = NumRegs; // Silence a compiler warning. 380 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 381 assert(RegisterVT.getSizeInBits() == 382 Parts[0].getSimpleValueType().getSizeInBits() && 383 "Part type sizes don't match!"); 384 385 // Assemble the parts into intermediate operands. 386 SmallVector<SDValue, 8> Ops(NumIntermediates); 387 if (NumIntermediates == NumParts) { 388 // If the register was not expanded, truncate or copy the value, 389 // as appropriate. 390 for (unsigned i = 0; i != NumParts; ++i) 391 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 392 PartVT, IntermediateVT, V); 393 } else if (NumParts > 0) { 394 // If the intermediate type was expanded, build the intermediate 395 // operands from the parts. 396 assert(NumParts % NumIntermediates == 0 && 397 "Must expand into a divisible number of parts!"); 398 unsigned Factor = NumParts / NumIntermediates; 399 for (unsigned i = 0; i != NumIntermediates; ++i) 400 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 401 PartVT, IntermediateVT, V); 402 } 403 404 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 405 // intermediate operands. 406 EVT BuiltVectorTy = 407 IntermediateVT.isVector() 408 ? EVT::getVectorVT( 409 *DAG.getContext(), IntermediateVT.getScalarType(), 410 IntermediateVT.getVectorElementCount() * NumParts) 411 : EVT::getVectorVT(*DAG.getContext(), 412 IntermediateVT.getScalarType(), 413 NumIntermediates); 414 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 415 : ISD::BUILD_VECTOR, 416 DL, BuiltVectorTy, Ops); 417 } 418 419 // There is now one part, held in Val. Correct it to match ValueVT. 420 EVT PartEVT = Val.getValueType(); 421 422 if (PartEVT == ValueVT) 423 return Val; 424 425 if (PartEVT.isVector()) { 426 // If the element type of the source/dest vectors are the same, but the 427 // parts vector has more elements than the value vector, then we have a 428 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 429 // elements we want. 430 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 431 assert((PartEVT.getVectorElementCount().Min > 432 ValueVT.getVectorElementCount().Min) && 433 (PartEVT.getVectorElementCount().Scalable == 434 ValueVT.getVectorElementCount().Scalable) && 435 "Cannot narrow, it would be a lossy transformation"); 436 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 437 DAG.getVectorIdxConstant(0, DL)); 438 } 439 440 // Vector/Vector bitcast. 441 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 442 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 443 444 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 445 "Cannot handle this kind of promotion"); 446 // Promoted vector extract 447 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 448 449 } 450 451 // Trivial bitcast if the types are the same size and the destination 452 // vector type is legal. 453 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 454 TLI.isTypeLegal(ValueVT)) 455 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 456 457 if (ValueVT.getVectorNumElements() != 1) { 458 // Certain ABIs require that vectors are passed as integers. For vectors 459 // are the same size, this is an obvious bitcast. 460 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 461 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 462 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 463 // Bitcast Val back the original type and extract the corresponding 464 // vector we want. 465 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 466 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 467 ValueVT.getVectorElementType(), Elts); 468 Val = DAG.getBitcast(WiderVecType, Val); 469 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 470 DAG.getVectorIdxConstant(0, DL)); 471 } 472 473 diagnosePossiblyInvalidConstraint( 474 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 475 return DAG.getUNDEF(ValueVT); 476 } 477 478 // Handle cases such as i8 -> <1 x i1> 479 EVT ValueSVT = ValueVT.getVectorElementType(); 480 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 481 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 482 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 483 else 484 Val = ValueVT.isFloatingPoint() 485 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 486 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 487 } 488 489 return DAG.getBuildVector(ValueVT, DL, Val); 490 } 491 492 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 493 SDValue Val, SDValue *Parts, unsigned NumParts, 494 MVT PartVT, const Value *V, 495 Optional<CallingConv::ID> CallConv); 496 497 /// getCopyToParts - Create a series of nodes that contain the specified value 498 /// split into legal parts. If the parts contain more bits than Val, then, for 499 /// integers, ExtendKind can be used to specify how to generate the extra bits. 500 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 501 SDValue *Parts, unsigned NumParts, MVT PartVT, 502 const Value *V, 503 Optional<CallingConv::ID> CallConv = None, 504 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 505 // Let the target split the parts if it wants to 506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 507 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 508 CallConv)) 509 return; 510 EVT ValueVT = Val.getValueType(); 511 512 // Handle the vector case separately. 513 if (ValueVT.isVector()) 514 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 515 CallConv); 516 517 unsigned PartBits = PartVT.getSizeInBits(); 518 unsigned OrigNumParts = NumParts; 519 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 520 "Copying to an illegal type!"); 521 522 if (NumParts == 0) 523 return; 524 525 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 526 EVT PartEVT = PartVT; 527 if (PartEVT == ValueVT) { 528 assert(NumParts == 1 && "No-op copy with multiple parts!"); 529 Parts[0] = Val; 530 return; 531 } 532 533 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 534 // If the parts cover more bits than the value has, promote the value. 535 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 536 assert(NumParts == 1 && "Do not know what to promote to!"); 537 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 538 } else { 539 if (ValueVT.isFloatingPoint()) { 540 // FP values need to be bitcast, then extended if they are being put 541 // into a larger container. 542 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 543 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 544 } 545 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 546 ValueVT.isInteger() && 547 "Unknown mismatch!"); 548 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 549 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 550 if (PartVT == MVT::x86mmx) 551 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 552 } 553 } else if (PartBits == ValueVT.getSizeInBits()) { 554 // Different types of the same size. 555 assert(NumParts == 1 && PartEVT != ValueVT); 556 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 557 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 558 // If the parts cover less bits than value has, truncate the value. 559 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 560 ValueVT.isInteger() && 561 "Unknown mismatch!"); 562 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 563 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 564 if (PartVT == MVT::x86mmx) 565 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 566 } 567 568 // The value may have changed - recompute ValueVT. 569 ValueVT = Val.getValueType(); 570 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 571 "Failed to tile the value with PartVT!"); 572 573 if (NumParts == 1) { 574 if (PartEVT != ValueVT) { 575 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 576 "scalar-to-vector conversion failed"); 577 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 578 } 579 580 Parts[0] = Val; 581 return; 582 } 583 584 // Expand the value into multiple parts. 585 if (NumParts & (NumParts - 1)) { 586 // The number of parts is not a power of 2. Split off and copy the tail. 587 assert(PartVT.isInteger() && ValueVT.isInteger() && 588 "Do not know what to expand to!"); 589 unsigned RoundParts = 1 << Log2_32(NumParts); 590 unsigned RoundBits = RoundParts * PartBits; 591 unsigned OddParts = NumParts - RoundParts; 592 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 593 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 594 595 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 596 CallConv); 597 598 if (DAG.getDataLayout().isBigEndian()) 599 // The odd parts were reversed by getCopyToParts - unreverse them. 600 std::reverse(Parts + RoundParts, Parts + NumParts); 601 602 NumParts = RoundParts; 603 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 604 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 605 } 606 607 // The number of parts is a power of 2. Repeatedly bisect the value using 608 // EXTRACT_ELEMENT. 609 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 610 EVT::getIntegerVT(*DAG.getContext(), 611 ValueVT.getSizeInBits()), 612 Val); 613 614 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 615 for (unsigned i = 0; i < NumParts; i += StepSize) { 616 unsigned ThisBits = StepSize * PartBits / 2; 617 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 618 SDValue &Part0 = Parts[i]; 619 SDValue &Part1 = Parts[i+StepSize/2]; 620 621 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 622 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 623 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 625 626 if (ThisBits == PartBits && ThisVT != PartVT) { 627 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 628 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 629 } 630 } 631 } 632 633 if (DAG.getDataLayout().isBigEndian()) 634 std::reverse(Parts, Parts + OrigNumParts); 635 } 636 637 static SDValue widenVectorToPartType(SelectionDAG &DAG, 638 SDValue Val, const SDLoc &DL, EVT PartVT) { 639 if (!PartVT.isFixedLengthVector()) 640 return SDValue(); 641 642 EVT ValueVT = Val.getValueType(); 643 unsigned PartNumElts = PartVT.getVectorNumElements(); 644 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 645 if (PartNumElts > ValueNumElts && 646 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 647 EVT ElementVT = PartVT.getVectorElementType(); 648 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 649 // undef elements. 650 SmallVector<SDValue, 16> Ops; 651 DAG.ExtractVectorElements(Val, Ops); 652 SDValue EltUndef = DAG.getUNDEF(ElementVT); 653 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 654 Ops.push_back(EltUndef); 655 656 // FIXME: Use CONCAT for 2x -> 4x. 657 return DAG.getBuildVector(PartVT, DL, Ops); 658 } 659 660 return SDValue(); 661 } 662 663 /// getCopyToPartsVector - Create a series of nodes that contain the specified 664 /// value split into legal parts. 665 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 666 SDValue Val, SDValue *Parts, unsigned NumParts, 667 MVT PartVT, const Value *V, 668 Optional<CallingConv::ID> CallConv) { 669 EVT ValueVT = Val.getValueType(); 670 assert(ValueVT.isVector() && "Not a vector"); 671 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 672 const bool IsABIRegCopy = CallConv.hasValue(); 673 674 if (NumParts == 1) { 675 EVT PartEVT = PartVT; 676 if (PartEVT == ValueVT) { 677 // Nothing to do. 678 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 679 // Bitconvert vector->vector case. 680 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 681 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 682 Val = Widened; 683 } else if (PartVT.isVector() && 684 PartEVT.getVectorElementType().bitsGE( 685 ValueVT.getVectorElementType()) && 686 PartEVT.getVectorElementCount() == 687 ValueVT.getVectorElementCount()) { 688 689 // Promoted vector extract 690 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 691 } else { 692 if (ValueVT.getVectorNumElements() == 1) { 693 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 694 DAG.getVectorIdxConstant(0, DL)); 695 } else { 696 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 697 "lossy conversion of vector to scalar type"); 698 EVT IntermediateType = 699 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 700 Val = DAG.getBitcast(IntermediateType, Val); 701 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 702 } 703 } 704 705 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 706 Parts[0] = Val; 707 return; 708 } 709 710 // Handle a multi-element vector. 711 EVT IntermediateVT; 712 MVT RegisterVT; 713 unsigned NumIntermediates; 714 unsigned NumRegs; 715 if (IsABIRegCopy) { 716 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 717 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 718 NumIntermediates, RegisterVT); 719 } else { 720 NumRegs = 721 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 722 NumIntermediates, RegisterVT); 723 } 724 725 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 726 NumParts = NumRegs; // Silence a compiler warning. 727 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 728 729 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 730 "Mixing scalable and fixed vectors when copying in parts"); 731 732 ElementCount DestEltCnt; 733 734 if (IntermediateVT.isVector()) 735 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 736 else 737 DestEltCnt = ElementCount(NumIntermediates, false); 738 739 EVT BuiltVectorTy = EVT::getVectorVT( 740 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt); 741 if (ValueVT != BuiltVectorTy) { 742 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 743 Val = Widened; 744 745 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 746 } 747 748 // Split the vector into intermediate operands. 749 SmallVector<SDValue, 8> Ops(NumIntermediates); 750 for (unsigned i = 0; i != NumIntermediates; ++i) { 751 if (IntermediateVT.isVector()) { 752 // This does something sensible for scalable vectors - see the 753 // definition of EXTRACT_SUBVECTOR for further details. 754 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 755 Ops[i] = 756 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 757 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 758 } else { 759 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 760 DAG.getVectorIdxConstant(i, DL)); 761 } 762 } 763 764 // Split the intermediate operands into legal parts. 765 if (NumParts == NumIntermediates) { 766 // If the register was not expanded, promote or copy the value, 767 // as appropriate. 768 for (unsigned i = 0; i != NumParts; ++i) 769 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 770 } else if (NumParts > 0) { 771 // If the intermediate type was expanded, split each the value into 772 // legal parts. 773 assert(NumIntermediates != 0 && "division by zero"); 774 assert(NumParts % NumIntermediates == 0 && 775 "Must expand into a divisible number of parts!"); 776 unsigned Factor = NumParts / NumIntermediates; 777 for (unsigned i = 0; i != NumIntermediates; ++i) 778 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 779 CallConv); 780 } 781 } 782 783 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 784 EVT valuevt, Optional<CallingConv::ID> CC) 785 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 786 RegCount(1, regs.size()), CallConv(CC) {} 787 788 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 789 const DataLayout &DL, unsigned Reg, Type *Ty, 790 Optional<CallingConv::ID> CC) { 791 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 792 793 CallConv = CC; 794 795 for (EVT ValueVT : ValueVTs) { 796 unsigned NumRegs = 797 isABIMangled() 798 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 799 : TLI.getNumRegisters(Context, ValueVT); 800 MVT RegisterVT = 801 isABIMangled() 802 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 803 : TLI.getRegisterType(Context, ValueVT); 804 for (unsigned i = 0; i != NumRegs; ++i) 805 Regs.push_back(Reg + i); 806 RegVTs.push_back(RegisterVT); 807 RegCount.push_back(NumRegs); 808 Reg += NumRegs; 809 } 810 } 811 812 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 813 FunctionLoweringInfo &FuncInfo, 814 const SDLoc &dl, SDValue &Chain, 815 SDValue *Flag, const Value *V) const { 816 // A Value with type {} or [0 x %t] needs no registers. 817 if (ValueVTs.empty()) 818 return SDValue(); 819 820 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 821 822 // Assemble the legal parts into the final values. 823 SmallVector<SDValue, 4> Values(ValueVTs.size()); 824 SmallVector<SDValue, 8> Parts; 825 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 826 // Copy the legal parts from the registers. 827 EVT ValueVT = ValueVTs[Value]; 828 unsigned NumRegs = RegCount[Value]; 829 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 830 *DAG.getContext(), 831 CallConv.getValue(), RegVTs[Value]) 832 : RegVTs[Value]; 833 834 Parts.resize(NumRegs); 835 for (unsigned i = 0; i != NumRegs; ++i) { 836 SDValue P; 837 if (!Flag) { 838 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 839 } else { 840 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 841 *Flag = P.getValue(2); 842 } 843 844 Chain = P.getValue(1); 845 Parts[i] = P; 846 847 // If the source register was virtual and if we know something about it, 848 // add an assert node. 849 if (!Register::isVirtualRegister(Regs[Part + i]) || 850 !RegisterVT.isInteger()) 851 continue; 852 853 const FunctionLoweringInfo::LiveOutInfo *LOI = 854 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 855 if (!LOI) 856 continue; 857 858 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 859 unsigned NumSignBits = LOI->NumSignBits; 860 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 861 862 if (NumZeroBits == RegSize) { 863 // The current value is a zero. 864 // Explicitly express that as it would be easier for 865 // optimizations to kick in. 866 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 867 continue; 868 } 869 870 // FIXME: We capture more information than the dag can represent. For 871 // now, just use the tightest assertzext/assertsext possible. 872 bool isSExt; 873 EVT FromVT(MVT::Other); 874 if (NumZeroBits) { 875 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 876 isSExt = false; 877 } else if (NumSignBits > 1) { 878 FromVT = 879 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 880 isSExt = true; 881 } else { 882 continue; 883 } 884 // Add an assertion node. 885 assert(FromVT != MVT::Other); 886 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 887 RegisterVT, P, DAG.getValueType(FromVT)); 888 } 889 890 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 891 RegisterVT, ValueVT, V, CallConv); 892 Part += NumRegs; 893 Parts.clear(); 894 } 895 896 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 897 } 898 899 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 900 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 901 const Value *V, 902 ISD::NodeType PreferredExtendType) const { 903 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 904 ISD::NodeType ExtendKind = PreferredExtendType; 905 906 // Get the list of the values's legal parts. 907 unsigned NumRegs = Regs.size(); 908 SmallVector<SDValue, 8> Parts(NumRegs); 909 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 910 unsigned NumParts = RegCount[Value]; 911 912 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 913 *DAG.getContext(), 914 CallConv.getValue(), RegVTs[Value]) 915 : RegVTs[Value]; 916 917 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 918 ExtendKind = ISD::ZERO_EXTEND; 919 920 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 921 NumParts, RegisterVT, V, CallConv, ExtendKind); 922 Part += NumParts; 923 } 924 925 // Copy the parts into the registers. 926 SmallVector<SDValue, 8> Chains(NumRegs); 927 for (unsigned i = 0; i != NumRegs; ++i) { 928 SDValue Part; 929 if (!Flag) { 930 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 931 } else { 932 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 933 *Flag = Part.getValue(1); 934 } 935 936 Chains[i] = Part.getValue(0); 937 } 938 939 if (NumRegs == 1 || Flag) 940 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 941 // flagged to it. That is the CopyToReg nodes and the user are considered 942 // a single scheduling unit. If we create a TokenFactor and return it as 943 // chain, then the TokenFactor is both a predecessor (operand) of the 944 // user as well as a successor (the TF operands are flagged to the user). 945 // c1, f1 = CopyToReg 946 // c2, f2 = CopyToReg 947 // c3 = TokenFactor c1, c2 948 // ... 949 // = op c3, ..., f2 950 Chain = Chains[NumRegs-1]; 951 else 952 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 953 } 954 955 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 956 unsigned MatchingIdx, const SDLoc &dl, 957 SelectionDAG &DAG, 958 std::vector<SDValue> &Ops) const { 959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 960 961 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 962 if (HasMatching) 963 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 964 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 965 // Put the register class of the virtual registers in the flag word. That 966 // way, later passes can recompute register class constraints for inline 967 // assembly as well as normal instructions. 968 // Don't do this for tied operands that can use the regclass information 969 // from the def. 970 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 971 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 972 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 973 } 974 975 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 976 Ops.push_back(Res); 977 978 if (Code == InlineAsm::Kind_Clobber) { 979 // Clobbers should always have a 1:1 mapping with registers, and may 980 // reference registers that have illegal (e.g. vector) types. Hence, we 981 // shouldn't try to apply any sort of splitting logic to them. 982 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 983 "No 1:1 mapping from clobbers to regs?"); 984 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 985 (void)SP; 986 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 987 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 988 assert( 989 (Regs[I] != SP || 990 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 991 "If we clobbered the stack pointer, MFI should know about it."); 992 } 993 return; 994 } 995 996 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 997 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 998 MVT RegisterVT = RegVTs[Value]; 999 for (unsigned i = 0; i != NumRegs; ++i) { 1000 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1001 unsigned TheReg = Regs[Reg++]; 1002 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1003 } 1004 } 1005 } 1006 1007 SmallVector<std::pair<unsigned, unsigned>, 4> 1008 RegsForValue::getRegsAndSizes() const { 1009 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1010 unsigned I = 0; 1011 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1012 unsigned RegCount = std::get<0>(CountAndVT); 1013 MVT RegisterVT = std::get<1>(CountAndVT); 1014 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1015 for (unsigned E = I + RegCount; I != E; ++I) 1016 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1017 } 1018 return OutVec; 1019 } 1020 1021 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1022 const TargetLibraryInfo *li) { 1023 AA = aa; 1024 GFI = gfi; 1025 LibInfo = li; 1026 DL = &DAG.getDataLayout(); 1027 Context = DAG.getContext(); 1028 LPadToCallSiteMap.clear(); 1029 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1030 } 1031 1032 void SelectionDAGBuilder::clear() { 1033 NodeMap.clear(); 1034 UnusedArgNodeMap.clear(); 1035 PendingLoads.clear(); 1036 PendingExports.clear(); 1037 PendingConstrainedFP.clear(); 1038 PendingConstrainedFPStrict.clear(); 1039 CurInst = nullptr; 1040 HasTailCall = false; 1041 SDNodeOrder = LowestSDNodeOrder; 1042 StatepointLowering.clear(); 1043 } 1044 1045 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1046 DanglingDebugInfoMap.clear(); 1047 } 1048 1049 // Update DAG root to include dependencies on Pending chains. 1050 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1051 SDValue Root = DAG.getRoot(); 1052 1053 if (Pending.empty()) 1054 return Root; 1055 1056 // Add current root to PendingChains, unless we already indirectly 1057 // depend on it. 1058 if (Root.getOpcode() != ISD::EntryToken) { 1059 unsigned i = 0, e = Pending.size(); 1060 for (; i != e; ++i) { 1061 assert(Pending[i].getNode()->getNumOperands() > 1); 1062 if (Pending[i].getNode()->getOperand(0) == Root) 1063 break; // Don't add the root if we already indirectly depend on it. 1064 } 1065 1066 if (i == e) 1067 Pending.push_back(Root); 1068 } 1069 1070 if (Pending.size() == 1) 1071 Root = Pending[0]; 1072 else 1073 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1074 1075 DAG.setRoot(Root); 1076 Pending.clear(); 1077 return Root; 1078 } 1079 1080 SDValue SelectionDAGBuilder::getMemoryRoot() { 1081 return updateRoot(PendingLoads); 1082 } 1083 1084 SDValue SelectionDAGBuilder::getRoot() { 1085 // Chain up all pending constrained intrinsics together with all 1086 // pending loads, by simply appending them to PendingLoads and 1087 // then calling getMemoryRoot(). 1088 PendingLoads.reserve(PendingLoads.size() + 1089 PendingConstrainedFP.size() + 1090 PendingConstrainedFPStrict.size()); 1091 PendingLoads.append(PendingConstrainedFP.begin(), 1092 PendingConstrainedFP.end()); 1093 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1094 PendingConstrainedFPStrict.end()); 1095 PendingConstrainedFP.clear(); 1096 PendingConstrainedFPStrict.clear(); 1097 return getMemoryRoot(); 1098 } 1099 1100 SDValue SelectionDAGBuilder::getControlRoot() { 1101 // We need to emit pending fpexcept.strict constrained intrinsics, 1102 // so append them to the PendingExports list. 1103 PendingExports.append(PendingConstrainedFPStrict.begin(), 1104 PendingConstrainedFPStrict.end()); 1105 PendingConstrainedFPStrict.clear(); 1106 return updateRoot(PendingExports); 1107 } 1108 1109 void SelectionDAGBuilder::visit(const Instruction &I) { 1110 // Set up outgoing PHI node register values before emitting the terminator. 1111 if (I.isTerminator()) { 1112 HandlePHINodesInSuccessorBlocks(I.getParent()); 1113 } 1114 1115 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1116 if (!isa<DbgInfoIntrinsic>(I)) 1117 ++SDNodeOrder; 1118 1119 CurInst = &I; 1120 1121 visit(I.getOpcode(), I); 1122 1123 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1124 // ConstrainedFPIntrinsics handle their own FMF. 1125 if (!isa<ConstrainedFPIntrinsic>(&I)) { 1126 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1127 // maps to this instruction. 1128 // TODO: We could handle all flags (nsw, etc) here. 1129 // TODO: If an IR instruction maps to >1 node, only the final node will have 1130 // flags set. 1131 if (SDNode *Node = getNodeForIRValue(&I)) { 1132 SDNodeFlags IncomingFlags; 1133 IncomingFlags.copyFMF(*FPMO); 1134 if (!Node->getFlags().isDefined()) 1135 Node->setFlags(IncomingFlags); 1136 else 1137 Node->intersectFlagsWith(IncomingFlags); 1138 } 1139 } 1140 } 1141 1142 if (!I.isTerminator() && !HasTailCall && 1143 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1144 CopyToExportRegsIfNeeded(&I); 1145 1146 CurInst = nullptr; 1147 } 1148 1149 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1150 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1151 } 1152 1153 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1154 // Note: this doesn't use InstVisitor, because it has to work with 1155 // ConstantExpr's in addition to instructions. 1156 switch (Opcode) { 1157 default: llvm_unreachable("Unknown instruction type encountered!"); 1158 // Build the switch statement using the Instruction.def file. 1159 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1160 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1161 #include "llvm/IR/Instruction.def" 1162 } 1163 } 1164 1165 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1166 const DIExpression *Expr) { 1167 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1168 const DbgValueInst *DI = DDI.getDI(); 1169 DIVariable *DanglingVariable = DI->getVariable(); 1170 DIExpression *DanglingExpr = DI->getExpression(); 1171 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1172 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1173 return true; 1174 } 1175 return false; 1176 }; 1177 1178 for (auto &DDIMI : DanglingDebugInfoMap) { 1179 DanglingDebugInfoVector &DDIV = DDIMI.second; 1180 1181 // If debug info is to be dropped, run it through final checks to see 1182 // whether it can be salvaged. 1183 for (auto &DDI : DDIV) 1184 if (isMatchingDbgValue(DDI)) 1185 salvageUnresolvedDbgValue(DDI); 1186 1187 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1188 } 1189 } 1190 1191 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1192 // generate the debug data structures now that we've seen its definition. 1193 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1194 SDValue Val) { 1195 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1196 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1197 return; 1198 1199 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1200 for (auto &DDI : DDIV) { 1201 const DbgValueInst *DI = DDI.getDI(); 1202 assert(DI && "Ill-formed DanglingDebugInfo"); 1203 DebugLoc dl = DDI.getdl(); 1204 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1205 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1206 DILocalVariable *Variable = DI->getVariable(); 1207 DIExpression *Expr = DI->getExpression(); 1208 assert(Variable->isValidLocationForIntrinsic(dl) && 1209 "Expected inlined-at fields to agree"); 1210 SDDbgValue *SDV; 1211 if (Val.getNode()) { 1212 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1213 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1214 // we couldn't resolve it directly when examining the DbgValue intrinsic 1215 // in the first place we should not be more successful here). Unless we 1216 // have some test case that prove this to be correct we should avoid 1217 // calling EmitFuncArgumentDbgValue here. 1218 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1219 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1220 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1221 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1222 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1223 // inserted after the definition of Val when emitting the instructions 1224 // after ISel. An alternative could be to teach 1225 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1226 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1227 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1228 << ValSDNodeOrder << "\n"); 1229 SDV = getDbgValue(Val, Variable, Expr, dl, 1230 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1231 DAG.AddDbgValue(SDV, Val.getNode(), false); 1232 } else 1233 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1234 << "in EmitFuncArgumentDbgValue\n"); 1235 } else { 1236 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1237 auto Undef = 1238 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1239 auto SDV = 1240 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1241 DAG.AddDbgValue(SDV, nullptr, false); 1242 } 1243 } 1244 DDIV.clear(); 1245 } 1246 1247 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1248 Value *V = DDI.getDI()->getValue(); 1249 DILocalVariable *Var = DDI.getDI()->getVariable(); 1250 DIExpression *Expr = DDI.getDI()->getExpression(); 1251 DebugLoc DL = DDI.getdl(); 1252 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1253 unsigned SDOrder = DDI.getSDNodeOrder(); 1254 1255 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1256 // that DW_OP_stack_value is desired. 1257 assert(isa<DbgValueInst>(DDI.getDI())); 1258 bool StackValue = true; 1259 1260 // Can this Value can be encoded without any further work? 1261 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1262 return; 1263 1264 // Attempt to salvage back through as many instructions as possible. Bail if 1265 // a non-instruction is seen, such as a constant expression or global 1266 // variable. FIXME: Further work could recover those too. 1267 while (isa<Instruction>(V)) { 1268 Instruction &VAsInst = *cast<Instruction>(V); 1269 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1270 1271 // If we cannot salvage any further, and haven't yet found a suitable debug 1272 // expression, bail out. 1273 if (!NewExpr) 1274 break; 1275 1276 // New value and expr now represent this debuginfo. 1277 V = VAsInst.getOperand(0); 1278 Expr = NewExpr; 1279 1280 // Some kind of simplification occurred: check whether the operand of the 1281 // salvaged debug expression can be encoded in this DAG. 1282 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1283 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1284 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1285 return; 1286 } 1287 } 1288 1289 // This was the final opportunity to salvage this debug information, and it 1290 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1291 // any earlier variable location. 1292 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1293 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1294 DAG.AddDbgValue(SDV, nullptr, false); 1295 1296 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1297 << "\n"); 1298 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1299 << "\n"); 1300 } 1301 1302 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1303 DIExpression *Expr, DebugLoc dl, 1304 DebugLoc InstDL, unsigned Order) { 1305 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1306 SDDbgValue *SDV; 1307 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1308 isa<ConstantPointerNull>(V)) { 1309 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1310 DAG.AddDbgValue(SDV, nullptr, false); 1311 return true; 1312 } 1313 1314 // If the Value is a frame index, we can create a FrameIndex debug value 1315 // without relying on the DAG at all. 1316 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1317 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1318 if (SI != FuncInfo.StaticAllocaMap.end()) { 1319 auto SDV = 1320 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1321 /*IsIndirect*/ false, dl, SDNodeOrder); 1322 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1323 // is still available even if the SDNode gets optimized out. 1324 DAG.AddDbgValue(SDV, nullptr, false); 1325 return true; 1326 } 1327 } 1328 1329 // Do not use getValue() in here; we don't want to generate code at 1330 // this point if it hasn't been done yet. 1331 SDValue N = NodeMap[V]; 1332 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1333 N = UnusedArgNodeMap[V]; 1334 if (N.getNode()) { 1335 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1336 return true; 1337 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1338 DAG.AddDbgValue(SDV, N.getNode(), false); 1339 return true; 1340 } 1341 1342 // Special rules apply for the first dbg.values of parameter variables in a 1343 // function. Identify them by the fact they reference Argument Values, that 1344 // they're parameters, and they are parameters of the current function. We 1345 // need to let them dangle until they get an SDNode. 1346 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1347 !InstDL.getInlinedAt(); 1348 if (!IsParamOfFunc) { 1349 // The value is not used in this block yet (or it would have an SDNode). 1350 // We still want the value to appear for the user if possible -- if it has 1351 // an associated VReg, we can refer to that instead. 1352 auto VMI = FuncInfo.ValueMap.find(V); 1353 if (VMI != FuncInfo.ValueMap.end()) { 1354 unsigned Reg = VMI->second; 1355 // If this is a PHI node, it may be split up into several MI PHI nodes 1356 // (in FunctionLoweringInfo::set). 1357 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1358 V->getType(), None); 1359 if (RFV.occupiesMultipleRegs()) { 1360 unsigned Offset = 0; 1361 unsigned BitsToDescribe = 0; 1362 if (auto VarSize = Var->getSizeInBits()) 1363 BitsToDescribe = *VarSize; 1364 if (auto Fragment = Expr->getFragmentInfo()) 1365 BitsToDescribe = Fragment->SizeInBits; 1366 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1367 unsigned RegisterSize = RegAndSize.second; 1368 // Bail out if all bits are described already. 1369 if (Offset >= BitsToDescribe) 1370 break; 1371 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1372 ? BitsToDescribe - Offset 1373 : RegisterSize; 1374 auto FragmentExpr = DIExpression::createFragmentExpression( 1375 Expr, Offset, FragmentSize); 1376 if (!FragmentExpr) 1377 continue; 1378 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1379 false, dl, SDNodeOrder); 1380 DAG.AddDbgValue(SDV, nullptr, false); 1381 Offset += RegisterSize; 1382 } 1383 } else { 1384 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1385 DAG.AddDbgValue(SDV, nullptr, false); 1386 } 1387 return true; 1388 } 1389 } 1390 1391 return false; 1392 } 1393 1394 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1395 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1396 for (auto &Pair : DanglingDebugInfoMap) 1397 for (auto &DDI : Pair.second) 1398 salvageUnresolvedDbgValue(DDI); 1399 clearDanglingDebugInfo(); 1400 } 1401 1402 /// getCopyFromRegs - If there was virtual register allocated for the value V 1403 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1404 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1405 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1406 SDValue Result; 1407 1408 if (It != FuncInfo.ValueMap.end()) { 1409 Register InReg = It->second; 1410 1411 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1412 DAG.getDataLayout(), InReg, Ty, 1413 None); // This is not an ABI copy. 1414 SDValue Chain = DAG.getEntryNode(); 1415 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1416 V); 1417 resolveDanglingDebugInfo(V, Result); 1418 } 1419 1420 return Result; 1421 } 1422 1423 /// getValue - Return an SDValue for the given Value. 1424 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1425 // If we already have an SDValue for this value, use it. It's important 1426 // to do this first, so that we don't create a CopyFromReg if we already 1427 // have a regular SDValue. 1428 SDValue &N = NodeMap[V]; 1429 if (N.getNode()) return N; 1430 1431 // If there's a virtual register allocated and initialized for this 1432 // value, use it. 1433 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1434 return copyFromReg; 1435 1436 // Otherwise create a new SDValue and remember it. 1437 SDValue Val = getValueImpl(V); 1438 NodeMap[V] = Val; 1439 resolveDanglingDebugInfo(V, Val); 1440 return Val; 1441 } 1442 1443 /// getNonRegisterValue - Return an SDValue for the given Value, but 1444 /// don't look in FuncInfo.ValueMap for a virtual register. 1445 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1446 // If we already have an SDValue for this value, use it. 1447 SDValue &N = NodeMap[V]; 1448 if (N.getNode()) { 1449 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1450 // Remove the debug location from the node as the node is about to be used 1451 // in a location which may differ from the original debug location. This 1452 // is relevant to Constant and ConstantFP nodes because they can appear 1453 // as constant expressions inside PHI nodes. 1454 N->setDebugLoc(DebugLoc()); 1455 } 1456 return N; 1457 } 1458 1459 // Otherwise create a new SDValue and remember it. 1460 SDValue Val = getValueImpl(V); 1461 NodeMap[V] = Val; 1462 resolveDanglingDebugInfo(V, Val); 1463 return Val; 1464 } 1465 1466 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1467 /// Create an SDValue for the given value. 1468 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1469 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1470 1471 if (const Constant *C = dyn_cast<Constant>(V)) { 1472 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1473 1474 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1475 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1476 1477 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1478 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1479 1480 if (isa<ConstantPointerNull>(C)) { 1481 unsigned AS = V->getType()->getPointerAddressSpace(); 1482 return DAG.getConstant(0, getCurSDLoc(), 1483 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1484 } 1485 1486 if (match(C, m_VScale(DAG.getDataLayout()))) 1487 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1488 1489 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1490 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1491 1492 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1493 return DAG.getUNDEF(VT); 1494 1495 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1496 visit(CE->getOpcode(), *CE); 1497 SDValue N1 = NodeMap[V]; 1498 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1499 return N1; 1500 } 1501 1502 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1503 SmallVector<SDValue, 4> Constants; 1504 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1505 OI != OE; ++OI) { 1506 SDNode *Val = getValue(*OI).getNode(); 1507 // If the operand is an empty aggregate, there are no values. 1508 if (!Val) continue; 1509 // Add each leaf value from the operand to the Constants list 1510 // to form a flattened list of all the values. 1511 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1512 Constants.push_back(SDValue(Val, i)); 1513 } 1514 1515 return DAG.getMergeValues(Constants, getCurSDLoc()); 1516 } 1517 1518 if (const ConstantDataSequential *CDS = 1519 dyn_cast<ConstantDataSequential>(C)) { 1520 SmallVector<SDValue, 4> Ops; 1521 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1522 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1523 // Add each leaf value from the operand to the Constants list 1524 // to form a flattened list of all the values. 1525 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1526 Ops.push_back(SDValue(Val, i)); 1527 } 1528 1529 if (isa<ArrayType>(CDS->getType())) 1530 return DAG.getMergeValues(Ops, getCurSDLoc()); 1531 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1532 } 1533 1534 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1535 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1536 "Unknown struct or array constant!"); 1537 1538 SmallVector<EVT, 4> ValueVTs; 1539 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1540 unsigned NumElts = ValueVTs.size(); 1541 if (NumElts == 0) 1542 return SDValue(); // empty struct 1543 SmallVector<SDValue, 4> Constants(NumElts); 1544 for (unsigned i = 0; i != NumElts; ++i) { 1545 EVT EltVT = ValueVTs[i]; 1546 if (isa<UndefValue>(C)) 1547 Constants[i] = DAG.getUNDEF(EltVT); 1548 else if (EltVT.isFloatingPoint()) 1549 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1550 else 1551 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1552 } 1553 1554 return DAG.getMergeValues(Constants, getCurSDLoc()); 1555 } 1556 1557 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1558 return DAG.getBlockAddress(BA, VT); 1559 1560 VectorType *VecTy = cast<VectorType>(V->getType()); 1561 1562 // Now that we know the number and type of the elements, get that number of 1563 // elements into the Ops array based on what kind of constant it is. 1564 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1565 SmallVector<SDValue, 16> Ops; 1566 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1567 for (unsigned i = 0; i != NumElements; ++i) 1568 Ops.push_back(getValue(CV->getOperand(i))); 1569 1570 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1571 } else if (isa<ConstantAggregateZero>(C)) { 1572 EVT EltVT = 1573 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1574 1575 SDValue Op; 1576 if (EltVT.isFloatingPoint()) 1577 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1578 else 1579 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1580 1581 if (isa<ScalableVectorType>(VecTy)) 1582 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1583 else { 1584 SmallVector<SDValue, 16> Ops; 1585 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1586 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1587 } 1588 } 1589 llvm_unreachable("Unknown vector constant"); 1590 } 1591 1592 // If this is a static alloca, generate it as the frameindex instead of 1593 // computation. 1594 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1595 DenseMap<const AllocaInst*, int>::iterator SI = 1596 FuncInfo.StaticAllocaMap.find(AI); 1597 if (SI != FuncInfo.StaticAllocaMap.end()) 1598 return DAG.getFrameIndex(SI->second, 1599 TLI.getFrameIndexTy(DAG.getDataLayout())); 1600 } 1601 1602 // If this is an instruction which fast-isel has deferred, select it now. 1603 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1604 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1605 1606 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1607 Inst->getType(), getABIRegCopyCC(V)); 1608 SDValue Chain = DAG.getEntryNode(); 1609 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1610 } 1611 1612 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1613 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1614 } 1615 llvm_unreachable("Can't get register for value!"); 1616 } 1617 1618 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1619 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1620 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1621 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1622 bool IsSEH = isAsynchronousEHPersonality(Pers); 1623 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1624 if (!IsSEH) 1625 CatchPadMBB->setIsEHScopeEntry(); 1626 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1627 if (IsMSVCCXX || IsCoreCLR) 1628 CatchPadMBB->setIsEHFuncletEntry(); 1629 } 1630 1631 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1632 // Update machine-CFG edge. 1633 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1634 FuncInfo.MBB->addSuccessor(TargetMBB); 1635 1636 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1637 bool IsSEH = isAsynchronousEHPersonality(Pers); 1638 if (IsSEH) { 1639 // If this is not a fall-through branch or optimizations are switched off, 1640 // emit the branch. 1641 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1642 TM.getOptLevel() == CodeGenOpt::None) 1643 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1644 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1645 return; 1646 } 1647 1648 // Figure out the funclet membership for the catchret's successor. 1649 // This will be used by the FuncletLayout pass to determine how to order the 1650 // BB's. 1651 // A 'catchret' returns to the outer scope's color. 1652 Value *ParentPad = I.getCatchSwitchParentPad(); 1653 const BasicBlock *SuccessorColor; 1654 if (isa<ConstantTokenNone>(ParentPad)) 1655 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1656 else 1657 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1658 assert(SuccessorColor && "No parent funclet for catchret!"); 1659 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1660 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1661 1662 // Create the terminator node. 1663 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1664 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1665 DAG.getBasicBlock(SuccessorColorMBB)); 1666 DAG.setRoot(Ret); 1667 } 1668 1669 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1670 // Don't emit any special code for the cleanuppad instruction. It just marks 1671 // the start of an EH scope/funclet. 1672 FuncInfo.MBB->setIsEHScopeEntry(); 1673 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1674 if (Pers != EHPersonality::Wasm_CXX) { 1675 FuncInfo.MBB->setIsEHFuncletEntry(); 1676 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1677 } 1678 } 1679 1680 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1681 // the control flow always stops at the single catch pad, as it does for a 1682 // cleanup pad. In case the exception caught is not of the types the catch pad 1683 // catches, it will be rethrown by a rethrow. 1684 static void findWasmUnwindDestinations( 1685 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1686 BranchProbability Prob, 1687 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1688 &UnwindDests) { 1689 while (EHPadBB) { 1690 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1691 if (isa<CleanupPadInst>(Pad)) { 1692 // Stop on cleanup pads. 1693 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1694 UnwindDests.back().first->setIsEHScopeEntry(); 1695 break; 1696 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1697 // Add the catchpad handlers to the possible destinations. We don't 1698 // continue to the unwind destination of the catchswitch for wasm. 1699 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1700 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1701 UnwindDests.back().first->setIsEHScopeEntry(); 1702 } 1703 break; 1704 } else { 1705 continue; 1706 } 1707 } 1708 } 1709 1710 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1711 /// many places it could ultimately go. In the IR, we have a single unwind 1712 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1713 /// This function skips over imaginary basic blocks that hold catchswitch 1714 /// instructions, and finds all the "real" machine 1715 /// basic block destinations. As those destinations may not be successors of 1716 /// EHPadBB, here we also calculate the edge probability to those destinations. 1717 /// The passed-in Prob is the edge probability to EHPadBB. 1718 static void findUnwindDestinations( 1719 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1720 BranchProbability Prob, 1721 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1722 &UnwindDests) { 1723 EHPersonality Personality = 1724 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1725 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1726 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1727 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1728 bool IsSEH = isAsynchronousEHPersonality(Personality); 1729 1730 if (IsWasmCXX) { 1731 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1732 assert(UnwindDests.size() <= 1 && 1733 "There should be at most one unwind destination for wasm"); 1734 return; 1735 } 1736 1737 while (EHPadBB) { 1738 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1739 BasicBlock *NewEHPadBB = nullptr; 1740 if (isa<LandingPadInst>(Pad)) { 1741 // Stop on landingpads. They are not funclets. 1742 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1743 break; 1744 } else if (isa<CleanupPadInst>(Pad)) { 1745 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1746 // personalities. 1747 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1748 UnwindDests.back().first->setIsEHScopeEntry(); 1749 UnwindDests.back().first->setIsEHFuncletEntry(); 1750 break; 1751 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1752 // Add the catchpad handlers to the possible destinations. 1753 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1754 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1755 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1756 if (IsMSVCCXX || IsCoreCLR) 1757 UnwindDests.back().first->setIsEHFuncletEntry(); 1758 if (!IsSEH) 1759 UnwindDests.back().first->setIsEHScopeEntry(); 1760 } 1761 NewEHPadBB = CatchSwitch->getUnwindDest(); 1762 } else { 1763 continue; 1764 } 1765 1766 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1767 if (BPI && NewEHPadBB) 1768 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1769 EHPadBB = NewEHPadBB; 1770 } 1771 } 1772 1773 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1774 // Update successor info. 1775 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1776 auto UnwindDest = I.getUnwindDest(); 1777 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1778 BranchProbability UnwindDestProb = 1779 (BPI && UnwindDest) 1780 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1781 : BranchProbability::getZero(); 1782 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1783 for (auto &UnwindDest : UnwindDests) { 1784 UnwindDest.first->setIsEHPad(); 1785 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1786 } 1787 FuncInfo.MBB->normalizeSuccProbs(); 1788 1789 // Create the terminator node. 1790 SDValue Ret = 1791 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1792 DAG.setRoot(Ret); 1793 } 1794 1795 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1796 report_fatal_error("visitCatchSwitch not yet implemented!"); 1797 } 1798 1799 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1801 auto &DL = DAG.getDataLayout(); 1802 SDValue Chain = getControlRoot(); 1803 SmallVector<ISD::OutputArg, 8> Outs; 1804 SmallVector<SDValue, 8> OutVals; 1805 1806 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1807 // lower 1808 // 1809 // %val = call <ty> @llvm.experimental.deoptimize() 1810 // ret <ty> %val 1811 // 1812 // differently. 1813 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1814 LowerDeoptimizingReturn(); 1815 return; 1816 } 1817 1818 if (!FuncInfo.CanLowerReturn) { 1819 unsigned DemoteReg = FuncInfo.DemoteRegister; 1820 const Function *F = I.getParent()->getParent(); 1821 1822 // Emit a store of the return value through the virtual register. 1823 // Leave Outs empty so that LowerReturn won't try to load return 1824 // registers the usual way. 1825 SmallVector<EVT, 1> PtrValueVTs; 1826 ComputeValueVTs(TLI, DL, 1827 F->getReturnType()->getPointerTo( 1828 DAG.getDataLayout().getAllocaAddrSpace()), 1829 PtrValueVTs); 1830 1831 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1832 DemoteReg, PtrValueVTs[0]); 1833 SDValue RetOp = getValue(I.getOperand(0)); 1834 1835 SmallVector<EVT, 4> ValueVTs, MemVTs; 1836 SmallVector<uint64_t, 4> Offsets; 1837 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1838 &Offsets); 1839 unsigned NumValues = ValueVTs.size(); 1840 1841 SmallVector<SDValue, 4> Chains(NumValues); 1842 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1843 for (unsigned i = 0; i != NumValues; ++i) { 1844 // An aggregate return value cannot wrap around the address space, so 1845 // offsets to its parts don't wrap either. 1846 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1847 1848 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1849 if (MemVTs[i] != ValueVTs[i]) 1850 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1851 Chains[i] = DAG.getStore( 1852 Chain, getCurSDLoc(), Val, 1853 // FIXME: better loc info would be nice. 1854 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1855 commonAlignment(BaseAlign, Offsets[i])); 1856 } 1857 1858 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1859 MVT::Other, Chains); 1860 } else if (I.getNumOperands() != 0) { 1861 SmallVector<EVT, 4> ValueVTs; 1862 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1863 unsigned NumValues = ValueVTs.size(); 1864 if (NumValues) { 1865 SDValue RetOp = getValue(I.getOperand(0)); 1866 1867 const Function *F = I.getParent()->getParent(); 1868 1869 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1870 I.getOperand(0)->getType(), F->getCallingConv(), 1871 /*IsVarArg*/ false); 1872 1873 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1874 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1875 Attribute::SExt)) 1876 ExtendKind = ISD::SIGN_EXTEND; 1877 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1878 Attribute::ZExt)) 1879 ExtendKind = ISD::ZERO_EXTEND; 1880 1881 LLVMContext &Context = F->getContext(); 1882 bool RetInReg = F->getAttributes().hasAttribute( 1883 AttributeList::ReturnIndex, Attribute::InReg); 1884 1885 for (unsigned j = 0; j != NumValues; ++j) { 1886 EVT VT = ValueVTs[j]; 1887 1888 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1889 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1890 1891 CallingConv::ID CC = F->getCallingConv(); 1892 1893 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1894 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1895 SmallVector<SDValue, 4> Parts(NumParts); 1896 getCopyToParts(DAG, getCurSDLoc(), 1897 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1898 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1899 1900 // 'inreg' on function refers to return value 1901 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1902 if (RetInReg) 1903 Flags.setInReg(); 1904 1905 if (I.getOperand(0)->getType()->isPointerTy()) { 1906 Flags.setPointer(); 1907 Flags.setPointerAddrSpace( 1908 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1909 } 1910 1911 if (NeedsRegBlock) { 1912 Flags.setInConsecutiveRegs(); 1913 if (j == NumValues - 1) 1914 Flags.setInConsecutiveRegsLast(); 1915 } 1916 1917 // Propagate extension type if any 1918 if (ExtendKind == ISD::SIGN_EXTEND) 1919 Flags.setSExt(); 1920 else if (ExtendKind == ISD::ZERO_EXTEND) 1921 Flags.setZExt(); 1922 1923 for (unsigned i = 0; i < NumParts; ++i) { 1924 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1925 VT, /*isfixed=*/true, 0, 0)); 1926 OutVals.push_back(Parts[i]); 1927 } 1928 } 1929 } 1930 } 1931 1932 // Push in swifterror virtual register as the last element of Outs. This makes 1933 // sure swifterror virtual register will be returned in the swifterror 1934 // physical register. 1935 const Function *F = I.getParent()->getParent(); 1936 if (TLI.supportSwiftError() && 1937 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1938 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1939 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1940 Flags.setSwiftError(); 1941 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1942 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1943 true /*isfixed*/, 1 /*origidx*/, 1944 0 /*partOffs*/)); 1945 // Create SDNode for the swifterror virtual register. 1946 OutVals.push_back( 1947 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1948 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1949 EVT(TLI.getPointerTy(DL)))); 1950 } 1951 1952 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1953 CallingConv::ID CallConv = 1954 DAG.getMachineFunction().getFunction().getCallingConv(); 1955 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1956 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1957 1958 // Verify that the target's LowerReturn behaved as expected. 1959 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1960 "LowerReturn didn't return a valid chain!"); 1961 1962 // Update the DAG with the new chain value resulting from return lowering. 1963 DAG.setRoot(Chain); 1964 } 1965 1966 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1967 /// created for it, emit nodes to copy the value into the virtual 1968 /// registers. 1969 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1970 // Skip empty types 1971 if (V->getType()->isEmptyTy()) 1972 return; 1973 1974 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1975 if (VMI != FuncInfo.ValueMap.end()) { 1976 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1977 CopyValueToVirtualRegister(V, VMI->second); 1978 } 1979 } 1980 1981 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1982 /// the current basic block, add it to ValueMap now so that we'll get a 1983 /// CopyTo/FromReg. 1984 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1985 // No need to export constants. 1986 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1987 1988 // Already exported? 1989 if (FuncInfo.isExportedInst(V)) return; 1990 1991 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1992 CopyValueToVirtualRegister(V, Reg); 1993 } 1994 1995 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1996 const BasicBlock *FromBB) { 1997 // The operands of the setcc have to be in this block. We don't know 1998 // how to export them from some other block. 1999 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 2000 // Can export from current BB. 2001 if (VI->getParent() == FromBB) 2002 return true; 2003 2004 // Is already exported, noop. 2005 return FuncInfo.isExportedInst(V); 2006 } 2007 2008 // If this is an argument, we can export it if the BB is the entry block or 2009 // if it is already exported. 2010 if (isa<Argument>(V)) { 2011 if (FromBB == &FromBB->getParent()->getEntryBlock()) 2012 return true; 2013 2014 // Otherwise, can only export this if it is already exported. 2015 return FuncInfo.isExportedInst(V); 2016 } 2017 2018 // Otherwise, constants can always be exported. 2019 return true; 2020 } 2021 2022 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2023 BranchProbability 2024 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2025 const MachineBasicBlock *Dst) const { 2026 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2027 const BasicBlock *SrcBB = Src->getBasicBlock(); 2028 const BasicBlock *DstBB = Dst->getBasicBlock(); 2029 if (!BPI) { 2030 // If BPI is not available, set the default probability as 1 / N, where N is 2031 // the number of successors. 2032 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2033 return BranchProbability(1, SuccSize); 2034 } 2035 return BPI->getEdgeProbability(SrcBB, DstBB); 2036 } 2037 2038 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2039 MachineBasicBlock *Dst, 2040 BranchProbability Prob) { 2041 if (!FuncInfo.BPI) 2042 Src->addSuccessorWithoutProb(Dst); 2043 else { 2044 if (Prob.isUnknown()) 2045 Prob = getEdgeProbability(Src, Dst); 2046 Src->addSuccessor(Dst, Prob); 2047 } 2048 } 2049 2050 static bool InBlock(const Value *V, const BasicBlock *BB) { 2051 if (const Instruction *I = dyn_cast<Instruction>(V)) 2052 return I->getParent() == BB; 2053 return true; 2054 } 2055 2056 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2057 /// This function emits a branch and is used at the leaves of an OR or an 2058 /// AND operator tree. 2059 void 2060 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2061 MachineBasicBlock *TBB, 2062 MachineBasicBlock *FBB, 2063 MachineBasicBlock *CurBB, 2064 MachineBasicBlock *SwitchBB, 2065 BranchProbability TProb, 2066 BranchProbability FProb, 2067 bool InvertCond) { 2068 const BasicBlock *BB = CurBB->getBasicBlock(); 2069 2070 // If the leaf of the tree is a comparison, merge the condition into 2071 // the caseblock. 2072 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2073 // The operands of the cmp have to be in this block. We don't know 2074 // how to export them from some other block. If this is the first block 2075 // of the sequence, no exporting is needed. 2076 if (CurBB == SwitchBB || 2077 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2078 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2079 ISD::CondCode Condition; 2080 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2081 ICmpInst::Predicate Pred = 2082 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2083 Condition = getICmpCondCode(Pred); 2084 } else { 2085 const FCmpInst *FC = cast<FCmpInst>(Cond); 2086 FCmpInst::Predicate Pred = 2087 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2088 Condition = getFCmpCondCode(Pred); 2089 if (TM.Options.NoNaNsFPMath) 2090 Condition = getFCmpCodeWithoutNaN(Condition); 2091 } 2092 2093 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2094 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2095 SL->SwitchCases.push_back(CB); 2096 return; 2097 } 2098 } 2099 2100 // Create a CaseBlock record representing this branch. 2101 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2102 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2103 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2104 SL->SwitchCases.push_back(CB); 2105 } 2106 2107 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2108 MachineBasicBlock *TBB, 2109 MachineBasicBlock *FBB, 2110 MachineBasicBlock *CurBB, 2111 MachineBasicBlock *SwitchBB, 2112 Instruction::BinaryOps Opc, 2113 BranchProbability TProb, 2114 BranchProbability FProb, 2115 bool InvertCond) { 2116 // Skip over not part of the tree and remember to invert op and operands at 2117 // next level. 2118 Value *NotCond; 2119 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2120 InBlock(NotCond, CurBB->getBasicBlock())) { 2121 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2122 !InvertCond); 2123 return; 2124 } 2125 2126 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2127 // Compute the effective opcode for Cond, taking into account whether it needs 2128 // to be inverted, e.g. 2129 // and (not (or A, B)), C 2130 // gets lowered as 2131 // and (and (not A, not B), C) 2132 unsigned BOpc = 0; 2133 if (BOp) { 2134 BOpc = BOp->getOpcode(); 2135 if (InvertCond) { 2136 if (BOpc == Instruction::And) 2137 BOpc = Instruction::Or; 2138 else if (BOpc == Instruction::Or) 2139 BOpc = Instruction::And; 2140 } 2141 } 2142 2143 // If this node is not part of the or/and tree, emit it as a branch. 2144 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2145 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2146 BOp->getParent() != CurBB->getBasicBlock() || 2147 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2148 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2149 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2150 TProb, FProb, InvertCond); 2151 return; 2152 } 2153 2154 // Create TmpBB after CurBB. 2155 MachineFunction::iterator BBI(CurBB); 2156 MachineFunction &MF = DAG.getMachineFunction(); 2157 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2158 CurBB->getParent()->insert(++BBI, TmpBB); 2159 2160 if (Opc == Instruction::Or) { 2161 // Codegen X | Y as: 2162 // BB1: 2163 // jmp_if_X TBB 2164 // jmp TmpBB 2165 // TmpBB: 2166 // jmp_if_Y TBB 2167 // jmp FBB 2168 // 2169 2170 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2171 // The requirement is that 2172 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2173 // = TrueProb for original BB. 2174 // Assuming the original probabilities are A and B, one choice is to set 2175 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2176 // A/(1+B) and 2B/(1+B). This choice assumes that 2177 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2178 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2179 // TmpBB, but the math is more complicated. 2180 2181 auto NewTrueProb = TProb / 2; 2182 auto NewFalseProb = TProb / 2 + FProb; 2183 // Emit the LHS condition. 2184 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2185 NewTrueProb, NewFalseProb, InvertCond); 2186 2187 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2188 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2189 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2190 // Emit the RHS condition into TmpBB. 2191 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2192 Probs[0], Probs[1], InvertCond); 2193 } else { 2194 assert(Opc == Instruction::And && "Unknown merge op!"); 2195 // Codegen X & Y as: 2196 // BB1: 2197 // jmp_if_X TmpBB 2198 // jmp FBB 2199 // TmpBB: 2200 // jmp_if_Y TBB 2201 // jmp FBB 2202 // 2203 // This requires creation of TmpBB after CurBB. 2204 2205 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2206 // The requirement is that 2207 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2208 // = FalseProb for original BB. 2209 // Assuming the original probabilities are A and B, one choice is to set 2210 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2211 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2212 // TrueProb for BB1 * FalseProb for TmpBB. 2213 2214 auto NewTrueProb = TProb + FProb / 2; 2215 auto NewFalseProb = FProb / 2; 2216 // Emit the LHS condition. 2217 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2218 NewTrueProb, NewFalseProb, InvertCond); 2219 2220 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2221 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2222 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2223 // Emit the RHS condition into TmpBB. 2224 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2225 Probs[0], Probs[1], InvertCond); 2226 } 2227 } 2228 2229 /// If the set of cases should be emitted as a series of branches, return true. 2230 /// If we should emit this as a bunch of and/or'd together conditions, return 2231 /// false. 2232 bool 2233 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2234 if (Cases.size() != 2) return true; 2235 2236 // If this is two comparisons of the same values or'd or and'd together, they 2237 // will get folded into a single comparison, so don't emit two blocks. 2238 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2239 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2240 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2241 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2242 return false; 2243 } 2244 2245 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2246 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2247 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2248 Cases[0].CC == Cases[1].CC && 2249 isa<Constant>(Cases[0].CmpRHS) && 2250 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2251 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2252 return false; 2253 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2254 return false; 2255 } 2256 2257 return true; 2258 } 2259 2260 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2261 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2262 2263 // Update machine-CFG edges. 2264 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2265 2266 if (I.isUnconditional()) { 2267 // Update machine-CFG edges. 2268 BrMBB->addSuccessor(Succ0MBB); 2269 2270 // If this is not a fall-through branch or optimizations are switched off, 2271 // emit the branch. 2272 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2273 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2274 MVT::Other, getControlRoot(), 2275 DAG.getBasicBlock(Succ0MBB))); 2276 2277 return; 2278 } 2279 2280 // If this condition is one of the special cases we handle, do special stuff 2281 // now. 2282 const Value *CondVal = I.getCondition(); 2283 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2284 2285 // If this is a series of conditions that are or'd or and'd together, emit 2286 // this as a sequence of branches instead of setcc's with and/or operations. 2287 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2288 // unpredictable branches, and vector extracts because those jumps are likely 2289 // expensive for any target), this should improve performance. 2290 // For example, instead of something like: 2291 // cmp A, B 2292 // C = seteq 2293 // cmp D, E 2294 // F = setle 2295 // or C, F 2296 // jnz foo 2297 // Emit: 2298 // cmp A, B 2299 // je foo 2300 // cmp D, E 2301 // jle foo 2302 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2303 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2304 Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1); 2305 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2306 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2307 (Opcode == Instruction::And || Opcode == Instruction::Or) && 2308 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2309 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2310 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2311 Opcode, 2312 getEdgeProbability(BrMBB, Succ0MBB), 2313 getEdgeProbability(BrMBB, Succ1MBB), 2314 /*InvertCond=*/false); 2315 // If the compares in later blocks need to use values not currently 2316 // exported from this block, export them now. This block should always 2317 // be the first entry. 2318 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2319 2320 // Allow some cases to be rejected. 2321 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2322 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2323 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2324 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2325 } 2326 2327 // Emit the branch for this block. 2328 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2329 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2330 return; 2331 } 2332 2333 // Okay, we decided not to do this, remove any inserted MBB's and clear 2334 // SwitchCases. 2335 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2336 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2337 2338 SL->SwitchCases.clear(); 2339 } 2340 } 2341 2342 // Create a CaseBlock record representing this branch. 2343 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2344 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2345 2346 // Use visitSwitchCase to actually insert the fast branch sequence for this 2347 // cond branch. 2348 visitSwitchCase(CB, BrMBB); 2349 } 2350 2351 /// visitSwitchCase - Emits the necessary code to represent a single node in 2352 /// the binary search tree resulting from lowering a switch instruction. 2353 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2354 MachineBasicBlock *SwitchBB) { 2355 SDValue Cond; 2356 SDValue CondLHS = getValue(CB.CmpLHS); 2357 SDLoc dl = CB.DL; 2358 2359 if (CB.CC == ISD::SETTRUE) { 2360 // Branch or fall through to TrueBB. 2361 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2362 SwitchBB->normalizeSuccProbs(); 2363 if (CB.TrueBB != NextBlock(SwitchBB)) { 2364 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2365 DAG.getBasicBlock(CB.TrueBB))); 2366 } 2367 return; 2368 } 2369 2370 auto &TLI = DAG.getTargetLoweringInfo(); 2371 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2372 2373 // Build the setcc now. 2374 if (!CB.CmpMHS) { 2375 // Fold "(X == true)" to X and "(X == false)" to !X to 2376 // handle common cases produced by branch lowering. 2377 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2378 CB.CC == ISD::SETEQ) 2379 Cond = CondLHS; 2380 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2381 CB.CC == ISD::SETEQ) { 2382 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2383 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2384 } else { 2385 SDValue CondRHS = getValue(CB.CmpRHS); 2386 2387 // If a pointer's DAG type is larger than its memory type then the DAG 2388 // values are zero-extended. This breaks signed comparisons so truncate 2389 // back to the underlying type before doing the compare. 2390 if (CondLHS.getValueType() != MemVT) { 2391 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2392 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2393 } 2394 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2395 } 2396 } else { 2397 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2398 2399 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2400 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2401 2402 SDValue CmpOp = getValue(CB.CmpMHS); 2403 EVT VT = CmpOp.getValueType(); 2404 2405 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2406 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2407 ISD::SETLE); 2408 } else { 2409 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2410 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2411 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2412 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2413 } 2414 } 2415 2416 // Update successor info 2417 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2418 // TrueBB and FalseBB are always different unless the incoming IR is 2419 // degenerate. This only happens when running llc on weird IR. 2420 if (CB.TrueBB != CB.FalseBB) 2421 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2422 SwitchBB->normalizeSuccProbs(); 2423 2424 // If the lhs block is the next block, invert the condition so that we can 2425 // fall through to the lhs instead of the rhs block. 2426 if (CB.TrueBB == NextBlock(SwitchBB)) { 2427 std::swap(CB.TrueBB, CB.FalseBB); 2428 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2429 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2430 } 2431 2432 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2433 MVT::Other, getControlRoot(), Cond, 2434 DAG.getBasicBlock(CB.TrueBB)); 2435 2436 // Insert the false branch. Do this even if it's a fall through branch, 2437 // this makes it easier to do DAG optimizations which require inverting 2438 // the branch condition. 2439 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2440 DAG.getBasicBlock(CB.FalseBB)); 2441 2442 DAG.setRoot(BrCond); 2443 } 2444 2445 /// visitJumpTable - Emit JumpTable node in the current MBB 2446 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2447 // Emit the code for the jump table 2448 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2449 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2450 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2451 JT.Reg, PTy); 2452 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2453 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2454 MVT::Other, Index.getValue(1), 2455 Table, Index); 2456 DAG.setRoot(BrJumpTable); 2457 } 2458 2459 /// visitJumpTableHeader - This function emits necessary code to produce index 2460 /// in the JumpTable from switch case. 2461 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2462 JumpTableHeader &JTH, 2463 MachineBasicBlock *SwitchBB) { 2464 SDLoc dl = getCurSDLoc(); 2465 2466 // Subtract the lowest switch case value from the value being switched on. 2467 SDValue SwitchOp = getValue(JTH.SValue); 2468 EVT VT = SwitchOp.getValueType(); 2469 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2470 DAG.getConstant(JTH.First, dl, VT)); 2471 2472 // The SDNode we just created, which holds the value being switched on minus 2473 // the smallest case value, needs to be copied to a virtual register so it 2474 // can be used as an index into the jump table in a subsequent basic block. 2475 // This value may be smaller or larger than the target's pointer type, and 2476 // therefore require extension or truncating. 2477 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2478 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2479 2480 unsigned JumpTableReg = 2481 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2482 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2483 JumpTableReg, SwitchOp); 2484 JT.Reg = JumpTableReg; 2485 2486 if (!JTH.OmitRangeCheck) { 2487 // Emit the range check for the jump table, and branch to the default block 2488 // for the switch statement if the value being switched on exceeds the 2489 // largest case in the switch. 2490 SDValue CMP = DAG.getSetCC( 2491 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2492 Sub.getValueType()), 2493 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2494 2495 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2496 MVT::Other, CopyTo, CMP, 2497 DAG.getBasicBlock(JT.Default)); 2498 2499 // Avoid emitting unnecessary branches to the next block. 2500 if (JT.MBB != NextBlock(SwitchBB)) 2501 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2502 DAG.getBasicBlock(JT.MBB)); 2503 2504 DAG.setRoot(BrCond); 2505 } else { 2506 // Avoid emitting unnecessary branches to the next block. 2507 if (JT.MBB != NextBlock(SwitchBB)) 2508 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2509 DAG.getBasicBlock(JT.MBB))); 2510 else 2511 DAG.setRoot(CopyTo); 2512 } 2513 } 2514 2515 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2516 /// variable if there exists one. 2517 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2518 SDValue &Chain) { 2519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2520 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2521 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2522 MachineFunction &MF = DAG.getMachineFunction(); 2523 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2524 MachineSDNode *Node = 2525 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2526 if (Global) { 2527 MachinePointerInfo MPInfo(Global); 2528 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2529 MachineMemOperand::MODereferenceable; 2530 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2531 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2532 DAG.setNodeMemRefs(Node, {MemRef}); 2533 } 2534 if (PtrTy != PtrMemTy) 2535 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2536 return SDValue(Node, 0); 2537 } 2538 2539 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2540 /// tail spliced into a stack protector check success bb. 2541 /// 2542 /// For a high level explanation of how this fits into the stack protector 2543 /// generation see the comment on the declaration of class 2544 /// StackProtectorDescriptor. 2545 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2546 MachineBasicBlock *ParentBB) { 2547 2548 // First create the loads to the guard/stack slot for the comparison. 2549 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2550 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2551 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2552 2553 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2554 int FI = MFI.getStackProtectorIndex(); 2555 2556 SDValue Guard; 2557 SDLoc dl = getCurSDLoc(); 2558 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2559 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2560 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2561 2562 // Generate code to load the content of the guard slot. 2563 SDValue GuardVal = DAG.getLoad( 2564 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2565 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2566 MachineMemOperand::MOVolatile); 2567 2568 if (TLI.useStackGuardXorFP()) 2569 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2570 2571 // Retrieve guard check function, nullptr if instrumentation is inlined. 2572 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2573 // The target provides a guard check function to validate the guard value. 2574 // Generate a call to that function with the content of the guard slot as 2575 // argument. 2576 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2577 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2578 2579 TargetLowering::ArgListTy Args; 2580 TargetLowering::ArgListEntry Entry; 2581 Entry.Node = GuardVal; 2582 Entry.Ty = FnTy->getParamType(0); 2583 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2584 Entry.IsInReg = true; 2585 Args.push_back(Entry); 2586 2587 TargetLowering::CallLoweringInfo CLI(DAG); 2588 CLI.setDebugLoc(getCurSDLoc()) 2589 .setChain(DAG.getEntryNode()) 2590 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2591 getValue(GuardCheckFn), std::move(Args)); 2592 2593 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2594 DAG.setRoot(Result.second); 2595 return; 2596 } 2597 2598 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2599 // Otherwise, emit a volatile load to retrieve the stack guard value. 2600 SDValue Chain = DAG.getEntryNode(); 2601 if (TLI.useLoadStackGuardNode()) { 2602 Guard = getLoadStackGuard(DAG, dl, Chain); 2603 } else { 2604 const Value *IRGuard = TLI.getSDagStackGuard(M); 2605 SDValue GuardPtr = getValue(IRGuard); 2606 2607 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2608 MachinePointerInfo(IRGuard, 0), Align, 2609 MachineMemOperand::MOVolatile); 2610 } 2611 2612 // Perform the comparison via a getsetcc. 2613 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2614 *DAG.getContext(), 2615 Guard.getValueType()), 2616 Guard, GuardVal, ISD::SETNE); 2617 2618 // If the guard/stackslot do not equal, branch to failure MBB. 2619 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2620 MVT::Other, GuardVal.getOperand(0), 2621 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2622 // Otherwise branch to success MBB. 2623 SDValue Br = DAG.getNode(ISD::BR, dl, 2624 MVT::Other, BrCond, 2625 DAG.getBasicBlock(SPD.getSuccessMBB())); 2626 2627 DAG.setRoot(Br); 2628 } 2629 2630 /// Codegen the failure basic block for a stack protector check. 2631 /// 2632 /// A failure stack protector machine basic block consists simply of a call to 2633 /// __stack_chk_fail(). 2634 /// 2635 /// For a high level explanation of how this fits into the stack protector 2636 /// generation see the comment on the declaration of class 2637 /// StackProtectorDescriptor. 2638 void 2639 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2641 TargetLowering::MakeLibCallOptions CallOptions; 2642 CallOptions.setDiscardResult(true); 2643 SDValue Chain = 2644 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2645 None, CallOptions, getCurSDLoc()).second; 2646 // On PS4, the "return address" must still be within the calling function, 2647 // even if it's at the very end, so emit an explicit TRAP here. 2648 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2649 if (TM.getTargetTriple().isPS4CPU()) 2650 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2651 // WebAssembly needs an unreachable instruction after a non-returning call, 2652 // because the function return type can be different from __stack_chk_fail's 2653 // return type (void). 2654 if (TM.getTargetTriple().isWasm()) 2655 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2656 2657 DAG.setRoot(Chain); 2658 } 2659 2660 /// visitBitTestHeader - This function emits necessary code to produce value 2661 /// suitable for "bit tests" 2662 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2663 MachineBasicBlock *SwitchBB) { 2664 SDLoc dl = getCurSDLoc(); 2665 2666 // Subtract the minimum value. 2667 SDValue SwitchOp = getValue(B.SValue); 2668 EVT VT = SwitchOp.getValueType(); 2669 SDValue RangeSub = 2670 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2671 2672 // Determine the type of the test operands. 2673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2674 bool UsePtrType = false; 2675 if (!TLI.isTypeLegal(VT)) { 2676 UsePtrType = true; 2677 } else { 2678 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2679 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2680 // Switch table case range are encoded into series of masks. 2681 // Just use pointer type, it's guaranteed to fit. 2682 UsePtrType = true; 2683 break; 2684 } 2685 } 2686 SDValue Sub = RangeSub; 2687 if (UsePtrType) { 2688 VT = TLI.getPointerTy(DAG.getDataLayout()); 2689 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2690 } 2691 2692 B.RegVT = VT.getSimpleVT(); 2693 B.Reg = FuncInfo.CreateReg(B.RegVT); 2694 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2695 2696 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2697 2698 if (!B.OmitRangeCheck) 2699 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2700 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2701 SwitchBB->normalizeSuccProbs(); 2702 2703 SDValue Root = CopyTo; 2704 if (!B.OmitRangeCheck) { 2705 // Conditional branch to the default block. 2706 SDValue RangeCmp = DAG.getSetCC(dl, 2707 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2708 RangeSub.getValueType()), 2709 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2710 ISD::SETUGT); 2711 2712 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2713 DAG.getBasicBlock(B.Default)); 2714 } 2715 2716 // Avoid emitting unnecessary branches to the next block. 2717 if (MBB != NextBlock(SwitchBB)) 2718 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2719 2720 DAG.setRoot(Root); 2721 } 2722 2723 /// visitBitTestCase - this function produces one "bit test" 2724 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2725 MachineBasicBlock* NextMBB, 2726 BranchProbability BranchProbToNext, 2727 unsigned Reg, 2728 BitTestCase &B, 2729 MachineBasicBlock *SwitchBB) { 2730 SDLoc dl = getCurSDLoc(); 2731 MVT VT = BB.RegVT; 2732 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2733 SDValue Cmp; 2734 unsigned PopCount = countPopulation(B.Mask); 2735 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2736 if (PopCount == 1) { 2737 // Testing for a single bit; just compare the shift count with what it 2738 // would need to be to shift a 1 bit in that position. 2739 Cmp = DAG.getSetCC( 2740 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2741 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2742 ISD::SETEQ); 2743 } else if (PopCount == BB.Range) { 2744 // There is only one zero bit in the range, test for it directly. 2745 Cmp = DAG.getSetCC( 2746 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2747 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2748 ISD::SETNE); 2749 } else { 2750 // Make desired shift 2751 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2752 DAG.getConstant(1, dl, VT), ShiftOp); 2753 2754 // Emit bit tests and jumps 2755 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2756 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2757 Cmp = DAG.getSetCC( 2758 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2759 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2760 } 2761 2762 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2763 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2764 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2765 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2766 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2767 // one as they are relative probabilities (and thus work more like weights), 2768 // and hence we need to normalize them to let the sum of them become one. 2769 SwitchBB->normalizeSuccProbs(); 2770 2771 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2772 MVT::Other, getControlRoot(), 2773 Cmp, DAG.getBasicBlock(B.TargetBB)); 2774 2775 // Avoid emitting unnecessary branches to the next block. 2776 if (NextMBB != NextBlock(SwitchBB)) 2777 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2778 DAG.getBasicBlock(NextMBB)); 2779 2780 DAG.setRoot(BrAnd); 2781 } 2782 2783 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2784 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2785 2786 // Retrieve successors. Look through artificial IR level blocks like 2787 // catchswitch for successors. 2788 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2789 const BasicBlock *EHPadBB = I.getSuccessor(1); 2790 2791 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2792 // have to do anything here to lower funclet bundles. 2793 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2794 LLVMContext::OB_gc_transition, 2795 LLVMContext::OB_gc_live, 2796 LLVMContext::OB_funclet, 2797 LLVMContext::OB_cfguardtarget}) && 2798 "Cannot lower invokes with arbitrary operand bundles yet!"); 2799 2800 const Value *Callee(I.getCalledOperand()); 2801 const Function *Fn = dyn_cast<Function>(Callee); 2802 if (isa<InlineAsm>(Callee)) 2803 visitInlineAsm(I); 2804 else if (Fn && Fn->isIntrinsic()) { 2805 switch (Fn->getIntrinsicID()) { 2806 default: 2807 llvm_unreachable("Cannot invoke this intrinsic"); 2808 case Intrinsic::donothing: 2809 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2810 break; 2811 case Intrinsic::experimental_patchpoint_void: 2812 case Intrinsic::experimental_patchpoint_i64: 2813 visitPatchpoint(I, EHPadBB); 2814 break; 2815 case Intrinsic::experimental_gc_statepoint: 2816 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2817 break; 2818 case Intrinsic::wasm_rethrow_in_catch: { 2819 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2820 // special because it can be invoked, so we manually lower it to a DAG 2821 // node here. 2822 SmallVector<SDValue, 8> Ops; 2823 Ops.push_back(getRoot()); // inchain 2824 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2825 Ops.push_back( 2826 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2827 TLI.getPointerTy(DAG.getDataLayout()))); 2828 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2829 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2830 break; 2831 } 2832 } 2833 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2834 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2835 // Eventually we will support lowering the @llvm.experimental.deoptimize 2836 // intrinsic, and right now there are no plans to support other intrinsics 2837 // with deopt state. 2838 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2839 } else { 2840 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2841 } 2842 2843 // If the value of the invoke is used outside of its defining block, make it 2844 // available as a virtual register. 2845 // We already took care of the exported value for the statepoint instruction 2846 // during call to the LowerStatepoint. 2847 if (!isa<GCStatepointInst>(I)) { 2848 CopyToExportRegsIfNeeded(&I); 2849 } 2850 2851 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2852 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2853 BranchProbability EHPadBBProb = 2854 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2855 : BranchProbability::getZero(); 2856 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2857 2858 // Update successor info. 2859 addSuccessorWithProb(InvokeMBB, Return); 2860 for (auto &UnwindDest : UnwindDests) { 2861 UnwindDest.first->setIsEHPad(); 2862 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2863 } 2864 InvokeMBB->normalizeSuccProbs(); 2865 2866 // Drop into normal successor. 2867 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2868 DAG.getBasicBlock(Return))); 2869 } 2870 2871 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2872 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2873 2874 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2875 // have to do anything here to lower funclet bundles. 2876 assert(!I.hasOperandBundlesOtherThan( 2877 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2878 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2879 2880 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2881 visitInlineAsm(I); 2882 CopyToExportRegsIfNeeded(&I); 2883 2884 // Retrieve successors. 2885 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2886 2887 // Update successor info. 2888 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2889 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2890 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2891 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2892 Target->setIsInlineAsmBrIndirectTarget(); 2893 } 2894 CallBrMBB->normalizeSuccProbs(); 2895 2896 // Drop into default successor. 2897 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2898 MVT::Other, getControlRoot(), 2899 DAG.getBasicBlock(Return))); 2900 } 2901 2902 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2903 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2904 } 2905 2906 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2907 assert(FuncInfo.MBB->isEHPad() && 2908 "Call to landingpad not in landing pad!"); 2909 2910 // If there aren't registers to copy the values into (e.g., during SjLj 2911 // exceptions), then don't bother to create these DAG nodes. 2912 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2913 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2914 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2915 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2916 return; 2917 2918 // If landingpad's return type is token type, we don't create DAG nodes 2919 // for its exception pointer and selector value. The extraction of exception 2920 // pointer or selector value from token type landingpads is not currently 2921 // supported. 2922 if (LP.getType()->isTokenTy()) 2923 return; 2924 2925 SmallVector<EVT, 2> ValueVTs; 2926 SDLoc dl = getCurSDLoc(); 2927 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2928 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2929 2930 // Get the two live-in registers as SDValues. The physregs have already been 2931 // copied into virtual registers. 2932 SDValue Ops[2]; 2933 if (FuncInfo.ExceptionPointerVirtReg) { 2934 Ops[0] = DAG.getZExtOrTrunc( 2935 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2936 FuncInfo.ExceptionPointerVirtReg, 2937 TLI.getPointerTy(DAG.getDataLayout())), 2938 dl, ValueVTs[0]); 2939 } else { 2940 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2941 } 2942 Ops[1] = DAG.getZExtOrTrunc( 2943 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2944 FuncInfo.ExceptionSelectorVirtReg, 2945 TLI.getPointerTy(DAG.getDataLayout())), 2946 dl, ValueVTs[1]); 2947 2948 // Merge into one. 2949 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2950 DAG.getVTList(ValueVTs), Ops); 2951 setValue(&LP, Res); 2952 } 2953 2954 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2955 MachineBasicBlock *Last) { 2956 // Update JTCases. 2957 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2958 if (SL->JTCases[i].first.HeaderBB == First) 2959 SL->JTCases[i].first.HeaderBB = Last; 2960 2961 // Update BitTestCases. 2962 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2963 if (SL->BitTestCases[i].Parent == First) 2964 SL->BitTestCases[i].Parent = Last; 2965 } 2966 2967 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2968 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2969 2970 // Update machine-CFG edges with unique successors. 2971 SmallSet<BasicBlock*, 32> Done; 2972 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2973 BasicBlock *BB = I.getSuccessor(i); 2974 bool Inserted = Done.insert(BB).second; 2975 if (!Inserted) 2976 continue; 2977 2978 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2979 addSuccessorWithProb(IndirectBrMBB, Succ); 2980 } 2981 IndirectBrMBB->normalizeSuccProbs(); 2982 2983 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2984 MVT::Other, getControlRoot(), 2985 getValue(I.getAddress()))); 2986 } 2987 2988 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2989 if (!DAG.getTarget().Options.TrapUnreachable) 2990 return; 2991 2992 // We may be able to ignore unreachable behind a noreturn call. 2993 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2994 const BasicBlock &BB = *I.getParent(); 2995 if (&I != &BB.front()) { 2996 BasicBlock::const_iterator PredI = 2997 std::prev(BasicBlock::const_iterator(&I)); 2998 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2999 if (Call->doesNotReturn()) 3000 return; 3001 } 3002 } 3003 } 3004 3005 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 3006 } 3007 3008 void SelectionDAGBuilder::visitFSub(const User &I) { 3009 // -0.0 - X --> fneg 3010 Type *Ty = I.getType(); 3011 if (isa<Constant>(I.getOperand(0)) && 3012 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 3013 SDValue Op2 = getValue(I.getOperand(1)); 3014 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 3015 Op2.getValueType(), Op2)); 3016 return; 3017 } 3018 3019 visitBinary(I, ISD::FSUB); 3020 } 3021 3022 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3023 SDNodeFlags Flags; 3024 3025 SDValue Op = getValue(I.getOperand(0)); 3026 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3027 Op, Flags); 3028 setValue(&I, UnNodeValue); 3029 } 3030 3031 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3032 SDNodeFlags Flags; 3033 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3034 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3035 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3036 } 3037 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3038 Flags.setExact(ExactOp->isExact()); 3039 } 3040 3041 SDValue Op1 = getValue(I.getOperand(0)); 3042 SDValue Op2 = getValue(I.getOperand(1)); 3043 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3044 Op1, Op2, Flags); 3045 setValue(&I, BinNodeValue); 3046 } 3047 3048 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3049 SDValue Op1 = getValue(I.getOperand(0)); 3050 SDValue Op2 = getValue(I.getOperand(1)); 3051 3052 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3053 Op1.getValueType(), DAG.getDataLayout()); 3054 3055 // Coerce the shift amount to the right type if we can. 3056 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3057 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3058 unsigned Op2Size = Op2.getValueSizeInBits(); 3059 SDLoc DL = getCurSDLoc(); 3060 3061 // If the operand is smaller than the shift count type, promote it. 3062 if (ShiftSize > Op2Size) 3063 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3064 3065 // If the operand is larger than the shift count type but the shift 3066 // count type has enough bits to represent any shift value, truncate 3067 // it now. This is a common case and it exposes the truncate to 3068 // optimization early. 3069 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3070 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3071 // Otherwise we'll need to temporarily settle for some other convenient 3072 // type. Type legalization will make adjustments once the shiftee is split. 3073 else 3074 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3075 } 3076 3077 bool nuw = false; 3078 bool nsw = false; 3079 bool exact = false; 3080 3081 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3082 3083 if (const OverflowingBinaryOperator *OFBinOp = 3084 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3085 nuw = OFBinOp->hasNoUnsignedWrap(); 3086 nsw = OFBinOp->hasNoSignedWrap(); 3087 } 3088 if (const PossiblyExactOperator *ExactOp = 3089 dyn_cast<const PossiblyExactOperator>(&I)) 3090 exact = ExactOp->isExact(); 3091 } 3092 SDNodeFlags Flags; 3093 Flags.setExact(exact); 3094 Flags.setNoSignedWrap(nsw); 3095 Flags.setNoUnsignedWrap(nuw); 3096 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3097 Flags); 3098 setValue(&I, Res); 3099 } 3100 3101 void SelectionDAGBuilder::visitSDiv(const User &I) { 3102 SDValue Op1 = getValue(I.getOperand(0)); 3103 SDValue Op2 = getValue(I.getOperand(1)); 3104 3105 SDNodeFlags Flags; 3106 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3107 cast<PossiblyExactOperator>(&I)->isExact()); 3108 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3109 Op2, Flags)); 3110 } 3111 3112 void SelectionDAGBuilder::visitICmp(const User &I) { 3113 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3114 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3115 predicate = IC->getPredicate(); 3116 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3117 predicate = ICmpInst::Predicate(IC->getPredicate()); 3118 SDValue Op1 = getValue(I.getOperand(0)); 3119 SDValue Op2 = getValue(I.getOperand(1)); 3120 ISD::CondCode Opcode = getICmpCondCode(predicate); 3121 3122 auto &TLI = DAG.getTargetLoweringInfo(); 3123 EVT MemVT = 3124 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3125 3126 // If a pointer's DAG type is larger than its memory type then the DAG values 3127 // are zero-extended. This breaks signed comparisons so truncate back to the 3128 // underlying type before doing the compare. 3129 if (Op1.getValueType() != MemVT) { 3130 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3131 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3132 } 3133 3134 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3135 I.getType()); 3136 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3137 } 3138 3139 void SelectionDAGBuilder::visitFCmp(const User &I) { 3140 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3141 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3142 predicate = FC->getPredicate(); 3143 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3144 predicate = FCmpInst::Predicate(FC->getPredicate()); 3145 SDValue Op1 = getValue(I.getOperand(0)); 3146 SDValue Op2 = getValue(I.getOperand(1)); 3147 3148 ISD::CondCode Condition = getFCmpCondCode(predicate); 3149 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3150 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3151 Condition = getFCmpCodeWithoutNaN(Condition); 3152 3153 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3154 I.getType()); 3155 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3156 } 3157 3158 // Check if the condition of the select has one use or two users that are both 3159 // selects with the same condition. 3160 static bool hasOnlySelectUsers(const Value *Cond) { 3161 return llvm::all_of(Cond->users(), [](const Value *V) { 3162 return isa<SelectInst>(V); 3163 }); 3164 } 3165 3166 void SelectionDAGBuilder::visitSelect(const User &I) { 3167 SmallVector<EVT, 4> ValueVTs; 3168 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3169 ValueVTs); 3170 unsigned NumValues = ValueVTs.size(); 3171 if (NumValues == 0) return; 3172 3173 SmallVector<SDValue, 4> Values(NumValues); 3174 SDValue Cond = getValue(I.getOperand(0)); 3175 SDValue LHSVal = getValue(I.getOperand(1)); 3176 SDValue RHSVal = getValue(I.getOperand(2)); 3177 SmallVector<SDValue, 1> BaseOps(1, Cond); 3178 ISD::NodeType OpCode = 3179 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3180 3181 bool IsUnaryAbs = false; 3182 3183 // Min/max matching is only viable if all output VTs are the same. 3184 if (is_splat(ValueVTs)) { 3185 EVT VT = ValueVTs[0]; 3186 LLVMContext &Ctx = *DAG.getContext(); 3187 auto &TLI = DAG.getTargetLoweringInfo(); 3188 3189 // We care about the legality of the operation after it has been type 3190 // legalized. 3191 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3192 VT = TLI.getTypeToTransformTo(Ctx, VT); 3193 3194 // If the vselect is legal, assume we want to leave this as a vector setcc + 3195 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3196 // min/max is legal on the scalar type. 3197 bool UseScalarMinMax = VT.isVector() && 3198 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3199 3200 Value *LHS, *RHS; 3201 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3202 ISD::NodeType Opc = ISD::DELETED_NODE; 3203 switch (SPR.Flavor) { 3204 case SPF_UMAX: Opc = ISD::UMAX; break; 3205 case SPF_UMIN: Opc = ISD::UMIN; break; 3206 case SPF_SMAX: Opc = ISD::SMAX; break; 3207 case SPF_SMIN: Opc = ISD::SMIN; break; 3208 case SPF_FMINNUM: 3209 switch (SPR.NaNBehavior) { 3210 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3211 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3212 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3213 case SPNB_RETURNS_ANY: { 3214 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3215 Opc = ISD::FMINNUM; 3216 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3217 Opc = ISD::FMINIMUM; 3218 else if (UseScalarMinMax) 3219 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3220 ISD::FMINNUM : ISD::FMINIMUM; 3221 break; 3222 } 3223 } 3224 break; 3225 case SPF_FMAXNUM: 3226 switch (SPR.NaNBehavior) { 3227 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3228 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3229 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3230 case SPNB_RETURNS_ANY: 3231 3232 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3233 Opc = ISD::FMAXNUM; 3234 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3235 Opc = ISD::FMAXIMUM; 3236 else if (UseScalarMinMax) 3237 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3238 ISD::FMAXNUM : ISD::FMAXIMUM; 3239 break; 3240 } 3241 break; 3242 case SPF_ABS: 3243 IsUnaryAbs = true; 3244 Opc = ISD::ABS; 3245 break; 3246 case SPF_NABS: 3247 // TODO: we need to produce sub(0, abs(X)). 3248 default: break; 3249 } 3250 3251 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3252 (TLI.isOperationLegalOrCustom(Opc, VT) || 3253 (UseScalarMinMax && 3254 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3255 // If the underlying comparison instruction is used by any other 3256 // instruction, the consumed instructions won't be destroyed, so it is 3257 // not profitable to convert to a min/max. 3258 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3259 OpCode = Opc; 3260 LHSVal = getValue(LHS); 3261 RHSVal = getValue(RHS); 3262 BaseOps.clear(); 3263 } 3264 3265 if (IsUnaryAbs) { 3266 OpCode = Opc; 3267 LHSVal = getValue(LHS); 3268 BaseOps.clear(); 3269 } 3270 } 3271 3272 if (IsUnaryAbs) { 3273 for (unsigned i = 0; i != NumValues; ++i) { 3274 Values[i] = 3275 DAG.getNode(OpCode, getCurSDLoc(), 3276 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3277 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3278 } 3279 } else { 3280 for (unsigned i = 0; i != NumValues; ++i) { 3281 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3282 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3283 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3284 Values[i] = DAG.getNode( 3285 OpCode, getCurSDLoc(), 3286 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3287 } 3288 } 3289 3290 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3291 DAG.getVTList(ValueVTs), Values)); 3292 } 3293 3294 void SelectionDAGBuilder::visitTrunc(const User &I) { 3295 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3296 SDValue N = getValue(I.getOperand(0)); 3297 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3298 I.getType()); 3299 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3300 } 3301 3302 void SelectionDAGBuilder::visitZExt(const User &I) { 3303 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3304 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3305 SDValue N = getValue(I.getOperand(0)); 3306 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3307 I.getType()); 3308 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3309 } 3310 3311 void SelectionDAGBuilder::visitSExt(const User &I) { 3312 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3313 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3314 SDValue N = getValue(I.getOperand(0)); 3315 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3316 I.getType()); 3317 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3318 } 3319 3320 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3321 // FPTrunc is never a no-op cast, no need to check 3322 SDValue N = getValue(I.getOperand(0)); 3323 SDLoc dl = getCurSDLoc(); 3324 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3325 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3326 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3327 DAG.getTargetConstant( 3328 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3329 } 3330 3331 void SelectionDAGBuilder::visitFPExt(const User &I) { 3332 // FPExt is never a no-op cast, no need to check 3333 SDValue N = getValue(I.getOperand(0)); 3334 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3335 I.getType()); 3336 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3337 } 3338 3339 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3340 // FPToUI is never a no-op cast, no need to check 3341 SDValue N = getValue(I.getOperand(0)); 3342 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3343 I.getType()); 3344 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3345 } 3346 3347 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3348 // FPToSI is never a no-op cast, no need to check 3349 SDValue N = getValue(I.getOperand(0)); 3350 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3351 I.getType()); 3352 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3353 } 3354 3355 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3356 // UIToFP is never a no-op cast, no need to check 3357 SDValue N = getValue(I.getOperand(0)); 3358 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3359 I.getType()); 3360 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3361 } 3362 3363 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3364 // SIToFP is never a no-op cast, no need to check 3365 SDValue N = getValue(I.getOperand(0)); 3366 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3367 I.getType()); 3368 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3369 } 3370 3371 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3372 // What to do depends on the size of the integer and the size of the pointer. 3373 // We can either truncate, zero extend, or no-op, accordingly. 3374 SDValue N = getValue(I.getOperand(0)); 3375 auto &TLI = DAG.getTargetLoweringInfo(); 3376 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3377 I.getType()); 3378 EVT PtrMemVT = 3379 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3380 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3381 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3382 setValue(&I, N); 3383 } 3384 3385 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3386 // What to do depends on the size of the integer and the size of the pointer. 3387 // We can either truncate, zero extend, or no-op, accordingly. 3388 SDValue N = getValue(I.getOperand(0)); 3389 auto &TLI = DAG.getTargetLoweringInfo(); 3390 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3391 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3392 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3393 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3394 setValue(&I, N); 3395 } 3396 3397 void SelectionDAGBuilder::visitBitCast(const User &I) { 3398 SDValue N = getValue(I.getOperand(0)); 3399 SDLoc dl = getCurSDLoc(); 3400 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3401 I.getType()); 3402 3403 // BitCast assures us that source and destination are the same size so this is 3404 // either a BITCAST or a no-op. 3405 if (DestVT != N.getValueType()) 3406 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3407 DestVT, N)); // convert types. 3408 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3409 // might fold any kind of constant expression to an integer constant and that 3410 // is not what we are looking for. Only recognize a bitcast of a genuine 3411 // constant integer as an opaque constant. 3412 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3413 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3414 /*isOpaque*/true)); 3415 else 3416 setValue(&I, N); // noop cast. 3417 } 3418 3419 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3421 const Value *SV = I.getOperand(0); 3422 SDValue N = getValue(SV); 3423 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3424 3425 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3426 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3427 3428 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3429 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3430 3431 setValue(&I, N); 3432 } 3433 3434 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3435 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3436 SDValue InVec = getValue(I.getOperand(0)); 3437 SDValue InVal = getValue(I.getOperand(1)); 3438 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3439 TLI.getVectorIdxTy(DAG.getDataLayout())); 3440 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3441 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3442 InVec, InVal, InIdx)); 3443 } 3444 3445 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3447 SDValue InVec = getValue(I.getOperand(0)); 3448 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3449 TLI.getVectorIdxTy(DAG.getDataLayout())); 3450 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3451 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3452 InVec, InIdx)); 3453 } 3454 3455 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3456 SDValue Src1 = getValue(I.getOperand(0)); 3457 SDValue Src2 = getValue(I.getOperand(1)); 3458 ArrayRef<int> Mask; 3459 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3460 Mask = SVI->getShuffleMask(); 3461 else 3462 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3463 SDLoc DL = getCurSDLoc(); 3464 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3465 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3466 EVT SrcVT = Src1.getValueType(); 3467 3468 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3469 VT.isScalableVector()) { 3470 // Canonical splat form of first element of first input vector. 3471 SDValue FirstElt = 3472 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3473 DAG.getVectorIdxConstant(0, DL)); 3474 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3475 return; 3476 } 3477 3478 // For now, we only handle splats for scalable vectors. 3479 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3480 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3481 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3482 3483 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3484 unsigned MaskNumElts = Mask.size(); 3485 3486 if (SrcNumElts == MaskNumElts) { 3487 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3488 return; 3489 } 3490 3491 // Normalize the shuffle vector since mask and vector length don't match. 3492 if (SrcNumElts < MaskNumElts) { 3493 // Mask is longer than the source vectors. We can use concatenate vector to 3494 // make the mask and vectors lengths match. 3495 3496 if (MaskNumElts % SrcNumElts == 0) { 3497 // Mask length is a multiple of the source vector length. 3498 // Check if the shuffle is some kind of concatenation of the input 3499 // vectors. 3500 unsigned NumConcat = MaskNumElts / SrcNumElts; 3501 bool IsConcat = true; 3502 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3503 for (unsigned i = 0; i != MaskNumElts; ++i) { 3504 int Idx = Mask[i]; 3505 if (Idx < 0) 3506 continue; 3507 // Ensure the indices in each SrcVT sized piece are sequential and that 3508 // the same source is used for the whole piece. 3509 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3510 (ConcatSrcs[i / SrcNumElts] >= 0 && 3511 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3512 IsConcat = false; 3513 break; 3514 } 3515 // Remember which source this index came from. 3516 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3517 } 3518 3519 // The shuffle is concatenating multiple vectors together. Just emit 3520 // a CONCAT_VECTORS operation. 3521 if (IsConcat) { 3522 SmallVector<SDValue, 8> ConcatOps; 3523 for (auto Src : ConcatSrcs) { 3524 if (Src < 0) 3525 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3526 else if (Src == 0) 3527 ConcatOps.push_back(Src1); 3528 else 3529 ConcatOps.push_back(Src2); 3530 } 3531 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3532 return; 3533 } 3534 } 3535 3536 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3537 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3538 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3539 PaddedMaskNumElts); 3540 3541 // Pad both vectors with undefs to make them the same length as the mask. 3542 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3543 3544 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3545 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3546 MOps1[0] = Src1; 3547 MOps2[0] = Src2; 3548 3549 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3550 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3551 3552 // Readjust mask for new input vector length. 3553 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3554 for (unsigned i = 0; i != MaskNumElts; ++i) { 3555 int Idx = Mask[i]; 3556 if (Idx >= (int)SrcNumElts) 3557 Idx -= SrcNumElts - PaddedMaskNumElts; 3558 MappedOps[i] = Idx; 3559 } 3560 3561 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3562 3563 // If the concatenated vector was padded, extract a subvector with the 3564 // correct number of elements. 3565 if (MaskNumElts != PaddedMaskNumElts) 3566 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3567 DAG.getVectorIdxConstant(0, DL)); 3568 3569 setValue(&I, Result); 3570 return; 3571 } 3572 3573 if (SrcNumElts > MaskNumElts) { 3574 // Analyze the access pattern of the vector to see if we can extract 3575 // two subvectors and do the shuffle. 3576 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3577 bool CanExtract = true; 3578 for (int Idx : Mask) { 3579 unsigned Input = 0; 3580 if (Idx < 0) 3581 continue; 3582 3583 if (Idx >= (int)SrcNumElts) { 3584 Input = 1; 3585 Idx -= SrcNumElts; 3586 } 3587 3588 // If all the indices come from the same MaskNumElts sized portion of 3589 // the sources we can use extract. Also make sure the extract wouldn't 3590 // extract past the end of the source. 3591 int NewStartIdx = alignDown(Idx, MaskNumElts); 3592 if (NewStartIdx + MaskNumElts > SrcNumElts || 3593 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3594 CanExtract = false; 3595 // Make sure we always update StartIdx as we use it to track if all 3596 // elements are undef. 3597 StartIdx[Input] = NewStartIdx; 3598 } 3599 3600 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3601 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3602 return; 3603 } 3604 if (CanExtract) { 3605 // Extract appropriate subvector and generate a vector shuffle 3606 for (unsigned Input = 0; Input < 2; ++Input) { 3607 SDValue &Src = Input == 0 ? Src1 : Src2; 3608 if (StartIdx[Input] < 0) 3609 Src = DAG.getUNDEF(VT); 3610 else { 3611 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3612 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3613 } 3614 } 3615 3616 // Calculate new mask. 3617 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3618 for (int &Idx : MappedOps) { 3619 if (Idx >= (int)SrcNumElts) 3620 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3621 else if (Idx >= 0) 3622 Idx -= StartIdx[0]; 3623 } 3624 3625 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3626 return; 3627 } 3628 } 3629 3630 // We can't use either concat vectors or extract subvectors so fall back to 3631 // replacing the shuffle with extract and build vector. 3632 // to insert and build vector. 3633 EVT EltVT = VT.getVectorElementType(); 3634 SmallVector<SDValue,8> Ops; 3635 for (int Idx : Mask) { 3636 SDValue Res; 3637 3638 if (Idx < 0) { 3639 Res = DAG.getUNDEF(EltVT); 3640 } else { 3641 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3642 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3643 3644 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3645 DAG.getVectorIdxConstant(Idx, DL)); 3646 } 3647 3648 Ops.push_back(Res); 3649 } 3650 3651 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3652 } 3653 3654 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3655 ArrayRef<unsigned> Indices; 3656 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3657 Indices = IV->getIndices(); 3658 else 3659 Indices = cast<ConstantExpr>(&I)->getIndices(); 3660 3661 const Value *Op0 = I.getOperand(0); 3662 const Value *Op1 = I.getOperand(1); 3663 Type *AggTy = I.getType(); 3664 Type *ValTy = Op1->getType(); 3665 bool IntoUndef = isa<UndefValue>(Op0); 3666 bool FromUndef = isa<UndefValue>(Op1); 3667 3668 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3669 3670 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3671 SmallVector<EVT, 4> AggValueVTs; 3672 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3673 SmallVector<EVT, 4> ValValueVTs; 3674 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3675 3676 unsigned NumAggValues = AggValueVTs.size(); 3677 unsigned NumValValues = ValValueVTs.size(); 3678 SmallVector<SDValue, 4> Values(NumAggValues); 3679 3680 // Ignore an insertvalue that produces an empty object 3681 if (!NumAggValues) { 3682 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3683 return; 3684 } 3685 3686 SDValue Agg = getValue(Op0); 3687 unsigned i = 0; 3688 // Copy the beginning value(s) from the original aggregate. 3689 for (; i != LinearIndex; ++i) 3690 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3691 SDValue(Agg.getNode(), Agg.getResNo() + i); 3692 // Copy values from the inserted value(s). 3693 if (NumValValues) { 3694 SDValue Val = getValue(Op1); 3695 for (; i != LinearIndex + NumValValues; ++i) 3696 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3697 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3698 } 3699 // Copy remaining value(s) from the original aggregate. 3700 for (; i != NumAggValues; ++i) 3701 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3702 SDValue(Agg.getNode(), Agg.getResNo() + i); 3703 3704 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3705 DAG.getVTList(AggValueVTs), Values)); 3706 } 3707 3708 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3709 ArrayRef<unsigned> Indices; 3710 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3711 Indices = EV->getIndices(); 3712 else 3713 Indices = cast<ConstantExpr>(&I)->getIndices(); 3714 3715 const Value *Op0 = I.getOperand(0); 3716 Type *AggTy = Op0->getType(); 3717 Type *ValTy = I.getType(); 3718 bool OutOfUndef = isa<UndefValue>(Op0); 3719 3720 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3721 3722 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3723 SmallVector<EVT, 4> ValValueVTs; 3724 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3725 3726 unsigned NumValValues = ValValueVTs.size(); 3727 3728 // Ignore a extractvalue that produces an empty object 3729 if (!NumValValues) { 3730 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3731 return; 3732 } 3733 3734 SmallVector<SDValue, 4> Values(NumValValues); 3735 3736 SDValue Agg = getValue(Op0); 3737 // Copy out the selected value(s). 3738 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3739 Values[i - LinearIndex] = 3740 OutOfUndef ? 3741 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3742 SDValue(Agg.getNode(), Agg.getResNo() + i); 3743 3744 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3745 DAG.getVTList(ValValueVTs), Values)); 3746 } 3747 3748 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3749 Value *Op0 = I.getOperand(0); 3750 // Note that the pointer operand may be a vector of pointers. Take the scalar 3751 // element which holds a pointer. 3752 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3753 SDValue N = getValue(Op0); 3754 SDLoc dl = getCurSDLoc(); 3755 auto &TLI = DAG.getTargetLoweringInfo(); 3756 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3757 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3758 3759 // Normalize Vector GEP - all scalar operands should be converted to the 3760 // splat vector. 3761 bool IsVectorGEP = I.getType()->isVectorTy(); 3762 ElementCount VectorElementCount = 3763 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3764 : ElementCount(0, false); 3765 3766 if (IsVectorGEP && !N.getValueType().isVector()) { 3767 LLVMContext &Context = *DAG.getContext(); 3768 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3769 if (VectorElementCount.Scalable) 3770 N = DAG.getSplatVector(VT, dl, N); 3771 else 3772 N = DAG.getSplatBuildVector(VT, dl, N); 3773 } 3774 3775 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3776 GTI != E; ++GTI) { 3777 const Value *Idx = GTI.getOperand(); 3778 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3779 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3780 if (Field) { 3781 // N = N + Offset 3782 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3783 3784 // In an inbounds GEP with an offset that is nonnegative even when 3785 // interpreted as signed, assume there is no unsigned overflow. 3786 SDNodeFlags Flags; 3787 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3788 Flags.setNoUnsignedWrap(true); 3789 3790 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3791 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3792 } 3793 } else { 3794 // IdxSize is the width of the arithmetic according to IR semantics. 3795 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3796 // (and fix up the result later). 3797 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3798 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3799 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3800 // We intentionally mask away the high bits here; ElementSize may not 3801 // fit in IdxTy. 3802 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3803 bool ElementScalable = ElementSize.isScalable(); 3804 3805 // If this is a scalar constant or a splat vector of constants, 3806 // handle it quickly. 3807 const auto *C = dyn_cast<Constant>(Idx); 3808 if (C && isa<VectorType>(C->getType())) 3809 C = C->getSplatValue(); 3810 3811 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3812 if (CI && CI->isZero()) 3813 continue; 3814 if (CI && !ElementScalable) { 3815 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3816 LLVMContext &Context = *DAG.getContext(); 3817 SDValue OffsVal; 3818 if (IsVectorGEP) 3819 OffsVal = DAG.getConstant( 3820 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3821 else 3822 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3823 3824 // In an inbounds GEP with an offset that is nonnegative even when 3825 // interpreted as signed, assume there is no unsigned overflow. 3826 SDNodeFlags Flags; 3827 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3828 Flags.setNoUnsignedWrap(true); 3829 3830 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3831 3832 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3833 continue; 3834 } 3835 3836 // N = N + Idx * ElementMul; 3837 SDValue IdxN = getValue(Idx); 3838 3839 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3840 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3841 VectorElementCount); 3842 if (VectorElementCount.Scalable) 3843 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3844 else 3845 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3846 } 3847 3848 // If the index is smaller or larger than intptr_t, truncate or extend 3849 // it. 3850 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3851 3852 if (ElementScalable) { 3853 EVT VScaleTy = N.getValueType().getScalarType(); 3854 SDValue VScale = DAG.getNode( 3855 ISD::VSCALE, dl, VScaleTy, 3856 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3857 if (IsVectorGEP) 3858 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3859 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3860 } else { 3861 // If this is a multiply by a power of two, turn it into a shl 3862 // immediately. This is a very common case. 3863 if (ElementMul != 1) { 3864 if (ElementMul.isPowerOf2()) { 3865 unsigned Amt = ElementMul.logBase2(); 3866 IdxN = DAG.getNode(ISD::SHL, dl, 3867 N.getValueType(), IdxN, 3868 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3869 } else { 3870 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3871 IdxN.getValueType()); 3872 IdxN = DAG.getNode(ISD::MUL, dl, 3873 N.getValueType(), IdxN, Scale); 3874 } 3875 } 3876 } 3877 3878 N = DAG.getNode(ISD::ADD, dl, 3879 N.getValueType(), N, IdxN); 3880 } 3881 } 3882 3883 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3884 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3885 3886 setValue(&I, N); 3887 } 3888 3889 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3890 // If this is a fixed sized alloca in the entry block of the function, 3891 // allocate it statically on the stack. 3892 if (FuncInfo.StaticAllocaMap.count(&I)) 3893 return; // getValue will auto-populate this. 3894 3895 SDLoc dl = getCurSDLoc(); 3896 Type *Ty = I.getAllocatedType(); 3897 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3898 auto &DL = DAG.getDataLayout(); 3899 uint64_t TySize = DL.getTypeAllocSize(Ty); 3900 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3901 3902 SDValue AllocSize = getValue(I.getArraySize()); 3903 3904 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3905 if (AllocSize.getValueType() != IntPtr) 3906 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3907 3908 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3909 AllocSize, 3910 DAG.getConstant(TySize, dl, IntPtr)); 3911 3912 // Handle alignment. If the requested alignment is less than or equal to 3913 // the stack alignment, ignore it. If the size is greater than or equal to 3914 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3915 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3916 if (*Alignment <= StackAlign) 3917 Alignment = None; 3918 3919 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3920 // Round the size of the allocation up to the stack alignment size 3921 // by add SA-1 to the size. This doesn't overflow because we're computing 3922 // an address inside an alloca. 3923 SDNodeFlags Flags; 3924 Flags.setNoUnsignedWrap(true); 3925 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3926 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3927 3928 // Mask out the low bits for alignment purposes. 3929 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3930 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3931 3932 SDValue Ops[] = { 3933 getRoot(), AllocSize, 3934 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3935 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3936 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3937 setValue(&I, DSA); 3938 DAG.setRoot(DSA.getValue(1)); 3939 3940 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3941 } 3942 3943 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3944 if (I.isAtomic()) 3945 return visitAtomicLoad(I); 3946 3947 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3948 const Value *SV = I.getOperand(0); 3949 if (TLI.supportSwiftError()) { 3950 // Swifterror values can come from either a function parameter with 3951 // swifterror attribute or an alloca with swifterror attribute. 3952 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3953 if (Arg->hasSwiftErrorAttr()) 3954 return visitLoadFromSwiftError(I); 3955 } 3956 3957 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3958 if (Alloca->isSwiftError()) 3959 return visitLoadFromSwiftError(I); 3960 } 3961 } 3962 3963 SDValue Ptr = getValue(SV); 3964 3965 Type *Ty = I.getType(); 3966 Align Alignment = I.getAlign(); 3967 3968 AAMDNodes AAInfo; 3969 I.getAAMetadata(AAInfo); 3970 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3971 3972 SmallVector<EVT, 4> ValueVTs, MemVTs; 3973 SmallVector<uint64_t, 4> Offsets; 3974 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3975 unsigned NumValues = ValueVTs.size(); 3976 if (NumValues == 0) 3977 return; 3978 3979 bool isVolatile = I.isVolatile(); 3980 3981 SDValue Root; 3982 bool ConstantMemory = false; 3983 if (isVolatile) 3984 // Serialize volatile loads with other side effects. 3985 Root = getRoot(); 3986 else if (NumValues > MaxParallelChains) 3987 Root = getMemoryRoot(); 3988 else if (AA && 3989 AA->pointsToConstantMemory(MemoryLocation( 3990 SV, 3991 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3992 AAInfo))) { 3993 // Do not serialize (non-volatile) loads of constant memory with anything. 3994 Root = DAG.getEntryNode(); 3995 ConstantMemory = true; 3996 } else { 3997 // Do not serialize non-volatile loads against each other. 3998 Root = DAG.getRoot(); 3999 } 4000 4001 SDLoc dl = getCurSDLoc(); 4002 4003 if (isVolatile) 4004 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4005 4006 // An aggregate load cannot wrap around the address space, so offsets to its 4007 // parts don't wrap either. 4008 SDNodeFlags Flags; 4009 Flags.setNoUnsignedWrap(true); 4010 4011 SmallVector<SDValue, 4> Values(NumValues); 4012 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4013 EVT PtrVT = Ptr.getValueType(); 4014 4015 MachineMemOperand::Flags MMOFlags 4016 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4017 4018 unsigned ChainI = 0; 4019 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4020 // Serializing loads here may result in excessive register pressure, and 4021 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4022 // could recover a bit by hoisting nodes upward in the chain by recognizing 4023 // they are side-effect free or do not alias. The optimizer should really 4024 // avoid this case by converting large object/array copies to llvm.memcpy 4025 // (MaxParallelChains should always remain as failsafe). 4026 if (ChainI == MaxParallelChains) { 4027 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4028 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4029 makeArrayRef(Chains.data(), ChainI)); 4030 Root = Chain; 4031 ChainI = 0; 4032 } 4033 SDValue A = DAG.getNode(ISD::ADD, dl, 4034 PtrVT, Ptr, 4035 DAG.getConstant(Offsets[i], dl, PtrVT), 4036 Flags); 4037 4038 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4039 MachinePointerInfo(SV, Offsets[i]), Alignment, 4040 MMOFlags, AAInfo, Ranges); 4041 Chains[ChainI] = L.getValue(1); 4042 4043 if (MemVTs[i] != ValueVTs[i]) 4044 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4045 4046 Values[i] = L; 4047 } 4048 4049 if (!ConstantMemory) { 4050 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4051 makeArrayRef(Chains.data(), ChainI)); 4052 if (isVolatile) 4053 DAG.setRoot(Chain); 4054 else 4055 PendingLoads.push_back(Chain); 4056 } 4057 4058 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4059 DAG.getVTList(ValueVTs), Values)); 4060 } 4061 4062 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4063 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4064 "call visitStoreToSwiftError when backend supports swifterror"); 4065 4066 SmallVector<EVT, 4> ValueVTs; 4067 SmallVector<uint64_t, 4> Offsets; 4068 const Value *SrcV = I.getOperand(0); 4069 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4070 SrcV->getType(), ValueVTs, &Offsets); 4071 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4072 "expect a single EVT for swifterror"); 4073 4074 SDValue Src = getValue(SrcV); 4075 // Create a virtual register, then update the virtual register. 4076 Register VReg = 4077 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4078 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4079 // Chain can be getRoot or getControlRoot. 4080 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4081 SDValue(Src.getNode(), Src.getResNo())); 4082 DAG.setRoot(CopyNode); 4083 } 4084 4085 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4086 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4087 "call visitLoadFromSwiftError when backend supports swifterror"); 4088 4089 assert(!I.isVolatile() && 4090 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4091 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4092 "Support volatile, non temporal, invariant for load_from_swift_error"); 4093 4094 const Value *SV = I.getOperand(0); 4095 Type *Ty = I.getType(); 4096 AAMDNodes AAInfo; 4097 I.getAAMetadata(AAInfo); 4098 assert( 4099 (!AA || 4100 !AA->pointsToConstantMemory(MemoryLocation( 4101 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4102 AAInfo))) && 4103 "load_from_swift_error should not be constant memory"); 4104 4105 SmallVector<EVT, 4> ValueVTs; 4106 SmallVector<uint64_t, 4> Offsets; 4107 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4108 ValueVTs, &Offsets); 4109 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4110 "expect a single EVT for swifterror"); 4111 4112 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4113 SDValue L = DAG.getCopyFromReg( 4114 getRoot(), getCurSDLoc(), 4115 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4116 4117 setValue(&I, L); 4118 } 4119 4120 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4121 if (I.isAtomic()) 4122 return visitAtomicStore(I); 4123 4124 const Value *SrcV = I.getOperand(0); 4125 const Value *PtrV = I.getOperand(1); 4126 4127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4128 if (TLI.supportSwiftError()) { 4129 // Swifterror values can come from either a function parameter with 4130 // swifterror attribute or an alloca with swifterror attribute. 4131 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4132 if (Arg->hasSwiftErrorAttr()) 4133 return visitStoreToSwiftError(I); 4134 } 4135 4136 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4137 if (Alloca->isSwiftError()) 4138 return visitStoreToSwiftError(I); 4139 } 4140 } 4141 4142 SmallVector<EVT, 4> ValueVTs, MemVTs; 4143 SmallVector<uint64_t, 4> Offsets; 4144 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4145 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4146 unsigned NumValues = ValueVTs.size(); 4147 if (NumValues == 0) 4148 return; 4149 4150 // Get the lowered operands. Note that we do this after 4151 // checking if NumResults is zero, because with zero results 4152 // the operands won't have values in the map. 4153 SDValue Src = getValue(SrcV); 4154 SDValue Ptr = getValue(PtrV); 4155 4156 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4157 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4158 SDLoc dl = getCurSDLoc(); 4159 Align Alignment = I.getAlign(); 4160 AAMDNodes AAInfo; 4161 I.getAAMetadata(AAInfo); 4162 4163 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4164 4165 // An aggregate load cannot wrap around the address space, so offsets to its 4166 // parts don't wrap either. 4167 SDNodeFlags Flags; 4168 Flags.setNoUnsignedWrap(true); 4169 4170 unsigned ChainI = 0; 4171 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4172 // See visitLoad comments. 4173 if (ChainI == MaxParallelChains) { 4174 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4175 makeArrayRef(Chains.data(), ChainI)); 4176 Root = Chain; 4177 ChainI = 0; 4178 } 4179 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4180 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4181 if (MemVTs[i] != ValueVTs[i]) 4182 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4183 SDValue St = 4184 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4185 Alignment, MMOFlags, AAInfo); 4186 Chains[ChainI] = St; 4187 } 4188 4189 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4190 makeArrayRef(Chains.data(), ChainI)); 4191 DAG.setRoot(StoreNode); 4192 } 4193 4194 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4195 bool IsCompressing) { 4196 SDLoc sdl = getCurSDLoc(); 4197 4198 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4199 MaybeAlign &Alignment) { 4200 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4201 Src0 = I.getArgOperand(0); 4202 Ptr = I.getArgOperand(1); 4203 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4204 Mask = I.getArgOperand(3); 4205 }; 4206 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4207 MaybeAlign &Alignment) { 4208 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4209 Src0 = I.getArgOperand(0); 4210 Ptr = I.getArgOperand(1); 4211 Mask = I.getArgOperand(2); 4212 Alignment = None; 4213 }; 4214 4215 Value *PtrOperand, *MaskOperand, *Src0Operand; 4216 MaybeAlign Alignment; 4217 if (IsCompressing) 4218 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4219 else 4220 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4221 4222 SDValue Ptr = getValue(PtrOperand); 4223 SDValue Src0 = getValue(Src0Operand); 4224 SDValue Mask = getValue(MaskOperand); 4225 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4226 4227 EVT VT = Src0.getValueType(); 4228 if (!Alignment) 4229 Alignment = DAG.getEVTAlign(VT); 4230 4231 AAMDNodes AAInfo; 4232 I.getAAMetadata(AAInfo); 4233 4234 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4235 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4236 // TODO: Make MachineMemOperands aware of scalable 4237 // vectors. 4238 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4239 SDValue StoreNode = 4240 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4241 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4242 DAG.setRoot(StoreNode); 4243 setValue(&I, StoreNode); 4244 } 4245 4246 // Get a uniform base for the Gather/Scatter intrinsic. 4247 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4248 // We try to represent it as a base pointer + vector of indices. 4249 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4250 // The first operand of the GEP may be a single pointer or a vector of pointers 4251 // Example: 4252 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4253 // or 4254 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4255 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4256 // 4257 // When the first GEP operand is a single pointer - it is the uniform base we 4258 // are looking for. If first operand of the GEP is a splat vector - we 4259 // extract the splat value and use it as a uniform base. 4260 // In all other cases the function returns 'false'. 4261 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4262 ISD::MemIndexType &IndexType, SDValue &Scale, 4263 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4264 SelectionDAG& DAG = SDB->DAG; 4265 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4266 const DataLayout &DL = DAG.getDataLayout(); 4267 4268 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4269 4270 // Handle splat constant pointer. 4271 if (auto *C = dyn_cast<Constant>(Ptr)) { 4272 C = C->getSplatValue(); 4273 if (!C) 4274 return false; 4275 4276 Base = SDB->getValue(C); 4277 4278 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4279 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4280 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4281 IndexType = ISD::SIGNED_SCALED; 4282 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4283 return true; 4284 } 4285 4286 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4287 if (!GEP || GEP->getParent() != CurBB) 4288 return false; 4289 4290 if (GEP->getNumOperands() != 2) 4291 return false; 4292 4293 const Value *BasePtr = GEP->getPointerOperand(); 4294 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4295 4296 // Make sure the base is scalar and the index is a vector. 4297 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4298 return false; 4299 4300 Base = SDB->getValue(BasePtr); 4301 Index = SDB->getValue(IndexVal); 4302 IndexType = ISD::SIGNED_SCALED; 4303 Scale = DAG.getTargetConstant( 4304 DL.getTypeAllocSize(GEP->getResultElementType()), 4305 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4306 return true; 4307 } 4308 4309 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4310 SDLoc sdl = getCurSDLoc(); 4311 4312 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4313 const Value *Ptr = I.getArgOperand(1); 4314 SDValue Src0 = getValue(I.getArgOperand(0)); 4315 SDValue Mask = getValue(I.getArgOperand(3)); 4316 EVT VT = Src0.getValueType(); 4317 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4318 ->getMaybeAlignValue() 4319 .getValueOr(DAG.getEVTAlign(VT)); 4320 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4321 4322 AAMDNodes AAInfo; 4323 I.getAAMetadata(AAInfo); 4324 4325 SDValue Base; 4326 SDValue Index; 4327 ISD::MemIndexType IndexType; 4328 SDValue Scale; 4329 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4330 I.getParent()); 4331 4332 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4333 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4334 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4335 // TODO: Make MachineMemOperands aware of scalable 4336 // vectors. 4337 MemoryLocation::UnknownSize, Alignment, AAInfo); 4338 if (!UniformBase) { 4339 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4340 Index = getValue(Ptr); 4341 IndexType = ISD::SIGNED_SCALED; 4342 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4343 } 4344 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4345 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4346 Ops, MMO, IndexType); 4347 DAG.setRoot(Scatter); 4348 setValue(&I, Scatter); 4349 } 4350 4351 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4352 SDLoc sdl = getCurSDLoc(); 4353 4354 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4355 MaybeAlign &Alignment) { 4356 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4357 Ptr = I.getArgOperand(0); 4358 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4359 Mask = I.getArgOperand(2); 4360 Src0 = I.getArgOperand(3); 4361 }; 4362 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4363 MaybeAlign &Alignment) { 4364 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4365 Ptr = I.getArgOperand(0); 4366 Alignment = None; 4367 Mask = I.getArgOperand(1); 4368 Src0 = I.getArgOperand(2); 4369 }; 4370 4371 Value *PtrOperand, *MaskOperand, *Src0Operand; 4372 MaybeAlign Alignment; 4373 if (IsExpanding) 4374 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4375 else 4376 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4377 4378 SDValue Ptr = getValue(PtrOperand); 4379 SDValue Src0 = getValue(Src0Operand); 4380 SDValue Mask = getValue(MaskOperand); 4381 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4382 4383 EVT VT = Src0.getValueType(); 4384 if (!Alignment) 4385 Alignment = DAG.getEVTAlign(VT); 4386 4387 AAMDNodes AAInfo; 4388 I.getAAMetadata(AAInfo); 4389 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4390 4391 // Do not serialize masked loads of constant memory with anything. 4392 MemoryLocation ML; 4393 if (VT.isScalableVector()) 4394 ML = MemoryLocation(PtrOperand); 4395 else 4396 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4397 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4398 AAInfo); 4399 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4400 4401 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4402 4403 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4404 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4405 // TODO: Make MachineMemOperands aware of scalable 4406 // vectors. 4407 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4408 4409 SDValue Load = 4410 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4411 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4412 if (AddToChain) 4413 PendingLoads.push_back(Load.getValue(1)); 4414 setValue(&I, Load); 4415 } 4416 4417 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4418 SDLoc sdl = getCurSDLoc(); 4419 4420 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4421 const Value *Ptr = I.getArgOperand(0); 4422 SDValue Src0 = getValue(I.getArgOperand(3)); 4423 SDValue Mask = getValue(I.getArgOperand(2)); 4424 4425 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4426 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4427 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4428 ->getMaybeAlignValue() 4429 .getValueOr(DAG.getEVTAlign(VT)); 4430 4431 AAMDNodes AAInfo; 4432 I.getAAMetadata(AAInfo); 4433 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4434 4435 SDValue Root = DAG.getRoot(); 4436 SDValue Base; 4437 SDValue Index; 4438 ISD::MemIndexType IndexType; 4439 SDValue Scale; 4440 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4441 I.getParent()); 4442 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4443 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4444 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4445 // TODO: Make MachineMemOperands aware of scalable 4446 // vectors. 4447 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4448 4449 if (!UniformBase) { 4450 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4451 Index = getValue(Ptr); 4452 IndexType = ISD::SIGNED_SCALED; 4453 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4454 } 4455 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4456 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4457 Ops, MMO, IndexType); 4458 4459 PendingLoads.push_back(Gather.getValue(1)); 4460 setValue(&I, Gather); 4461 } 4462 4463 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4464 SDLoc dl = getCurSDLoc(); 4465 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4466 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4467 SyncScope::ID SSID = I.getSyncScopeID(); 4468 4469 SDValue InChain = getRoot(); 4470 4471 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4472 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4473 4474 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4475 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4476 4477 MachineFunction &MF = DAG.getMachineFunction(); 4478 MachineMemOperand *MMO = MF.getMachineMemOperand( 4479 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4480 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4481 FailureOrdering); 4482 4483 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4484 dl, MemVT, VTs, InChain, 4485 getValue(I.getPointerOperand()), 4486 getValue(I.getCompareOperand()), 4487 getValue(I.getNewValOperand()), MMO); 4488 4489 SDValue OutChain = L.getValue(2); 4490 4491 setValue(&I, L); 4492 DAG.setRoot(OutChain); 4493 } 4494 4495 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4496 SDLoc dl = getCurSDLoc(); 4497 ISD::NodeType NT; 4498 switch (I.getOperation()) { 4499 default: llvm_unreachable("Unknown atomicrmw operation"); 4500 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4501 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4502 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4503 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4504 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4505 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4506 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4507 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4508 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4509 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4510 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4511 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4512 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4513 } 4514 AtomicOrdering Ordering = I.getOrdering(); 4515 SyncScope::ID SSID = I.getSyncScopeID(); 4516 4517 SDValue InChain = getRoot(); 4518 4519 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4520 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4521 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4522 4523 MachineFunction &MF = DAG.getMachineFunction(); 4524 MachineMemOperand *MMO = MF.getMachineMemOperand( 4525 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4526 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4527 4528 SDValue L = 4529 DAG.getAtomic(NT, dl, MemVT, InChain, 4530 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4531 MMO); 4532 4533 SDValue OutChain = L.getValue(1); 4534 4535 setValue(&I, L); 4536 DAG.setRoot(OutChain); 4537 } 4538 4539 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4540 SDLoc dl = getCurSDLoc(); 4541 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4542 SDValue Ops[3]; 4543 Ops[0] = getRoot(); 4544 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4545 TLI.getFenceOperandTy(DAG.getDataLayout())); 4546 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4547 TLI.getFenceOperandTy(DAG.getDataLayout())); 4548 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4549 } 4550 4551 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4552 SDLoc dl = getCurSDLoc(); 4553 AtomicOrdering Order = I.getOrdering(); 4554 SyncScope::ID SSID = I.getSyncScopeID(); 4555 4556 SDValue InChain = getRoot(); 4557 4558 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4559 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4560 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4561 4562 if (!TLI.supportsUnalignedAtomics() && 4563 I.getAlignment() < MemVT.getSizeInBits() / 8) 4564 report_fatal_error("Cannot generate unaligned atomic load"); 4565 4566 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4567 4568 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4569 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4570 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4571 4572 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4573 4574 SDValue Ptr = getValue(I.getPointerOperand()); 4575 4576 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4577 // TODO: Once this is better exercised by tests, it should be merged with 4578 // the normal path for loads to prevent future divergence. 4579 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4580 if (MemVT != VT) 4581 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4582 4583 setValue(&I, L); 4584 SDValue OutChain = L.getValue(1); 4585 if (!I.isUnordered()) 4586 DAG.setRoot(OutChain); 4587 else 4588 PendingLoads.push_back(OutChain); 4589 return; 4590 } 4591 4592 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4593 Ptr, MMO); 4594 4595 SDValue OutChain = L.getValue(1); 4596 if (MemVT != VT) 4597 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4598 4599 setValue(&I, L); 4600 DAG.setRoot(OutChain); 4601 } 4602 4603 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4604 SDLoc dl = getCurSDLoc(); 4605 4606 AtomicOrdering Ordering = I.getOrdering(); 4607 SyncScope::ID SSID = I.getSyncScopeID(); 4608 4609 SDValue InChain = getRoot(); 4610 4611 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4612 EVT MemVT = 4613 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4614 4615 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4616 report_fatal_error("Cannot generate unaligned atomic store"); 4617 4618 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4619 4620 MachineFunction &MF = DAG.getMachineFunction(); 4621 MachineMemOperand *MMO = MF.getMachineMemOperand( 4622 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4623 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4624 4625 SDValue Val = getValue(I.getValueOperand()); 4626 if (Val.getValueType() != MemVT) 4627 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4628 SDValue Ptr = getValue(I.getPointerOperand()); 4629 4630 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4631 // TODO: Once this is better exercised by tests, it should be merged with 4632 // the normal path for stores to prevent future divergence. 4633 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4634 DAG.setRoot(S); 4635 return; 4636 } 4637 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4638 Ptr, Val, MMO); 4639 4640 4641 DAG.setRoot(OutChain); 4642 } 4643 4644 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4645 /// node. 4646 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4647 unsigned Intrinsic) { 4648 // Ignore the callsite's attributes. A specific call site may be marked with 4649 // readnone, but the lowering code will expect the chain based on the 4650 // definition. 4651 const Function *F = I.getCalledFunction(); 4652 bool HasChain = !F->doesNotAccessMemory(); 4653 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4654 4655 // Build the operand list. 4656 SmallVector<SDValue, 8> Ops; 4657 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4658 if (OnlyLoad) { 4659 // We don't need to serialize loads against other loads. 4660 Ops.push_back(DAG.getRoot()); 4661 } else { 4662 Ops.push_back(getRoot()); 4663 } 4664 } 4665 4666 // Info is set by getTgtMemInstrinsic 4667 TargetLowering::IntrinsicInfo Info; 4668 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4669 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4670 DAG.getMachineFunction(), 4671 Intrinsic); 4672 4673 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4674 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4675 Info.opc == ISD::INTRINSIC_W_CHAIN) 4676 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4677 TLI.getPointerTy(DAG.getDataLayout()))); 4678 4679 // Add all operands of the call to the operand list. 4680 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4681 const Value *Arg = I.getArgOperand(i); 4682 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4683 Ops.push_back(getValue(Arg)); 4684 continue; 4685 } 4686 4687 // Use TargetConstant instead of a regular constant for immarg. 4688 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4689 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4690 assert(CI->getBitWidth() <= 64 && 4691 "large intrinsic immediates not handled"); 4692 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4693 } else { 4694 Ops.push_back( 4695 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4696 } 4697 } 4698 4699 SmallVector<EVT, 4> ValueVTs; 4700 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4701 4702 if (HasChain) 4703 ValueVTs.push_back(MVT::Other); 4704 4705 SDVTList VTs = DAG.getVTList(ValueVTs); 4706 4707 // Create the node. 4708 SDValue Result; 4709 if (IsTgtIntrinsic) { 4710 // This is target intrinsic that touches memory 4711 AAMDNodes AAInfo; 4712 I.getAAMetadata(AAInfo); 4713 Result = 4714 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4715 MachinePointerInfo(Info.ptrVal, Info.offset), 4716 Info.align, Info.flags, Info.size, AAInfo); 4717 } else if (!HasChain) { 4718 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4719 } else if (!I.getType()->isVoidTy()) { 4720 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4721 } else { 4722 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4723 } 4724 4725 if (HasChain) { 4726 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4727 if (OnlyLoad) 4728 PendingLoads.push_back(Chain); 4729 else 4730 DAG.setRoot(Chain); 4731 } 4732 4733 if (!I.getType()->isVoidTy()) { 4734 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4735 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4736 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4737 } else 4738 Result = lowerRangeToAssertZExt(DAG, I, Result); 4739 4740 MaybeAlign Alignment = I.getRetAlign(); 4741 if (!Alignment) 4742 Alignment = F->getAttributes().getRetAlignment(); 4743 // Insert `assertalign` node if there's an alignment. 4744 if (InsertAssertAlign && Alignment) { 4745 Result = 4746 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4747 } 4748 4749 setValue(&I, Result); 4750 } 4751 } 4752 4753 /// GetSignificand - Get the significand and build it into a floating-point 4754 /// number with exponent of 1: 4755 /// 4756 /// Op = (Op & 0x007fffff) | 0x3f800000; 4757 /// 4758 /// where Op is the hexadecimal representation of floating point value. 4759 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4760 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4761 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4762 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4763 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4764 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4765 } 4766 4767 /// GetExponent - Get the exponent: 4768 /// 4769 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4770 /// 4771 /// where Op is the hexadecimal representation of floating point value. 4772 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4773 const TargetLowering &TLI, const SDLoc &dl) { 4774 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4775 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4776 SDValue t1 = DAG.getNode( 4777 ISD::SRL, dl, MVT::i32, t0, 4778 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4779 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4780 DAG.getConstant(127, dl, MVT::i32)); 4781 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4782 } 4783 4784 /// getF32Constant - Get 32-bit floating point constant. 4785 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4786 const SDLoc &dl) { 4787 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4788 MVT::f32); 4789 } 4790 4791 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4792 SelectionDAG &DAG) { 4793 // TODO: What fast-math-flags should be set on the floating-point nodes? 4794 4795 // IntegerPartOfX = ((int32_t)(t0); 4796 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4797 4798 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4799 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4800 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4801 4802 // IntegerPartOfX <<= 23; 4803 IntegerPartOfX = DAG.getNode( 4804 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4805 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4806 DAG.getDataLayout()))); 4807 4808 SDValue TwoToFractionalPartOfX; 4809 if (LimitFloatPrecision <= 6) { 4810 // For floating-point precision of 6: 4811 // 4812 // TwoToFractionalPartOfX = 4813 // 0.997535578f + 4814 // (0.735607626f + 0.252464424f * x) * x; 4815 // 4816 // error 0.0144103317, which is 6 bits 4817 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4818 getF32Constant(DAG, 0x3e814304, dl)); 4819 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4820 getF32Constant(DAG, 0x3f3c50c8, dl)); 4821 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4822 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4823 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4824 } else if (LimitFloatPrecision <= 12) { 4825 // For floating-point precision of 12: 4826 // 4827 // TwoToFractionalPartOfX = 4828 // 0.999892986f + 4829 // (0.696457318f + 4830 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4831 // 4832 // error 0.000107046256, which is 13 to 14 bits 4833 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4834 getF32Constant(DAG, 0x3da235e3, dl)); 4835 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4836 getF32Constant(DAG, 0x3e65b8f3, dl)); 4837 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4838 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4839 getF32Constant(DAG, 0x3f324b07, dl)); 4840 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4841 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4842 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4843 } else { // LimitFloatPrecision <= 18 4844 // For floating-point precision of 18: 4845 // 4846 // TwoToFractionalPartOfX = 4847 // 0.999999982f + 4848 // (0.693148872f + 4849 // (0.240227044f + 4850 // (0.554906021e-1f + 4851 // (0.961591928e-2f + 4852 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4853 // error 2.47208000*10^(-7), which is better than 18 bits 4854 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4855 getF32Constant(DAG, 0x3924b03e, dl)); 4856 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4857 getF32Constant(DAG, 0x3ab24b87, dl)); 4858 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4859 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4860 getF32Constant(DAG, 0x3c1d8c17, dl)); 4861 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4862 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4863 getF32Constant(DAG, 0x3d634a1d, dl)); 4864 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4865 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4866 getF32Constant(DAG, 0x3e75fe14, dl)); 4867 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4868 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4869 getF32Constant(DAG, 0x3f317234, dl)); 4870 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4871 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4872 getF32Constant(DAG, 0x3f800000, dl)); 4873 } 4874 4875 // Add the exponent into the result in integer domain. 4876 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4877 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4878 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4879 } 4880 4881 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4882 /// limited-precision mode. 4883 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4884 const TargetLowering &TLI) { 4885 if (Op.getValueType() == MVT::f32 && 4886 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4887 4888 // Put the exponent in the right bit position for later addition to the 4889 // final result: 4890 // 4891 // t0 = Op * log2(e) 4892 4893 // TODO: What fast-math-flags should be set here? 4894 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4895 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4896 return getLimitedPrecisionExp2(t0, dl, DAG); 4897 } 4898 4899 // No special expansion. 4900 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4901 } 4902 4903 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4904 /// limited-precision mode. 4905 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4906 const TargetLowering &TLI) { 4907 // TODO: What fast-math-flags should be set on the floating-point nodes? 4908 4909 if (Op.getValueType() == MVT::f32 && 4910 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4911 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4912 4913 // Scale the exponent by log(2). 4914 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4915 SDValue LogOfExponent = 4916 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4917 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4918 4919 // Get the significand and build it into a floating-point number with 4920 // exponent of 1. 4921 SDValue X = GetSignificand(DAG, Op1, dl); 4922 4923 SDValue LogOfMantissa; 4924 if (LimitFloatPrecision <= 6) { 4925 // For floating-point precision of 6: 4926 // 4927 // LogofMantissa = 4928 // -1.1609546f + 4929 // (1.4034025f - 0.23903021f * x) * x; 4930 // 4931 // error 0.0034276066, which is better than 8 bits 4932 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4933 getF32Constant(DAG, 0xbe74c456, dl)); 4934 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4935 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4936 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4937 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4938 getF32Constant(DAG, 0x3f949a29, dl)); 4939 } else if (LimitFloatPrecision <= 12) { 4940 // For floating-point precision of 12: 4941 // 4942 // LogOfMantissa = 4943 // -1.7417939f + 4944 // (2.8212026f + 4945 // (-1.4699568f + 4946 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4947 // 4948 // error 0.000061011436, which is 14 bits 4949 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4950 getF32Constant(DAG, 0xbd67b6d6, dl)); 4951 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4952 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4953 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4954 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4955 getF32Constant(DAG, 0x3fbc278b, dl)); 4956 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4957 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4958 getF32Constant(DAG, 0x40348e95, dl)); 4959 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4960 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4961 getF32Constant(DAG, 0x3fdef31a, dl)); 4962 } else { // LimitFloatPrecision <= 18 4963 // For floating-point precision of 18: 4964 // 4965 // LogOfMantissa = 4966 // -2.1072184f + 4967 // (4.2372794f + 4968 // (-3.7029485f + 4969 // (2.2781945f + 4970 // (-0.87823314f + 4971 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4972 // 4973 // error 0.0000023660568, which is better than 18 bits 4974 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4975 getF32Constant(DAG, 0xbc91e5ac, dl)); 4976 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4977 getF32Constant(DAG, 0x3e4350aa, dl)); 4978 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4979 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4980 getF32Constant(DAG, 0x3f60d3e3, dl)); 4981 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4982 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4983 getF32Constant(DAG, 0x4011cdf0, dl)); 4984 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4985 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4986 getF32Constant(DAG, 0x406cfd1c, dl)); 4987 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4988 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4989 getF32Constant(DAG, 0x408797cb, dl)); 4990 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4991 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4992 getF32Constant(DAG, 0x4006dcab, dl)); 4993 } 4994 4995 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4996 } 4997 4998 // No special expansion. 4999 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5000 } 5001 5002 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5003 /// limited-precision mode. 5004 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5005 const TargetLowering &TLI) { 5006 // TODO: What fast-math-flags should be set on the floating-point nodes? 5007 5008 if (Op.getValueType() == MVT::f32 && 5009 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5010 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5011 5012 // Get the exponent. 5013 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5014 5015 // Get the significand and build it into a floating-point number with 5016 // exponent of 1. 5017 SDValue X = GetSignificand(DAG, Op1, dl); 5018 5019 // Different possible minimax approximations of significand in 5020 // floating-point for various degrees of accuracy over [1,2]. 5021 SDValue Log2ofMantissa; 5022 if (LimitFloatPrecision <= 6) { 5023 // For floating-point precision of 6: 5024 // 5025 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5026 // 5027 // error 0.0049451742, which is more than 7 bits 5028 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5029 getF32Constant(DAG, 0xbeb08fe0, dl)); 5030 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5031 getF32Constant(DAG, 0x40019463, dl)); 5032 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5033 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5034 getF32Constant(DAG, 0x3fd6633d, dl)); 5035 } else if (LimitFloatPrecision <= 12) { 5036 // For floating-point precision of 12: 5037 // 5038 // Log2ofMantissa = 5039 // -2.51285454f + 5040 // (4.07009056f + 5041 // (-2.12067489f + 5042 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5043 // 5044 // error 0.0000876136000, which is better than 13 bits 5045 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5046 getF32Constant(DAG, 0xbda7262e, dl)); 5047 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5048 getF32Constant(DAG, 0x3f25280b, dl)); 5049 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5050 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5051 getF32Constant(DAG, 0x4007b923, dl)); 5052 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5053 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5054 getF32Constant(DAG, 0x40823e2f, dl)); 5055 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5056 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5057 getF32Constant(DAG, 0x4020d29c, dl)); 5058 } else { // LimitFloatPrecision <= 18 5059 // For floating-point precision of 18: 5060 // 5061 // Log2ofMantissa = 5062 // -3.0400495f + 5063 // (6.1129976f + 5064 // (-5.3420409f + 5065 // (3.2865683f + 5066 // (-1.2669343f + 5067 // (0.27515199f - 5068 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5069 // 5070 // error 0.0000018516, which is better than 18 bits 5071 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5072 getF32Constant(DAG, 0xbcd2769e, dl)); 5073 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5074 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5075 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5076 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5077 getF32Constant(DAG, 0x3fa22ae7, dl)); 5078 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5079 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5080 getF32Constant(DAG, 0x40525723, dl)); 5081 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5082 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5083 getF32Constant(DAG, 0x40aaf200, dl)); 5084 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5085 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5086 getF32Constant(DAG, 0x40c39dad, dl)); 5087 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5088 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5089 getF32Constant(DAG, 0x4042902c, dl)); 5090 } 5091 5092 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5093 } 5094 5095 // No special expansion. 5096 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5097 } 5098 5099 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5100 /// limited-precision mode. 5101 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5102 const TargetLowering &TLI) { 5103 // TODO: What fast-math-flags should be set on the floating-point nodes? 5104 5105 if (Op.getValueType() == MVT::f32 && 5106 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5107 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5108 5109 // Scale the exponent by log10(2) [0.30102999f]. 5110 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5111 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5112 getF32Constant(DAG, 0x3e9a209a, dl)); 5113 5114 // Get the significand and build it into a floating-point number with 5115 // exponent of 1. 5116 SDValue X = GetSignificand(DAG, Op1, dl); 5117 5118 SDValue Log10ofMantissa; 5119 if (LimitFloatPrecision <= 6) { 5120 // For floating-point precision of 6: 5121 // 5122 // Log10ofMantissa = 5123 // -0.50419619f + 5124 // (0.60948995f - 0.10380950f * x) * x; 5125 // 5126 // error 0.0014886165, which is 6 bits 5127 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5128 getF32Constant(DAG, 0xbdd49a13, dl)); 5129 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5130 getF32Constant(DAG, 0x3f1c0789, dl)); 5131 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5132 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5133 getF32Constant(DAG, 0x3f011300, dl)); 5134 } else if (LimitFloatPrecision <= 12) { 5135 // For floating-point precision of 12: 5136 // 5137 // Log10ofMantissa = 5138 // -0.64831180f + 5139 // (0.91751397f + 5140 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5141 // 5142 // error 0.00019228036, which is better than 12 bits 5143 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5144 getF32Constant(DAG, 0x3d431f31, dl)); 5145 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5146 getF32Constant(DAG, 0x3ea21fb2, dl)); 5147 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5148 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5149 getF32Constant(DAG, 0x3f6ae232, dl)); 5150 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5151 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5152 getF32Constant(DAG, 0x3f25f7c3, dl)); 5153 } else { // LimitFloatPrecision <= 18 5154 // For floating-point precision of 18: 5155 // 5156 // Log10ofMantissa = 5157 // -0.84299375f + 5158 // (1.5327582f + 5159 // (-1.0688956f + 5160 // (0.49102474f + 5161 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5162 // 5163 // error 0.0000037995730, which is better than 18 bits 5164 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5165 getF32Constant(DAG, 0x3c5d51ce, dl)); 5166 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5167 getF32Constant(DAG, 0x3e00685a, dl)); 5168 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5169 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5170 getF32Constant(DAG, 0x3efb6798, dl)); 5171 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5172 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5173 getF32Constant(DAG, 0x3f88d192, dl)); 5174 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5175 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5176 getF32Constant(DAG, 0x3fc4316c, dl)); 5177 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5178 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5179 getF32Constant(DAG, 0x3f57ce70, dl)); 5180 } 5181 5182 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5183 } 5184 5185 // No special expansion. 5186 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5187 } 5188 5189 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5190 /// limited-precision mode. 5191 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5192 const TargetLowering &TLI) { 5193 if (Op.getValueType() == MVT::f32 && 5194 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5195 return getLimitedPrecisionExp2(Op, dl, DAG); 5196 5197 // No special expansion. 5198 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5199 } 5200 5201 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5202 /// limited-precision mode with x == 10.0f. 5203 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5204 SelectionDAG &DAG, const TargetLowering &TLI) { 5205 bool IsExp10 = false; 5206 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5207 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5208 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5209 APFloat Ten(10.0f); 5210 IsExp10 = LHSC->isExactlyValue(Ten); 5211 } 5212 } 5213 5214 // TODO: What fast-math-flags should be set on the FMUL node? 5215 if (IsExp10) { 5216 // Put the exponent in the right bit position for later addition to the 5217 // final result: 5218 // 5219 // #define LOG2OF10 3.3219281f 5220 // t0 = Op * LOG2OF10; 5221 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5222 getF32Constant(DAG, 0x40549a78, dl)); 5223 return getLimitedPrecisionExp2(t0, dl, DAG); 5224 } 5225 5226 // No special expansion. 5227 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5228 } 5229 5230 /// ExpandPowI - Expand a llvm.powi intrinsic. 5231 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5232 SelectionDAG &DAG) { 5233 // If RHS is a constant, we can expand this out to a multiplication tree, 5234 // otherwise we end up lowering to a call to __powidf2 (for example). When 5235 // optimizing for size, we only want to do this if the expansion would produce 5236 // a small number of multiplies, otherwise we do the full expansion. 5237 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5238 // Get the exponent as a positive value. 5239 unsigned Val = RHSC->getSExtValue(); 5240 if ((int)Val < 0) Val = -Val; 5241 5242 // powi(x, 0) -> 1.0 5243 if (Val == 0) 5244 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5245 5246 bool OptForSize = DAG.shouldOptForSize(); 5247 if (!OptForSize || 5248 // If optimizing for size, don't insert too many multiplies. 5249 // This inserts up to 5 multiplies. 5250 countPopulation(Val) + Log2_32(Val) < 7) { 5251 // We use the simple binary decomposition method to generate the multiply 5252 // sequence. There are more optimal ways to do this (for example, 5253 // powi(x,15) generates one more multiply than it should), but this has 5254 // the benefit of being both really simple and much better than a libcall. 5255 SDValue Res; // Logically starts equal to 1.0 5256 SDValue CurSquare = LHS; 5257 // TODO: Intrinsics should have fast-math-flags that propagate to these 5258 // nodes. 5259 while (Val) { 5260 if (Val & 1) { 5261 if (Res.getNode()) 5262 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5263 else 5264 Res = CurSquare; // 1.0*CurSquare. 5265 } 5266 5267 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5268 CurSquare, CurSquare); 5269 Val >>= 1; 5270 } 5271 5272 // If the original was negative, invert the result, producing 1/(x*x*x). 5273 if (RHSC->getSExtValue() < 0) 5274 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5275 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5276 return Res; 5277 } 5278 } 5279 5280 // Otherwise, expand to a libcall. 5281 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5282 } 5283 5284 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5285 SDValue LHS, SDValue RHS, SDValue Scale, 5286 SelectionDAG &DAG, const TargetLowering &TLI) { 5287 EVT VT = LHS.getValueType(); 5288 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5289 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5290 LLVMContext &Ctx = *DAG.getContext(); 5291 5292 // If the type is legal but the operation isn't, this node might survive all 5293 // the way to operation legalization. If we end up there and we do not have 5294 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5295 // node. 5296 5297 // Coax the legalizer into expanding the node during type legalization instead 5298 // by bumping the size by one bit. This will force it to Promote, enabling the 5299 // early expansion and avoiding the need to expand later. 5300 5301 // We don't have to do this if Scale is 0; that can always be expanded, unless 5302 // it's a saturating signed operation. Those can experience true integer 5303 // division overflow, a case which we must avoid. 5304 5305 // FIXME: We wouldn't have to do this (or any of the early 5306 // expansion/promotion) if it was possible to expand a libcall of an 5307 // illegal type during operation legalization. But it's not, so things 5308 // get a bit hacky. 5309 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5310 if ((ScaleInt > 0 || (Saturating && Signed)) && 5311 (TLI.isTypeLegal(VT) || 5312 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5313 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5314 Opcode, VT, ScaleInt); 5315 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5316 EVT PromVT; 5317 if (VT.isScalarInteger()) 5318 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5319 else if (VT.isVector()) { 5320 PromVT = VT.getVectorElementType(); 5321 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5322 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5323 } else 5324 llvm_unreachable("Wrong VT for DIVFIX?"); 5325 if (Signed) { 5326 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5327 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5328 } else { 5329 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5330 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5331 } 5332 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5333 // For saturating operations, we need to shift up the LHS to get the 5334 // proper saturation width, and then shift down again afterwards. 5335 if (Saturating) 5336 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5337 DAG.getConstant(1, DL, ShiftTy)); 5338 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5339 if (Saturating) 5340 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5341 DAG.getConstant(1, DL, ShiftTy)); 5342 return DAG.getZExtOrTrunc(Res, DL, VT); 5343 } 5344 } 5345 5346 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5347 } 5348 5349 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5350 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5351 static void 5352 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5353 const SDValue &N) { 5354 switch (N.getOpcode()) { 5355 case ISD::CopyFromReg: { 5356 SDValue Op = N.getOperand(1); 5357 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5358 Op.getValueType().getSizeInBits()); 5359 return; 5360 } 5361 case ISD::BITCAST: 5362 case ISD::AssertZext: 5363 case ISD::AssertSext: 5364 case ISD::TRUNCATE: 5365 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5366 return; 5367 case ISD::BUILD_PAIR: 5368 case ISD::BUILD_VECTOR: 5369 case ISD::CONCAT_VECTORS: 5370 for (SDValue Op : N->op_values()) 5371 getUnderlyingArgRegs(Regs, Op); 5372 return; 5373 default: 5374 return; 5375 } 5376 } 5377 5378 /// If the DbgValueInst is a dbg_value of a function argument, create the 5379 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5380 /// instruction selection, they will be inserted to the entry BB. 5381 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5382 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5383 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5384 const Argument *Arg = dyn_cast<Argument>(V); 5385 if (!Arg) 5386 return false; 5387 5388 if (!IsDbgDeclare) { 5389 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5390 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5391 // the entry block. 5392 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5393 if (!IsInEntryBlock) 5394 return false; 5395 5396 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5397 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5398 // variable that also is a param. 5399 // 5400 // Although, if we are at the top of the entry block already, we can still 5401 // emit using ArgDbgValue. This might catch some situations when the 5402 // dbg.value refers to an argument that isn't used in the entry block, so 5403 // any CopyToReg node would be optimized out and the only way to express 5404 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5405 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5406 // we should only emit as ArgDbgValue if the Variable is an argument to the 5407 // current function, and the dbg.value intrinsic is found in the entry 5408 // block. 5409 bool VariableIsFunctionInputArg = Variable->isParameter() && 5410 !DL->getInlinedAt(); 5411 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5412 if (!IsInPrologue && !VariableIsFunctionInputArg) 5413 return false; 5414 5415 // Here we assume that a function argument on IR level only can be used to 5416 // describe one input parameter on source level. If we for example have 5417 // source code like this 5418 // 5419 // struct A { long x, y; }; 5420 // void foo(struct A a, long b) { 5421 // ... 5422 // b = a.x; 5423 // ... 5424 // } 5425 // 5426 // and IR like this 5427 // 5428 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5429 // entry: 5430 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5431 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5432 // call void @llvm.dbg.value(metadata i32 %b, "b", 5433 // ... 5434 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5435 // ... 5436 // 5437 // then the last dbg.value is describing a parameter "b" using a value that 5438 // is an argument. But since we already has used %a1 to describe a parameter 5439 // we should not handle that last dbg.value here (that would result in an 5440 // incorrect hoisting of the DBG_VALUE to the function entry). 5441 // Notice that we allow one dbg.value per IR level argument, to accommodate 5442 // for the situation with fragments above. 5443 if (VariableIsFunctionInputArg) { 5444 unsigned ArgNo = Arg->getArgNo(); 5445 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5446 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5447 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5448 return false; 5449 FuncInfo.DescribedArgs.set(ArgNo); 5450 } 5451 } 5452 5453 MachineFunction &MF = DAG.getMachineFunction(); 5454 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5455 5456 bool IsIndirect = false; 5457 Optional<MachineOperand> Op; 5458 // Some arguments' frame index is recorded during argument lowering. 5459 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5460 if (FI != std::numeric_limits<int>::max()) 5461 Op = MachineOperand::CreateFI(FI); 5462 5463 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5464 if (!Op && N.getNode()) { 5465 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5466 Register Reg; 5467 if (ArgRegsAndSizes.size() == 1) 5468 Reg = ArgRegsAndSizes.front().first; 5469 5470 if (Reg && Reg.isVirtual()) { 5471 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5472 Register PR = RegInfo.getLiveInPhysReg(Reg); 5473 if (PR) 5474 Reg = PR; 5475 } 5476 if (Reg) { 5477 Op = MachineOperand::CreateReg(Reg, false); 5478 IsIndirect = IsDbgDeclare; 5479 } 5480 } 5481 5482 if (!Op && N.getNode()) { 5483 // Check if frame index is available. 5484 SDValue LCandidate = peekThroughBitcasts(N); 5485 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5486 if (FrameIndexSDNode *FINode = 5487 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5488 Op = MachineOperand::CreateFI(FINode->getIndex()); 5489 } 5490 5491 if (!Op) { 5492 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5493 auto splitMultiRegDbgValue 5494 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5495 unsigned Offset = 0; 5496 for (auto RegAndSize : SplitRegs) { 5497 // If the expression is already a fragment, the current register 5498 // offset+size might extend beyond the fragment. In this case, only 5499 // the register bits that are inside the fragment are relevant. 5500 int RegFragmentSizeInBits = RegAndSize.second; 5501 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5502 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5503 // The register is entirely outside the expression fragment, 5504 // so is irrelevant for debug info. 5505 if (Offset >= ExprFragmentSizeInBits) 5506 break; 5507 // The register is partially outside the expression fragment, only 5508 // the low bits within the fragment are relevant for debug info. 5509 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5510 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5511 } 5512 } 5513 5514 auto FragmentExpr = DIExpression::createFragmentExpression( 5515 Expr, Offset, RegFragmentSizeInBits); 5516 Offset += RegAndSize.second; 5517 // If a valid fragment expression cannot be created, the variable's 5518 // correct value cannot be determined and so it is set as Undef. 5519 if (!FragmentExpr) { 5520 SDDbgValue *SDV = DAG.getConstantDbgValue( 5521 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5522 DAG.AddDbgValue(SDV, nullptr, false); 5523 continue; 5524 } 5525 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5526 FuncInfo.ArgDbgValues.push_back( 5527 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5528 RegAndSize.first, Variable, *FragmentExpr)); 5529 } 5530 }; 5531 5532 // Check if ValueMap has reg number. 5533 DenseMap<const Value *, Register>::const_iterator 5534 VMI = FuncInfo.ValueMap.find(V); 5535 if (VMI != FuncInfo.ValueMap.end()) { 5536 const auto &TLI = DAG.getTargetLoweringInfo(); 5537 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5538 V->getType(), getABIRegCopyCC(V)); 5539 if (RFV.occupiesMultipleRegs()) { 5540 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5541 return true; 5542 } 5543 5544 Op = MachineOperand::CreateReg(VMI->second, false); 5545 IsIndirect = IsDbgDeclare; 5546 } else if (ArgRegsAndSizes.size() > 1) { 5547 // This was split due to the calling convention, and no virtual register 5548 // mapping exists for the value. 5549 splitMultiRegDbgValue(ArgRegsAndSizes); 5550 return true; 5551 } 5552 } 5553 5554 if (!Op) 5555 return false; 5556 5557 assert(Variable->isValidLocationForIntrinsic(DL) && 5558 "Expected inlined-at fields to agree"); 5559 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5560 FuncInfo.ArgDbgValues.push_back( 5561 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5562 *Op, Variable, Expr)); 5563 5564 return true; 5565 } 5566 5567 /// Return the appropriate SDDbgValue based on N. 5568 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5569 DILocalVariable *Variable, 5570 DIExpression *Expr, 5571 const DebugLoc &dl, 5572 unsigned DbgSDNodeOrder) { 5573 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5574 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5575 // stack slot locations. 5576 // 5577 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5578 // debug values here after optimization: 5579 // 5580 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5581 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5582 // 5583 // Both describe the direct values of their associated variables. 5584 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5585 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5586 } 5587 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5588 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5589 } 5590 5591 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5592 switch (Intrinsic) { 5593 case Intrinsic::smul_fix: 5594 return ISD::SMULFIX; 5595 case Intrinsic::umul_fix: 5596 return ISD::UMULFIX; 5597 case Intrinsic::smul_fix_sat: 5598 return ISD::SMULFIXSAT; 5599 case Intrinsic::umul_fix_sat: 5600 return ISD::UMULFIXSAT; 5601 case Intrinsic::sdiv_fix: 5602 return ISD::SDIVFIX; 5603 case Intrinsic::udiv_fix: 5604 return ISD::UDIVFIX; 5605 case Intrinsic::sdiv_fix_sat: 5606 return ISD::SDIVFIXSAT; 5607 case Intrinsic::udiv_fix_sat: 5608 return ISD::UDIVFIXSAT; 5609 default: 5610 llvm_unreachable("Unhandled fixed point intrinsic"); 5611 } 5612 } 5613 5614 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5615 const char *FunctionName) { 5616 assert(FunctionName && "FunctionName must not be nullptr"); 5617 SDValue Callee = DAG.getExternalSymbol( 5618 FunctionName, 5619 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5620 LowerCallTo(I, Callee, I.isTailCall()); 5621 } 5622 5623 /// Given a @llvm.call.preallocated.setup, return the corresponding 5624 /// preallocated call. 5625 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5626 assert(cast<CallBase>(PreallocatedSetup) 5627 ->getCalledFunction() 5628 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5629 "expected call_preallocated_setup Value"); 5630 for (auto *U : PreallocatedSetup->users()) { 5631 auto *UseCall = cast<CallBase>(U); 5632 const Function *Fn = UseCall->getCalledFunction(); 5633 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5634 return UseCall; 5635 } 5636 } 5637 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5638 } 5639 5640 /// Lower the call to the specified intrinsic function. 5641 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5642 unsigned Intrinsic) { 5643 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5644 SDLoc sdl = getCurSDLoc(); 5645 DebugLoc dl = getCurDebugLoc(); 5646 SDValue Res; 5647 5648 switch (Intrinsic) { 5649 default: 5650 // By default, turn this into a target intrinsic node. 5651 visitTargetIntrinsic(I, Intrinsic); 5652 return; 5653 case Intrinsic::vscale: { 5654 match(&I, m_VScale(DAG.getDataLayout())); 5655 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5656 setValue(&I, 5657 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5658 return; 5659 } 5660 case Intrinsic::vastart: visitVAStart(I); return; 5661 case Intrinsic::vaend: visitVAEnd(I); return; 5662 case Intrinsic::vacopy: visitVACopy(I); return; 5663 case Intrinsic::returnaddress: 5664 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5665 TLI.getPointerTy(DAG.getDataLayout()), 5666 getValue(I.getArgOperand(0)))); 5667 return; 5668 case Intrinsic::addressofreturnaddress: 5669 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5670 TLI.getPointerTy(DAG.getDataLayout()))); 5671 return; 5672 case Intrinsic::sponentry: 5673 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5674 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5675 return; 5676 case Intrinsic::frameaddress: 5677 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5678 TLI.getFrameIndexTy(DAG.getDataLayout()), 5679 getValue(I.getArgOperand(0)))); 5680 return; 5681 case Intrinsic::read_volatile_register: 5682 case Intrinsic::read_register: { 5683 Value *Reg = I.getArgOperand(0); 5684 SDValue Chain = getRoot(); 5685 SDValue RegName = 5686 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5687 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5688 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5689 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5690 setValue(&I, Res); 5691 DAG.setRoot(Res.getValue(1)); 5692 return; 5693 } 5694 case Intrinsic::write_register: { 5695 Value *Reg = I.getArgOperand(0); 5696 Value *RegValue = I.getArgOperand(1); 5697 SDValue Chain = getRoot(); 5698 SDValue RegName = 5699 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5700 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5701 RegName, getValue(RegValue))); 5702 return; 5703 } 5704 case Intrinsic::memcpy: { 5705 const auto &MCI = cast<MemCpyInst>(I); 5706 SDValue Op1 = getValue(I.getArgOperand(0)); 5707 SDValue Op2 = getValue(I.getArgOperand(1)); 5708 SDValue Op3 = getValue(I.getArgOperand(2)); 5709 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5710 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5711 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5712 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5713 bool isVol = MCI.isVolatile(); 5714 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5715 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5716 // node. 5717 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5718 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5719 /* AlwaysInline */ false, isTC, 5720 MachinePointerInfo(I.getArgOperand(0)), 5721 MachinePointerInfo(I.getArgOperand(1))); 5722 updateDAGForMaybeTailCall(MC); 5723 return; 5724 } 5725 case Intrinsic::memcpy_inline: { 5726 const auto &MCI = cast<MemCpyInlineInst>(I); 5727 SDValue Dst = getValue(I.getArgOperand(0)); 5728 SDValue Src = getValue(I.getArgOperand(1)); 5729 SDValue Size = getValue(I.getArgOperand(2)); 5730 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5731 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5732 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5733 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5734 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5735 bool isVol = MCI.isVolatile(); 5736 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5737 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5738 // node. 5739 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5740 /* AlwaysInline */ true, isTC, 5741 MachinePointerInfo(I.getArgOperand(0)), 5742 MachinePointerInfo(I.getArgOperand(1))); 5743 updateDAGForMaybeTailCall(MC); 5744 return; 5745 } 5746 case Intrinsic::memset: { 5747 const auto &MSI = cast<MemSetInst>(I); 5748 SDValue Op1 = getValue(I.getArgOperand(0)); 5749 SDValue Op2 = getValue(I.getArgOperand(1)); 5750 SDValue Op3 = getValue(I.getArgOperand(2)); 5751 // @llvm.memset defines 0 and 1 to both mean no alignment. 5752 Align Alignment = MSI.getDestAlign().valueOrOne(); 5753 bool isVol = MSI.isVolatile(); 5754 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5755 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5756 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5757 MachinePointerInfo(I.getArgOperand(0))); 5758 updateDAGForMaybeTailCall(MS); 5759 return; 5760 } 5761 case Intrinsic::memmove: { 5762 const auto &MMI = cast<MemMoveInst>(I); 5763 SDValue Op1 = getValue(I.getArgOperand(0)); 5764 SDValue Op2 = getValue(I.getArgOperand(1)); 5765 SDValue Op3 = getValue(I.getArgOperand(2)); 5766 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5767 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5768 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5769 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5770 bool isVol = MMI.isVolatile(); 5771 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5772 // FIXME: Support passing different dest/src alignments to the memmove DAG 5773 // node. 5774 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5775 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5776 isTC, MachinePointerInfo(I.getArgOperand(0)), 5777 MachinePointerInfo(I.getArgOperand(1))); 5778 updateDAGForMaybeTailCall(MM); 5779 return; 5780 } 5781 case Intrinsic::memcpy_element_unordered_atomic: { 5782 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5783 SDValue Dst = getValue(MI.getRawDest()); 5784 SDValue Src = getValue(MI.getRawSource()); 5785 SDValue Length = getValue(MI.getLength()); 5786 5787 unsigned DstAlign = MI.getDestAlignment(); 5788 unsigned SrcAlign = MI.getSourceAlignment(); 5789 Type *LengthTy = MI.getLength()->getType(); 5790 unsigned ElemSz = MI.getElementSizeInBytes(); 5791 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5792 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5793 SrcAlign, Length, LengthTy, ElemSz, isTC, 5794 MachinePointerInfo(MI.getRawDest()), 5795 MachinePointerInfo(MI.getRawSource())); 5796 updateDAGForMaybeTailCall(MC); 5797 return; 5798 } 5799 case Intrinsic::memmove_element_unordered_atomic: { 5800 auto &MI = cast<AtomicMemMoveInst>(I); 5801 SDValue Dst = getValue(MI.getRawDest()); 5802 SDValue Src = getValue(MI.getRawSource()); 5803 SDValue Length = getValue(MI.getLength()); 5804 5805 unsigned DstAlign = MI.getDestAlignment(); 5806 unsigned SrcAlign = MI.getSourceAlignment(); 5807 Type *LengthTy = MI.getLength()->getType(); 5808 unsigned ElemSz = MI.getElementSizeInBytes(); 5809 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5810 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5811 SrcAlign, Length, LengthTy, ElemSz, isTC, 5812 MachinePointerInfo(MI.getRawDest()), 5813 MachinePointerInfo(MI.getRawSource())); 5814 updateDAGForMaybeTailCall(MC); 5815 return; 5816 } 5817 case Intrinsic::memset_element_unordered_atomic: { 5818 auto &MI = cast<AtomicMemSetInst>(I); 5819 SDValue Dst = getValue(MI.getRawDest()); 5820 SDValue Val = getValue(MI.getValue()); 5821 SDValue Length = getValue(MI.getLength()); 5822 5823 unsigned DstAlign = MI.getDestAlignment(); 5824 Type *LengthTy = MI.getLength()->getType(); 5825 unsigned ElemSz = MI.getElementSizeInBytes(); 5826 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5827 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5828 LengthTy, ElemSz, isTC, 5829 MachinePointerInfo(MI.getRawDest())); 5830 updateDAGForMaybeTailCall(MC); 5831 return; 5832 } 5833 case Intrinsic::call_preallocated_setup: { 5834 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5835 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5836 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5837 getRoot(), SrcValue); 5838 setValue(&I, Res); 5839 DAG.setRoot(Res); 5840 return; 5841 } 5842 case Intrinsic::call_preallocated_arg: { 5843 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5844 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5845 SDValue Ops[3]; 5846 Ops[0] = getRoot(); 5847 Ops[1] = SrcValue; 5848 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5849 MVT::i32); // arg index 5850 SDValue Res = DAG.getNode( 5851 ISD::PREALLOCATED_ARG, sdl, 5852 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5853 setValue(&I, Res); 5854 DAG.setRoot(Res.getValue(1)); 5855 return; 5856 } 5857 case Intrinsic::dbg_addr: 5858 case Intrinsic::dbg_declare: { 5859 const auto &DI = cast<DbgVariableIntrinsic>(I); 5860 DILocalVariable *Variable = DI.getVariable(); 5861 DIExpression *Expression = DI.getExpression(); 5862 dropDanglingDebugInfo(Variable, Expression); 5863 assert(Variable && "Missing variable"); 5864 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5865 << "\n"); 5866 // Check if address has undef value. 5867 const Value *Address = DI.getVariableLocation(); 5868 if (!Address || isa<UndefValue>(Address) || 5869 (Address->use_empty() && !isa<Argument>(Address))) { 5870 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5871 << " (bad/undef/unused-arg address)\n"); 5872 return; 5873 } 5874 5875 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5876 5877 // Check if this variable can be described by a frame index, typically 5878 // either as a static alloca or a byval parameter. 5879 int FI = std::numeric_limits<int>::max(); 5880 if (const auto *AI = 5881 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5882 if (AI->isStaticAlloca()) { 5883 auto I = FuncInfo.StaticAllocaMap.find(AI); 5884 if (I != FuncInfo.StaticAllocaMap.end()) 5885 FI = I->second; 5886 } 5887 } else if (const auto *Arg = dyn_cast<Argument>( 5888 Address->stripInBoundsConstantOffsets())) { 5889 FI = FuncInfo.getArgumentFrameIndex(Arg); 5890 } 5891 5892 // llvm.dbg.addr is control dependent and always generates indirect 5893 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5894 // the MachineFunction variable table. 5895 if (FI != std::numeric_limits<int>::max()) { 5896 if (Intrinsic == Intrinsic::dbg_addr) { 5897 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5898 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5899 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5900 } else { 5901 LLVM_DEBUG(dbgs() << "Skipping " << DI 5902 << " (variable info stashed in MF side table)\n"); 5903 } 5904 return; 5905 } 5906 5907 SDValue &N = NodeMap[Address]; 5908 if (!N.getNode() && isa<Argument>(Address)) 5909 // Check unused arguments map. 5910 N = UnusedArgNodeMap[Address]; 5911 SDDbgValue *SDV; 5912 if (N.getNode()) { 5913 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5914 Address = BCI->getOperand(0); 5915 // Parameters are handled specially. 5916 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5917 if (isParameter && FINode) { 5918 // Byval parameter. We have a frame index at this point. 5919 SDV = 5920 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5921 /*IsIndirect*/ true, dl, SDNodeOrder); 5922 } else if (isa<Argument>(Address)) { 5923 // Address is an argument, so try to emit its dbg value using 5924 // virtual register info from the FuncInfo.ValueMap. 5925 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5926 return; 5927 } else { 5928 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5929 true, dl, SDNodeOrder); 5930 } 5931 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5932 } else { 5933 // If Address is an argument then try to emit its dbg value using 5934 // virtual register info from the FuncInfo.ValueMap. 5935 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5936 N)) { 5937 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5938 << " (could not emit func-arg dbg_value)\n"); 5939 } 5940 } 5941 return; 5942 } 5943 case Intrinsic::dbg_label: { 5944 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5945 DILabel *Label = DI.getLabel(); 5946 assert(Label && "Missing label"); 5947 5948 SDDbgLabel *SDV; 5949 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5950 DAG.AddDbgLabel(SDV); 5951 return; 5952 } 5953 case Intrinsic::dbg_value: { 5954 const DbgValueInst &DI = cast<DbgValueInst>(I); 5955 assert(DI.getVariable() && "Missing variable"); 5956 5957 DILocalVariable *Variable = DI.getVariable(); 5958 DIExpression *Expression = DI.getExpression(); 5959 dropDanglingDebugInfo(Variable, Expression); 5960 const Value *V = DI.getValue(); 5961 if (!V) 5962 return; 5963 5964 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5965 SDNodeOrder)) 5966 return; 5967 5968 // TODO: Dangling debug info will eventually either be resolved or produce 5969 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5970 // between the original dbg.value location and its resolved DBG_VALUE, which 5971 // we should ideally fill with an extra Undef DBG_VALUE. 5972 5973 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5974 return; 5975 } 5976 5977 case Intrinsic::eh_typeid_for: { 5978 // Find the type id for the given typeinfo. 5979 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5980 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5981 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5982 setValue(&I, Res); 5983 return; 5984 } 5985 5986 case Intrinsic::eh_return_i32: 5987 case Intrinsic::eh_return_i64: 5988 DAG.getMachineFunction().setCallsEHReturn(true); 5989 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5990 MVT::Other, 5991 getControlRoot(), 5992 getValue(I.getArgOperand(0)), 5993 getValue(I.getArgOperand(1)))); 5994 return; 5995 case Intrinsic::eh_unwind_init: 5996 DAG.getMachineFunction().setCallsUnwindInit(true); 5997 return; 5998 case Intrinsic::eh_dwarf_cfa: 5999 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6000 TLI.getPointerTy(DAG.getDataLayout()), 6001 getValue(I.getArgOperand(0)))); 6002 return; 6003 case Intrinsic::eh_sjlj_callsite: { 6004 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6005 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6006 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6007 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6008 6009 MMI.setCurrentCallSite(CI->getZExtValue()); 6010 return; 6011 } 6012 case Intrinsic::eh_sjlj_functioncontext: { 6013 // Get and store the index of the function context. 6014 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6015 AllocaInst *FnCtx = 6016 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6017 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6018 MFI.setFunctionContextIndex(FI); 6019 return; 6020 } 6021 case Intrinsic::eh_sjlj_setjmp: { 6022 SDValue Ops[2]; 6023 Ops[0] = getRoot(); 6024 Ops[1] = getValue(I.getArgOperand(0)); 6025 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6026 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6027 setValue(&I, Op.getValue(0)); 6028 DAG.setRoot(Op.getValue(1)); 6029 return; 6030 } 6031 case Intrinsic::eh_sjlj_longjmp: 6032 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6033 getRoot(), getValue(I.getArgOperand(0)))); 6034 return; 6035 case Intrinsic::eh_sjlj_setup_dispatch: 6036 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6037 getRoot())); 6038 return; 6039 case Intrinsic::masked_gather: 6040 visitMaskedGather(I); 6041 return; 6042 case Intrinsic::masked_load: 6043 visitMaskedLoad(I); 6044 return; 6045 case Intrinsic::masked_scatter: 6046 visitMaskedScatter(I); 6047 return; 6048 case Intrinsic::masked_store: 6049 visitMaskedStore(I); 6050 return; 6051 case Intrinsic::masked_expandload: 6052 visitMaskedLoad(I, true /* IsExpanding */); 6053 return; 6054 case Intrinsic::masked_compressstore: 6055 visitMaskedStore(I, true /* IsCompressing */); 6056 return; 6057 case Intrinsic::powi: 6058 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6059 getValue(I.getArgOperand(1)), DAG)); 6060 return; 6061 case Intrinsic::log: 6062 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6063 return; 6064 case Intrinsic::log2: 6065 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6066 return; 6067 case Intrinsic::log10: 6068 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6069 return; 6070 case Intrinsic::exp: 6071 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6072 return; 6073 case Intrinsic::exp2: 6074 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6075 return; 6076 case Intrinsic::pow: 6077 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6078 getValue(I.getArgOperand(1)), DAG, TLI)); 6079 return; 6080 case Intrinsic::sqrt: 6081 case Intrinsic::fabs: 6082 case Intrinsic::sin: 6083 case Intrinsic::cos: 6084 case Intrinsic::floor: 6085 case Intrinsic::ceil: 6086 case Intrinsic::trunc: 6087 case Intrinsic::rint: 6088 case Intrinsic::nearbyint: 6089 case Intrinsic::round: 6090 case Intrinsic::roundeven: 6091 case Intrinsic::canonicalize: { 6092 unsigned Opcode; 6093 switch (Intrinsic) { 6094 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6095 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6096 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6097 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6098 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6099 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6100 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6101 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6102 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6103 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6104 case Intrinsic::round: Opcode = ISD::FROUND; break; 6105 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6106 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6107 } 6108 6109 setValue(&I, DAG.getNode(Opcode, sdl, 6110 getValue(I.getArgOperand(0)).getValueType(), 6111 getValue(I.getArgOperand(0)))); 6112 return; 6113 } 6114 case Intrinsic::lround: 6115 case Intrinsic::llround: 6116 case Intrinsic::lrint: 6117 case Intrinsic::llrint: { 6118 unsigned Opcode; 6119 switch (Intrinsic) { 6120 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6121 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6122 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6123 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6124 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6125 } 6126 6127 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6128 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6129 getValue(I.getArgOperand(0)))); 6130 return; 6131 } 6132 case Intrinsic::minnum: 6133 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6134 getValue(I.getArgOperand(0)).getValueType(), 6135 getValue(I.getArgOperand(0)), 6136 getValue(I.getArgOperand(1)))); 6137 return; 6138 case Intrinsic::maxnum: 6139 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6140 getValue(I.getArgOperand(0)).getValueType(), 6141 getValue(I.getArgOperand(0)), 6142 getValue(I.getArgOperand(1)))); 6143 return; 6144 case Intrinsic::minimum: 6145 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6146 getValue(I.getArgOperand(0)).getValueType(), 6147 getValue(I.getArgOperand(0)), 6148 getValue(I.getArgOperand(1)))); 6149 return; 6150 case Intrinsic::maximum: 6151 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6152 getValue(I.getArgOperand(0)).getValueType(), 6153 getValue(I.getArgOperand(0)), 6154 getValue(I.getArgOperand(1)))); 6155 return; 6156 case Intrinsic::copysign: 6157 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6158 getValue(I.getArgOperand(0)).getValueType(), 6159 getValue(I.getArgOperand(0)), 6160 getValue(I.getArgOperand(1)))); 6161 return; 6162 case Intrinsic::fma: 6163 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6164 getValue(I.getArgOperand(0)).getValueType(), 6165 getValue(I.getArgOperand(0)), 6166 getValue(I.getArgOperand(1)), 6167 getValue(I.getArgOperand(2)))); 6168 return; 6169 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6170 case Intrinsic::INTRINSIC: 6171 #include "llvm/IR/ConstrainedOps.def" 6172 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6173 return; 6174 case Intrinsic::fmuladd: { 6175 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6176 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6177 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6178 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6179 getValue(I.getArgOperand(0)).getValueType(), 6180 getValue(I.getArgOperand(0)), 6181 getValue(I.getArgOperand(1)), 6182 getValue(I.getArgOperand(2)))); 6183 } else { 6184 // TODO: Intrinsic calls should have fast-math-flags. 6185 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6186 getValue(I.getArgOperand(0)).getValueType(), 6187 getValue(I.getArgOperand(0)), 6188 getValue(I.getArgOperand(1))); 6189 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6190 getValue(I.getArgOperand(0)).getValueType(), 6191 Mul, 6192 getValue(I.getArgOperand(2))); 6193 setValue(&I, Add); 6194 } 6195 return; 6196 } 6197 case Intrinsic::convert_to_fp16: 6198 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6199 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6200 getValue(I.getArgOperand(0)), 6201 DAG.getTargetConstant(0, sdl, 6202 MVT::i32)))); 6203 return; 6204 case Intrinsic::convert_from_fp16: 6205 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6206 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6207 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6208 getValue(I.getArgOperand(0))))); 6209 return; 6210 case Intrinsic::pcmarker: { 6211 SDValue Tmp = getValue(I.getArgOperand(0)); 6212 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6213 return; 6214 } 6215 case Intrinsic::readcyclecounter: { 6216 SDValue Op = getRoot(); 6217 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6218 DAG.getVTList(MVT::i64, MVT::Other), Op); 6219 setValue(&I, Res); 6220 DAG.setRoot(Res.getValue(1)); 6221 return; 6222 } 6223 case Intrinsic::bitreverse: 6224 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6225 getValue(I.getArgOperand(0)).getValueType(), 6226 getValue(I.getArgOperand(0)))); 6227 return; 6228 case Intrinsic::bswap: 6229 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6230 getValue(I.getArgOperand(0)).getValueType(), 6231 getValue(I.getArgOperand(0)))); 6232 return; 6233 case Intrinsic::cttz: { 6234 SDValue Arg = getValue(I.getArgOperand(0)); 6235 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6236 EVT Ty = Arg.getValueType(); 6237 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6238 sdl, Ty, Arg)); 6239 return; 6240 } 6241 case Intrinsic::ctlz: { 6242 SDValue Arg = getValue(I.getArgOperand(0)); 6243 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6244 EVT Ty = Arg.getValueType(); 6245 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6246 sdl, Ty, Arg)); 6247 return; 6248 } 6249 case Intrinsic::ctpop: { 6250 SDValue Arg = getValue(I.getArgOperand(0)); 6251 EVT Ty = Arg.getValueType(); 6252 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6253 return; 6254 } 6255 case Intrinsic::fshl: 6256 case Intrinsic::fshr: { 6257 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6258 SDValue X = getValue(I.getArgOperand(0)); 6259 SDValue Y = getValue(I.getArgOperand(1)); 6260 SDValue Z = getValue(I.getArgOperand(2)); 6261 EVT VT = X.getValueType(); 6262 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6263 SDValue Zero = DAG.getConstant(0, sdl, VT); 6264 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6265 6266 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6267 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6268 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6269 return; 6270 } 6271 6272 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6273 // avoid the select that is necessary in the general case to filter out 6274 // the 0-shift possibility that leads to UB. 6275 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6276 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6277 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6278 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6279 return; 6280 } 6281 6282 // Some targets only rotate one way. Try the opposite direction. 6283 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6284 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6285 // Negate the shift amount because it is safe to ignore the high bits. 6286 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6287 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6288 return; 6289 } 6290 6291 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6292 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6293 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6294 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6295 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6296 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6297 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6298 return; 6299 } 6300 6301 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6302 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6303 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6304 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6305 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6306 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6307 6308 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6309 // and that is undefined. We must compare and select to avoid UB. 6310 EVT CCVT = MVT::i1; 6311 if (VT.isVector()) 6312 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6313 6314 // For fshl, 0-shift returns the 1st arg (X). 6315 // For fshr, 0-shift returns the 2nd arg (Y). 6316 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6317 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6318 return; 6319 } 6320 case Intrinsic::sadd_sat: { 6321 SDValue Op1 = getValue(I.getArgOperand(0)); 6322 SDValue Op2 = getValue(I.getArgOperand(1)); 6323 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6324 return; 6325 } 6326 case Intrinsic::uadd_sat: { 6327 SDValue Op1 = getValue(I.getArgOperand(0)); 6328 SDValue Op2 = getValue(I.getArgOperand(1)); 6329 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6330 return; 6331 } 6332 case Intrinsic::ssub_sat: { 6333 SDValue Op1 = getValue(I.getArgOperand(0)); 6334 SDValue Op2 = getValue(I.getArgOperand(1)); 6335 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6336 return; 6337 } 6338 case Intrinsic::usub_sat: { 6339 SDValue Op1 = getValue(I.getArgOperand(0)); 6340 SDValue Op2 = getValue(I.getArgOperand(1)); 6341 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6342 return; 6343 } 6344 case Intrinsic::smul_fix: 6345 case Intrinsic::umul_fix: 6346 case Intrinsic::smul_fix_sat: 6347 case Intrinsic::umul_fix_sat: { 6348 SDValue Op1 = getValue(I.getArgOperand(0)); 6349 SDValue Op2 = getValue(I.getArgOperand(1)); 6350 SDValue Op3 = getValue(I.getArgOperand(2)); 6351 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6352 Op1.getValueType(), Op1, Op2, Op3)); 6353 return; 6354 } 6355 case Intrinsic::sdiv_fix: 6356 case Intrinsic::udiv_fix: 6357 case Intrinsic::sdiv_fix_sat: 6358 case Intrinsic::udiv_fix_sat: { 6359 SDValue Op1 = getValue(I.getArgOperand(0)); 6360 SDValue Op2 = getValue(I.getArgOperand(1)); 6361 SDValue Op3 = getValue(I.getArgOperand(2)); 6362 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6363 Op1, Op2, Op3, DAG, TLI)); 6364 return; 6365 } 6366 case Intrinsic::stacksave: { 6367 SDValue Op = getRoot(); 6368 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6369 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6370 setValue(&I, Res); 6371 DAG.setRoot(Res.getValue(1)); 6372 return; 6373 } 6374 case Intrinsic::stackrestore: 6375 Res = getValue(I.getArgOperand(0)); 6376 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6377 return; 6378 case Intrinsic::get_dynamic_area_offset: { 6379 SDValue Op = getRoot(); 6380 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6381 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6382 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6383 // target. 6384 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6385 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6386 " intrinsic!"); 6387 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6388 Op); 6389 DAG.setRoot(Op); 6390 setValue(&I, Res); 6391 return; 6392 } 6393 case Intrinsic::stackguard: { 6394 MachineFunction &MF = DAG.getMachineFunction(); 6395 const Module &M = *MF.getFunction().getParent(); 6396 SDValue Chain = getRoot(); 6397 if (TLI.useLoadStackGuardNode()) { 6398 Res = getLoadStackGuard(DAG, sdl, Chain); 6399 } else { 6400 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6401 const Value *Global = TLI.getSDagStackGuard(M); 6402 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6403 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6404 MachinePointerInfo(Global, 0), Align, 6405 MachineMemOperand::MOVolatile); 6406 } 6407 if (TLI.useStackGuardXorFP()) 6408 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6409 DAG.setRoot(Chain); 6410 setValue(&I, Res); 6411 return; 6412 } 6413 case Intrinsic::stackprotector: { 6414 // Emit code into the DAG to store the stack guard onto the stack. 6415 MachineFunction &MF = DAG.getMachineFunction(); 6416 MachineFrameInfo &MFI = MF.getFrameInfo(); 6417 SDValue Src, Chain = getRoot(); 6418 6419 if (TLI.useLoadStackGuardNode()) 6420 Src = getLoadStackGuard(DAG, sdl, Chain); 6421 else 6422 Src = getValue(I.getArgOperand(0)); // The guard's value. 6423 6424 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6425 6426 int FI = FuncInfo.StaticAllocaMap[Slot]; 6427 MFI.setStackProtectorIndex(FI); 6428 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6429 6430 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6431 6432 // Store the stack protector onto the stack. 6433 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6434 DAG.getMachineFunction(), FI), 6435 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6436 setValue(&I, Res); 6437 DAG.setRoot(Res); 6438 return; 6439 } 6440 case Intrinsic::objectsize: 6441 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6442 6443 case Intrinsic::is_constant: 6444 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6445 6446 case Intrinsic::annotation: 6447 case Intrinsic::ptr_annotation: 6448 case Intrinsic::launder_invariant_group: 6449 case Intrinsic::strip_invariant_group: 6450 // Drop the intrinsic, but forward the value 6451 setValue(&I, getValue(I.getOperand(0))); 6452 return; 6453 case Intrinsic::assume: 6454 case Intrinsic::var_annotation: 6455 case Intrinsic::sideeffect: 6456 // Discard annotate attributes, assumptions, and artificial side-effects. 6457 return; 6458 6459 case Intrinsic::codeview_annotation: { 6460 // Emit a label associated with this metadata. 6461 MachineFunction &MF = DAG.getMachineFunction(); 6462 MCSymbol *Label = 6463 MF.getMMI().getContext().createTempSymbol("annotation", true); 6464 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6465 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6466 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6467 DAG.setRoot(Res); 6468 return; 6469 } 6470 6471 case Intrinsic::init_trampoline: { 6472 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6473 6474 SDValue Ops[6]; 6475 Ops[0] = getRoot(); 6476 Ops[1] = getValue(I.getArgOperand(0)); 6477 Ops[2] = getValue(I.getArgOperand(1)); 6478 Ops[3] = getValue(I.getArgOperand(2)); 6479 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6480 Ops[5] = DAG.getSrcValue(F); 6481 6482 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6483 6484 DAG.setRoot(Res); 6485 return; 6486 } 6487 case Intrinsic::adjust_trampoline: 6488 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6489 TLI.getPointerTy(DAG.getDataLayout()), 6490 getValue(I.getArgOperand(0)))); 6491 return; 6492 case Intrinsic::gcroot: { 6493 assert(DAG.getMachineFunction().getFunction().hasGC() && 6494 "only valid in functions with gc specified, enforced by Verifier"); 6495 assert(GFI && "implied by previous"); 6496 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6497 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6498 6499 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6500 GFI->addStackRoot(FI->getIndex(), TypeMap); 6501 return; 6502 } 6503 case Intrinsic::gcread: 6504 case Intrinsic::gcwrite: 6505 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6506 case Intrinsic::flt_rounds: 6507 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6508 setValue(&I, Res); 6509 DAG.setRoot(Res.getValue(1)); 6510 return; 6511 6512 case Intrinsic::expect: 6513 // Just replace __builtin_expect(exp, c) with EXP. 6514 setValue(&I, getValue(I.getArgOperand(0))); 6515 return; 6516 6517 case Intrinsic::debugtrap: 6518 case Intrinsic::trap: { 6519 StringRef TrapFuncName = 6520 I.getAttributes() 6521 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6522 .getValueAsString(); 6523 if (TrapFuncName.empty()) { 6524 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6525 ISD::TRAP : ISD::DEBUGTRAP; 6526 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6527 return; 6528 } 6529 TargetLowering::ArgListTy Args; 6530 6531 TargetLowering::CallLoweringInfo CLI(DAG); 6532 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6533 CallingConv::C, I.getType(), 6534 DAG.getExternalSymbol(TrapFuncName.data(), 6535 TLI.getPointerTy(DAG.getDataLayout())), 6536 std::move(Args)); 6537 6538 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6539 DAG.setRoot(Result.second); 6540 return; 6541 } 6542 6543 case Intrinsic::uadd_with_overflow: 6544 case Intrinsic::sadd_with_overflow: 6545 case Intrinsic::usub_with_overflow: 6546 case Intrinsic::ssub_with_overflow: 6547 case Intrinsic::umul_with_overflow: 6548 case Intrinsic::smul_with_overflow: { 6549 ISD::NodeType Op; 6550 switch (Intrinsic) { 6551 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6552 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6553 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6554 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6555 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6556 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6557 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6558 } 6559 SDValue Op1 = getValue(I.getArgOperand(0)); 6560 SDValue Op2 = getValue(I.getArgOperand(1)); 6561 6562 EVT ResultVT = Op1.getValueType(); 6563 EVT OverflowVT = MVT::i1; 6564 if (ResultVT.isVector()) 6565 OverflowVT = EVT::getVectorVT( 6566 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6567 6568 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6569 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6570 return; 6571 } 6572 case Intrinsic::prefetch: { 6573 SDValue Ops[5]; 6574 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6575 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6576 Ops[0] = DAG.getRoot(); 6577 Ops[1] = getValue(I.getArgOperand(0)); 6578 Ops[2] = getValue(I.getArgOperand(1)); 6579 Ops[3] = getValue(I.getArgOperand(2)); 6580 Ops[4] = getValue(I.getArgOperand(3)); 6581 SDValue Result = DAG.getMemIntrinsicNode( 6582 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6583 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6584 /* align */ None, Flags); 6585 6586 // Chain the prefetch in parallell with any pending loads, to stay out of 6587 // the way of later optimizations. 6588 PendingLoads.push_back(Result); 6589 Result = getRoot(); 6590 DAG.setRoot(Result); 6591 return; 6592 } 6593 case Intrinsic::lifetime_start: 6594 case Intrinsic::lifetime_end: { 6595 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6596 // Stack coloring is not enabled in O0, discard region information. 6597 if (TM.getOptLevel() == CodeGenOpt::None) 6598 return; 6599 6600 const int64_t ObjectSize = 6601 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6602 Value *const ObjectPtr = I.getArgOperand(1); 6603 SmallVector<const Value *, 4> Allocas; 6604 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6605 6606 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6607 E = Allocas.end(); Object != E; ++Object) { 6608 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6609 6610 // Could not find an Alloca. 6611 if (!LifetimeObject) 6612 continue; 6613 6614 // First check that the Alloca is static, otherwise it won't have a 6615 // valid frame index. 6616 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6617 if (SI == FuncInfo.StaticAllocaMap.end()) 6618 return; 6619 6620 const int FrameIndex = SI->second; 6621 int64_t Offset; 6622 if (GetPointerBaseWithConstantOffset( 6623 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6624 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6625 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6626 Offset); 6627 DAG.setRoot(Res); 6628 } 6629 return; 6630 } 6631 case Intrinsic::invariant_start: 6632 // Discard region information. 6633 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6634 return; 6635 case Intrinsic::invariant_end: 6636 // Discard region information. 6637 return; 6638 case Intrinsic::clear_cache: 6639 /// FunctionName may be null. 6640 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6641 lowerCallToExternalSymbol(I, FunctionName); 6642 return; 6643 case Intrinsic::donothing: 6644 // ignore 6645 return; 6646 case Intrinsic::experimental_stackmap: 6647 visitStackmap(I); 6648 return; 6649 case Intrinsic::experimental_patchpoint_void: 6650 case Intrinsic::experimental_patchpoint_i64: 6651 visitPatchpoint(I); 6652 return; 6653 case Intrinsic::experimental_gc_statepoint: 6654 LowerStatepoint(cast<GCStatepointInst>(I)); 6655 return; 6656 case Intrinsic::experimental_gc_result: 6657 visitGCResult(cast<GCResultInst>(I)); 6658 return; 6659 case Intrinsic::experimental_gc_relocate: 6660 visitGCRelocate(cast<GCRelocateInst>(I)); 6661 return; 6662 case Intrinsic::instrprof_increment: 6663 llvm_unreachable("instrprof failed to lower an increment"); 6664 case Intrinsic::instrprof_value_profile: 6665 llvm_unreachable("instrprof failed to lower a value profiling call"); 6666 case Intrinsic::localescape: { 6667 MachineFunction &MF = DAG.getMachineFunction(); 6668 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6669 6670 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6671 // is the same on all targets. 6672 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6673 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6674 if (isa<ConstantPointerNull>(Arg)) 6675 continue; // Skip null pointers. They represent a hole in index space. 6676 AllocaInst *Slot = cast<AllocaInst>(Arg); 6677 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6678 "can only escape static allocas"); 6679 int FI = FuncInfo.StaticAllocaMap[Slot]; 6680 MCSymbol *FrameAllocSym = 6681 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6682 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6684 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6685 .addSym(FrameAllocSym) 6686 .addFrameIndex(FI); 6687 } 6688 6689 return; 6690 } 6691 6692 case Intrinsic::localrecover: { 6693 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6694 MachineFunction &MF = DAG.getMachineFunction(); 6695 6696 // Get the symbol that defines the frame offset. 6697 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6698 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6699 unsigned IdxVal = 6700 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6701 MCSymbol *FrameAllocSym = 6702 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6703 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6704 6705 Value *FP = I.getArgOperand(1); 6706 SDValue FPVal = getValue(FP); 6707 EVT PtrVT = FPVal.getValueType(); 6708 6709 // Create a MCSymbol for the label to avoid any target lowering 6710 // that would make this PC relative. 6711 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6712 SDValue OffsetVal = 6713 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6714 6715 // Add the offset to the FP. 6716 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6717 setValue(&I, Add); 6718 6719 return; 6720 } 6721 6722 case Intrinsic::eh_exceptionpointer: 6723 case Intrinsic::eh_exceptioncode: { 6724 // Get the exception pointer vreg, copy from it, and resize it to fit. 6725 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6726 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6727 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6728 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6729 SDValue N = 6730 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6731 if (Intrinsic == Intrinsic::eh_exceptioncode) 6732 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6733 setValue(&I, N); 6734 return; 6735 } 6736 case Intrinsic::xray_customevent: { 6737 // Here we want to make sure that the intrinsic behaves as if it has a 6738 // specific calling convention, and only for x86_64. 6739 // FIXME: Support other platforms later. 6740 const auto &Triple = DAG.getTarget().getTargetTriple(); 6741 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6742 return; 6743 6744 SDLoc DL = getCurSDLoc(); 6745 SmallVector<SDValue, 8> Ops; 6746 6747 // We want to say that we always want the arguments in registers. 6748 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6749 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6750 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6751 SDValue Chain = getRoot(); 6752 Ops.push_back(LogEntryVal); 6753 Ops.push_back(StrSizeVal); 6754 Ops.push_back(Chain); 6755 6756 // We need to enforce the calling convention for the callsite, so that 6757 // argument ordering is enforced correctly, and that register allocation can 6758 // see that some registers may be assumed clobbered and have to preserve 6759 // them across calls to the intrinsic. 6760 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6761 DL, NodeTys, Ops); 6762 SDValue patchableNode = SDValue(MN, 0); 6763 DAG.setRoot(patchableNode); 6764 setValue(&I, patchableNode); 6765 return; 6766 } 6767 case Intrinsic::xray_typedevent: { 6768 // Here we want to make sure that the intrinsic behaves as if it has a 6769 // specific calling convention, and only for x86_64. 6770 // FIXME: Support other platforms later. 6771 const auto &Triple = DAG.getTarget().getTargetTriple(); 6772 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6773 return; 6774 6775 SDLoc DL = getCurSDLoc(); 6776 SmallVector<SDValue, 8> Ops; 6777 6778 // We want to say that we always want the arguments in registers. 6779 // It's unclear to me how manipulating the selection DAG here forces callers 6780 // to provide arguments in registers instead of on the stack. 6781 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6782 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6783 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6784 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6785 SDValue Chain = getRoot(); 6786 Ops.push_back(LogTypeId); 6787 Ops.push_back(LogEntryVal); 6788 Ops.push_back(StrSizeVal); 6789 Ops.push_back(Chain); 6790 6791 // We need to enforce the calling convention for the callsite, so that 6792 // argument ordering is enforced correctly, and that register allocation can 6793 // see that some registers may be assumed clobbered and have to preserve 6794 // them across calls to the intrinsic. 6795 MachineSDNode *MN = DAG.getMachineNode( 6796 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6797 SDValue patchableNode = SDValue(MN, 0); 6798 DAG.setRoot(patchableNode); 6799 setValue(&I, patchableNode); 6800 return; 6801 } 6802 case Intrinsic::experimental_deoptimize: 6803 LowerDeoptimizeCall(&I); 6804 return; 6805 6806 case Intrinsic::experimental_vector_reduce_v2_fadd: 6807 case Intrinsic::experimental_vector_reduce_v2_fmul: 6808 case Intrinsic::experimental_vector_reduce_add: 6809 case Intrinsic::experimental_vector_reduce_mul: 6810 case Intrinsic::experimental_vector_reduce_and: 6811 case Intrinsic::experimental_vector_reduce_or: 6812 case Intrinsic::experimental_vector_reduce_xor: 6813 case Intrinsic::experimental_vector_reduce_smax: 6814 case Intrinsic::experimental_vector_reduce_smin: 6815 case Intrinsic::experimental_vector_reduce_umax: 6816 case Intrinsic::experimental_vector_reduce_umin: 6817 case Intrinsic::experimental_vector_reduce_fmax: 6818 case Intrinsic::experimental_vector_reduce_fmin: 6819 visitVectorReduce(I, Intrinsic); 6820 return; 6821 6822 case Intrinsic::icall_branch_funnel: { 6823 SmallVector<SDValue, 16> Ops; 6824 Ops.push_back(getValue(I.getArgOperand(0))); 6825 6826 int64_t Offset; 6827 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6828 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6829 if (!Base) 6830 report_fatal_error( 6831 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6832 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6833 6834 struct BranchFunnelTarget { 6835 int64_t Offset; 6836 SDValue Target; 6837 }; 6838 SmallVector<BranchFunnelTarget, 8> Targets; 6839 6840 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6841 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6842 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6843 if (ElemBase != Base) 6844 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6845 "to the same GlobalValue"); 6846 6847 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6848 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6849 if (!GA) 6850 report_fatal_error( 6851 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6852 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6853 GA->getGlobal(), getCurSDLoc(), 6854 Val.getValueType(), GA->getOffset())}); 6855 } 6856 llvm::sort(Targets, 6857 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6858 return T1.Offset < T2.Offset; 6859 }); 6860 6861 for (auto &T : Targets) { 6862 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6863 Ops.push_back(T.Target); 6864 } 6865 6866 Ops.push_back(DAG.getRoot()); // Chain 6867 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6868 getCurSDLoc(), MVT::Other, Ops), 6869 0); 6870 DAG.setRoot(N); 6871 setValue(&I, N); 6872 HasTailCall = true; 6873 return; 6874 } 6875 6876 case Intrinsic::wasm_landingpad_index: 6877 // Information this intrinsic contained has been transferred to 6878 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6879 // delete it now. 6880 return; 6881 6882 case Intrinsic::aarch64_settag: 6883 case Intrinsic::aarch64_settag_zero: { 6884 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6885 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6886 SDValue Val = TSI.EmitTargetCodeForSetTag( 6887 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6888 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6889 ZeroMemory); 6890 DAG.setRoot(Val); 6891 setValue(&I, Val); 6892 return; 6893 } 6894 case Intrinsic::ptrmask: { 6895 SDValue Ptr = getValue(I.getOperand(0)); 6896 SDValue Const = getValue(I.getOperand(1)); 6897 6898 EVT PtrVT = Ptr.getValueType(); 6899 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 6900 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 6901 return; 6902 } 6903 case Intrinsic::get_active_lane_mask: { 6904 auto DL = getCurSDLoc(); 6905 SDValue Index = getValue(I.getOperand(0)); 6906 SDValue BTC = getValue(I.getOperand(1)); 6907 Type *ElementTy = I.getOperand(0)->getType(); 6908 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6909 unsigned VecWidth = VT.getVectorNumElements(); 6910 6911 SmallVector<SDValue, 16> OpsBTC; 6912 SmallVector<SDValue, 16> OpsIndex; 6913 SmallVector<SDValue, 16> OpsStepConstants; 6914 for (unsigned i = 0; i < VecWidth; i++) { 6915 OpsBTC.push_back(BTC); 6916 OpsIndex.push_back(Index); 6917 OpsStepConstants.push_back(DAG.getConstant(i, DL, MVT::getVT(ElementTy))); 6918 } 6919 6920 EVT CCVT = MVT::i1; 6921 CCVT = EVT::getVectorVT(I.getContext(), CCVT, VecWidth); 6922 6923 auto VecTy = MVT::getVT(FixedVectorType::get(ElementTy, VecWidth)); 6924 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 6925 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 6926 SDValue VectorInduction = DAG.getNode( 6927 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 6928 SDValue VectorBTC = DAG.getBuildVector(VecTy, DL, OpsBTC); 6929 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 6930 VectorBTC, ISD::CondCode::SETULE); 6931 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 6932 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 6933 SetCC)); 6934 return; 6935 } 6936 } 6937 } 6938 6939 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6940 const ConstrainedFPIntrinsic &FPI) { 6941 SDLoc sdl = getCurSDLoc(); 6942 6943 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6944 SmallVector<EVT, 4> ValueVTs; 6945 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6946 ValueVTs.push_back(MVT::Other); // Out chain 6947 6948 // We do not need to serialize constrained FP intrinsics against 6949 // each other or against (nonvolatile) loads, so they can be 6950 // chained like loads. 6951 SDValue Chain = DAG.getRoot(); 6952 SmallVector<SDValue, 4> Opers; 6953 Opers.push_back(Chain); 6954 if (FPI.isUnaryOp()) { 6955 Opers.push_back(getValue(FPI.getArgOperand(0))); 6956 } else if (FPI.isTernaryOp()) { 6957 Opers.push_back(getValue(FPI.getArgOperand(0))); 6958 Opers.push_back(getValue(FPI.getArgOperand(1))); 6959 Opers.push_back(getValue(FPI.getArgOperand(2))); 6960 } else { 6961 Opers.push_back(getValue(FPI.getArgOperand(0))); 6962 Opers.push_back(getValue(FPI.getArgOperand(1))); 6963 } 6964 6965 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6966 assert(Result.getNode()->getNumValues() == 2); 6967 6968 // Push node to the appropriate list so that future instructions can be 6969 // chained up correctly. 6970 SDValue OutChain = Result.getValue(1); 6971 switch (EB) { 6972 case fp::ExceptionBehavior::ebIgnore: 6973 // The only reason why ebIgnore nodes still need to be chained is that 6974 // they might depend on the current rounding mode, and therefore must 6975 // not be moved across instruction that may change that mode. 6976 LLVM_FALLTHROUGH; 6977 case fp::ExceptionBehavior::ebMayTrap: 6978 // These must not be moved across calls or instructions that may change 6979 // floating-point exception masks. 6980 PendingConstrainedFP.push_back(OutChain); 6981 break; 6982 case fp::ExceptionBehavior::ebStrict: 6983 // These must not be moved across calls or instructions that may change 6984 // floating-point exception masks or read floating-point exception flags. 6985 // In addition, they cannot be optimized out even if unused. 6986 PendingConstrainedFPStrict.push_back(OutChain); 6987 break; 6988 } 6989 }; 6990 6991 SDVTList VTs = DAG.getVTList(ValueVTs); 6992 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 6993 6994 SDNodeFlags Flags; 6995 if (EB == fp::ExceptionBehavior::ebIgnore) 6996 Flags.setNoFPExcept(true); 6997 6998 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 6999 Flags.copyFMF(*FPOp); 7000 7001 unsigned Opcode; 7002 switch (FPI.getIntrinsicID()) { 7003 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7004 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7005 case Intrinsic::INTRINSIC: \ 7006 Opcode = ISD::STRICT_##DAGN; \ 7007 break; 7008 #include "llvm/IR/ConstrainedOps.def" 7009 case Intrinsic::experimental_constrained_fmuladd: { 7010 Opcode = ISD::STRICT_FMA; 7011 // Break fmuladd into fmul and fadd. 7012 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7013 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7014 ValueVTs[0])) { 7015 Opers.pop_back(); 7016 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7017 pushOutChain(Mul, EB); 7018 Opcode = ISD::STRICT_FADD; 7019 Opers.clear(); 7020 Opers.push_back(Mul.getValue(1)); 7021 Opers.push_back(Mul.getValue(0)); 7022 Opers.push_back(getValue(FPI.getArgOperand(2))); 7023 } 7024 break; 7025 } 7026 } 7027 7028 // A few strict DAG nodes carry additional operands that are not 7029 // set up by the default code above. 7030 switch (Opcode) { 7031 default: break; 7032 case ISD::STRICT_FP_ROUND: 7033 Opers.push_back( 7034 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7035 break; 7036 case ISD::STRICT_FSETCC: 7037 case ISD::STRICT_FSETCCS: { 7038 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7039 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7040 break; 7041 } 7042 } 7043 7044 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7045 pushOutChain(Result, EB); 7046 7047 SDValue FPResult = Result.getValue(0); 7048 setValue(&FPI, FPResult); 7049 } 7050 7051 std::pair<SDValue, SDValue> 7052 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7053 const BasicBlock *EHPadBB) { 7054 MachineFunction &MF = DAG.getMachineFunction(); 7055 MachineModuleInfo &MMI = MF.getMMI(); 7056 MCSymbol *BeginLabel = nullptr; 7057 7058 if (EHPadBB) { 7059 // Insert a label before the invoke call to mark the try range. This can be 7060 // used to detect deletion of the invoke via the MachineModuleInfo. 7061 BeginLabel = MMI.getContext().createTempSymbol(); 7062 7063 // For SjLj, keep track of which landing pads go with which invokes 7064 // so as to maintain the ordering of pads in the LSDA. 7065 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7066 if (CallSiteIndex) { 7067 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7068 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7069 7070 // Now that the call site is handled, stop tracking it. 7071 MMI.setCurrentCallSite(0); 7072 } 7073 7074 // Both PendingLoads and PendingExports must be flushed here; 7075 // this call might not return. 7076 (void)getRoot(); 7077 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7078 7079 CLI.setChain(getRoot()); 7080 } 7081 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7082 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7083 7084 assert((CLI.IsTailCall || Result.second.getNode()) && 7085 "Non-null chain expected with non-tail call!"); 7086 assert((Result.second.getNode() || !Result.first.getNode()) && 7087 "Null value expected with tail call!"); 7088 7089 if (!Result.second.getNode()) { 7090 // As a special case, a null chain means that a tail call has been emitted 7091 // and the DAG root is already updated. 7092 HasTailCall = true; 7093 7094 // Since there's no actual continuation from this block, nothing can be 7095 // relying on us setting vregs for them. 7096 PendingExports.clear(); 7097 } else { 7098 DAG.setRoot(Result.second); 7099 } 7100 7101 if (EHPadBB) { 7102 // Insert a label at the end of the invoke call to mark the try range. This 7103 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7104 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7105 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7106 7107 // Inform MachineModuleInfo of range. 7108 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7109 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7110 // actually use outlined funclets and their LSDA info style. 7111 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7112 assert(CLI.CB); 7113 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7114 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7115 } else if (!isScopedEHPersonality(Pers)) { 7116 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7117 } 7118 } 7119 7120 return Result; 7121 } 7122 7123 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7124 bool isTailCall, 7125 const BasicBlock *EHPadBB) { 7126 auto &DL = DAG.getDataLayout(); 7127 FunctionType *FTy = CB.getFunctionType(); 7128 Type *RetTy = CB.getType(); 7129 7130 TargetLowering::ArgListTy Args; 7131 Args.reserve(CB.arg_size()); 7132 7133 const Value *SwiftErrorVal = nullptr; 7134 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7135 7136 if (isTailCall) { 7137 // Avoid emitting tail calls in functions with the disable-tail-calls 7138 // attribute. 7139 auto *Caller = CB.getParent()->getParent(); 7140 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7141 "true") 7142 isTailCall = false; 7143 7144 // We can't tail call inside a function with a swifterror argument. Lowering 7145 // does not support this yet. It would have to move into the swifterror 7146 // register before the call. 7147 if (TLI.supportSwiftError() && 7148 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7149 isTailCall = false; 7150 } 7151 7152 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7153 TargetLowering::ArgListEntry Entry; 7154 const Value *V = *I; 7155 7156 // Skip empty types 7157 if (V->getType()->isEmptyTy()) 7158 continue; 7159 7160 SDValue ArgNode = getValue(V); 7161 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7162 7163 Entry.setAttributes(&CB, I - CB.arg_begin()); 7164 7165 // Use swifterror virtual register as input to the call. 7166 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7167 SwiftErrorVal = V; 7168 // We find the virtual register for the actual swifterror argument. 7169 // Instead of using the Value, we use the virtual register instead. 7170 Entry.Node = 7171 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7172 EVT(TLI.getPointerTy(DL))); 7173 } 7174 7175 Args.push_back(Entry); 7176 7177 // If we have an explicit sret argument that is an Instruction, (i.e., it 7178 // might point to function-local memory), we can't meaningfully tail-call. 7179 if (Entry.IsSRet && isa<Instruction>(V)) 7180 isTailCall = false; 7181 } 7182 7183 // If call site has a cfguardtarget operand bundle, create and add an 7184 // additional ArgListEntry. 7185 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7186 TargetLowering::ArgListEntry Entry; 7187 Value *V = Bundle->Inputs[0]; 7188 SDValue ArgNode = getValue(V); 7189 Entry.Node = ArgNode; 7190 Entry.Ty = V->getType(); 7191 Entry.IsCFGuardTarget = true; 7192 Args.push_back(Entry); 7193 } 7194 7195 // Check if target-independent constraints permit a tail call here. 7196 // Target-dependent constraints are checked within TLI->LowerCallTo. 7197 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7198 isTailCall = false; 7199 7200 // Disable tail calls if there is an swifterror argument. Targets have not 7201 // been updated to support tail calls. 7202 if (TLI.supportSwiftError() && SwiftErrorVal) 7203 isTailCall = false; 7204 7205 TargetLowering::CallLoweringInfo CLI(DAG); 7206 CLI.setDebugLoc(getCurSDLoc()) 7207 .setChain(getRoot()) 7208 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7209 .setTailCall(isTailCall) 7210 .setConvergent(CB.isConvergent()) 7211 .setIsPreallocated( 7212 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7213 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7214 7215 if (Result.first.getNode()) { 7216 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7217 setValue(&CB, Result.first); 7218 } 7219 7220 // The last element of CLI.InVals has the SDValue for swifterror return. 7221 // Here we copy it to a virtual register and update SwiftErrorMap for 7222 // book-keeping. 7223 if (SwiftErrorVal && TLI.supportSwiftError()) { 7224 // Get the last element of InVals. 7225 SDValue Src = CLI.InVals.back(); 7226 Register VReg = 7227 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7228 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7229 DAG.setRoot(CopyNode); 7230 } 7231 } 7232 7233 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7234 SelectionDAGBuilder &Builder) { 7235 // Check to see if this load can be trivially constant folded, e.g. if the 7236 // input is from a string literal. 7237 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7238 // Cast pointer to the type we really want to load. 7239 Type *LoadTy = 7240 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7241 if (LoadVT.isVector()) 7242 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7243 7244 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7245 PointerType::getUnqual(LoadTy)); 7246 7247 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7248 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7249 return Builder.getValue(LoadCst); 7250 } 7251 7252 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7253 // still constant memory, the input chain can be the entry node. 7254 SDValue Root; 7255 bool ConstantMemory = false; 7256 7257 // Do not serialize (non-volatile) loads of constant memory with anything. 7258 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7259 Root = Builder.DAG.getEntryNode(); 7260 ConstantMemory = true; 7261 } else { 7262 // Do not serialize non-volatile loads against each other. 7263 Root = Builder.DAG.getRoot(); 7264 } 7265 7266 SDValue Ptr = Builder.getValue(PtrVal); 7267 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7268 Ptr, MachinePointerInfo(PtrVal), 7269 /* Alignment = */ 1); 7270 7271 if (!ConstantMemory) 7272 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7273 return LoadVal; 7274 } 7275 7276 /// Record the value for an instruction that produces an integer result, 7277 /// converting the type where necessary. 7278 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7279 SDValue Value, 7280 bool IsSigned) { 7281 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7282 I.getType(), true); 7283 if (IsSigned) 7284 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7285 else 7286 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7287 setValue(&I, Value); 7288 } 7289 7290 /// See if we can lower a memcmp call into an optimized form. If so, return 7291 /// true and lower it. Otherwise return false, and it will be lowered like a 7292 /// normal call. 7293 /// The caller already checked that \p I calls the appropriate LibFunc with a 7294 /// correct prototype. 7295 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7296 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7297 const Value *Size = I.getArgOperand(2); 7298 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7299 if (CSize && CSize->getZExtValue() == 0) { 7300 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7301 I.getType(), true); 7302 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7303 return true; 7304 } 7305 7306 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7307 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7308 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7309 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7310 if (Res.first.getNode()) { 7311 processIntegerCallValue(I, Res.first, true); 7312 PendingLoads.push_back(Res.second); 7313 return true; 7314 } 7315 7316 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7317 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7318 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7319 return false; 7320 7321 // If the target has a fast compare for the given size, it will return a 7322 // preferred load type for that size. Require that the load VT is legal and 7323 // that the target supports unaligned loads of that type. Otherwise, return 7324 // INVALID. 7325 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7326 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7327 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7328 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7329 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7330 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7331 // TODO: Check alignment of src and dest ptrs. 7332 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7333 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7334 if (!TLI.isTypeLegal(LVT) || 7335 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7336 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7337 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7338 } 7339 7340 return LVT; 7341 }; 7342 7343 // This turns into unaligned loads. We only do this if the target natively 7344 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7345 // we'll only produce a small number of byte loads. 7346 MVT LoadVT; 7347 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7348 switch (NumBitsToCompare) { 7349 default: 7350 return false; 7351 case 16: 7352 LoadVT = MVT::i16; 7353 break; 7354 case 32: 7355 LoadVT = MVT::i32; 7356 break; 7357 case 64: 7358 case 128: 7359 case 256: 7360 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7361 break; 7362 } 7363 7364 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7365 return false; 7366 7367 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7368 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7369 7370 // Bitcast to a wide integer type if the loads are vectors. 7371 if (LoadVT.isVector()) { 7372 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7373 LoadL = DAG.getBitcast(CmpVT, LoadL); 7374 LoadR = DAG.getBitcast(CmpVT, LoadR); 7375 } 7376 7377 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7378 processIntegerCallValue(I, Cmp, false); 7379 return true; 7380 } 7381 7382 /// See if we can lower a memchr call into an optimized form. If so, return 7383 /// true and lower it. Otherwise return false, and it will be lowered like a 7384 /// normal call. 7385 /// The caller already checked that \p I calls the appropriate LibFunc with a 7386 /// correct prototype. 7387 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7388 const Value *Src = I.getArgOperand(0); 7389 const Value *Char = I.getArgOperand(1); 7390 const Value *Length = I.getArgOperand(2); 7391 7392 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7393 std::pair<SDValue, SDValue> Res = 7394 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7395 getValue(Src), getValue(Char), getValue(Length), 7396 MachinePointerInfo(Src)); 7397 if (Res.first.getNode()) { 7398 setValue(&I, Res.first); 7399 PendingLoads.push_back(Res.second); 7400 return true; 7401 } 7402 7403 return false; 7404 } 7405 7406 /// See if we can lower a mempcpy call into an optimized form. If so, return 7407 /// true and lower it. Otherwise return false, and it will be lowered like a 7408 /// normal call. 7409 /// The caller already checked that \p I calls the appropriate LibFunc with a 7410 /// correct prototype. 7411 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7412 SDValue Dst = getValue(I.getArgOperand(0)); 7413 SDValue Src = getValue(I.getArgOperand(1)); 7414 SDValue Size = getValue(I.getArgOperand(2)); 7415 7416 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7417 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7418 // DAG::getMemcpy needs Alignment to be defined. 7419 Align Alignment = std::min(DstAlign, SrcAlign); 7420 7421 bool isVol = false; 7422 SDLoc sdl = getCurSDLoc(); 7423 7424 // In the mempcpy context we need to pass in a false value for isTailCall 7425 // because the return pointer needs to be adjusted by the size of 7426 // the copied memory. 7427 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7428 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7429 /*isTailCall=*/false, 7430 MachinePointerInfo(I.getArgOperand(0)), 7431 MachinePointerInfo(I.getArgOperand(1))); 7432 assert(MC.getNode() != nullptr && 7433 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7434 DAG.setRoot(MC); 7435 7436 // Check if Size needs to be truncated or extended. 7437 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7438 7439 // Adjust return pointer to point just past the last dst byte. 7440 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7441 Dst, Size); 7442 setValue(&I, DstPlusSize); 7443 return true; 7444 } 7445 7446 /// See if we can lower a strcpy call into an optimized form. If so, return 7447 /// true and lower it, otherwise return false and it will be lowered like a 7448 /// normal call. 7449 /// The caller already checked that \p I calls the appropriate LibFunc with a 7450 /// correct prototype. 7451 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7452 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7453 7454 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7455 std::pair<SDValue, SDValue> Res = 7456 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7457 getValue(Arg0), getValue(Arg1), 7458 MachinePointerInfo(Arg0), 7459 MachinePointerInfo(Arg1), isStpcpy); 7460 if (Res.first.getNode()) { 7461 setValue(&I, Res.first); 7462 DAG.setRoot(Res.second); 7463 return true; 7464 } 7465 7466 return false; 7467 } 7468 7469 /// See if we can lower a strcmp call into an optimized form. If so, return 7470 /// true and lower it, otherwise return false and it will be lowered like a 7471 /// normal call. 7472 /// The caller already checked that \p I calls the appropriate LibFunc with a 7473 /// correct prototype. 7474 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7475 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7476 7477 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7478 std::pair<SDValue, SDValue> Res = 7479 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7480 getValue(Arg0), getValue(Arg1), 7481 MachinePointerInfo(Arg0), 7482 MachinePointerInfo(Arg1)); 7483 if (Res.first.getNode()) { 7484 processIntegerCallValue(I, Res.first, true); 7485 PendingLoads.push_back(Res.second); 7486 return true; 7487 } 7488 7489 return false; 7490 } 7491 7492 /// See if we can lower a strlen call into an optimized form. If so, return 7493 /// true and lower it, otherwise return false and it will be lowered like a 7494 /// normal call. 7495 /// The caller already checked that \p I calls the appropriate LibFunc with a 7496 /// correct prototype. 7497 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7498 const Value *Arg0 = I.getArgOperand(0); 7499 7500 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7501 std::pair<SDValue, SDValue> Res = 7502 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7503 getValue(Arg0), MachinePointerInfo(Arg0)); 7504 if (Res.first.getNode()) { 7505 processIntegerCallValue(I, Res.first, false); 7506 PendingLoads.push_back(Res.second); 7507 return true; 7508 } 7509 7510 return false; 7511 } 7512 7513 /// See if we can lower a strnlen call into an optimized form. If so, return 7514 /// true and lower it, otherwise return false and it will be lowered like a 7515 /// normal call. 7516 /// The caller already checked that \p I calls the appropriate LibFunc with a 7517 /// correct prototype. 7518 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7519 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7520 7521 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7522 std::pair<SDValue, SDValue> Res = 7523 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7524 getValue(Arg0), getValue(Arg1), 7525 MachinePointerInfo(Arg0)); 7526 if (Res.first.getNode()) { 7527 processIntegerCallValue(I, Res.first, false); 7528 PendingLoads.push_back(Res.second); 7529 return true; 7530 } 7531 7532 return false; 7533 } 7534 7535 /// See if we can lower a unary floating-point operation into an SDNode with 7536 /// the specified Opcode. If so, return true and lower it, otherwise return 7537 /// false and it will be lowered like a normal call. 7538 /// The caller already checked that \p I calls the appropriate LibFunc with a 7539 /// correct prototype. 7540 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7541 unsigned Opcode) { 7542 // We already checked this call's prototype; verify it doesn't modify errno. 7543 if (!I.onlyReadsMemory()) 7544 return false; 7545 7546 SDValue Tmp = getValue(I.getArgOperand(0)); 7547 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7548 return true; 7549 } 7550 7551 /// See if we can lower a binary floating-point operation into an SDNode with 7552 /// the specified Opcode. If so, return true and lower it. Otherwise return 7553 /// false, and it will be lowered like a normal call. 7554 /// The caller already checked that \p I calls the appropriate LibFunc with a 7555 /// correct prototype. 7556 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7557 unsigned Opcode) { 7558 // We already checked this call's prototype; verify it doesn't modify errno. 7559 if (!I.onlyReadsMemory()) 7560 return false; 7561 7562 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7563 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7564 EVT VT = Tmp0.getValueType(); 7565 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7566 return true; 7567 } 7568 7569 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7570 // Handle inline assembly differently. 7571 if (I.isInlineAsm()) { 7572 visitInlineAsm(I); 7573 return; 7574 } 7575 7576 if (Function *F = I.getCalledFunction()) { 7577 if (F->isDeclaration()) { 7578 // Is this an LLVM intrinsic or a target-specific intrinsic? 7579 unsigned IID = F->getIntrinsicID(); 7580 if (!IID) 7581 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7582 IID = II->getIntrinsicID(F); 7583 7584 if (IID) { 7585 visitIntrinsicCall(I, IID); 7586 return; 7587 } 7588 } 7589 7590 // Check for well-known libc/libm calls. If the function is internal, it 7591 // can't be a library call. Don't do the check if marked as nobuiltin for 7592 // some reason or the call site requires strict floating point semantics. 7593 LibFunc Func; 7594 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7595 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7596 LibInfo->hasOptimizedCodeGen(Func)) { 7597 switch (Func) { 7598 default: break; 7599 case LibFunc_copysign: 7600 case LibFunc_copysignf: 7601 case LibFunc_copysignl: 7602 // We already checked this call's prototype; verify it doesn't modify 7603 // errno. 7604 if (I.onlyReadsMemory()) { 7605 SDValue LHS = getValue(I.getArgOperand(0)); 7606 SDValue RHS = getValue(I.getArgOperand(1)); 7607 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7608 LHS.getValueType(), LHS, RHS)); 7609 return; 7610 } 7611 break; 7612 case LibFunc_fabs: 7613 case LibFunc_fabsf: 7614 case LibFunc_fabsl: 7615 if (visitUnaryFloatCall(I, ISD::FABS)) 7616 return; 7617 break; 7618 case LibFunc_fmin: 7619 case LibFunc_fminf: 7620 case LibFunc_fminl: 7621 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7622 return; 7623 break; 7624 case LibFunc_fmax: 7625 case LibFunc_fmaxf: 7626 case LibFunc_fmaxl: 7627 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7628 return; 7629 break; 7630 case LibFunc_sin: 7631 case LibFunc_sinf: 7632 case LibFunc_sinl: 7633 if (visitUnaryFloatCall(I, ISD::FSIN)) 7634 return; 7635 break; 7636 case LibFunc_cos: 7637 case LibFunc_cosf: 7638 case LibFunc_cosl: 7639 if (visitUnaryFloatCall(I, ISD::FCOS)) 7640 return; 7641 break; 7642 case LibFunc_sqrt: 7643 case LibFunc_sqrtf: 7644 case LibFunc_sqrtl: 7645 case LibFunc_sqrt_finite: 7646 case LibFunc_sqrtf_finite: 7647 case LibFunc_sqrtl_finite: 7648 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7649 return; 7650 break; 7651 case LibFunc_floor: 7652 case LibFunc_floorf: 7653 case LibFunc_floorl: 7654 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7655 return; 7656 break; 7657 case LibFunc_nearbyint: 7658 case LibFunc_nearbyintf: 7659 case LibFunc_nearbyintl: 7660 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7661 return; 7662 break; 7663 case LibFunc_ceil: 7664 case LibFunc_ceilf: 7665 case LibFunc_ceill: 7666 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7667 return; 7668 break; 7669 case LibFunc_rint: 7670 case LibFunc_rintf: 7671 case LibFunc_rintl: 7672 if (visitUnaryFloatCall(I, ISD::FRINT)) 7673 return; 7674 break; 7675 case LibFunc_round: 7676 case LibFunc_roundf: 7677 case LibFunc_roundl: 7678 if (visitUnaryFloatCall(I, ISD::FROUND)) 7679 return; 7680 break; 7681 case LibFunc_trunc: 7682 case LibFunc_truncf: 7683 case LibFunc_truncl: 7684 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7685 return; 7686 break; 7687 case LibFunc_log2: 7688 case LibFunc_log2f: 7689 case LibFunc_log2l: 7690 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7691 return; 7692 break; 7693 case LibFunc_exp2: 7694 case LibFunc_exp2f: 7695 case LibFunc_exp2l: 7696 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7697 return; 7698 break; 7699 case LibFunc_memcmp: 7700 if (visitMemCmpCall(I)) 7701 return; 7702 break; 7703 case LibFunc_mempcpy: 7704 if (visitMemPCpyCall(I)) 7705 return; 7706 break; 7707 case LibFunc_memchr: 7708 if (visitMemChrCall(I)) 7709 return; 7710 break; 7711 case LibFunc_strcpy: 7712 if (visitStrCpyCall(I, false)) 7713 return; 7714 break; 7715 case LibFunc_stpcpy: 7716 if (visitStrCpyCall(I, true)) 7717 return; 7718 break; 7719 case LibFunc_strcmp: 7720 if (visitStrCmpCall(I)) 7721 return; 7722 break; 7723 case LibFunc_strlen: 7724 if (visitStrLenCall(I)) 7725 return; 7726 break; 7727 case LibFunc_strnlen: 7728 if (visitStrNLenCall(I)) 7729 return; 7730 break; 7731 } 7732 } 7733 } 7734 7735 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7736 // have to do anything here to lower funclet bundles. 7737 // CFGuardTarget bundles are lowered in LowerCallTo. 7738 assert(!I.hasOperandBundlesOtherThan( 7739 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7740 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) && 7741 "Cannot lower calls with arbitrary operand bundles!"); 7742 7743 SDValue Callee = getValue(I.getCalledOperand()); 7744 7745 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7746 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7747 else 7748 // Check if we can potentially perform a tail call. More detailed checking 7749 // is be done within LowerCallTo, after more information about the call is 7750 // known. 7751 LowerCallTo(I, Callee, I.isTailCall()); 7752 } 7753 7754 namespace { 7755 7756 /// AsmOperandInfo - This contains information for each constraint that we are 7757 /// lowering. 7758 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7759 public: 7760 /// CallOperand - If this is the result output operand or a clobber 7761 /// this is null, otherwise it is the incoming operand to the CallInst. 7762 /// This gets modified as the asm is processed. 7763 SDValue CallOperand; 7764 7765 /// AssignedRegs - If this is a register or register class operand, this 7766 /// contains the set of register corresponding to the operand. 7767 RegsForValue AssignedRegs; 7768 7769 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7770 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7771 } 7772 7773 /// Whether or not this operand accesses memory 7774 bool hasMemory(const TargetLowering &TLI) const { 7775 // Indirect operand accesses access memory. 7776 if (isIndirect) 7777 return true; 7778 7779 for (const auto &Code : Codes) 7780 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7781 return true; 7782 7783 return false; 7784 } 7785 7786 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7787 /// corresponds to. If there is no Value* for this operand, it returns 7788 /// MVT::Other. 7789 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7790 const DataLayout &DL) const { 7791 if (!CallOperandVal) return MVT::Other; 7792 7793 if (isa<BasicBlock>(CallOperandVal)) 7794 return TLI.getProgramPointerTy(DL); 7795 7796 llvm::Type *OpTy = CallOperandVal->getType(); 7797 7798 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7799 // If this is an indirect operand, the operand is a pointer to the 7800 // accessed type. 7801 if (isIndirect) { 7802 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7803 if (!PtrTy) 7804 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7805 OpTy = PtrTy->getElementType(); 7806 } 7807 7808 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7809 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7810 if (STy->getNumElements() == 1) 7811 OpTy = STy->getElementType(0); 7812 7813 // If OpTy is not a single value, it may be a struct/union that we 7814 // can tile with integers. 7815 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7816 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7817 switch (BitSize) { 7818 default: break; 7819 case 1: 7820 case 8: 7821 case 16: 7822 case 32: 7823 case 64: 7824 case 128: 7825 OpTy = IntegerType::get(Context, BitSize); 7826 break; 7827 } 7828 } 7829 7830 return TLI.getValueType(DL, OpTy, true); 7831 } 7832 }; 7833 7834 7835 } // end anonymous namespace 7836 7837 /// Make sure that the output operand \p OpInfo and its corresponding input 7838 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7839 /// out). 7840 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7841 SDISelAsmOperandInfo &MatchingOpInfo, 7842 SelectionDAG &DAG) { 7843 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7844 return; 7845 7846 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7847 const auto &TLI = DAG.getTargetLoweringInfo(); 7848 7849 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7850 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7851 OpInfo.ConstraintVT); 7852 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7853 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7854 MatchingOpInfo.ConstraintVT); 7855 if ((OpInfo.ConstraintVT.isInteger() != 7856 MatchingOpInfo.ConstraintVT.isInteger()) || 7857 (MatchRC.second != InputRC.second)) { 7858 // FIXME: error out in a more elegant fashion 7859 report_fatal_error("Unsupported asm: input constraint" 7860 " with a matching output constraint of" 7861 " incompatible type!"); 7862 } 7863 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7864 } 7865 7866 /// Get a direct memory input to behave well as an indirect operand. 7867 /// This may introduce stores, hence the need for a \p Chain. 7868 /// \return The (possibly updated) chain. 7869 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7870 SDISelAsmOperandInfo &OpInfo, 7871 SelectionDAG &DAG) { 7872 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7873 7874 // If we don't have an indirect input, put it in the constpool if we can, 7875 // otherwise spill it to a stack slot. 7876 // TODO: This isn't quite right. We need to handle these according to 7877 // the addressing mode that the constraint wants. Also, this may take 7878 // an additional register for the computation and we don't want that 7879 // either. 7880 7881 // If the operand is a float, integer, or vector constant, spill to a 7882 // constant pool entry to get its address. 7883 const Value *OpVal = OpInfo.CallOperandVal; 7884 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7885 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7886 OpInfo.CallOperand = DAG.getConstantPool( 7887 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7888 return Chain; 7889 } 7890 7891 // Otherwise, create a stack slot and emit a store to it before the asm. 7892 Type *Ty = OpVal->getType(); 7893 auto &DL = DAG.getDataLayout(); 7894 uint64_t TySize = DL.getTypeAllocSize(Ty); 7895 MachineFunction &MF = DAG.getMachineFunction(); 7896 int SSFI = MF.getFrameInfo().CreateStackObject( 7897 TySize, DL.getPrefTypeAlign(Ty), false); 7898 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7899 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7900 MachinePointerInfo::getFixedStack(MF, SSFI), 7901 TLI.getMemValueType(DL, Ty)); 7902 OpInfo.CallOperand = StackSlot; 7903 7904 return Chain; 7905 } 7906 7907 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7908 /// specified operand. We prefer to assign virtual registers, to allow the 7909 /// register allocator to handle the assignment process. However, if the asm 7910 /// uses features that we can't model on machineinstrs, we have SDISel do the 7911 /// allocation. This produces generally horrible, but correct, code. 7912 /// 7913 /// OpInfo describes the operand 7914 /// RefOpInfo describes the matching operand if any, the operand otherwise 7915 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7916 SDISelAsmOperandInfo &OpInfo, 7917 SDISelAsmOperandInfo &RefOpInfo) { 7918 LLVMContext &Context = *DAG.getContext(); 7919 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7920 7921 MachineFunction &MF = DAG.getMachineFunction(); 7922 SmallVector<unsigned, 4> Regs; 7923 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7924 7925 // No work to do for memory operations. 7926 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7927 return; 7928 7929 // If this is a constraint for a single physreg, or a constraint for a 7930 // register class, find it. 7931 unsigned AssignedReg; 7932 const TargetRegisterClass *RC; 7933 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7934 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7935 // RC is unset only on failure. Return immediately. 7936 if (!RC) 7937 return; 7938 7939 // Get the actual register value type. This is important, because the user 7940 // may have asked for (e.g.) the AX register in i32 type. We need to 7941 // remember that AX is actually i16 to get the right extension. 7942 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7943 7944 if (OpInfo.ConstraintVT != MVT::Other) { 7945 // If this is an FP operand in an integer register (or visa versa), or more 7946 // generally if the operand value disagrees with the register class we plan 7947 // to stick it in, fix the operand type. 7948 // 7949 // If this is an input value, the bitcast to the new type is done now. 7950 // Bitcast for output value is done at the end of visitInlineAsm(). 7951 if ((OpInfo.Type == InlineAsm::isOutput || 7952 OpInfo.Type == InlineAsm::isInput) && 7953 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7954 // Try to convert to the first EVT that the reg class contains. If the 7955 // types are identical size, use a bitcast to convert (e.g. two differing 7956 // vector types). Note: output bitcast is done at the end of 7957 // visitInlineAsm(). 7958 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7959 // Exclude indirect inputs while they are unsupported because the code 7960 // to perform the load is missing and thus OpInfo.CallOperand still 7961 // refers to the input address rather than the pointed-to value. 7962 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7963 OpInfo.CallOperand = 7964 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7965 OpInfo.ConstraintVT = RegVT; 7966 // If the operand is an FP value and we want it in integer registers, 7967 // use the corresponding integer type. This turns an f64 value into 7968 // i64, which can be passed with two i32 values on a 32-bit machine. 7969 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7970 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7971 if (OpInfo.Type == InlineAsm::isInput) 7972 OpInfo.CallOperand = 7973 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7974 OpInfo.ConstraintVT = VT; 7975 } 7976 } 7977 } 7978 7979 // No need to allocate a matching input constraint since the constraint it's 7980 // matching to has already been allocated. 7981 if (OpInfo.isMatchingInputConstraint()) 7982 return; 7983 7984 EVT ValueVT = OpInfo.ConstraintVT; 7985 if (OpInfo.ConstraintVT == MVT::Other) 7986 ValueVT = RegVT; 7987 7988 // Initialize NumRegs. 7989 unsigned NumRegs = 1; 7990 if (OpInfo.ConstraintVT != MVT::Other) 7991 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7992 7993 // If this is a constraint for a specific physical register, like {r17}, 7994 // assign it now. 7995 7996 // If this associated to a specific register, initialize iterator to correct 7997 // place. If virtual, make sure we have enough registers 7998 7999 // Initialize iterator if necessary 8000 TargetRegisterClass::iterator I = RC->begin(); 8001 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8002 8003 // Do not check for single registers. 8004 if (AssignedReg) { 8005 for (; *I != AssignedReg; ++I) 8006 assert(I != RC->end() && "AssignedReg should be member of RC"); 8007 } 8008 8009 for (; NumRegs; --NumRegs, ++I) { 8010 assert(I != RC->end() && "Ran out of registers to allocate!"); 8011 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8012 Regs.push_back(R); 8013 } 8014 8015 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8016 } 8017 8018 static unsigned 8019 findMatchingInlineAsmOperand(unsigned OperandNo, 8020 const std::vector<SDValue> &AsmNodeOperands) { 8021 // Scan until we find the definition we already emitted of this operand. 8022 unsigned CurOp = InlineAsm::Op_FirstOperand; 8023 for (; OperandNo; --OperandNo) { 8024 // Advance to the next operand. 8025 unsigned OpFlag = 8026 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8027 assert((InlineAsm::isRegDefKind(OpFlag) || 8028 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8029 InlineAsm::isMemKind(OpFlag)) && 8030 "Skipped past definitions?"); 8031 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8032 } 8033 return CurOp; 8034 } 8035 8036 namespace { 8037 8038 class ExtraFlags { 8039 unsigned Flags = 0; 8040 8041 public: 8042 explicit ExtraFlags(const CallBase &Call) { 8043 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8044 if (IA->hasSideEffects()) 8045 Flags |= InlineAsm::Extra_HasSideEffects; 8046 if (IA->isAlignStack()) 8047 Flags |= InlineAsm::Extra_IsAlignStack; 8048 if (Call.isConvergent()) 8049 Flags |= InlineAsm::Extra_IsConvergent; 8050 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8051 } 8052 8053 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8054 // Ideally, we would only check against memory constraints. However, the 8055 // meaning of an Other constraint can be target-specific and we can't easily 8056 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8057 // for Other constraints as well. 8058 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8059 OpInfo.ConstraintType == TargetLowering::C_Other) { 8060 if (OpInfo.Type == InlineAsm::isInput) 8061 Flags |= InlineAsm::Extra_MayLoad; 8062 else if (OpInfo.Type == InlineAsm::isOutput) 8063 Flags |= InlineAsm::Extra_MayStore; 8064 else if (OpInfo.Type == InlineAsm::isClobber) 8065 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8066 } 8067 } 8068 8069 unsigned get() const { return Flags; } 8070 }; 8071 8072 } // end anonymous namespace 8073 8074 /// visitInlineAsm - Handle a call to an InlineAsm object. 8075 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8076 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8077 8078 /// ConstraintOperands - Information about all of the constraints. 8079 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8080 8081 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8082 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8083 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8084 8085 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8086 // AsmDialect, MayLoad, MayStore). 8087 bool HasSideEffect = IA->hasSideEffects(); 8088 ExtraFlags ExtraInfo(Call); 8089 8090 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8091 unsigned ResNo = 0; // ResNo - The result number of the next output. 8092 unsigned NumMatchingOps = 0; 8093 for (auto &T : TargetConstraints) { 8094 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8095 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8096 8097 // Compute the value type for each operand. 8098 if (OpInfo.Type == InlineAsm::isInput || 8099 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8100 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8101 8102 // Process the call argument. BasicBlocks are labels, currently appearing 8103 // only in asm's. 8104 if (isa<CallBrInst>(Call) && 8105 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8106 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8107 NumMatchingOps) && 8108 (NumMatchingOps == 0 || 8109 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8110 NumMatchingOps))) { 8111 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8112 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8113 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8114 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8115 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8116 } else { 8117 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8118 } 8119 8120 OpInfo.ConstraintVT = 8121 OpInfo 8122 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8123 .getSimpleVT(); 8124 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8125 // The return value of the call is this value. As such, there is no 8126 // corresponding argument. 8127 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8128 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8129 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8130 DAG.getDataLayout(), STy->getElementType(ResNo)); 8131 } else { 8132 assert(ResNo == 0 && "Asm only has one result!"); 8133 OpInfo.ConstraintVT = 8134 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8135 } 8136 ++ResNo; 8137 } else { 8138 OpInfo.ConstraintVT = MVT::Other; 8139 } 8140 8141 if (OpInfo.hasMatchingInput()) 8142 ++NumMatchingOps; 8143 8144 if (!HasSideEffect) 8145 HasSideEffect = OpInfo.hasMemory(TLI); 8146 8147 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8148 // FIXME: Could we compute this on OpInfo rather than T? 8149 8150 // Compute the constraint code and ConstraintType to use. 8151 TLI.ComputeConstraintToUse(T, SDValue()); 8152 8153 if (T.ConstraintType == TargetLowering::C_Immediate && 8154 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8155 // We've delayed emitting a diagnostic like the "n" constraint because 8156 // inlining could cause an integer showing up. 8157 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8158 "' expects an integer constant " 8159 "expression"); 8160 8161 ExtraInfo.update(T); 8162 } 8163 8164 8165 // We won't need to flush pending loads if this asm doesn't touch 8166 // memory and is nonvolatile. 8167 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8168 8169 bool IsCallBr = isa<CallBrInst>(Call); 8170 if (IsCallBr) { 8171 // If this is a callbr we need to flush pending exports since inlineasm_br 8172 // is a terminator. We need to do this before nodes are glued to 8173 // the inlineasm_br node. 8174 Chain = getControlRoot(); 8175 } 8176 8177 // Second pass over the constraints: compute which constraint option to use. 8178 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8179 // If this is an output operand with a matching input operand, look up the 8180 // matching input. If their types mismatch, e.g. one is an integer, the 8181 // other is floating point, or their sizes are different, flag it as an 8182 // error. 8183 if (OpInfo.hasMatchingInput()) { 8184 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8185 patchMatchingInput(OpInfo, Input, DAG); 8186 } 8187 8188 // Compute the constraint code and ConstraintType to use. 8189 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8190 8191 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8192 OpInfo.Type == InlineAsm::isClobber) 8193 continue; 8194 8195 // If this is a memory input, and if the operand is not indirect, do what we 8196 // need to provide an address for the memory input. 8197 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8198 !OpInfo.isIndirect) { 8199 assert((OpInfo.isMultipleAlternative || 8200 (OpInfo.Type == InlineAsm::isInput)) && 8201 "Can only indirectify direct input operands!"); 8202 8203 // Memory operands really want the address of the value. 8204 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8205 8206 // There is no longer a Value* corresponding to this operand. 8207 OpInfo.CallOperandVal = nullptr; 8208 8209 // It is now an indirect operand. 8210 OpInfo.isIndirect = true; 8211 } 8212 8213 } 8214 8215 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8216 std::vector<SDValue> AsmNodeOperands; 8217 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8218 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8219 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8220 8221 // If we have a !srcloc metadata node associated with it, we want to attach 8222 // this to the ultimately generated inline asm machineinstr. To do this, we 8223 // pass in the third operand as this (potentially null) inline asm MDNode. 8224 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8225 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8226 8227 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8228 // bits as operand 3. 8229 AsmNodeOperands.push_back(DAG.getTargetConstant( 8230 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8231 8232 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8233 // this, assign virtual and physical registers for inputs and otput. 8234 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8235 // Assign Registers. 8236 SDISelAsmOperandInfo &RefOpInfo = 8237 OpInfo.isMatchingInputConstraint() 8238 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8239 : OpInfo; 8240 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8241 8242 auto DetectWriteToReservedRegister = [&]() { 8243 const MachineFunction &MF = DAG.getMachineFunction(); 8244 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8245 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8246 if (Register::isPhysicalRegister(Reg) && 8247 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8248 const char *RegName = TRI.getName(Reg); 8249 emitInlineAsmError(Call, "write to reserved register '" + 8250 Twine(RegName) + "'"); 8251 return true; 8252 } 8253 } 8254 return false; 8255 }; 8256 8257 switch (OpInfo.Type) { 8258 case InlineAsm::isOutput: 8259 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8260 unsigned ConstraintID = 8261 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8262 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8263 "Failed to convert memory constraint code to constraint id."); 8264 8265 // Add information to the INLINEASM node to know about this output. 8266 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8267 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8268 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8269 MVT::i32)); 8270 AsmNodeOperands.push_back(OpInfo.CallOperand); 8271 } else { 8272 // Otherwise, this outputs to a register (directly for C_Register / 8273 // C_RegisterClass, and a target-defined fashion for 8274 // C_Immediate/C_Other). Find a register that we can use. 8275 if (OpInfo.AssignedRegs.Regs.empty()) { 8276 emitInlineAsmError( 8277 Call, "couldn't allocate output register for constraint '" + 8278 Twine(OpInfo.ConstraintCode) + "'"); 8279 return; 8280 } 8281 8282 if (DetectWriteToReservedRegister()) 8283 return; 8284 8285 // Add information to the INLINEASM node to know that this register is 8286 // set. 8287 OpInfo.AssignedRegs.AddInlineAsmOperands( 8288 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8289 : InlineAsm::Kind_RegDef, 8290 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8291 } 8292 break; 8293 8294 case InlineAsm::isInput: { 8295 SDValue InOperandVal = OpInfo.CallOperand; 8296 8297 if (OpInfo.isMatchingInputConstraint()) { 8298 // If this is required to match an output register we have already set, 8299 // just use its register. 8300 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8301 AsmNodeOperands); 8302 unsigned OpFlag = 8303 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8304 if (InlineAsm::isRegDefKind(OpFlag) || 8305 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8306 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8307 if (OpInfo.isIndirect) { 8308 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8309 emitInlineAsmError(Call, "inline asm not supported yet: " 8310 "don't know how to handle tied " 8311 "indirect register inputs"); 8312 return; 8313 } 8314 8315 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8316 SmallVector<unsigned, 4> Regs; 8317 8318 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8319 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8320 MachineRegisterInfo &RegInfo = 8321 DAG.getMachineFunction().getRegInfo(); 8322 for (unsigned i = 0; i != NumRegs; ++i) 8323 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8324 } else { 8325 emitInlineAsmError(Call, 8326 "inline asm error: This value type register " 8327 "class is not natively supported!"); 8328 return; 8329 } 8330 8331 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8332 8333 SDLoc dl = getCurSDLoc(); 8334 // Use the produced MatchedRegs object to 8335 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8336 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8337 true, OpInfo.getMatchedOperand(), dl, 8338 DAG, AsmNodeOperands); 8339 break; 8340 } 8341 8342 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8343 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8344 "Unexpected number of operands"); 8345 // Add information to the INLINEASM node to know about this input. 8346 // See InlineAsm.h isUseOperandTiedToDef. 8347 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8348 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8349 OpInfo.getMatchedOperand()); 8350 AsmNodeOperands.push_back(DAG.getTargetConstant( 8351 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8352 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8353 break; 8354 } 8355 8356 // Treat indirect 'X' constraint as memory. 8357 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8358 OpInfo.isIndirect) 8359 OpInfo.ConstraintType = TargetLowering::C_Memory; 8360 8361 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8362 OpInfo.ConstraintType == TargetLowering::C_Other) { 8363 std::vector<SDValue> Ops; 8364 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8365 Ops, DAG); 8366 if (Ops.empty()) { 8367 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8368 if (isa<ConstantSDNode>(InOperandVal)) { 8369 emitInlineAsmError(Call, "value out of range for constraint '" + 8370 Twine(OpInfo.ConstraintCode) + "'"); 8371 return; 8372 } 8373 8374 emitInlineAsmError(Call, 8375 "invalid operand for inline asm constraint '" + 8376 Twine(OpInfo.ConstraintCode) + "'"); 8377 return; 8378 } 8379 8380 // Add information to the INLINEASM node to know about this input. 8381 unsigned ResOpType = 8382 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8383 AsmNodeOperands.push_back(DAG.getTargetConstant( 8384 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8385 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8386 break; 8387 } 8388 8389 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8390 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8391 assert(InOperandVal.getValueType() == 8392 TLI.getPointerTy(DAG.getDataLayout()) && 8393 "Memory operands expect pointer values"); 8394 8395 unsigned ConstraintID = 8396 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8397 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8398 "Failed to convert memory constraint code to constraint id."); 8399 8400 // Add information to the INLINEASM node to know about this input. 8401 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8402 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8403 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8404 getCurSDLoc(), 8405 MVT::i32)); 8406 AsmNodeOperands.push_back(InOperandVal); 8407 break; 8408 } 8409 8410 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8411 OpInfo.ConstraintType == TargetLowering::C_Register) && 8412 "Unknown constraint type!"); 8413 8414 // TODO: Support this. 8415 if (OpInfo.isIndirect) { 8416 emitInlineAsmError( 8417 Call, "Don't know how to handle indirect register inputs yet " 8418 "for constraint '" + 8419 Twine(OpInfo.ConstraintCode) + "'"); 8420 return; 8421 } 8422 8423 // Copy the input into the appropriate registers. 8424 if (OpInfo.AssignedRegs.Regs.empty()) { 8425 emitInlineAsmError(Call, 8426 "couldn't allocate input reg for constraint '" + 8427 Twine(OpInfo.ConstraintCode) + "'"); 8428 return; 8429 } 8430 8431 if (DetectWriteToReservedRegister()) 8432 return; 8433 8434 SDLoc dl = getCurSDLoc(); 8435 8436 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8437 &Call); 8438 8439 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8440 dl, DAG, AsmNodeOperands); 8441 break; 8442 } 8443 case InlineAsm::isClobber: 8444 // Add the clobbered value to the operand list, so that the register 8445 // allocator is aware that the physreg got clobbered. 8446 if (!OpInfo.AssignedRegs.Regs.empty()) 8447 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8448 false, 0, getCurSDLoc(), DAG, 8449 AsmNodeOperands); 8450 break; 8451 } 8452 } 8453 8454 // Finish up input operands. Set the input chain and add the flag last. 8455 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8456 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8457 8458 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8459 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8460 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8461 Flag = Chain.getValue(1); 8462 8463 // Do additional work to generate outputs. 8464 8465 SmallVector<EVT, 1> ResultVTs; 8466 SmallVector<SDValue, 1> ResultValues; 8467 SmallVector<SDValue, 8> OutChains; 8468 8469 llvm::Type *CallResultType = Call.getType(); 8470 ArrayRef<Type *> ResultTypes; 8471 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8472 ResultTypes = StructResult->elements(); 8473 else if (!CallResultType->isVoidTy()) 8474 ResultTypes = makeArrayRef(CallResultType); 8475 8476 auto CurResultType = ResultTypes.begin(); 8477 auto handleRegAssign = [&](SDValue V) { 8478 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8479 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8480 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8481 ++CurResultType; 8482 // If the type of the inline asm call site return value is different but has 8483 // same size as the type of the asm output bitcast it. One example of this 8484 // is for vectors with different width / number of elements. This can 8485 // happen for register classes that can contain multiple different value 8486 // types. The preg or vreg allocated may not have the same VT as was 8487 // expected. 8488 // 8489 // This can also happen for a return value that disagrees with the register 8490 // class it is put in, eg. a double in a general-purpose register on a 8491 // 32-bit machine. 8492 if (ResultVT != V.getValueType() && 8493 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8494 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8495 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8496 V.getValueType().isInteger()) { 8497 // If a result value was tied to an input value, the computed result 8498 // may have a wider width than the expected result. Extract the 8499 // relevant portion. 8500 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8501 } 8502 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8503 ResultVTs.push_back(ResultVT); 8504 ResultValues.push_back(V); 8505 }; 8506 8507 // Deal with output operands. 8508 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8509 if (OpInfo.Type == InlineAsm::isOutput) { 8510 SDValue Val; 8511 // Skip trivial output operands. 8512 if (OpInfo.AssignedRegs.Regs.empty()) 8513 continue; 8514 8515 switch (OpInfo.ConstraintType) { 8516 case TargetLowering::C_Register: 8517 case TargetLowering::C_RegisterClass: 8518 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8519 Chain, &Flag, &Call); 8520 break; 8521 case TargetLowering::C_Immediate: 8522 case TargetLowering::C_Other: 8523 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8524 OpInfo, DAG); 8525 break; 8526 case TargetLowering::C_Memory: 8527 break; // Already handled. 8528 case TargetLowering::C_Unknown: 8529 assert(false && "Unexpected unknown constraint"); 8530 } 8531 8532 // Indirect output manifest as stores. Record output chains. 8533 if (OpInfo.isIndirect) { 8534 const Value *Ptr = OpInfo.CallOperandVal; 8535 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8536 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8537 MachinePointerInfo(Ptr)); 8538 OutChains.push_back(Store); 8539 } else { 8540 // generate CopyFromRegs to associated registers. 8541 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8542 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8543 for (const SDValue &V : Val->op_values()) 8544 handleRegAssign(V); 8545 } else 8546 handleRegAssign(Val); 8547 } 8548 } 8549 } 8550 8551 // Set results. 8552 if (!ResultValues.empty()) { 8553 assert(CurResultType == ResultTypes.end() && 8554 "Mismatch in number of ResultTypes"); 8555 assert(ResultValues.size() == ResultTypes.size() && 8556 "Mismatch in number of output operands in asm result"); 8557 8558 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8559 DAG.getVTList(ResultVTs), ResultValues); 8560 setValue(&Call, V); 8561 } 8562 8563 // Collect store chains. 8564 if (!OutChains.empty()) 8565 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8566 8567 // Only Update Root if inline assembly has a memory effect. 8568 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8569 DAG.setRoot(Chain); 8570 } 8571 8572 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8573 const Twine &Message) { 8574 LLVMContext &Ctx = *DAG.getContext(); 8575 Ctx.emitError(&Call, Message); 8576 8577 // Make sure we leave the DAG in a valid state 8578 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8579 SmallVector<EVT, 1> ValueVTs; 8580 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8581 8582 if (ValueVTs.empty()) 8583 return; 8584 8585 SmallVector<SDValue, 1> Ops; 8586 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8587 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8588 8589 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8590 } 8591 8592 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8593 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8594 MVT::Other, getRoot(), 8595 getValue(I.getArgOperand(0)), 8596 DAG.getSrcValue(I.getArgOperand(0)))); 8597 } 8598 8599 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8600 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8601 const DataLayout &DL = DAG.getDataLayout(); 8602 SDValue V = DAG.getVAArg( 8603 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8604 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8605 DL.getABITypeAlign(I.getType()).value()); 8606 DAG.setRoot(V.getValue(1)); 8607 8608 if (I.getType()->isPointerTy()) 8609 V = DAG.getPtrExtOrTrunc( 8610 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8611 setValue(&I, V); 8612 } 8613 8614 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8615 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8616 MVT::Other, getRoot(), 8617 getValue(I.getArgOperand(0)), 8618 DAG.getSrcValue(I.getArgOperand(0)))); 8619 } 8620 8621 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8622 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8623 MVT::Other, getRoot(), 8624 getValue(I.getArgOperand(0)), 8625 getValue(I.getArgOperand(1)), 8626 DAG.getSrcValue(I.getArgOperand(0)), 8627 DAG.getSrcValue(I.getArgOperand(1)))); 8628 } 8629 8630 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8631 const Instruction &I, 8632 SDValue Op) { 8633 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8634 if (!Range) 8635 return Op; 8636 8637 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8638 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8639 return Op; 8640 8641 APInt Lo = CR.getUnsignedMin(); 8642 if (!Lo.isMinValue()) 8643 return Op; 8644 8645 APInt Hi = CR.getUnsignedMax(); 8646 unsigned Bits = std::max(Hi.getActiveBits(), 8647 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8648 8649 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8650 8651 SDLoc SL = getCurSDLoc(); 8652 8653 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8654 DAG.getValueType(SmallVT)); 8655 unsigned NumVals = Op.getNode()->getNumValues(); 8656 if (NumVals == 1) 8657 return ZExt; 8658 8659 SmallVector<SDValue, 4> Ops; 8660 8661 Ops.push_back(ZExt); 8662 for (unsigned I = 1; I != NumVals; ++I) 8663 Ops.push_back(Op.getValue(I)); 8664 8665 return DAG.getMergeValues(Ops, SL); 8666 } 8667 8668 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8669 /// the call being lowered. 8670 /// 8671 /// This is a helper for lowering intrinsics that follow a target calling 8672 /// convention or require stack pointer adjustment. Only a subset of the 8673 /// intrinsic's operands need to participate in the calling convention. 8674 void SelectionDAGBuilder::populateCallLoweringInfo( 8675 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8676 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8677 bool IsPatchPoint) { 8678 TargetLowering::ArgListTy Args; 8679 Args.reserve(NumArgs); 8680 8681 // Populate the argument list. 8682 // Attributes for args start at offset 1, after the return attribute. 8683 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8684 ArgI != ArgE; ++ArgI) { 8685 const Value *V = Call->getOperand(ArgI); 8686 8687 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8688 8689 TargetLowering::ArgListEntry Entry; 8690 Entry.Node = getValue(V); 8691 Entry.Ty = V->getType(); 8692 Entry.setAttributes(Call, ArgI); 8693 Args.push_back(Entry); 8694 } 8695 8696 CLI.setDebugLoc(getCurSDLoc()) 8697 .setChain(getRoot()) 8698 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8699 .setDiscardResult(Call->use_empty()) 8700 .setIsPatchPoint(IsPatchPoint) 8701 .setIsPreallocated( 8702 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8703 } 8704 8705 /// Add a stack map intrinsic call's live variable operands to a stackmap 8706 /// or patchpoint target node's operand list. 8707 /// 8708 /// Constants are converted to TargetConstants purely as an optimization to 8709 /// avoid constant materialization and register allocation. 8710 /// 8711 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8712 /// generate addess computation nodes, and so FinalizeISel can convert the 8713 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8714 /// address materialization and register allocation, but may also be required 8715 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8716 /// alloca in the entry block, then the runtime may assume that the alloca's 8717 /// StackMap location can be read immediately after compilation and that the 8718 /// location is valid at any point during execution (this is similar to the 8719 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8720 /// only available in a register, then the runtime would need to trap when 8721 /// execution reaches the StackMap in order to read the alloca's location. 8722 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8723 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8724 SelectionDAGBuilder &Builder) { 8725 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8726 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8728 Ops.push_back( 8729 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8730 Ops.push_back( 8731 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8732 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8733 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8734 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8735 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8736 } else 8737 Ops.push_back(OpVal); 8738 } 8739 } 8740 8741 /// Lower llvm.experimental.stackmap directly to its target opcode. 8742 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8743 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8744 // [live variables...]) 8745 8746 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8747 8748 SDValue Chain, InFlag, Callee, NullPtr; 8749 SmallVector<SDValue, 32> Ops; 8750 8751 SDLoc DL = getCurSDLoc(); 8752 Callee = getValue(CI.getCalledOperand()); 8753 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8754 8755 // The stackmap intrinsic only records the live variables (the arguments 8756 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8757 // intrinsic, this won't be lowered to a function call. This means we don't 8758 // have to worry about calling conventions and target specific lowering code. 8759 // Instead we perform the call lowering right here. 8760 // 8761 // chain, flag = CALLSEQ_START(chain, 0, 0) 8762 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8763 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8764 // 8765 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8766 InFlag = Chain.getValue(1); 8767 8768 // Add the <id> and <numBytes> constants. 8769 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8770 Ops.push_back(DAG.getTargetConstant( 8771 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8772 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8773 Ops.push_back(DAG.getTargetConstant( 8774 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8775 MVT::i32)); 8776 8777 // Push live variables for the stack map. 8778 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8779 8780 // We are not pushing any register mask info here on the operands list, 8781 // because the stackmap doesn't clobber anything. 8782 8783 // Push the chain and the glue flag. 8784 Ops.push_back(Chain); 8785 Ops.push_back(InFlag); 8786 8787 // Create the STACKMAP node. 8788 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8789 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8790 Chain = SDValue(SM, 0); 8791 InFlag = Chain.getValue(1); 8792 8793 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8794 8795 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8796 8797 // Set the root to the target-lowered call chain. 8798 DAG.setRoot(Chain); 8799 8800 // Inform the Frame Information that we have a stackmap in this function. 8801 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8802 } 8803 8804 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8805 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8806 const BasicBlock *EHPadBB) { 8807 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8808 // i32 <numBytes>, 8809 // i8* <target>, 8810 // i32 <numArgs>, 8811 // [Args...], 8812 // [live variables...]) 8813 8814 CallingConv::ID CC = CB.getCallingConv(); 8815 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8816 bool HasDef = !CB.getType()->isVoidTy(); 8817 SDLoc dl = getCurSDLoc(); 8818 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8819 8820 // Handle immediate and symbolic callees. 8821 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8822 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8823 /*isTarget=*/true); 8824 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8825 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8826 SDLoc(SymbolicCallee), 8827 SymbolicCallee->getValueType(0)); 8828 8829 // Get the real number of arguments participating in the call <numArgs> 8830 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8831 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8832 8833 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8834 // Intrinsics include all meta-operands up to but not including CC. 8835 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8836 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8837 "Not enough arguments provided to the patchpoint intrinsic"); 8838 8839 // For AnyRegCC the arguments are lowered later on manually. 8840 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8841 Type *ReturnTy = 8842 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8843 8844 TargetLowering::CallLoweringInfo CLI(DAG); 8845 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8846 ReturnTy, true); 8847 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8848 8849 SDNode *CallEnd = Result.second.getNode(); 8850 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8851 CallEnd = CallEnd->getOperand(0).getNode(); 8852 8853 /// Get a call instruction from the call sequence chain. 8854 /// Tail calls are not allowed. 8855 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8856 "Expected a callseq node."); 8857 SDNode *Call = CallEnd->getOperand(0).getNode(); 8858 bool HasGlue = Call->getGluedNode(); 8859 8860 // Replace the target specific call node with the patchable intrinsic. 8861 SmallVector<SDValue, 8> Ops; 8862 8863 // Add the <id> and <numBytes> constants. 8864 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8865 Ops.push_back(DAG.getTargetConstant( 8866 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8867 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8868 Ops.push_back(DAG.getTargetConstant( 8869 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8870 MVT::i32)); 8871 8872 // Add the callee. 8873 Ops.push_back(Callee); 8874 8875 // Adjust <numArgs> to account for any arguments that have been passed on the 8876 // stack instead. 8877 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8878 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8879 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8880 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8881 8882 // Add the calling convention 8883 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8884 8885 // Add the arguments we omitted previously. The register allocator should 8886 // place these in any free register. 8887 if (IsAnyRegCC) 8888 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8889 Ops.push_back(getValue(CB.getArgOperand(i))); 8890 8891 // Push the arguments from the call instruction up to the register mask. 8892 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8893 Ops.append(Call->op_begin() + 2, e); 8894 8895 // Push live variables for the stack map. 8896 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8897 8898 // Push the register mask info. 8899 if (HasGlue) 8900 Ops.push_back(*(Call->op_end()-2)); 8901 else 8902 Ops.push_back(*(Call->op_end()-1)); 8903 8904 // Push the chain (this is originally the first operand of the call, but 8905 // becomes now the last or second to last operand). 8906 Ops.push_back(*(Call->op_begin())); 8907 8908 // Push the glue flag (last operand). 8909 if (HasGlue) 8910 Ops.push_back(*(Call->op_end()-1)); 8911 8912 SDVTList NodeTys; 8913 if (IsAnyRegCC && HasDef) { 8914 // Create the return types based on the intrinsic definition 8915 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8916 SmallVector<EVT, 3> ValueVTs; 8917 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8918 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8919 8920 // There is always a chain and a glue type at the end 8921 ValueVTs.push_back(MVT::Other); 8922 ValueVTs.push_back(MVT::Glue); 8923 NodeTys = DAG.getVTList(ValueVTs); 8924 } else 8925 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8926 8927 // Replace the target specific call node with a PATCHPOINT node. 8928 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8929 dl, NodeTys, Ops); 8930 8931 // Update the NodeMap. 8932 if (HasDef) { 8933 if (IsAnyRegCC) 8934 setValue(&CB, SDValue(MN, 0)); 8935 else 8936 setValue(&CB, Result.first); 8937 } 8938 8939 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8940 // call sequence. Furthermore the location of the chain and glue can change 8941 // when the AnyReg calling convention is used and the intrinsic returns a 8942 // value. 8943 if (IsAnyRegCC && HasDef) { 8944 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8945 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8946 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8947 } else 8948 DAG.ReplaceAllUsesWith(Call, MN); 8949 DAG.DeleteNode(Call); 8950 8951 // Inform the Frame Information that we have a patchpoint in this function. 8952 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8953 } 8954 8955 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8956 unsigned Intrinsic) { 8957 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8958 SDValue Op1 = getValue(I.getArgOperand(0)); 8959 SDValue Op2; 8960 if (I.getNumArgOperands() > 1) 8961 Op2 = getValue(I.getArgOperand(1)); 8962 SDLoc dl = getCurSDLoc(); 8963 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8964 SDValue Res; 8965 FastMathFlags FMF; 8966 if (isa<FPMathOperator>(I)) 8967 FMF = I.getFastMathFlags(); 8968 8969 switch (Intrinsic) { 8970 case Intrinsic::experimental_vector_reduce_v2_fadd: 8971 if (FMF.allowReassoc()) 8972 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8973 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8974 else 8975 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8976 break; 8977 case Intrinsic::experimental_vector_reduce_v2_fmul: 8978 if (FMF.allowReassoc()) 8979 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8980 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8981 else 8982 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8983 break; 8984 case Intrinsic::experimental_vector_reduce_add: 8985 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8986 break; 8987 case Intrinsic::experimental_vector_reduce_mul: 8988 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8989 break; 8990 case Intrinsic::experimental_vector_reduce_and: 8991 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8992 break; 8993 case Intrinsic::experimental_vector_reduce_or: 8994 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8995 break; 8996 case Intrinsic::experimental_vector_reduce_xor: 8997 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8998 break; 8999 case Intrinsic::experimental_vector_reduce_smax: 9000 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9001 break; 9002 case Intrinsic::experimental_vector_reduce_smin: 9003 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9004 break; 9005 case Intrinsic::experimental_vector_reduce_umax: 9006 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9007 break; 9008 case Intrinsic::experimental_vector_reduce_umin: 9009 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9010 break; 9011 case Intrinsic::experimental_vector_reduce_fmax: 9012 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 9013 break; 9014 case Intrinsic::experimental_vector_reduce_fmin: 9015 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 9016 break; 9017 default: 9018 llvm_unreachable("Unhandled vector reduce intrinsic"); 9019 } 9020 setValue(&I, Res); 9021 } 9022 9023 /// Returns an AttributeList representing the attributes applied to the return 9024 /// value of the given call. 9025 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9026 SmallVector<Attribute::AttrKind, 2> Attrs; 9027 if (CLI.RetSExt) 9028 Attrs.push_back(Attribute::SExt); 9029 if (CLI.RetZExt) 9030 Attrs.push_back(Attribute::ZExt); 9031 if (CLI.IsInReg) 9032 Attrs.push_back(Attribute::InReg); 9033 9034 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9035 Attrs); 9036 } 9037 9038 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9039 /// implementation, which just calls LowerCall. 9040 /// FIXME: When all targets are 9041 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9042 std::pair<SDValue, SDValue> 9043 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9044 // Handle the incoming return values from the call. 9045 CLI.Ins.clear(); 9046 Type *OrigRetTy = CLI.RetTy; 9047 SmallVector<EVT, 4> RetTys; 9048 SmallVector<uint64_t, 4> Offsets; 9049 auto &DL = CLI.DAG.getDataLayout(); 9050 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9051 9052 if (CLI.IsPostTypeLegalization) { 9053 // If we are lowering a libcall after legalization, split the return type. 9054 SmallVector<EVT, 4> OldRetTys; 9055 SmallVector<uint64_t, 4> OldOffsets; 9056 RetTys.swap(OldRetTys); 9057 Offsets.swap(OldOffsets); 9058 9059 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9060 EVT RetVT = OldRetTys[i]; 9061 uint64_t Offset = OldOffsets[i]; 9062 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9063 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9064 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9065 RetTys.append(NumRegs, RegisterVT); 9066 for (unsigned j = 0; j != NumRegs; ++j) 9067 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9068 } 9069 } 9070 9071 SmallVector<ISD::OutputArg, 4> Outs; 9072 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9073 9074 bool CanLowerReturn = 9075 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9076 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9077 9078 SDValue DemoteStackSlot; 9079 int DemoteStackIdx = -100; 9080 if (!CanLowerReturn) { 9081 // FIXME: equivalent assert? 9082 // assert(!CS.hasInAllocaArgument() && 9083 // "sret demotion is incompatible with inalloca"); 9084 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9085 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9086 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9087 DemoteStackIdx = 9088 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9089 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9090 DL.getAllocaAddrSpace()); 9091 9092 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9093 ArgListEntry Entry; 9094 Entry.Node = DemoteStackSlot; 9095 Entry.Ty = StackSlotPtrType; 9096 Entry.IsSExt = false; 9097 Entry.IsZExt = false; 9098 Entry.IsInReg = false; 9099 Entry.IsSRet = true; 9100 Entry.IsNest = false; 9101 Entry.IsByVal = false; 9102 Entry.IsByRef = false; 9103 Entry.IsReturned = false; 9104 Entry.IsSwiftSelf = false; 9105 Entry.IsSwiftError = false; 9106 Entry.IsCFGuardTarget = false; 9107 Entry.Alignment = Alignment; 9108 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9109 CLI.NumFixedArgs += 1; 9110 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9111 9112 // sret demotion isn't compatible with tail-calls, since the sret argument 9113 // points into the callers stack frame. 9114 CLI.IsTailCall = false; 9115 } else { 9116 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9117 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9118 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9119 ISD::ArgFlagsTy Flags; 9120 if (NeedsRegBlock) { 9121 Flags.setInConsecutiveRegs(); 9122 if (I == RetTys.size() - 1) 9123 Flags.setInConsecutiveRegsLast(); 9124 } 9125 EVT VT = RetTys[I]; 9126 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9127 CLI.CallConv, VT); 9128 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9129 CLI.CallConv, VT); 9130 for (unsigned i = 0; i != NumRegs; ++i) { 9131 ISD::InputArg MyFlags; 9132 MyFlags.Flags = Flags; 9133 MyFlags.VT = RegisterVT; 9134 MyFlags.ArgVT = VT; 9135 MyFlags.Used = CLI.IsReturnValueUsed; 9136 if (CLI.RetTy->isPointerTy()) { 9137 MyFlags.Flags.setPointer(); 9138 MyFlags.Flags.setPointerAddrSpace( 9139 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9140 } 9141 if (CLI.RetSExt) 9142 MyFlags.Flags.setSExt(); 9143 if (CLI.RetZExt) 9144 MyFlags.Flags.setZExt(); 9145 if (CLI.IsInReg) 9146 MyFlags.Flags.setInReg(); 9147 CLI.Ins.push_back(MyFlags); 9148 } 9149 } 9150 } 9151 9152 // We push in swifterror return as the last element of CLI.Ins. 9153 ArgListTy &Args = CLI.getArgs(); 9154 if (supportSwiftError()) { 9155 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9156 if (Args[i].IsSwiftError) { 9157 ISD::InputArg MyFlags; 9158 MyFlags.VT = getPointerTy(DL); 9159 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9160 MyFlags.Flags.setSwiftError(); 9161 CLI.Ins.push_back(MyFlags); 9162 } 9163 } 9164 } 9165 9166 // Handle all of the outgoing arguments. 9167 CLI.Outs.clear(); 9168 CLI.OutVals.clear(); 9169 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9170 SmallVector<EVT, 4> ValueVTs; 9171 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9172 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9173 Type *FinalType = Args[i].Ty; 9174 if (Args[i].IsByVal) 9175 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9176 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9177 FinalType, CLI.CallConv, CLI.IsVarArg); 9178 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9179 ++Value) { 9180 EVT VT = ValueVTs[Value]; 9181 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9182 SDValue Op = SDValue(Args[i].Node.getNode(), 9183 Args[i].Node.getResNo() + Value); 9184 ISD::ArgFlagsTy Flags; 9185 9186 // Certain targets (such as MIPS), may have a different ABI alignment 9187 // for a type depending on the context. Give the target a chance to 9188 // specify the alignment it wants. 9189 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9190 9191 if (Args[i].Ty->isPointerTy()) { 9192 Flags.setPointer(); 9193 Flags.setPointerAddrSpace( 9194 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9195 } 9196 if (Args[i].IsZExt) 9197 Flags.setZExt(); 9198 if (Args[i].IsSExt) 9199 Flags.setSExt(); 9200 if (Args[i].IsInReg) { 9201 // If we are using vectorcall calling convention, a structure that is 9202 // passed InReg - is surely an HVA 9203 if (CLI.CallConv == CallingConv::X86_VectorCall && 9204 isa<StructType>(FinalType)) { 9205 // The first value of a structure is marked 9206 if (0 == Value) 9207 Flags.setHvaStart(); 9208 Flags.setHva(); 9209 } 9210 // Set InReg Flag 9211 Flags.setInReg(); 9212 } 9213 if (Args[i].IsSRet) 9214 Flags.setSRet(); 9215 if (Args[i].IsSwiftSelf) 9216 Flags.setSwiftSelf(); 9217 if (Args[i].IsSwiftError) 9218 Flags.setSwiftError(); 9219 if (Args[i].IsCFGuardTarget) 9220 Flags.setCFGuardTarget(); 9221 if (Args[i].IsByVal) 9222 Flags.setByVal(); 9223 if (Args[i].IsByRef) 9224 Flags.setByRef(); 9225 if (Args[i].IsPreallocated) { 9226 Flags.setPreallocated(); 9227 // Set the byval flag for CCAssignFn callbacks that don't know about 9228 // preallocated. This way we can know how many bytes we should've 9229 // allocated and how many bytes a callee cleanup function will pop. If 9230 // we port preallocated to more targets, we'll have to add custom 9231 // preallocated handling in the various CC lowering callbacks. 9232 Flags.setByVal(); 9233 } 9234 if (Args[i].IsInAlloca) { 9235 Flags.setInAlloca(); 9236 // Set the byval flag for CCAssignFn callbacks that don't know about 9237 // inalloca. This way we can know how many bytes we should've allocated 9238 // and how many bytes a callee cleanup function will pop. If we port 9239 // inalloca to more targets, we'll have to add custom inalloca handling 9240 // in the various CC lowering callbacks. 9241 Flags.setByVal(); 9242 } 9243 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9244 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9245 Type *ElementTy = Ty->getElementType(); 9246 9247 unsigned FrameSize = DL.getTypeAllocSize( 9248 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9249 Flags.setByValSize(FrameSize); 9250 9251 // info is not there but there are cases it cannot get right. 9252 Align FrameAlign; 9253 if (auto MA = Args[i].Alignment) 9254 FrameAlign = *MA; 9255 else 9256 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9257 Flags.setByValAlign(FrameAlign); 9258 } 9259 if (Args[i].IsNest) 9260 Flags.setNest(); 9261 if (NeedsRegBlock) 9262 Flags.setInConsecutiveRegs(); 9263 Flags.setOrigAlign(OriginalAlignment); 9264 9265 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9266 CLI.CallConv, VT); 9267 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9268 CLI.CallConv, VT); 9269 SmallVector<SDValue, 4> Parts(NumParts); 9270 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9271 9272 if (Args[i].IsSExt) 9273 ExtendKind = ISD::SIGN_EXTEND; 9274 else if (Args[i].IsZExt) 9275 ExtendKind = ISD::ZERO_EXTEND; 9276 9277 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9278 // for now. 9279 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9280 CanLowerReturn) { 9281 assert((CLI.RetTy == Args[i].Ty || 9282 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9283 CLI.RetTy->getPointerAddressSpace() == 9284 Args[i].Ty->getPointerAddressSpace())) && 9285 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9286 // Before passing 'returned' to the target lowering code, ensure that 9287 // either the register MVT and the actual EVT are the same size or that 9288 // the return value and argument are extended in the same way; in these 9289 // cases it's safe to pass the argument register value unchanged as the 9290 // return register value (although it's at the target's option whether 9291 // to do so) 9292 // TODO: allow code generation to take advantage of partially preserved 9293 // registers rather than clobbering the entire register when the 9294 // parameter extension method is not compatible with the return 9295 // extension method 9296 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9297 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9298 CLI.RetZExt == Args[i].IsZExt)) 9299 Flags.setReturned(); 9300 } 9301 9302 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9303 CLI.CallConv, ExtendKind); 9304 9305 for (unsigned j = 0; j != NumParts; ++j) { 9306 // if it isn't first piece, alignment must be 1 9307 // For scalable vectors the scalable part is currently handled 9308 // by individual targets, so we just use the known minimum size here. 9309 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9310 i < CLI.NumFixedArgs, i, 9311 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9312 if (NumParts > 1 && j == 0) 9313 MyFlags.Flags.setSplit(); 9314 else if (j != 0) { 9315 MyFlags.Flags.setOrigAlign(Align(1)); 9316 if (j == NumParts - 1) 9317 MyFlags.Flags.setSplitEnd(); 9318 } 9319 9320 CLI.Outs.push_back(MyFlags); 9321 CLI.OutVals.push_back(Parts[j]); 9322 } 9323 9324 if (NeedsRegBlock && Value == NumValues - 1) 9325 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9326 } 9327 } 9328 9329 SmallVector<SDValue, 4> InVals; 9330 CLI.Chain = LowerCall(CLI, InVals); 9331 9332 // Update CLI.InVals to use outside of this function. 9333 CLI.InVals = InVals; 9334 9335 // Verify that the target's LowerCall behaved as expected. 9336 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9337 "LowerCall didn't return a valid chain!"); 9338 assert((!CLI.IsTailCall || InVals.empty()) && 9339 "LowerCall emitted a return value for a tail call!"); 9340 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9341 "LowerCall didn't emit the correct number of values!"); 9342 9343 // For a tail call, the return value is merely live-out and there aren't 9344 // any nodes in the DAG representing it. Return a special value to 9345 // indicate that a tail call has been emitted and no more Instructions 9346 // should be processed in the current block. 9347 if (CLI.IsTailCall) { 9348 CLI.DAG.setRoot(CLI.Chain); 9349 return std::make_pair(SDValue(), SDValue()); 9350 } 9351 9352 #ifndef NDEBUG 9353 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9354 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9355 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9356 "LowerCall emitted a value with the wrong type!"); 9357 } 9358 #endif 9359 9360 SmallVector<SDValue, 4> ReturnValues; 9361 if (!CanLowerReturn) { 9362 // The instruction result is the result of loading from the 9363 // hidden sret parameter. 9364 SmallVector<EVT, 1> PVTs; 9365 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9366 9367 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9368 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9369 EVT PtrVT = PVTs[0]; 9370 9371 unsigned NumValues = RetTys.size(); 9372 ReturnValues.resize(NumValues); 9373 SmallVector<SDValue, 4> Chains(NumValues); 9374 9375 // An aggregate return value cannot wrap around the address space, so 9376 // offsets to its parts don't wrap either. 9377 SDNodeFlags Flags; 9378 Flags.setNoUnsignedWrap(true); 9379 9380 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9381 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9382 for (unsigned i = 0; i < NumValues; ++i) { 9383 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9384 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9385 PtrVT), Flags); 9386 SDValue L = CLI.DAG.getLoad( 9387 RetTys[i], CLI.DL, CLI.Chain, Add, 9388 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9389 DemoteStackIdx, Offsets[i]), 9390 HiddenSRetAlign); 9391 ReturnValues[i] = L; 9392 Chains[i] = L.getValue(1); 9393 } 9394 9395 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9396 } else { 9397 // Collect the legal value parts into potentially illegal values 9398 // that correspond to the original function's return values. 9399 Optional<ISD::NodeType> AssertOp; 9400 if (CLI.RetSExt) 9401 AssertOp = ISD::AssertSext; 9402 else if (CLI.RetZExt) 9403 AssertOp = ISD::AssertZext; 9404 unsigned CurReg = 0; 9405 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9406 EVT VT = RetTys[I]; 9407 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9408 CLI.CallConv, VT); 9409 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9410 CLI.CallConv, VT); 9411 9412 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9413 NumRegs, RegisterVT, VT, nullptr, 9414 CLI.CallConv, AssertOp)); 9415 CurReg += NumRegs; 9416 } 9417 9418 // For a function returning void, there is no return value. We can't create 9419 // such a node, so we just return a null return value in that case. In 9420 // that case, nothing will actually look at the value. 9421 if (ReturnValues.empty()) 9422 return std::make_pair(SDValue(), CLI.Chain); 9423 } 9424 9425 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9426 CLI.DAG.getVTList(RetTys), ReturnValues); 9427 return std::make_pair(Res, CLI.Chain); 9428 } 9429 9430 void TargetLowering::LowerOperationWrapper(SDNode *N, 9431 SmallVectorImpl<SDValue> &Results, 9432 SelectionDAG &DAG) const { 9433 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9434 Results.push_back(Res); 9435 } 9436 9437 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9438 llvm_unreachable("LowerOperation not implemented for this target!"); 9439 } 9440 9441 void 9442 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9443 SDValue Op = getNonRegisterValue(V); 9444 assert((Op.getOpcode() != ISD::CopyFromReg || 9445 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9446 "Copy from a reg to the same reg!"); 9447 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9448 9449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9450 // If this is an InlineAsm we have to match the registers required, not the 9451 // notional registers required by the type. 9452 9453 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9454 None); // This is not an ABI copy. 9455 SDValue Chain = DAG.getEntryNode(); 9456 9457 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9458 FuncInfo.PreferredExtendType.end()) 9459 ? ISD::ANY_EXTEND 9460 : FuncInfo.PreferredExtendType[V]; 9461 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9462 PendingExports.push_back(Chain); 9463 } 9464 9465 #include "llvm/CodeGen/SelectionDAGISel.h" 9466 9467 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9468 /// entry block, return true. This includes arguments used by switches, since 9469 /// the switch may expand into multiple basic blocks. 9470 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9471 // With FastISel active, we may be splitting blocks, so force creation 9472 // of virtual registers for all non-dead arguments. 9473 if (FastISel) 9474 return A->use_empty(); 9475 9476 const BasicBlock &Entry = A->getParent()->front(); 9477 for (const User *U : A->users()) 9478 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9479 return false; // Use not in entry block. 9480 9481 return true; 9482 } 9483 9484 using ArgCopyElisionMapTy = 9485 DenseMap<const Argument *, 9486 std::pair<const AllocaInst *, const StoreInst *>>; 9487 9488 /// Scan the entry block of the function in FuncInfo for arguments that look 9489 /// like copies into a local alloca. Record any copied arguments in 9490 /// ArgCopyElisionCandidates. 9491 static void 9492 findArgumentCopyElisionCandidates(const DataLayout &DL, 9493 FunctionLoweringInfo *FuncInfo, 9494 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9495 // Record the state of every static alloca used in the entry block. Argument 9496 // allocas are all used in the entry block, so we need approximately as many 9497 // entries as we have arguments. 9498 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9499 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9500 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9501 StaticAllocas.reserve(NumArgs * 2); 9502 9503 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9504 if (!V) 9505 return nullptr; 9506 V = V->stripPointerCasts(); 9507 const auto *AI = dyn_cast<AllocaInst>(V); 9508 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9509 return nullptr; 9510 auto Iter = StaticAllocas.insert({AI, Unknown}); 9511 return &Iter.first->second; 9512 }; 9513 9514 // Look for stores of arguments to static allocas. Look through bitcasts and 9515 // GEPs to handle type coercions, as long as the alloca is fully initialized 9516 // by the store. Any non-store use of an alloca escapes it and any subsequent 9517 // unanalyzed store might write it. 9518 // FIXME: Handle structs initialized with multiple stores. 9519 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9520 // Look for stores, and handle non-store uses conservatively. 9521 const auto *SI = dyn_cast<StoreInst>(&I); 9522 if (!SI) { 9523 // We will look through cast uses, so ignore them completely. 9524 if (I.isCast()) 9525 continue; 9526 // Ignore debug info intrinsics, they don't escape or store to allocas. 9527 if (isa<DbgInfoIntrinsic>(I)) 9528 continue; 9529 // This is an unknown instruction. Assume it escapes or writes to all 9530 // static alloca operands. 9531 for (const Use &U : I.operands()) { 9532 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9533 *Info = StaticAllocaInfo::Clobbered; 9534 } 9535 continue; 9536 } 9537 9538 // If the stored value is a static alloca, mark it as escaped. 9539 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9540 *Info = StaticAllocaInfo::Clobbered; 9541 9542 // Check if the destination is a static alloca. 9543 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9544 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9545 if (!Info) 9546 continue; 9547 const AllocaInst *AI = cast<AllocaInst>(Dst); 9548 9549 // Skip allocas that have been initialized or clobbered. 9550 if (*Info != StaticAllocaInfo::Unknown) 9551 continue; 9552 9553 // Check if the stored value is an argument, and that this store fully 9554 // initializes the alloca. Don't elide copies from the same argument twice. 9555 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9556 const auto *Arg = dyn_cast<Argument>(Val); 9557 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9558 Arg->getType()->isEmptyTy() || 9559 DL.getTypeStoreSize(Arg->getType()) != 9560 DL.getTypeAllocSize(AI->getAllocatedType()) || 9561 ArgCopyElisionCandidates.count(Arg)) { 9562 *Info = StaticAllocaInfo::Clobbered; 9563 continue; 9564 } 9565 9566 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9567 << '\n'); 9568 9569 // Mark this alloca and store for argument copy elision. 9570 *Info = StaticAllocaInfo::Elidable; 9571 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9572 9573 // Stop scanning if we've seen all arguments. This will happen early in -O0 9574 // builds, which is useful, because -O0 builds have large entry blocks and 9575 // many allocas. 9576 if (ArgCopyElisionCandidates.size() == NumArgs) 9577 break; 9578 } 9579 } 9580 9581 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9582 /// ArgVal is a load from a suitable fixed stack object. 9583 static void tryToElideArgumentCopy( 9584 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9585 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9586 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9587 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9588 SDValue ArgVal, bool &ArgHasUses) { 9589 // Check if this is a load from a fixed stack object. 9590 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9591 if (!LNode) 9592 return; 9593 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9594 if (!FINode) 9595 return; 9596 9597 // Check that the fixed stack object is the right size and alignment. 9598 // Look at the alignment that the user wrote on the alloca instead of looking 9599 // at the stack object. 9600 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9601 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9602 const AllocaInst *AI = ArgCopyIter->second.first; 9603 int FixedIndex = FINode->getIndex(); 9604 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9605 int OldIndex = AllocaIndex; 9606 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9607 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9608 LLVM_DEBUG( 9609 dbgs() << " argument copy elision failed due to bad fixed stack " 9610 "object size\n"); 9611 return; 9612 } 9613 Align RequiredAlignment = AI->getAlign(); 9614 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9615 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9616 "greater than stack argument alignment (" 9617 << DebugStr(RequiredAlignment) << " vs " 9618 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9619 return; 9620 } 9621 9622 // Perform the elision. Delete the old stack object and replace its only use 9623 // in the variable info map. Mark the stack object as mutable. 9624 LLVM_DEBUG({ 9625 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9626 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9627 << '\n'; 9628 }); 9629 MFI.RemoveStackObject(OldIndex); 9630 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9631 AllocaIndex = FixedIndex; 9632 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9633 Chains.push_back(ArgVal.getValue(1)); 9634 9635 // Avoid emitting code for the store implementing the copy. 9636 const StoreInst *SI = ArgCopyIter->second.second; 9637 ElidedArgCopyInstrs.insert(SI); 9638 9639 // Check for uses of the argument again so that we can avoid exporting ArgVal 9640 // if it is't used by anything other than the store. 9641 for (const Value *U : Arg.users()) { 9642 if (U != SI) { 9643 ArgHasUses = true; 9644 break; 9645 } 9646 } 9647 } 9648 9649 void SelectionDAGISel::LowerArguments(const Function &F) { 9650 SelectionDAG &DAG = SDB->DAG; 9651 SDLoc dl = SDB->getCurSDLoc(); 9652 const DataLayout &DL = DAG.getDataLayout(); 9653 SmallVector<ISD::InputArg, 16> Ins; 9654 9655 // In Naked functions we aren't going to save any registers. 9656 if (F.hasFnAttribute(Attribute::Naked)) 9657 return; 9658 9659 if (!FuncInfo->CanLowerReturn) { 9660 // Put in an sret pointer parameter before all the other parameters. 9661 SmallVector<EVT, 1> ValueVTs; 9662 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9663 F.getReturnType()->getPointerTo( 9664 DAG.getDataLayout().getAllocaAddrSpace()), 9665 ValueVTs); 9666 9667 // NOTE: Assuming that a pointer will never break down to more than one VT 9668 // or one register. 9669 ISD::ArgFlagsTy Flags; 9670 Flags.setSRet(); 9671 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9672 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9673 ISD::InputArg::NoArgIndex, 0); 9674 Ins.push_back(RetArg); 9675 } 9676 9677 // Look for stores of arguments to static allocas. Mark such arguments with a 9678 // flag to ask the target to give us the memory location of that argument if 9679 // available. 9680 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9681 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9682 ArgCopyElisionCandidates); 9683 9684 // Set up the incoming argument description vector. 9685 for (const Argument &Arg : F.args()) { 9686 unsigned ArgNo = Arg.getArgNo(); 9687 SmallVector<EVT, 4> ValueVTs; 9688 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9689 bool isArgValueUsed = !Arg.use_empty(); 9690 unsigned PartBase = 0; 9691 Type *FinalType = Arg.getType(); 9692 if (Arg.hasAttribute(Attribute::ByVal)) 9693 FinalType = Arg.getParamByValType(); 9694 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9695 FinalType, F.getCallingConv(), F.isVarArg()); 9696 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9697 Value != NumValues; ++Value) { 9698 EVT VT = ValueVTs[Value]; 9699 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9700 ISD::ArgFlagsTy Flags; 9701 9702 // Certain targets (such as MIPS), may have a different ABI alignment 9703 // for a type depending on the context. Give the target a chance to 9704 // specify the alignment it wants. 9705 const Align OriginalAlignment( 9706 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9707 9708 if (Arg.getType()->isPointerTy()) { 9709 Flags.setPointer(); 9710 Flags.setPointerAddrSpace( 9711 cast<PointerType>(Arg.getType())->getAddressSpace()); 9712 } 9713 if (Arg.hasAttribute(Attribute::ZExt)) 9714 Flags.setZExt(); 9715 if (Arg.hasAttribute(Attribute::SExt)) 9716 Flags.setSExt(); 9717 if (Arg.hasAttribute(Attribute::InReg)) { 9718 // If we are using vectorcall calling convention, a structure that is 9719 // passed InReg - is surely an HVA 9720 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9721 isa<StructType>(Arg.getType())) { 9722 // The first value of a structure is marked 9723 if (0 == Value) 9724 Flags.setHvaStart(); 9725 Flags.setHva(); 9726 } 9727 // Set InReg Flag 9728 Flags.setInReg(); 9729 } 9730 if (Arg.hasAttribute(Attribute::StructRet)) 9731 Flags.setSRet(); 9732 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9733 Flags.setSwiftSelf(); 9734 if (Arg.hasAttribute(Attribute::SwiftError)) 9735 Flags.setSwiftError(); 9736 if (Arg.hasAttribute(Attribute::ByVal)) 9737 Flags.setByVal(); 9738 if (Arg.hasAttribute(Attribute::ByRef)) 9739 Flags.setByRef(); 9740 if (Arg.hasAttribute(Attribute::InAlloca)) { 9741 Flags.setInAlloca(); 9742 // Set the byval flag for CCAssignFn callbacks that don't know about 9743 // inalloca. This way we can know how many bytes we should've allocated 9744 // and how many bytes a callee cleanup function will pop. If we port 9745 // inalloca to more targets, we'll have to add custom inalloca handling 9746 // in the various CC lowering callbacks. 9747 Flags.setByVal(); 9748 } 9749 if (Arg.hasAttribute(Attribute::Preallocated)) { 9750 Flags.setPreallocated(); 9751 // Set the byval flag for CCAssignFn callbacks that don't know about 9752 // preallocated. This way we can know how many bytes we should've 9753 // allocated and how many bytes a callee cleanup function will pop. If 9754 // we port preallocated to more targets, we'll have to add custom 9755 // preallocated handling in the various CC lowering callbacks. 9756 Flags.setByVal(); 9757 } 9758 9759 Type *ArgMemTy = nullptr; 9760 if (F.getCallingConv() == CallingConv::X86_INTR) { 9761 // IA Interrupt passes frame (1st parameter) by value in the stack. 9762 if (ArgNo == 0) { 9763 Flags.setByVal(); 9764 // FIXME: Dependence on pointee element type. See bug 46672. 9765 ArgMemTy = Arg.getType()->getPointerElementType(); 9766 } 9767 } 9768 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 9769 Flags.isByRef()) { 9770 if (!ArgMemTy) 9771 ArgMemTy = Arg.getPointeeInMemoryValueType(); 9772 9773 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 9774 9775 // For in-memory arguments, size and alignment should be passed from FE. 9776 // BE will guess if this info is not there but there are cases it cannot 9777 // get right. 9778 MaybeAlign MemAlign = Arg.getParamAlign(); 9779 if (!MemAlign) 9780 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 9781 9782 if (Flags.isByRef()) { 9783 Flags.setByRefSize(MemSize); 9784 Flags.setByRefAlign(*MemAlign); 9785 } else { 9786 Flags.setByValSize(MemSize); 9787 Flags.setByValAlign(*MemAlign); 9788 } 9789 } 9790 9791 if (Arg.hasAttribute(Attribute::Nest)) 9792 Flags.setNest(); 9793 if (NeedsRegBlock) 9794 Flags.setInConsecutiveRegs(); 9795 Flags.setOrigAlign(OriginalAlignment); 9796 if (ArgCopyElisionCandidates.count(&Arg)) 9797 Flags.setCopyElisionCandidate(); 9798 if (Arg.hasAttribute(Attribute::Returned)) 9799 Flags.setReturned(); 9800 9801 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9802 *CurDAG->getContext(), F.getCallingConv(), VT); 9803 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9804 *CurDAG->getContext(), F.getCallingConv(), VT); 9805 for (unsigned i = 0; i != NumRegs; ++i) { 9806 // For scalable vectors, use the minimum size; individual targets 9807 // are responsible for handling scalable vector arguments and 9808 // return values. 9809 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9810 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9811 if (NumRegs > 1 && i == 0) 9812 MyFlags.Flags.setSplit(); 9813 // if it isn't first piece, alignment must be 1 9814 else if (i > 0) { 9815 MyFlags.Flags.setOrigAlign(Align(1)); 9816 if (i == NumRegs - 1) 9817 MyFlags.Flags.setSplitEnd(); 9818 } 9819 Ins.push_back(MyFlags); 9820 } 9821 if (NeedsRegBlock && Value == NumValues - 1) 9822 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9823 PartBase += VT.getStoreSize().getKnownMinSize(); 9824 } 9825 } 9826 9827 // Call the target to set up the argument values. 9828 SmallVector<SDValue, 8> InVals; 9829 SDValue NewRoot = TLI->LowerFormalArguments( 9830 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9831 9832 // Verify that the target's LowerFormalArguments behaved as expected. 9833 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9834 "LowerFormalArguments didn't return a valid chain!"); 9835 assert(InVals.size() == Ins.size() && 9836 "LowerFormalArguments didn't emit the correct number of values!"); 9837 LLVM_DEBUG({ 9838 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9839 assert(InVals[i].getNode() && 9840 "LowerFormalArguments emitted a null value!"); 9841 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9842 "LowerFormalArguments emitted a value with the wrong type!"); 9843 } 9844 }); 9845 9846 // Update the DAG with the new chain value resulting from argument lowering. 9847 DAG.setRoot(NewRoot); 9848 9849 // Set up the argument values. 9850 unsigned i = 0; 9851 if (!FuncInfo->CanLowerReturn) { 9852 // Create a virtual register for the sret pointer, and put in a copy 9853 // from the sret argument into it. 9854 SmallVector<EVT, 1> ValueVTs; 9855 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9856 F.getReturnType()->getPointerTo( 9857 DAG.getDataLayout().getAllocaAddrSpace()), 9858 ValueVTs); 9859 MVT VT = ValueVTs[0].getSimpleVT(); 9860 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9861 Optional<ISD::NodeType> AssertOp = None; 9862 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9863 nullptr, F.getCallingConv(), AssertOp); 9864 9865 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9866 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9867 Register SRetReg = 9868 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9869 FuncInfo->DemoteRegister = SRetReg; 9870 NewRoot = 9871 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9872 DAG.setRoot(NewRoot); 9873 9874 // i indexes lowered arguments. Bump it past the hidden sret argument. 9875 ++i; 9876 } 9877 9878 SmallVector<SDValue, 4> Chains; 9879 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9880 for (const Argument &Arg : F.args()) { 9881 SmallVector<SDValue, 4> ArgValues; 9882 SmallVector<EVT, 4> ValueVTs; 9883 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9884 unsigned NumValues = ValueVTs.size(); 9885 if (NumValues == 0) 9886 continue; 9887 9888 bool ArgHasUses = !Arg.use_empty(); 9889 9890 // Elide the copying store if the target loaded this argument from a 9891 // suitable fixed stack object. 9892 if (Ins[i].Flags.isCopyElisionCandidate()) { 9893 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9894 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9895 InVals[i], ArgHasUses); 9896 } 9897 9898 // If this argument is unused then remember its value. It is used to generate 9899 // debugging information. 9900 bool isSwiftErrorArg = 9901 TLI->supportSwiftError() && 9902 Arg.hasAttribute(Attribute::SwiftError); 9903 if (!ArgHasUses && !isSwiftErrorArg) { 9904 SDB->setUnusedArgValue(&Arg, InVals[i]); 9905 9906 // Also remember any frame index for use in FastISel. 9907 if (FrameIndexSDNode *FI = 9908 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9909 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9910 } 9911 9912 for (unsigned Val = 0; Val != NumValues; ++Val) { 9913 EVT VT = ValueVTs[Val]; 9914 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9915 F.getCallingConv(), VT); 9916 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9917 *CurDAG->getContext(), F.getCallingConv(), VT); 9918 9919 // Even an apparent 'unused' swifterror argument needs to be returned. So 9920 // we do generate a copy for it that can be used on return from the 9921 // function. 9922 if (ArgHasUses || isSwiftErrorArg) { 9923 Optional<ISD::NodeType> AssertOp; 9924 if (Arg.hasAttribute(Attribute::SExt)) 9925 AssertOp = ISD::AssertSext; 9926 else if (Arg.hasAttribute(Attribute::ZExt)) 9927 AssertOp = ISD::AssertZext; 9928 9929 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9930 PartVT, VT, nullptr, 9931 F.getCallingConv(), AssertOp)); 9932 } 9933 9934 i += NumParts; 9935 } 9936 9937 // We don't need to do anything else for unused arguments. 9938 if (ArgValues.empty()) 9939 continue; 9940 9941 // Note down frame index. 9942 if (FrameIndexSDNode *FI = 9943 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9944 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9945 9946 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9947 SDB->getCurSDLoc()); 9948 9949 SDB->setValue(&Arg, Res); 9950 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9951 // We want to associate the argument with the frame index, among 9952 // involved operands, that correspond to the lowest address. The 9953 // getCopyFromParts function, called earlier, is swapping the order of 9954 // the operands to BUILD_PAIR depending on endianness. The result of 9955 // that swapping is that the least significant bits of the argument will 9956 // be in the first operand of the BUILD_PAIR node, and the most 9957 // significant bits will be in the second operand. 9958 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9959 if (LoadSDNode *LNode = 9960 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9961 if (FrameIndexSDNode *FI = 9962 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9963 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9964 } 9965 9966 // Analyses past this point are naive and don't expect an assertion. 9967 if (Res.getOpcode() == ISD::AssertZext) 9968 Res = Res.getOperand(0); 9969 9970 // Update the SwiftErrorVRegDefMap. 9971 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9972 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9973 if (Register::isVirtualRegister(Reg)) 9974 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9975 Reg); 9976 } 9977 9978 // If this argument is live outside of the entry block, insert a copy from 9979 // wherever we got it to the vreg that other BB's will reference it as. 9980 if (Res.getOpcode() == ISD::CopyFromReg) { 9981 // If we can, though, try to skip creating an unnecessary vreg. 9982 // FIXME: This isn't very clean... it would be nice to make this more 9983 // general. 9984 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9985 if (Register::isVirtualRegister(Reg)) { 9986 FuncInfo->ValueMap[&Arg] = Reg; 9987 continue; 9988 } 9989 } 9990 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9991 FuncInfo->InitializeRegForValue(&Arg); 9992 SDB->CopyToExportRegsIfNeeded(&Arg); 9993 } 9994 } 9995 9996 if (!Chains.empty()) { 9997 Chains.push_back(NewRoot); 9998 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9999 } 10000 10001 DAG.setRoot(NewRoot); 10002 10003 assert(i == InVals.size() && "Argument register count mismatch!"); 10004 10005 // If any argument copy elisions occurred and we have debug info, update the 10006 // stale frame indices used in the dbg.declare variable info table. 10007 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10008 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10009 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10010 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10011 if (I != ArgCopyElisionFrameIndexMap.end()) 10012 VI.Slot = I->second; 10013 } 10014 } 10015 10016 // Finally, if the target has anything special to do, allow it to do so. 10017 emitFunctionEntryCode(); 10018 } 10019 10020 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10021 /// ensure constants are generated when needed. Remember the virtual registers 10022 /// that need to be added to the Machine PHI nodes as input. We cannot just 10023 /// directly add them, because expansion might result in multiple MBB's for one 10024 /// BB. As such, the start of the BB might correspond to a different MBB than 10025 /// the end. 10026 void 10027 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10028 const Instruction *TI = LLVMBB->getTerminator(); 10029 10030 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10031 10032 // Check PHI nodes in successors that expect a value to be available from this 10033 // block. 10034 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10035 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10036 if (!isa<PHINode>(SuccBB->begin())) continue; 10037 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10038 10039 // If this terminator has multiple identical successors (common for 10040 // switches), only handle each succ once. 10041 if (!SuccsHandled.insert(SuccMBB).second) 10042 continue; 10043 10044 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10045 10046 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10047 // nodes and Machine PHI nodes, but the incoming operands have not been 10048 // emitted yet. 10049 for (const PHINode &PN : SuccBB->phis()) { 10050 // Ignore dead phi's. 10051 if (PN.use_empty()) 10052 continue; 10053 10054 // Skip empty types 10055 if (PN.getType()->isEmptyTy()) 10056 continue; 10057 10058 unsigned Reg; 10059 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10060 10061 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10062 unsigned &RegOut = ConstantsOut[C]; 10063 if (RegOut == 0) { 10064 RegOut = FuncInfo.CreateRegs(C); 10065 CopyValueToVirtualRegister(C, RegOut); 10066 } 10067 Reg = RegOut; 10068 } else { 10069 DenseMap<const Value *, Register>::iterator I = 10070 FuncInfo.ValueMap.find(PHIOp); 10071 if (I != FuncInfo.ValueMap.end()) 10072 Reg = I->second; 10073 else { 10074 assert(isa<AllocaInst>(PHIOp) && 10075 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10076 "Didn't codegen value into a register!??"); 10077 Reg = FuncInfo.CreateRegs(PHIOp); 10078 CopyValueToVirtualRegister(PHIOp, Reg); 10079 } 10080 } 10081 10082 // Remember that this register needs to added to the machine PHI node as 10083 // the input for this MBB. 10084 SmallVector<EVT, 4> ValueVTs; 10085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10086 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10087 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10088 EVT VT = ValueVTs[vti]; 10089 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10090 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10091 FuncInfo.PHINodesToUpdate.push_back( 10092 std::make_pair(&*MBBI++, Reg + i)); 10093 Reg += NumRegisters; 10094 } 10095 } 10096 } 10097 10098 ConstantsOut.clear(); 10099 } 10100 10101 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10102 /// is 0. 10103 MachineBasicBlock * 10104 SelectionDAGBuilder::StackProtectorDescriptor:: 10105 AddSuccessorMBB(const BasicBlock *BB, 10106 MachineBasicBlock *ParentMBB, 10107 bool IsLikely, 10108 MachineBasicBlock *SuccMBB) { 10109 // If SuccBB has not been created yet, create it. 10110 if (!SuccMBB) { 10111 MachineFunction *MF = ParentMBB->getParent(); 10112 MachineFunction::iterator BBI(ParentMBB); 10113 SuccMBB = MF->CreateMachineBasicBlock(BB); 10114 MF->insert(++BBI, SuccMBB); 10115 } 10116 // Add it as a successor of ParentMBB. 10117 ParentMBB->addSuccessor( 10118 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10119 return SuccMBB; 10120 } 10121 10122 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10123 MachineFunction::iterator I(MBB); 10124 if (++I == FuncInfo.MF->end()) 10125 return nullptr; 10126 return &*I; 10127 } 10128 10129 /// During lowering new call nodes can be created (such as memset, etc.). 10130 /// Those will become new roots of the current DAG, but complications arise 10131 /// when they are tail calls. In such cases, the call lowering will update 10132 /// the root, but the builder still needs to know that a tail call has been 10133 /// lowered in order to avoid generating an additional return. 10134 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10135 // If the node is null, we do have a tail call. 10136 if (MaybeTC.getNode() != nullptr) 10137 DAG.setRoot(MaybeTC); 10138 else 10139 HasTailCall = true; 10140 } 10141 10142 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10143 MachineBasicBlock *SwitchMBB, 10144 MachineBasicBlock *DefaultMBB) { 10145 MachineFunction *CurMF = FuncInfo.MF; 10146 MachineBasicBlock *NextMBB = nullptr; 10147 MachineFunction::iterator BBI(W.MBB); 10148 if (++BBI != FuncInfo.MF->end()) 10149 NextMBB = &*BBI; 10150 10151 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10152 10153 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10154 10155 if (Size == 2 && W.MBB == SwitchMBB) { 10156 // If any two of the cases has the same destination, and if one value 10157 // is the same as the other, but has one bit unset that the other has set, 10158 // use bit manipulation to do two compares at once. For example: 10159 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10160 // TODO: This could be extended to merge any 2 cases in switches with 3 10161 // cases. 10162 // TODO: Handle cases where W.CaseBB != SwitchBB. 10163 CaseCluster &Small = *W.FirstCluster; 10164 CaseCluster &Big = *W.LastCluster; 10165 10166 if (Small.Low == Small.High && Big.Low == Big.High && 10167 Small.MBB == Big.MBB) { 10168 const APInt &SmallValue = Small.Low->getValue(); 10169 const APInt &BigValue = Big.Low->getValue(); 10170 10171 // Check that there is only one bit different. 10172 APInt CommonBit = BigValue ^ SmallValue; 10173 if (CommonBit.isPowerOf2()) { 10174 SDValue CondLHS = getValue(Cond); 10175 EVT VT = CondLHS.getValueType(); 10176 SDLoc DL = getCurSDLoc(); 10177 10178 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10179 DAG.getConstant(CommonBit, DL, VT)); 10180 SDValue Cond = DAG.getSetCC( 10181 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10182 ISD::SETEQ); 10183 10184 // Update successor info. 10185 // Both Small and Big will jump to Small.BB, so we sum up the 10186 // probabilities. 10187 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10188 if (BPI) 10189 addSuccessorWithProb( 10190 SwitchMBB, DefaultMBB, 10191 // The default destination is the first successor in IR. 10192 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10193 else 10194 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10195 10196 // Insert the true branch. 10197 SDValue BrCond = 10198 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10199 DAG.getBasicBlock(Small.MBB)); 10200 // Insert the false branch. 10201 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10202 DAG.getBasicBlock(DefaultMBB)); 10203 10204 DAG.setRoot(BrCond); 10205 return; 10206 } 10207 } 10208 } 10209 10210 if (TM.getOptLevel() != CodeGenOpt::None) { 10211 // Here, we order cases by probability so the most likely case will be 10212 // checked first. However, two clusters can have the same probability in 10213 // which case their relative ordering is non-deterministic. So we use Low 10214 // as a tie-breaker as clusters are guaranteed to never overlap. 10215 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10216 [](const CaseCluster &a, const CaseCluster &b) { 10217 return a.Prob != b.Prob ? 10218 a.Prob > b.Prob : 10219 a.Low->getValue().slt(b.Low->getValue()); 10220 }); 10221 10222 // Rearrange the case blocks so that the last one falls through if possible 10223 // without changing the order of probabilities. 10224 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10225 --I; 10226 if (I->Prob > W.LastCluster->Prob) 10227 break; 10228 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10229 std::swap(*I, *W.LastCluster); 10230 break; 10231 } 10232 } 10233 } 10234 10235 // Compute total probability. 10236 BranchProbability DefaultProb = W.DefaultProb; 10237 BranchProbability UnhandledProbs = DefaultProb; 10238 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10239 UnhandledProbs += I->Prob; 10240 10241 MachineBasicBlock *CurMBB = W.MBB; 10242 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10243 bool FallthroughUnreachable = false; 10244 MachineBasicBlock *Fallthrough; 10245 if (I == W.LastCluster) { 10246 // For the last cluster, fall through to the default destination. 10247 Fallthrough = DefaultMBB; 10248 FallthroughUnreachable = isa<UnreachableInst>( 10249 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10250 } else { 10251 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10252 CurMF->insert(BBI, Fallthrough); 10253 // Put Cond in a virtual register to make it available from the new blocks. 10254 ExportFromCurrentBlock(Cond); 10255 } 10256 UnhandledProbs -= I->Prob; 10257 10258 switch (I->Kind) { 10259 case CC_JumpTable: { 10260 // FIXME: Optimize away range check based on pivot comparisons. 10261 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10262 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10263 10264 // The jump block hasn't been inserted yet; insert it here. 10265 MachineBasicBlock *JumpMBB = JT->MBB; 10266 CurMF->insert(BBI, JumpMBB); 10267 10268 auto JumpProb = I->Prob; 10269 auto FallthroughProb = UnhandledProbs; 10270 10271 // If the default statement is a target of the jump table, we evenly 10272 // distribute the default probability to successors of CurMBB. Also 10273 // update the probability on the edge from JumpMBB to Fallthrough. 10274 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10275 SE = JumpMBB->succ_end(); 10276 SI != SE; ++SI) { 10277 if (*SI == DefaultMBB) { 10278 JumpProb += DefaultProb / 2; 10279 FallthroughProb -= DefaultProb / 2; 10280 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10281 JumpMBB->normalizeSuccProbs(); 10282 break; 10283 } 10284 } 10285 10286 if (FallthroughUnreachable) { 10287 // Skip the range check if the fallthrough block is unreachable. 10288 JTH->OmitRangeCheck = true; 10289 } 10290 10291 if (!JTH->OmitRangeCheck) 10292 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10293 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10294 CurMBB->normalizeSuccProbs(); 10295 10296 // The jump table header will be inserted in our current block, do the 10297 // range check, and fall through to our fallthrough block. 10298 JTH->HeaderBB = CurMBB; 10299 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10300 10301 // If we're in the right place, emit the jump table header right now. 10302 if (CurMBB == SwitchMBB) { 10303 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10304 JTH->Emitted = true; 10305 } 10306 break; 10307 } 10308 case CC_BitTests: { 10309 // FIXME: Optimize away range check based on pivot comparisons. 10310 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10311 10312 // The bit test blocks haven't been inserted yet; insert them here. 10313 for (BitTestCase &BTC : BTB->Cases) 10314 CurMF->insert(BBI, BTC.ThisBB); 10315 10316 // Fill in fields of the BitTestBlock. 10317 BTB->Parent = CurMBB; 10318 BTB->Default = Fallthrough; 10319 10320 BTB->DefaultProb = UnhandledProbs; 10321 // If the cases in bit test don't form a contiguous range, we evenly 10322 // distribute the probability on the edge to Fallthrough to two 10323 // successors of CurMBB. 10324 if (!BTB->ContiguousRange) { 10325 BTB->Prob += DefaultProb / 2; 10326 BTB->DefaultProb -= DefaultProb / 2; 10327 } 10328 10329 if (FallthroughUnreachable) { 10330 // Skip the range check if the fallthrough block is unreachable. 10331 BTB->OmitRangeCheck = true; 10332 } 10333 10334 // If we're in the right place, emit the bit test header right now. 10335 if (CurMBB == SwitchMBB) { 10336 visitBitTestHeader(*BTB, SwitchMBB); 10337 BTB->Emitted = true; 10338 } 10339 break; 10340 } 10341 case CC_Range: { 10342 const Value *RHS, *LHS, *MHS; 10343 ISD::CondCode CC; 10344 if (I->Low == I->High) { 10345 // Check Cond == I->Low. 10346 CC = ISD::SETEQ; 10347 LHS = Cond; 10348 RHS=I->Low; 10349 MHS = nullptr; 10350 } else { 10351 // Check I->Low <= Cond <= I->High. 10352 CC = ISD::SETLE; 10353 LHS = I->Low; 10354 MHS = Cond; 10355 RHS = I->High; 10356 } 10357 10358 // If Fallthrough is unreachable, fold away the comparison. 10359 if (FallthroughUnreachable) 10360 CC = ISD::SETTRUE; 10361 10362 // The false probability is the sum of all unhandled cases. 10363 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10364 getCurSDLoc(), I->Prob, UnhandledProbs); 10365 10366 if (CurMBB == SwitchMBB) 10367 visitSwitchCase(CB, SwitchMBB); 10368 else 10369 SL->SwitchCases.push_back(CB); 10370 10371 break; 10372 } 10373 } 10374 CurMBB = Fallthrough; 10375 } 10376 } 10377 10378 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10379 CaseClusterIt First, 10380 CaseClusterIt Last) { 10381 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10382 if (X.Prob != CC.Prob) 10383 return X.Prob > CC.Prob; 10384 10385 // Ties are broken by comparing the case value. 10386 return X.Low->getValue().slt(CC.Low->getValue()); 10387 }); 10388 } 10389 10390 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10391 const SwitchWorkListItem &W, 10392 Value *Cond, 10393 MachineBasicBlock *SwitchMBB) { 10394 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10395 "Clusters not sorted?"); 10396 10397 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10398 10399 // Balance the tree based on branch probabilities to create a near-optimal (in 10400 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10401 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10402 CaseClusterIt LastLeft = W.FirstCluster; 10403 CaseClusterIt FirstRight = W.LastCluster; 10404 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10405 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10406 10407 // Move LastLeft and FirstRight towards each other from opposite directions to 10408 // find a partitioning of the clusters which balances the probability on both 10409 // sides. If LeftProb and RightProb are equal, alternate which side is 10410 // taken to ensure 0-probability nodes are distributed evenly. 10411 unsigned I = 0; 10412 while (LastLeft + 1 < FirstRight) { 10413 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10414 LeftProb += (++LastLeft)->Prob; 10415 else 10416 RightProb += (--FirstRight)->Prob; 10417 I++; 10418 } 10419 10420 while (true) { 10421 // Our binary search tree differs from a typical BST in that ours can have up 10422 // to three values in each leaf. The pivot selection above doesn't take that 10423 // into account, which means the tree might require more nodes and be less 10424 // efficient. We compensate for this here. 10425 10426 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10427 unsigned NumRight = W.LastCluster - FirstRight + 1; 10428 10429 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10430 // If one side has less than 3 clusters, and the other has more than 3, 10431 // consider taking a cluster from the other side. 10432 10433 if (NumLeft < NumRight) { 10434 // Consider moving the first cluster on the right to the left side. 10435 CaseCluster &CC = *FirstRight; 10436 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10437 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10438 if (LeftSideRank <= RightSideRank) { 10439 // Moving the cluster to the left does not demote it. 10440 ++LastLeft; 10441 ++FirstRight; 10442 continue; 10443 } 10444 } else { 10445 assert(NumRight < NumLeft); 10446 // Consider moving the last element on the left to the right side. 10447 CaseCluster &CC = *LastLeft; 10448 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10449 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10450 if (RightSideRank <= LeftSideRank) { 10451 // Moving the cluster to the right does not demot it. 10452 --LastLeft; 10453 --FirstRight; 10454 continue; 10455 } 10456 } 10457 } 10458 break; 10459 } 10460 10461 assert(LastLeft + 1 == FirstRight); 10462 assert(LastLeft >= W.FirstCluster); 10463 assert(FirstRight <= W.LastCluster); 10464 10465 // Use the first element on the right as pivot since we will make less-than 10466 // comparisons against it. 10467 CaseClusterIt PivotCluster = FirstRight; 10468 assert(PivotCluster > W.FirstCluster); 10469 assert(PivotCluster <= W.LastCluster); 10470 10471 CaseClusterIt FirstLeft = W.FirstCluster; 10472 CaseClusterIt LastRight = W.LastCluster; 10473 10474 const ConstantInt *Pivot = PivotCluster->Low; 10475 10476 // New blocks will be inserted immediately after the current one. 10477 MachineFunction::iterator BBI(W.MBB); 10478 ++BBI; 10479 10480 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10481 // we can branch to its destination directly if it's squeezed exactly in 10482 // between the known lower bound and Pivot - 1. 10483 MachineBasicBlock *LeftMBB; 10484 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10485 FirstLeft->Low == W.GE && 10486 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10487 LeftMBB = FirstLeft->MBB; 10488 } else { 10489 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10490 FuncInfo.MF->insert(BBI, LeftMBB); 10491 WorkList.push_back( 10492 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10493 // Put Cond in a virtual register to make it available from the new blocks. 10494 ExportFromCurrentBlock(Cond); 10495 } 10496 10497 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10498 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10499 // directly if RHS.High equals the current upper bound. 10500 MachineBasicBlock *RightMBB; 10501 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10502 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10503 RightMBB = FirstRight->MBB; 10504 } else { 10505 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10506 FuncInfo.MF->insert(BBI, RightMBB); 10507 WorkList.push_back( 10508 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10509 // Put Cond in a virtual register to make it available from the new blocks. 10510 ExportFromCurrentBlock(Cond); 10511 } 10512 10513 // Create the CaseBlock record that will be used to lower the branch. 10514 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10515 getCurSDLoc(), LeftProb, RightProb); 10516 10517 if (W.MBB == SwitchMBB) 10518 visitSwitchCase(CB, SwitchMBB); 10519 else 10520 SL->SwitchCases.push_back(CB); 10521 } 10522 10523 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10524 // from the swith statement. 10525 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10526 BranchProbability PeeledCaseProb) { 10527 if (PeeledCaseProb == BranchProbability::getOne()) 10528 return BranchProbability::getZero(); 10529 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10530 10531 uint32_t Numerator = CaseProb.getNumerator(); 10532 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10533 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10534 } 10535 10536 // Try to peel the top probability case if it exceeds the threshold. 10537 // Return current MachineBasicBlock for the switch statement if the peeling 10538 // does not occur. 10539 // If the peeling is performed, return the newly created MachineBasicBlock 10540 // for the peeled switch statement. Also update Clusters to remove the peeled 10541 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10542 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10543 const SwitchInst &SI, CaseClusterVector &Clusters, 10544 BranchProbability &PeeledCaseProb) { 10545 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10546 // Don't perform if there is only one cluster or optimizing for size. 10547 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10548 TM.getOptLevel() == CodeGenOpt::None || 10549 SwitchMBB->getParent()->getFunction().hasMinSize()) 10550 return SwitchMBB; 10551 10552 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10553 unsigned PeeledCaseIndex = 0; 10554 bool SwitchPeeled = false; 10555 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10556 CaseCluster &CC = Clusters[Index]; 10557 if (CC.Prob < TopCaseProb) 10558 continue; 10559 TopCaseProb = CC.Prob; 10560 PeeledCaseIndex = Index; 10561 SwitchPeeled = true; 10562 } 10563 if (!SwitchPeeled) 10564 return SwitchMBB; 10565 10566 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10567 << TopCaseProb << "\n"); 10568 10569 // Record the MBB for the peeled switch statement. 10570 MachineFunction::iterator BBI(SwitchMBB); 10571 ++BBI; 10572 MachineBasicBlock *PeeledSwitchMBB = 10573 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10574 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10575 10576 ExportFromCurrentBlock(SI.getCondition()); 10577 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10578 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10579 nullptr, nullptr, TopCaseProb.getCompl()}; 10580 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10581 10582 Clusters.erase(PeeledCaseIt); 10583 for (CaseCluster &CC : Clusters) { 10584 LLVM_DEBUG( 10585 dbgs() << "Scale the probablity for one cluster, before scaling: " 10586 << CC.Prob << "\n"); 10587 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10588 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10589 } 10590 PeeledCaseProb = TopCaseProb; 10591 return PeeledSwitchMBB; 10592 } 10593 10594 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10595 // Extract cases from the switch. 10596 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10597 CaseClusterVector Clusters; 10598 Clusters.reserve(SI.getNumCases()); 10599 for (auto I : SI.cases()) { 10600 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10601 const ConstantInt *CaseVal = I.getCaseValue(); 10602 BranchProbability Prob = 10603 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10604 : BranchProbability(1, SI.getNumCases() + 1); 10605 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10606 } 10607 10608 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10609 10610 // Cluster adjacent cases with the same destination. We do this at all 10611 // optimization levels because it's cheap to do and will make codegen faster 10612 // if there are many clusters. 10613 sortAndRangeify(Clusters); 10614 10615 // The branch probablity of the peeled case. 10616 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10617 MachineBasicBlock *PeeledSwitchMBB = 10618 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10619 10620 // If there is only the default destination, jump there directly. 10621 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10622 if (Clusters.empty()) { 10623 assert(PeeledSwitchMBB == SwitchMBB); 10624 SwitchMBB->addSuccessor(DefaultMBB); 10625 if (DefaultMBB != NextBlock(SwitchMBB)) { 10626 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10627 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10628 } 10629 return; 10630 } 10631 10632 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10633 SL->findBitTestClusters(Clusters, &SI); 10634 10635 LLVM_DEBUG({ 10636 dbgs() << "Case clusters: "; 10637 for (const CaseCluster &C : Clusters) { 10638 if (C.Kind == CC_JumpTable) 10639 dbgs() << "JT:"; 10640 if (C.Kind == CC_BitTests) 10641 dbgs() << "BT:"; 10642 10643 C.Low->getValue().print(dbgs(), true); 10644 if (C.Low != C.High) { 10645 dbgs() << '-'; 10646 C.High->getValue().print(dbgs(), true); 10647 } 10648 dbgs() << ' '; 10649 } 10650 dbgs() << '\n'; 10651 }); 10652 10653 assert(!Clusters.empty()); 10654 SwitchWorkList WorkList; 10655 CaseClusterIt First = Clusters.begin(); 10656 CaseClusterIt Last = Clusters.end() - 1; 10657 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10658 // Scale the branchprobability for DefaultMBB if the peel occurs and 10659 // DefaultMBB is not replaced. 10660 if (PeeledCaseProb != BranchProbability::getZero() && 10661 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10662 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10663 WorkList.push_back( 10664 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10665 10666 while (!WorkList.empty()) { 10667 SwitchWorkListItem W = WorkList.back(); 10668 WorkList.pop_back(); 10669 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10670 10671 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10672 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10673 // For optimized builds, lower large range as a balanced binary tree. 10674 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10675 continue; 10676 } 10677 10678 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10679 } 10680 } 10681 10682 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10683 SmallVector<EVT, 4> ValueVTs; 10684 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10685 ValueVTs); 10686 unsigned NumValues = ValueVTs.size(); 10687 if (NumValues == 0) return; 10688 10689 SmallVector<SDValue, 4> Values(NumValues); 10690 SDValue Op = getValue(I.getOperand(0)); 10691 10692 for (unsigned i = 0; i != NumValues; ++i) 10693 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10694 SDValue(Op.getNode(), Op.getResNo() + i)); 10695 10696 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10697 DAG.getVTList(ValueVTs), Values)); 10698 } 10699