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/AliasAnalysis.h" 27 #include "llvm/Analysis/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/Loads.h" 32 #include "llvm/Analysis/MemoryLocation.h" 33 #include "llvm/Analysis/ProfileSummaryInfo.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/CodeGen/Analysis.h" 38 #include "llvm/CodeGen/FunctionLoweringInfo.h" 39 #include "llvm/CodeGen/GCMetadata.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineJumpTableInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/RuntimeLibcalls.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 53 #include "llvm/CodeGen/StackMaps.h" 54 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 55 #include "llvm/CodeGen/TargetFrameLowering.h" 56 #include "llvm/CodeGen/TargetInstrInfo.h" 57 #include "llvm/CodeGen/TargetOpcodes.h" 58 #include "llvm/CodeGen/TargetRegisterInfo.h" 59 #include "llvm/CodeGen/TargetSubtargetInfo.h" 60 #include "llvm/CodeGen/WinEHFuncInfo.h" 61 #include "llvm/IR/Argument.h" 62 #include "llvm/IR/Attributes.h" 63 #include "llvm/IR/BasicBlock.h" 64 #include "llvm/IR/CFG.h" 65 #include "llvm/IR/CallingConv.h" 66 #include "llvm/IR/Constant.h" 67 #include "llvm/IR/ConstantRange.h" 68 #include "llvm/IR/Constants.h" 69 #include "llvm/IR/DataLayout.h" 70 #include "llvm/IR/DebugInfoMetadata.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/Function.h" 73 #include "llvm/IR/GetElementPtrTypeIterator.h" 74 #include "llvm/IR/InlineAsm.h" 75 #include "llvm/IR/InstrTypes.h" 76 #include "llvm/IR/Instructions.h" 77 #include "llvm/IR/IntrinsicInst.h" 78 #include "llvm/IR/Intrinsics.h" 79 #include "llvm/IR/IntrinsicsAArch64.h" 80 #include "llvm/IR/IntrinsicsWebAssembly.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/Operator.h" 85 #include "llvm/IR/PatternMatch.h" 86 #include "llvm/IR/Statepoint.h" 87 #include "llvm/IR/Type.h" 88 #include "llvm/IR/User.h" 89 #include "llvm/IR/Value.h" 90 #include "llvm/MC/MCContext.h" 91 #include "llvm/MC/MCSymbol.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Casting.h" 94 #include "llvm/Support/CommandLine.h" 95 #include "llvm/Support/Compiler.h" 96 #include "llvm/Support/Debug.h" 97 #include "llvm/Support/MathExtras.h" 98 #include "llvm/Support/raw_ostream.h" 99 #include "llvm/Target/TargetIntrinsicInfo.h" 100 #include "llvm/Target/TargetMachine.h" 101 #include "llvm/Target/TargetOptions.h" 102 #include "llvm/Transforms/Utils/Local.h" 103 #include <cstddef> 104 #include <cstring> 105 #include <iterator> 106 #include <limits> 107 #include <numeric> 108 #include <tuple> 109 110 using namespace llvm; 111 using namespace PatternMatch; 112 using namespace SwitchCG; 113 114 #define DEBUG_TYPE "isel" 115 116 /// LimitFloatPrecision - Generate low-precision inline sequences for 117 /// some float libcalls (6, 8 or 12 bits). 118 static unsigned LimitFloatPrecision; 119 120 static cl::opt<bool> 121 InsertAssertAlign("insert-assert-align", cl::init(true), 122 cl::desc("Insert the experimental `assertalign` node."), 123 cl::ReallyHidden); 124 125 static cl::opt<unsigned, true> 126 LimitFPPrecision("limit-float-precision", 127 cl::desc("Generate low-precision inline sequences " 128 "for some float libcalls"), 129 cl::location(LimitFloatPrecision), cl::Hidden, 130 cl::init(0)); 131 132 static cl::opt<unsigned> SwitchPeelThreshold( 133 "switch-peel-threshold", cl::Hidden, cl::init(66), 134 cl::desc("Set the case probability threshold for peeling the case from a " 135 "switch statement. A value greater than 100 will void this " 136 "optimization")); 137 138 // Limit the width of DAG chains. This is important in general to prevent 139 // DAG-based analysis from blowing up. For example, alias analysis and 140 // load clustering may not complete in reasonable time. It is difficult to 141 // recognize and avoid this situation within each individual analysis, and 142 // future analyses are likely to have the same behavior. Limiting DAG width is 143 // the safe approach and will be especially important with global DAGs. 144 // 145 // MaxParallelChains default is arbitrarily high to avoid affecting 146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 147 // sequence over this should have been converted to llvm.memcpy by the 148 // frontend. It is easy to induce this behavior with .ll code such as: 149 // %buffer = alloca [4096 x i8] 150 // %data = load [4096 x i8]* %argPtr 151 // store [4096 x i8] %data, [4096 x i8]* %buffer 152 static const unsigned MaxParallelChains = 64; 153 154 // Return the calling convention if the Value passed requires ABI mangling as it 155 // is a parameter to a function or a return value from a function which is not 156 // an intrinsic. 157 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 158 if (auto *R = dyn_cast<ReturnInst>(V)) 159 return R->getParent()->getParent()->getCallingConv(); 160 161 if (auto *CI = dyn_cast<CallInst>(V)) { 162 const bool IsInlineAsm = CI->isInlineAsm(); 163 const bool IsIndirectFunctionCall = 164 !IsInlineAsm && !CI->getCalledFunction(); 165 166 // It is possible that the call instruction is an inline asm statement or an 167 // indirect function call in which case the return value of 168 // getCalledFunction() would be nullptr. 169 const bool IsInstrinsicCall = 170 !IsInlineAsm && !IsIndirectFunctionCall && 171 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 172 173 if (!IsInlineAsm && !IsInstrinsicCall) 174 return CI->getCallingConv(); 175 } 176 177 return None; 178 } 179 180 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 181 const SDValue *Parts, unsigned NumParts, 182 MVT PartVT, EVT ValueVT, const Value *V, 183 Optional<CallingConv::ID> CC); 184 185 /// getCopyFromParts - Create a value that contains the specified legal parts 186 /// combined into the value they represent. If the parts combine to a type 187 /// larger than ValueVT then AssertOp can be used to specify whether the extra 188 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 189 /// (ISD::AssertSext). 190 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 191 const SDValue *Parts, unsigned NumParts, 192 MVT PartVT, EVT ValueVT, const Value *V, 193 Optional<CallingConv::ID> CC = None, 194 Optional<ISD::NodeType> AssertOp = None) { 195 // Let the target assemble the parts if it wants to 196 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 197 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 198 PartVT, ValueVT, CC)) 199 return Val; 200 201 if (ValueVT.isVector()) 202 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 203 CC); 204 205 assert(NumParts > 0 && "No parts to assemble!"); 206 SDValue Val = Parts[0]; 207 208 if (NumParts > 1) { 209 // Assemble the value from multiple parts. 210 if (ValueVT.isInteger()) { 211 unsigned PartBits = PartVT.getSizeInBits(); 212 unsigned ValueBits = ValueVT.getSizeInBits(); 213 214 // Assemble the power of 2 part. 215 unsigned RoundParts = 216 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 217 unsigned RoundBits = PartBits * RoundParts; 218 EVT RoundVT = RoundBits == ValueBits ? 219 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 220 SDValue Lo, Hi; 221 222 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 223 224 if (RoundParts > 2) { 225 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 226 PartVT, HalfVT, V); 227 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 228 RoundParts / 2, PartVT, HalfVT, V); 229 } else { 230 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 231 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 232 } 233 234 if (DAG.getDataLayout().isBigEndian()) 235 std::swap(Lo, Hi); 236 237 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 238 239 if (RoundParts < NumParts) { 240 // Assemble the trailing non-power-of-2 part. 241 unsigned OddParts = NumParts - RoundParts; 242 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 243 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 244 OddVT, V, CC); 245 246 // Combine the round and odd parts. 247 Lo = Val; 248 if (DAG.getDataLayout().isBigEndian()) 249 std::swap(Lo, Hi); 250 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 251 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 252 Hi = 253 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 254 DAG.getConstant(Lo.getValueSizeInBits(), DL, 255 TLI.getPointerTy(DAG.getDataLayout()))); 256 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 257 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 258 } 259 } else if (PartVT.isFloatingPoint()) { 260 // FP split into multiple FP parts (for ppcf128) 261 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 262 "Unexpected split"); 263 SDValue Lo, Hi; 264 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 265 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 266 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 267 std::swap(Lo, Hi); 268 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 269 } else { 270 // FP split into integer parts (soft fp) 271 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 272 !PartVT.isVector() && "Unexpected split"); 273 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 274 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 275 } 276 } 277 278 // There is now one part, held in Val. Correct it to match ValueVT. 279 // PartEVT is the type of the register class that holds the value. 280 // ValueVT is the type of the inline asm operation. 281 EVT PartEVT = Val.getValueType(); 282 283 if (PartEVT == ValueVT) 284 return Val; 285 286 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 287 ValueVT.bitsLT(PartEVT)) { 288 // For an FP value in an integer part, we need to truncate to the right 289 // width first. 290 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 291 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 292 } 293 294 // Handle types that have the same size. 295 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 296 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 297 298 // Handle types with different sizes. 299 if (PartEVT.isInteger() && ValueVT.isInteger()) { 300 if (ValueVT.bitsLT(PartEVT)) { 301 // For a truncate, see if we have any information to 302 // indicate whether the truncated bits will always be 303 // zero or sign-extension. 304 if (AssertOp.hasValue()) 305 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 306 DAG.getValueType(ValueVT)); 307 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 308 } 309 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 310 } 311 312 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 313 // FP_ROUND's are always exact here. 314 if (ValueVT.bitsLT(Val.getValueType())) 315 return DAG.getNode( 316 ISD::FP_ROUND, DL, ValueVT, Val, 317 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 318 319 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 320 } 321 322 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 323 // then truncating. 324 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 325 ValueVT.bitsLT(PartEVT)) { 326 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 327 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 328 } 329 330 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 331 } 332 333 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 334 const Twine &ErrMsg) { 335 const Instruction *I = dyn_cast_or_null<Instruction>(V); 336 if (!V) 337 return Ctx.emitError(ErrMsg); 338 339 const char *AsmError = ", possible invalid constraint for vector type"; 340 if (const CallInst *CI = dyn_cast<CallInst>(I)) 341 if (CI->isInlineAsm()) 342 return Ctx.emitError(I, ErrMsg + AsmError); 343 344 return Ctx.emitError(I, ErrMsg); 345 } 346 347 /// getCopyFromPartsVector - Create a value that contains the specified legal 348 /// parts combined into the value they represent. If the parts combine to a 349 /// type larger than ValueVT then AssertOp can be used to specify whether the 350 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 351 /// ValueVT (ISD::AssertSext). 352 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 353 const SDValue *Parts, unsigned NumParts, 354 MVT PartVT, EVT ValueVT, const Value *V, 355 Optional<CallingConv::ID> CallConv) { 356 assert(ValueVT.isVector() && "Not a vector value"); 357 assert(NumParts > 0 && "No parts to assemble!"); 358 const bool IsABIRegCopy = CallConv.hasValue(); 359 360 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 361 SDValue Val = Parts[0]; 362 363 // Handle a multi-element vector. 364 if (NumParts > 1) { 365 EVT IntermediateVT; 366 MVT RegisterVT; 367 unsigned NumIntermediates; 368 unsigned NumRegs; 369 370 if (IsABIRegCopy) { 371 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 372 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 373 NumIntermediates, RegisterVT); 374 } else { 375 NumRegs = 376 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 377 NumIntermediates, RegisterVT); 378 } 379 380 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 381 NumParts = NumRegs; // Silence a compiler warning. 382 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 383 assert(RegisterVT.getSizeInBits() == 384 Parts[0].getSimpleValueType().getSizeInBits() && 385 "Part type sizes don't match!"); 386 387 // Assemble the parts into intermediate operands. 388 SmallVector<SDValue, 8> Ops(NumIntermediates); 389 if (NumIntermediates == NumParts) { 390 // If the register was not expanded, truncate or copy the value, 391 // as appropriate. 392 for (unsigned i = 0; i != NumParts; ++i) 393 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 394 PartVT, IntermediateVT, V, CallConv); 395 } else if (NumParts > 0) { 396 // If the intermediate type was expanded, build the intermediate 397 // operands from the parts. 398 assert(NumParts % NumIntermediates == 0 && 399 "Must expand into a divisible number of parts!"); 400 unsigned Factor = NumParts / NumIntermediates; 401 for (unsigned i = 0; i != NumIntermediates; ++i) 402 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 403 PartVT, IntermediateVT, V, CallConv); 404 } 405 406 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 407 // intermediate operands. 408 EVT BuiltVectorTy = 409 IntermediateVT.isVector() 410 ? EVT::getVectorVT( 411 *DAG.getContext(), IntermediateVT.getScalarType(), 412 IntermediateVT.getVectorElementCount() * NumParts) 413 : EVT::getVectorVT(*DAG.getContext(), 414 IntermediateVT.getScalarType(), 415 NumIntermediates); 416 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 417 : ISD::BUILD_VECTOR, 418 DL, BuiltVectorTy, Ops); 419 } 420 421 // There is now one part, held in Val. Correct it to match ValueVT. 422 EVT PartEVT = Val.getValueType(); 423 424 if (PartEVT == ValueVT) 425 return Val; 426 427 if (PartEVT.isVector()) { 428 // If the element type of the source/dest vectors are the same, but the 429 // parts vector has more elements than the value vector, then we have a 430 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 431 // elements we want. 432 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 433 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 434 ValueVT.getVectorElementCount().getKnownMinValue()) && 435 (PartEVT.getVectorElementCount().isScalable() == 436 ValueVT.getVectorElementCount().isScalable()) && 437 "Cannot narrow, it would be a lossy transformation"); 438 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 439 DAG.getVectorIdxConstant(0, DL)); 440 } 441 442 // Vector/Vector bitcast. 443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 445 446 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 447 "Cannot handle this kind of promotion"); 448 // Promoted vector extract 449 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 450 451 } 452 453 // Trivial bitcast if the types are the same size and the destination 454 // vector type is legal. 455 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 456 TLI.isTypeLegal(ValueVT)) 457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 458 459 if (ValueVT.getVectorNumElements() != 1) { 460 // Certain ABIs require that vectors are passed as integers. For vectors 461 // are the same size, this is an obvious bitcast. 462 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 464 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 465 // Bitcast Val back the original type and extract the corresponding 466 // vector we want. 467 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 468 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 469 ValueVT.getVectorElementType(), Elts); 470 Val = DAG.getBitcast(WiderVecType, Val); 471 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 472 DAG.getVectorIdxConstant(0, DL)); 473 } 474 475 diagnosePossiblyInvalidConstraint( 476 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 477 return DAG.getUNDEF(ValueVT); 478 } 479 480 // Handle cases such as i8 -> <1 x i1> 481 EVT ValueSVT = ValueVT.getVectorElementType(); 482 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 483 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 484 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 485 else 486 Val = ValueVT.isFloatingPoint() 487 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 488 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 489 } 490 491 return DAG.getBuildVector(ValueVT, DL, Val); 492 } 493 494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 495 SDValue Val, SDValue *Parts, unsigned NumParts, 496 MVT PartVT, const Value *V, 497 Optional<CallingConv::ID> CallConv); 498 499 /// getCopyToParts - Create a series of nodes that contain the specified value 500 /// split into legal parts. If the parts contain more bits than Val, then, for 501 /// integers, ExtendKind can be used to specify how to generate the extra bits. 502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 503 SDValue *Parts, unsigned NumParts, MVT PartVT, 504 const Value *V, 505 Optional<CallingConv::ID> CallConv = None, 506 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 507 // Let the target split the parts if it wants to 508 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 509 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 510 CallConv)) 511 return; 512 EVT ValueVT = Val.getValueType(); 513 514 // Handle the vector case separately. 515 if (ValueVT.isVector()) 516 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 517 CallConv); 518 519 unsigned PartBits = PartVT.getSizeInBits(); 520 unsigned OrigNumParts = NumParts; 521 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 522 "Copying to an illegal type!"); 523 524 if (NumParts == 0) 525 return; 526 527 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 528 EVT PartEVT = PartVT; 529 if (PartEVT == ValueVT) { 530 assert(NumParts == 1 && "No-op copy with multiple parts!"); 531 Parts[0] = Val; 532 return; 533 } 534 535 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 536 // If the parts cover more bits than the value has, promote the value. 537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 538 assert(NumParts == 1 && "Do not know what to promote to!"); 539 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 540 } else { 541 if (ValueVT.isFloatingPoint()) { 542 // FP values need to be bitcast, then extended if they are being put 543 // into a larger container. 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 545 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 546 } 547 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 548 ValueVT.isInteger() && 549 "Unknown mismatch!"); 550 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 551 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 552 if (PartVT == MVT::x86mmx) 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 } else if (PartBits == ValueVT.getSizeInBits()) { 556 // Different types of the same size. 557 assert(NumParts == 1 && PartEVT != ValueVT); 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 560 // If the parts cover less bits than value has, truncate the value. 561 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 562 ValueVT.isInteger() && 563 "Unknown mismatch!"); 564 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 565 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 566 if (PartVT == MVT::x86mmx) 567 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 568 } 569 570 // The value may have changed - recompute ValueVT. 571 ValueVT = Val.getValueType(); 572 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 573 "Failed to tile the value with PartVT!"); 574 575 if (NumParts == 1) { 576 if (PartEVT != ValueVT) { 577 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 578 "scalar-to-vector conversion failed"); 579 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 580 } 581 582 Parts[0] = Val; 583 return; 584 } 585 586 // Expand the value into multiple parts. 587 if (NumParts & (NumParts - 1)) { 588 // The number of parts is not a power of 2. Split off and copy the tail. 589 assert(PartVT.isInteger() && ValueVT.isInteger() && 590 "Do not know what to expand to!"); 591 unsigned RoundParts = 1 << Log2_32(NumParts); 592 unsigned RoundBits = RoundParts * PartBits; 593 unsigned OddParts = NumParts - RoundParts; 594 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 595 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 596 597 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 598 CallConv); 599 600 if (DAG.getDataLayout().isBigEndian()) 601 // The odd parts were reversed by getCopyToParts - unreverse them. 602 std::reverse(Parts + RoundParts, Parts + NumParts); 603 604 NumParts = RoundParts; 605 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 606 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 607 } 608 609 // The number of parts is a power of 2. Repeatedly bisect the value using 610 // EXTRACT_ELEMENT. 611 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 612 EVT::getIntegerVT(*DAG.getContext(), 613 ValueVT.getSizeInBits()), 614 Val); 615 616 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 617 for (unsigned i = 0; i < NumParts; i += StepSize) { 618 unsigned ThisBits = StepSize * PartBits / 2; 619 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 620 SDValue &Part0 = Parts[i]; 621 SDValue &Part1 = Parts[i+StepSize/2]; 622 623 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 624 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 625 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 626 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 627 628 if (ThisBits == PartBits && ThisVT != PartVT) { 629 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 630 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 631 } 632 } 633 } 634 635 if (DAG.getDataLayout().isBigEndian()) 636 std::reverse(Parts, Parts + OrigNumParts); 637 } 638 639 static SDValue widenVectorToPartType(SelectionDAG &DAG, 640 SDValue Val, const SDLoc &DL, EVT PartVT) { 641 if (!PartVT.isFixedLengthVector()) 642 return SDValue(); 643 644 EVT ValueVT = Val.getValueType(); 645 unsigned PartNumElts = PartVT.getVectorNumElements(); 646 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 647 if (PartNumElts > ValueNumElts && 648 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 649 EVT ElementVT = PartVT.getVectorElementType(); 650 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 651 // undef elements. 652 SmallVector<SDValue, 16> Ops; 653 DAG.ExtractVectorElements(Val, Ops); 654 SDValue EltUndef = DAG.getUNDEF(ElementVT); 655 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 656 Ops.push_back(EltUndef); 657 658 // FIXME: Use CONCAT for 2x -> 4x. 659 return DAG.getBuildVector(PartVT, DL, Ops); 660 } 661 662 return SDValue(); 663 } 664 665 /// getCopyToPartsVector - Create a series of nodes that contain the specified 666 /// value split into legal parts. 667 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 668 SDValue Val, SDValue *Parts, unsigned NumParts, 669 MVT PartVT, const Value *V, 670 Optional<CallingConv::ID> CallConv) { 671 EVT ValueVT = Val.getValueType(); 672 assert(ValueVT.isVector() && "Not a vector"); 673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 674 const bool IsABIRegCopy = CallConv.hasValue(); 675 676 if (NumParts == 1) { 677 EVT PartEVT = PartVT; 678 if (PartEVT == ValueVT) { 679 // Nothing to do. 680 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 681 // Bitconvert vector->vector case. 682 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 683 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 684 Val = Widened; 685 } else if (PartVT.isVector() && 686 PartEVT.getVectorElementType().bitsGE( 687 ValueVT.getVectorElementType()) && 688 PartEVT.getVectorElementCount() == 689 ValueVT.getVectorElementCount()) { 690 691 // Promoted vector extract 692 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 693 } else { 694 if (ValueVT.getVectorNumElements() == 1) { 695 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 696 DAG.getVectorIdxConstant(0, DL)); 697 } else { 698 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 699 "lossy conversion of vector to scalar type"); 700 EVT IntermediateType = 701 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 702 Val = DAG.getBitcast(IntermediateType, Val); 703 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 704 } 705 } 706 707 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 708 Parts[0] = Val; 709 return; 710 } 711 712 // Handle a multi-element vector. 713 EVT IntermediateVT; 714 MVT RegisterVT; 715 unsigned NumIntermediates; 716 unsigned NumRegs; 717 if (IsABIRegCopy) { 718 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 719 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 720 NumIntermediates, RegisterVT); 721 } else { 722 NumRegs = 723 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 724 NumIntermediates, RegisterVT); 725 } 726 727 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 728 NumParts = NumRegs; // Silence a compiler warning. 729 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 730 731 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 732 "Mixing scalable and fixed vectors when copying in parts"); 733 734 Optional<ElementCount> DestEltCnt; 735 736 if (IntermediateVT.isVector()) 737 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 738 else 739 DestEltCnt = ElementCount::getFixed(NumIntermediates); 740 741 EVT BuiltVectorTy = EVT::getVectorVT( 742 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 743 if (ValueVT != BuiltVectorTy) { 744 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 745 Val = Widened; 746 747 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 748 } 749 750 // Split the vector into intermediate operands. 751 SmallVector<SDValue, 8> Ops(NumIntermediates); 752 for (unsigned i = 0; i != NumIntermediates; ++i) { 753 if (IntermediateVT.isVector()) { 754 // This does something sensible for scalable vectors - see the 755 // definition of EXTRACT_SUBVECTOR for further details. 756 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 757 Ops[i] = 758 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 759 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 760 } else { 761 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 762 DAG.getVectorIdxConstant(i, DL)); 763 } 764 } 765 766 // Split the intermediate operands into legal parts. 767 if (NumParts == NumIntermediates) { 768 // If the register was not expanded, promote or copy the value, 769 // as appropriate. 770 for (unsigned i = 0; i != NumParts; ++i) 771 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 772 } else if (NumParts > 0) { 773 // If the intermediate type was expanded, split each the value into 774 // legal parts. 775 assert(NumIntermediates != 0 && "division by zero"); 776 assert(NumParts % NumIntermediates == 0 && 777 "Must expand into a divisible number of parts!"); 778 unsigned Factor = NumParts / NumIntermediates; 779 for (unsigned i = 0; i != NumIntermediates; ++i) 780 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 781 CallConv); 782 } 783 } 784 785 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 786 EVT valuevt, Optional<CallingConv::ID> CC) 787 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 788 RegCount(1, regs.size()), CallConv(CC) {} 789 790 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 791 const DataLayout &DL, unsigned Reg, Type *Ty, 792 Optional<CallingConv::ID> CC) { 793 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 794 795 CallConv = CC; 796 797 for (EVT ValueVT : ValueVTs) { 798 unsigned NumRegs = 799 isABIMangled() 800 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 801 : TLI.getNumRegisters(Context, ValueVT); 802 MVT RegisterVT = 803 isABIMangled() 804 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 805 : TLI.getRegisterType(Context, ValueVT); 806 for (unsigned i = 0; i != NumRegs; ++i) 807 Regs.push_back(Reg + i); 808 RegVTs.push_back(RegisterVT); 809 RegCount.push_back(NumRegs); 810 Reg += NumRegs; 811 } 812 } 813 814 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 815 FunctionLoweringInfo &FuncInfo, 816 const SDLoc &dl, SDValue &Chain, 817 SDValue *Flag, const Value *V) const { 818 // A Value with type {} or [0 x %t] needs no registers. 819 if (ValueVTs.empty()) 820 return SDValue(); 821 822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 823 824 // Assemble the legal parts into the final values. 825 SmallVector<SDValue, 4> Values(ValueVTs.size()); 826 SmallVector<SDValue, 8> Parts; 827 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 828 // Copy the legal parts from the registers. 829 EVT ValueVT = ValueVTs[Value]; 830 unsigned NumRegs = RegCount[Value]; 831 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 832 *DAG.getContext(), 833 CallConv.getValue(), RegVTs[Value]) 834 : RegVTs[Value]; 835 836 Parts.resize(NumRegs); 837 for (unsigned i = 0; i != NumRegs; ++i) { 838 SDValue P; 839 if (!Flag) { 840 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 841 } else { 842 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 843 *Flag = P.getValue(2); 844 } 845 846 Chain = P.getValue(1); 847 Parts[i] = P; 848 849 // If the source register was virtual and if we know something about it, 850 // add an assert node. 851 if (!Register::isVirtualRegister(Regs[Part + i]) || 852 !RegisterVT.isInteger()) 853 continue; 854 855 const FunctionLoweringInfo::LiveOutInfo *LOI = 856 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 857 if (!LOI) 858 continue; 859 860 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 861 unsigned NumSignBits = LOI->NumSignBits; 862 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 863 864 if (NumZeroBits == RegSize) { 865 // The current value is a zero. 866 // Explicitly express that as it would be easier for 867 // optimizations to kick in. 868 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 869 continue; 870 } 871 872 // FIXME: We capture more information than the dag can represent. For 873 // now, just use the tightest assertzext/assertsext possible. 874 bool isSExt; 875 EVT FromVT(MVT::Other); 876 if (NumZeroBits) { 877 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 878 isSExt = false; 879 } else if (NumSignBits > 1) { 880 FromVT = 881 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 882 isSExt = true; 883 } else { 884 continue; 885 } 886 // Add an assertion node. 887 assert(FromVT != MVT::Other); 888 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 889 RegisterVT, P, DAG.getValueType(FromVT)); 890 } 891 892 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 893 RegisterVT, ValueVT, V, CallConv); 894 Part += NumRegs; 895 Parts.clear(); 896 } 897 898 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 899 } 900 901 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 902 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 903 const Value *V, 904 ISD::NodeType PreferredExtendType) const { 905 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 906 ISD::NodeType ExtendKind = PreferredExtendType; 907 908 // Get the list of the values's legal parts. 909 unsigned NumRegs = Regs.size(); 910 SmallVector<SDValue, 8> Parts(NumRegs); 911 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 912 unsigned NumParts = RegCount[Value]; 913 914 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 915 *DAG.getContext(), 916 CallConv.getValue(), RegVTs[Value]) 917 : RegVTs[Value]; 918 919 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 920 ExtendKind = ISD::ZERO_EXTEND; 921 922 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 923 NumParts, RegisterVT, V, CallConv, ExtendKind); 924 Part += NumParts; 925 } 926 927 // Copy the parts into the registers. 928 SmallVector<SDValue, 8> Chains(NumRegs); 929 for (unsigned i = 0; i != NumRegs; ++i) { 930 SDValue Part; 931 if (!Flag) { 932 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 933 } else { 934 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 935 *Flag = Part.getValue(1); 936 } 937 938 Chains[i] = Part.getValue(0); 939 } 940 941 if (NumRegs == 1 || Flag) 942 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 943 // flagged to it. That is the CopyToReg nodes and the user are considered 944 // a single scheduling unit. If we create a TokenFactor and return it as 945 // chain, then the TokenFactor is both a predecessor (operand) of the 946 // user as well as a successor (the TF operands are flagged to the user). 947 // c1, f1 = CopyToReg 948 // c2, f2 = CopyToReg 949 // c3 = TokenFactor c1, c2 950 // ... 951 // = op c3, ..., f2 952 Chain = Chains[NumRegs-1]; 953 else 954 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 955 } 956 957 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 958 unsigned MatchingIdx, const SDLoc &dl, 959 SelectionDAG &DAG, 960 std::vector<SDValue> &Ops) const { 961 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 962 963 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 964 if (HasMatching) 965 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 966 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 967 // Put the register class of the virtual registers in the flag word. That 968 // way, later passes can recompute register class constraints for inline 969 // assembly as well as normal instructions. 970 // Don't do this for tied operands that can use the regclass information 971 // from the def. 972 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 973 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 974 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 975 } 976 977 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 978 Ops.push_back(Res); 979 980 if (Code == InlineAsm::Kind_Clobber) { 981 // Clobbers should always have a 1:1 mapping with registers, and may 982 // reference registers that have illegal (e.g. vector) types. Hence, we 983 // shouldn't try to apply any sort of splitting logic to them. 984 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 985 "No 1:1 mapping from clobbers to regs?"); 986 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 987 (void)SP; 988 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 989 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 990 assert( 991 (Regs[I] != SP || 992 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 993 "If we clobbered the stack pointer, MFI should know about it."); 994 } 995 return; 996 } 997 998 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 999 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 1000 MVT RegisterVT = RegVTs[Value]; 1001 for (unsigned i = 0; i != NumRegs; ++i) { 1002 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 1003 unsigned TheReg = Regs[Reg++]; 1004 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 1005 } 1006 } 1007 } 1008 1009 SmallVector<std::pair<unsigned, unsigned>, 4> 1010 RegsForValue::getRegsAndSizes() const { 1011 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1012 unsigned I = 0; 1013 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1014 unsigned RegCount = std::get<0>(CountAndVT); 1015 MVT RegisterVT = std::get<1>(CountAndVT); 1016 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1017 for (unsigned E = I + RegCount; I != E; ++I) 1018 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1019 } 1020 return OutVec; 1021 } 1022 1023 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1024 const TargetLibraryInfo *li) { 1025 AA = aa; 1026 GFI = gfi; 1027 LibInfo = li; 1028 DL = &DAG.getDataLayout(); 1029 Context = DAG.getContext(); 1030 LPadToCallSiteMap.clear(); 1031 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1032 } 1033 1034 void SelectionDAGBuilder::clear() { 1035 NodeMap.clear(); 1036 UnusedArgNodeMap.clear(); 1037 PendingLoads.clear(); 1038 PendingExports.clear(); 1039 PendingConstrainedFP.clear(); 1040 PendingConstrainedFPStrict.clear(); 1041 CurInst = nullptr; 1042 HasTailCall = false; 1043 SDNodeOrder = LowestSDNodeOrder; 1044 StatepointLowering.clear(); 1045 } 1046 1047 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1048 DanglingDebugInfoMap.clear(); 1049 } 1050 1051 // Update DAG root to include dependencies on Pending chains. 1052 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1053 SDValue Root = DAG.getRoot(); 1054 1055 if (Pending.empty()) 1056 return Root; 1057 1058 // Add current root to PendingChains, unless we already indirectly 1059 // depend on it. 1060 if (Root.getOpcode() != ISD::EntryToken) { 1061 unsigned i = 0, e = Pending.size(); 1062 for (; i != e; ++i) { 1063 assert(Pending[i].getNode()->getNumOperands() > 1); 1064 if (Pending[i].getNode()->getOperand(0) == Root) 1065 break; // Don't add the root if we already indirectly depend on it. 1066 } 1067 1068 if (i == e) 1069 Pending.push_back(Root); 1070 } 1071 1072 if (Pending.size() == 1) 1073 Root = Pending[0]; 1074 else 1075 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1076 1077 DAG.setRoot(Root); 1078 Pending.clear(); 1079 return Root; 1080 } 1081 1082 SDValue SelectionDAGBuilder::getMemoryRoot() { 1083 return updateRoot(PendingLoads); 1084 } 1085 1086 SDValue SelectionDAGBuilder::getRoot() { 1087 // Chain up all pending constrained intrinsics together with all 1088 // pending loads, by simply appending them to PendingLoads and 1089 // then calling getMemoryRoot(). 1090 PendingLoads.reserve(PendingLoads.size() + 1091 PendingConstrainedFP.size() + 1092 PendingConstrainedFPStrict.size()); 1093 PendingLoads.append(PendingConstrainedFP.begin(), 1094 PendingConstrainedFP.end()); 1095 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1096 PendingConstrainedFPStrict.end()); 1097 PendingConstrainedFP.clear(); 1098 PendingConstrainedFPStrict.clear(); 1099 return getMemoryRoot(); 1100 } 1101 1102 SDValue SelectionDAGBuilder::getControlRoot() { 1103 // We need to emit pending fpexcept.strict constrained intrinsics, 1104 // so append them to the PendingExports list. 1105 PendingExports.append(PendingConstrainedFPStrict.begin(), 1106 PendingConstrainedFPStrict.end()); 1107 PendingConstrainedFPStrict.clear(); 1108 return updateRoot(PendingExports); 1109 } 1110 1111 void SelectionDAGBuilder::visit(const Instruction &I) { 1112 // Set up outgoing PHI node register values before emitting the terminator. 1113 if (I.isTerminator()) { 1114 HandlePHINodesInSuccessorBlocks(I.getParent()); 1115 } 1116 1117 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1118 if (!isa<DbgInfoIntrinsic>(I)) 1119 ++SDNodeOrder; 1120 1121 CurInst = &I; 1122 1123 visit(I.getOpcode(), I); 1124 1125 if (!I.isTerminator() && !HasTailCall && 1126 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1127 CopyToExportRegsIfNeeded(&I); 1128 1129 CurInst = nullptr; 1130 } 1131 1132 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1133 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1134 } 1135 1136 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1137 // Note: this doesn't use InstVisitor, because it has to work with 1138 // ConstantExpr's in addition to instructions. 1139 switch (Opcode) { 1140 default: llvm_unreachable("Unknown instruction type encountered!"); 1141 // Build the switch statement using the Instruction.def file. 1142 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1143 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1144 #include "llvm/IR/Instruction.def" 1145 } 1146 } 1147 1148 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1149 const DIExpression *Expr) { 1150 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1151 const DbgValueInst *DI = DDI.getDI(); 1152 DIVariable *DanglingVariable = DI->getVariable(); 1153 DIExpression *DanglingExpr = DI->getExpression(); 1154 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1155 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1156 return true; 1157 } 1158 return false; 1159 }; 1160 1161 for (auto &DDIMI : DanglingDebugInfoMap) { 1162 DanglingDebugInfoVector &DDIV = DDIMI.second; 1163 1164 // If debug info is to be dropped, run it through final checks to see 1165 // whether it can be salvaged. 1166 for (auto &DDI : DDIV) 1167 if (isMatchingDbgValue(DDI)) 1168 salvageUnresolvedDbgValue(DDI); 1169 1170 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1171 } 1172 } 1173 1174 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1175 // generate the debug data structures now that we've seen its definition. 1176 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1177 SDValue Val) { 1178 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1179 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1180 return; 1181 1182 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1183 for (auto &DDI : DDIV) { 1184 const DbgValueInst *DI = DDI.getDI(); 1185 assert(DI && "Ill-formed DanglingDebugInfo"); 1186 DebugLoc dl = DDI.getdl(); 1187 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1188 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1189 DILocalVariable *Variable = DI->getVariable(); 1190 DIExpression *Expr = DI->getExpression(); 1191 assert(Variable->isValidLocationForIntrinsic(dl) && 1192 "Expected inlined-at fields to agree"); 1193 SDDbgValue *SDV; 1194 if (Val.getNode()) { 1195 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1196 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1197 // we couldn't resolve it directly when examining the DbgValue intrinsic 1198 // in the first place we should not be more successful here). Unless we 1199 // have some test case that prove this to be correct we should avoid 1200 // calling EmitFuncArgumentDbgValue here. 1201 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1202 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1203 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1204 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1205 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1206 // inserted after the definition of Val when emitting the instructions 1207 // after ISel. An alternative could be to teach 1208 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1209 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1210 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1211 << ValSDNodeOrder << "\n"); 1212 SDV = getDbgValue(Val, Variable, Expr, dl, 1213 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1214 DAG.AddDbgValue(SDV, Val.getNode(), false); 1215 } else 1216 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1217 << "in EmitFuncArgumentDbgValue\n"); 1218 } else { 1219 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1220 auto Undef = 1221 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1222 auto SDV = 1223 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1224 DAG.AddDbgValue(SDV, nullptr, false); 1225 } 1226 } 1227 DDIV.clear(); 1228 } 1229 1230 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1231 Value *V = DDI.getDI()->getValue(); 1232 DILocalVariable *Var = DDI.getDI()->getVariable(); 1233 DIExpression *Expr = DDI.getDI()->getExpression(); 1234 DebugLoc DL = DDI.getdl(); 1235 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1236 unsigned SDOrder = DDI.getSDNodeOrder(); 1237 1238 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1239 // that DW_OP_stack_value is desired. 1240 assert(isa<DbgValueInst>(DDI.getDI())); 1241 bool StackValue = true; 1242 1243 // Can this Value can be encoded without any further work? 1244 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1245 return; 1246 1247 // Attempt to salvage back through as many instructions as possible. Bail if 1248 // a non-instruction is seen, such as a constant expression or global 1249 // variable. FIXME: Further work could recover those too. 1250 while (isa<Instruction>(V)) { 1251 Instruction &VAsInst = *cast<Instruction>(V); 1252 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1253 1254 // If we cannot salvage any further, and haven't yet found a suitable debug 1255 // expression, bail out. 1256 if (!NewExpr) 1257 break; 1258 1259 // New value and expr now represent this debuginfo. 1260 V = VAsInst.getOperand(0); 1261 Expr = NewExpr; 1262 1263 // Some kind of simplification occurred: check whether the operand of the 1264 // salvaged debug expression can be encoded in this DAG. 1265 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1266 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1267 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1268 return; 1269 } 1270 } 1271 1272 // This was the final opportunity to salvage this debug information, and it 1273 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1274 // any earlier variable location. 1275 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1276 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1277 DAG.AddDbgValue(SDV, nullptr, false); 1278 1279 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1280 << "\n"); 1281 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1282 << "\n"); 1283 } 1284 1285 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1286 DIExpression *Expr, DebugLoc dl, 1287 DebugLoc InstDL, unsigned Order) { 1288 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1289 SDDbgValue *SDV; 1290 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1291 isa<ConstantPointerNull>(V)) { 1292 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1293 DAG.AddDbgValue(SDV, nullptr, false); 1294 return true; 1295 } 1296 1297 // If the Value is a frame index, we can create a FrameIndex debug value 1298 // without relying on the DAG at all. 1299 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1300 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1301 if (SI != FuncInfo.StaticAllocaMap.end()) { 1302 auto SDV = 1303 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1304 /*IsIndirect*/ false, dl, SDNodeOrder); 1305 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1306 // is still available even if the SDNode gets optimized out. 1307 DAG.AddDbgValue(SDV, nullptr, false); 1308 return true; 1309 } 1310 } 1311 1312 // Do not use getValue() in here; we don't want to generate code at 1313 // this point if it hasn't been done yet. 1314 SDValue N = NodeMap[V]; 1315 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1316 N = UnusedArgNodeMap[V]; 1317 if (N.getNode()) { 1318 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1319 return true; 1320 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1321 DAG.AddDbgValue(SDV, N.getNode(), false); 1322 return true; 1323 } 1324 1325 // Special rules apply for the first dbg.values of parameter variables in a 1326 // function. Identify them by the fact they reference Argument Values, that 1327 // they're parameters, and they are parameters of the current function. We 1328 // need to let them dangle until they get an SDNode. 1329 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1330 !InstDL.getInlinedAt(); 1331 if (!IsParamOfFunc) { 1332 // The value is not used in this block yet (or it would have an SDNode). 1333 // We still want the value to appear for the user if possible -- if it has 1334 // an associated VReg, we can refer to that instead. 1335 auto VMI = FuncInfo.ValueMap.find(V); 1336 if (VMI != FuncInfo.ValueMap.end()) { 1337 unsigned Reg = VMI->second; 1338 // If this is a PHI node, it may be split up into several MI PHI nodes 1339 // (in FunctionLoweringInfo::set). 1340 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1341 V->getType(), None); 1342 if (RFV.occupiesMultipleRegs()) { 1343 unsigned Offset = 0; 1344 unsigned BitsToDescribe = 0; 1345 if (auto VarSize = Var->getSizeInBits()) 1346 BitsToDescribe = *VarSize; 1347 if (auto Fragment = Expr->getFragmentInfo()) 1348 BitsToDescribe = Fragment->SizeInBits; 1349 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1350 unsigned RegisterSize = RegAndSize.second; 1351 // Bail out if all bits are described already. 1352 if (Offset >= BitsToDescribe) 1353 break; 1354 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1355 ? BitsToDescribe - Offset 1356 : RegisterSize; 1357 auto FragmentExpr = DIExpression::createFragmentExpression( 1358 Expr, Offset, FragmentSize); 1359 if (!FragmentExpr) 1360 continue; 1361 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1362 false, dl, SDNodeOrder); 1363 DAG.AddDbgValue(SDV, nullptr, false); 1364 Offset += RegisterSize; 1365 } 1366 } else { 1367 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1368 DAG.AddDbgValue(SDV, nullptr, false); 1369 } 1370 return true; 1371 } 1372 } 1373 1374 return false; 1375 } 1376 1377 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1378 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1379 for (auto &Pair : DanglingDebugInfoMap) 1380 for (auto &DDI : Pair.second) 1381 salvageUnresolvedDbgValue(DDI); 1382 clearDanglingDebugInfo(); 1383 } 1384 1385 /// getCopyFromRegs - If there was virtual register allocated for the value V 1386 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1387 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1388 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1389 SDValue Result; 1390 1391 if (It != FuncInfo.ValueMap.end()) { 1392 Register InReg = It->second; 1393 1394 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1395 DAG.getDataLayout(), InReg, Ty, 1396 None); // This is not an ABI copy. 1397 SDValue Chain = DAG.getEntryNode(); 1398 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1399 V); 1400 resolveDanglingDebugInfo(V, Result); 1401 } 1402 1403 return Result; 1404 } 1405 1406 /// getValue - Return an SDValue for the given Value. 1407 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1408 // If we already have an SDValue for this value, use it. It's important 1409 // to do this first, so that we don't create a CopyFromReg if we already 1410 // have a regular SDValue. 1411 SDValue &N = NodeMap[V]; 1412 if (N.getNode()) return N; 1413 1414 // If there's a virtual register allocated and initialized for this 1415 // value, use it. 1416 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1417 return copyFromReg; 1418 1419 // Otherwise create a new SDValue and remember it. 1420 SDValue Val = getValueImpl(V); 1421 NodeMap[V] = Val; 1422 resolveDanglingDebugInfo(V, Val); 1423 return Val; 1424 } 1425 1426 /// getNonRegisterValue - Return an SDValue for the given Value, but 1427 /// don't look in FuncInfo.ValueMap for a virtual register. 1428 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1429 // If we already have an SDValue for this value, use it. 1430 SDValue &N = NodeMap[V]; 1431 if (N.getNode()) { 1432 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1433 // Remove the debug location from the node as the node is about to be used 1434 // in a location which may differ from the original debug location. This 1435 // is relevant to Constant and ConstantFP nodes because they can appear 1436 // as constant expressions inside PHI nodes. 1437 N->setDebugLoc(DebugLoc()); 1438 } 1439 return N; 1440 } 1441 1442 // Otherwise create a new SDValue and remember it. 1443 SDValue Val = getValueImpl(V); 1444 NodeMap[V] = Val; 1445 resolveDanglingDebugInfo(V, Val); 1446 return Val; 1447 } 1448 1449 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1450 /// Create an SDValue for the given value. 1451 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1452 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1453 1454 if (const Constant *C = dyn_cast<Constant>(V)) { 1455 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1456 1457 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1458 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1459 1460 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1461 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1462 1463 if (isa<ConstantPointerNull>(C)) { 1464 unsigned AS = V->getType()->getPointerAddressSpace(); 1465 return DAG.getConstant(0, getCurSDLoc(), 1466 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1467 } 1468 1469 if (match(C, m_VScale(DAG.getDataLayout()))) 1470 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1471 1472 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1473 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1474 1475 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1476 return DAG.getUNDEF(VT); 1477 1478 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1479 visit(CE->getOpcode(), *CE); 1480 SDValue N1 = NodeMap[V]; 1481 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1482 return N1; 1483 } 1484 1485 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1486 SmallVector<SDValue, 4> Constants; 1487 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1488 OI != OE; ++OI) { 1489 SDNode *Val = getValue(*OI).getNode(); 1490 // If the operand is an empty aggregate, there are no values. 1491 if (!Val) continue; 1492 // Add each leaf value from the operand to the Constants list 1493 // to form a flattened list of all the values. 1494 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1495 Constants.push_back(SDValue(Val, i)); 1496 } 1497 1498 return DAG.getMergeValues(Constants, getCurSDLoc()); 1499 } 1500 1501 if (const ConstantDataSequential *CDS = 1502 dyn_cast<ConstantDataSequential>(C)) { 1503 SmallVector<SDValue, 4> Ops; 1504 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1505 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1506 // Add each leaf value from the operand to the Constants list 1507 // to form a flattened list of all the values. 1508 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1509 Ops.push_back(SDValue(Val, i)); 1510 } 1511 1512 if (isa<ArrayType>(CDS->getType())) 1513 return DAG.getMergeValues(Ops, getCurSDLoc()); 1514 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1515 } 1516 1517 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1518 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1519 "Unknown struct or array constant!"); 1520 1521 SmallVector<EVT, 4> ValueVTs; 1522 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1523 unsigned NumElts = ValueVTs.size(); 1524 if (NumElts == 0) 1525 return SDValue(); // empty struct 1526 SmallVector<SDValue, 4> Constants(NumElts); 1527 for (unsigned i = 0; i != NumElts; ++i) { 1528 EVT EltVT = ValueVTs[i]; 1529 if (isa<UndefValue>(C)) 1530 Constants[i] = DAG.getUNDEF(EltVT); 1531 else if (EltVT.isFloatingPoint()) 1532 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1533 else 1534 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1535 } 1536 1537 return DAG.getMergeValues(Constants, getCurSDLoc()); 1538 } 1539 1540 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1541 return DAG.getBlockAddress(BA, VT); 1542 1543 VectorType *VecTy = cast<VectorType>(V->getType()); 1544 1545 // Now that we know the number and type of the elements, get that number of 1546 // elements into the Ops array based on what kind of constant it is. 1547 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1548 SmallVector<SDValue, 16> Ops; 1549 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1550 for (unsigned i = 0; i != NumElements; ++i) 1551 Ops.push_back(getValue(CV->getOperand(i))); 1552 1553 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1554 } else if (isa<ConstantAggregateZero>(C)) { 1555 EVT EltVT = 1556 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1557 1558 SDValue Op; 1559 if (EltVT.isFloatingPoint()) 1560 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1561 else 1562 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1563 1564 if (isa<ScalableVectorType>(VecTy)) 1565 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1566 else { 1567 SmallVector<SDValue, 16> Ops; 1568 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1569 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1570 } 1571 } 1572 llvm_unreachable("Unknown vector constant"); 1573 } 1574 1575 // If this is a static alloca, generate it as the frameindex instead of 1576 // computation. 1577 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1578 DenseMap<const AllocaInst*, int>::iterator SI = 1579 FuncInfo.StaticAllocaMap.find(AI); 1580 if (SI != FuncInfo.StaticAllocaMap.end()) 1581 return DAG.getFrameIndex(SI->second, 1582 TLI.getFrameIndexTy(DAG.getDataLayout())); 1583 } 1584 1585 // If this is an instruction which fast-isel has deferred, select it now. 1586 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1587 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1588 1589 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1590 Inst->getType(), getABIRegCopyCC(V)); 1591 SDValue Chain = DAG.getEntryNode(); 1592 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1593 } 1594 1595 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1596 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1597 } 1598 llvm_unreachable("Can't get register for value!"); 1599 } 1600 1601 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1602 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1603 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1604 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1605 bool IsSEH = isAsynchronousEHPersonality(Pers); 1606 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1607 if (!IsSEH) 1608 CatchPadMBB->setIsEHScopeEntry(); 1609 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1610 if (IsMSVCCXX || IsCoreCLR) 1611 CatchPadMBB->setIsEHFuncletEntry(); 1612 } 1613 1614 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1615 // Update machine-CFG edge. 1616 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1617 FuncInfo.MBB->addSuccessor(TargetMBB); 1618 1619 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1620 bool IsSEH = isAsynchronousEHPersonality(Pers); 1621 if (IsSEH) { 1622 // If this is not a fall-through branch or optimizations are switched off, 1623 // emit the branch. 1624 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1625 TM.getOptLevel() == CodeGenOpt::None) 1626 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1627 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1628 return; 1629 } 1630 1631 // Figure out the funclet membership for the catchret's successor. 1632 // This will be used by the FuncletLayout pass to determine how to order the 1633 // BB's. 1634 // A 'catchret' returns to the outer scope's color. 1635 Value *ParentPad = I.getCatchSwitchParentPad(); 1636 const BasicBlock *SuccessorColor; 1637 if (isa<ConstantTokenNone>(ParentPad)) 1638 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1639 else 1640 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1641 assert(SuccessorColor && "No parent funclet for catchret!"); 1642 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1643 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1644 1645 // Create the terminator node. 1646 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1647 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1648 DAG.getBasicBlock(SuccessorColorMBB)); 1649 DAG.setRoot(Ret); 1650 } 1651 1652 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1653 // Don't emit any special code for the cleanuppad instruction. It just marks 1654 // the start of an EH scope/funclet. 1655 FuncInfo.MBB->setIsEHScopeEntry(); 1656 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1657 if (Pers != EHPersonality::Wasm_CXX) { 1658 FuncInfo.MBB->setIsEHFuncletEntry(); 1659 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1660 } 1661 } 1662 1663 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1664 // the control flow always stops at the single catch pad, as it does for a 1665 // cleanup pad. In case the exception caught is not of the types the catch pad 1666 // catches, it will be rethrown by a rethrow. 1667 static void findWasmUnwindDestinations( 1668 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1669 BranchProbability Prob, 1670 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1671 &UnwindDests) { 1672 while (EHPadBB) { 1673 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1674 if (isa<CleanupPadInst>(Pad)) { 1675 // Stop on cleanup pads. 1676 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1677 UnwindDests.back().first->setIsEHScopeEntry(); 1678 break; 1679 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1680 // Add the catchpad handlers to the possible destinations. We don't 1681 // continue to the unwind destination of the catchswitch for wasm. 1682 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1683 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1684 UnwindDests.back().first->setIsEHScopeEntry(); 1685 } 1686 break; 1687 } else { 1688 continue; 1689 } 1690 } 1691 } 1692 1693 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1694 /// many places it could ultimately go. In the IR, we have a single unwind 1695 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1696 /// This function skips over imaginary basic blocks that hold catchswitch 1697 /// instructions, and finds all the "real" machine 1698 /// basic block destinations. As those destinations may not be successors of 1699 /// EHPadBB, here we also calculate the edge probability to those destinations. 1700 /// The passed-in Prob is the edge probability to EHPadBB. 1701 static void findUnwindDestinations( 1702 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1703 BranchProbability Prob, 1704 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1705 &UnwindDests) { 1706 EHPersonality Personality = 1707 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1708 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1709 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1710 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1711 bool IsSEH = isAsynchronousEHPersonality(Personality); 1712 1713 if (IsWasmCXX) { 1714 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1715 assert(UnwindDests.size() <= 1 && 1716 "There should be at most one unwind destination for wasm"); 1717 return; 1718 } 1719 1720 while (EHPadBB) { 1721 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1722 BasicBlock *NewEHPadBB = nullptr; 1723 if (isa<LandingPadInst>(Pad)) { 1724 // Stop on landingpads. They are not funclets. 1725 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1726 break; 1727 } else if (isa<CleanupPadInst>(Pad)) { 1728 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1729 // personalities. 1730 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1731 UnwindDests.back().first->setIsEHScopeEntry(); 1732 UnwindDests.back().first->setIsEHFuncletEntry(); 1733 break; 1734 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1735 // Add the catchpad handlers to the possible destinations. 1736 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1737 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1738 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1739 if (IsMSVCCXX || IsCoreCLR) 1740 UnwindDests.back().first->setIsEHFuncletEntry(); 1741 if (!IsSEH) 1742 UnwindDests.back().first->setIsEHScopeEntry(); 1743 } 1744 NewEHPadBB = CatchSwitch->getUnwindDest(); 1745 } else { 1746 continue; 1747 } 1748 1749 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1750 if (BPI && NewEHPadBB) 1751 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1752 EHPadBB = NewEHPadBB; 1753 } 1754 } 1755 1756 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1757 // Update successor info. 1758 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1759 auto UnwindDest = I.getUnwindDest(); 1760 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1761 BranchProbability UnwindDestProb = 1762 (BPI && UnwindDest) 1763 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1764 : BranchProbability::getZero(); 1765 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1766 for (auto &UnwindDest : UnwindDests) { 1767 UnwindDest.first->setIsEHPad(); 1768 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1769 } 1770 FuncInfo.MBB->normalizeSuccProbs(); 1771 1772 // Create the terminator node. 1773 SDValue Ret = 1774 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1775 DAG.setRoot(Ret); 1776 } 1777 1778 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1779 report_fatal_error("visitCatchSwitch not yet implemented!"); 1780 } 1781 1782 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1783 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1784 auto &DL = DAG.getDataLayout(); 1785 SDValue Chain = getControlRoot(); 1786 SmallVector<ISD::OutputArg, 8> Outs; 1787 SmallVector<SDValue, 8> OutVals; 1788 1789 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1790 // lower 1791 // 1792 // %val = call <ty> @llvm.experimental.deoptimize() 1793 // ret <ty> %val 1794 // 1795 // differently. 1796 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1797 LowerDeoptimizingReturn(); 1798 return; 1799 } 1800 1801 if (!FuncInfo.CanLowerReturn) { 1802 unsigned DemoteReg = FuncInfo.DemoteRegister; 1803 const Function *F = I.getParent()->getParent(); 1804 1805 // Emit a store of the return value through the virtual register. 1806 // Leave Outs empty so that LowerReturn won't try to load return 1807 // registers the usual way. 1808 SmallVector<EVT, 1> PtrValueVTs; 1809 ComputeValueVTs(TLI, DL, 1810 F->getReturnType()->getPointerTo( 1811 DAG.getDataLayout().getAllocaAddrSpace()), 1812 PtrValueVTs); 1813 1814 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1815 DemoteReg, PtrValueVTs[0]); 1816 SDValue RetOp = getValue(I.getOperand(0)); 1817 1818 SmallVector<EVT, 4> ValueVTs, MemVTs; 1819 SmallVector<uint64_t, 4> Offsets; 1820 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1821 &Offsets); 1822 unsigned NumValues = ValueVTs.size(); 1823 1824 SmallVector<SDValue, 4> Chains(NumValues); 1825 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1826 for (unsigned i = 0; i != NumValues; ++i) { 1827 // An aggregate return value cannot wrap around the address space, so 1828 // offsets to its parts don't wrap either. 1829 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1830 TypeSize::Fixed(Offsets[i])); 1831 1832 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1833 if (MemVTs[i] != ValueVTs[i]) 1834 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1835 Chains[i] = DAG.getStore( 1836 Chain, getCurSDLoc(), Val, 1837 // FIXME: better loc info would be nice. 1838 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1839 commonAlignment(BaseAlign, Offsets[i])); 1840 } 1841 1842 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1843 MVT::Other, Chains); 1844 } else if (I.getNumOperands() != 0) { 1845 SmallVector<EVT, 4> ValueVTs; 1846 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1847 unsigned NumValues = ValueVTs.size(); 1848 if (NumValues) { 1849 SDValue RetOp = getValue(I.getOperand(0)); 1850 1851 const Function *F = I.getParent()->getParent(); 1852 1853 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1854 I.getOperand(0)->getType(), F->getCallingConv(), 1855 /*IsVarArg*/ false); 1856 1857 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1858 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1859 Attribute::SExt)) 1860 ExtendKind = ISD::SIGN_EXTEND; 1861 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1862 Attribute::ZExt)) 1863 ExtendKind = ISD::ZERO_EXTEND; 1864 1865 LLVMContext &Context = F->getContext(); 1866 bool RetInReg = F->getAttributes().hasAttribute( 1867 AttributeList::ReturnIndex, Attribute::InReg); 1868 1869 for (unsigned j = 0; j != NumValues; ++j) { 1870 EVT VT = ValueVTs[j]; 1871 1872 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1873 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1874 1875 CallingConv::ID CC = F->getCallingConv(); 1876 1877 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1878 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1879 SmallVector<SDValue, 4> Parts(NumParts); 1880 getCopyToParts(DAG, getCurSDLoc(), 1881 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1882 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1883 1884 // 'inreg' on function refers to return value 1885 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1886 if (RetInReg) 1887 Flags.setInReg(); 1888 1889 if (I.getOperand(0)->getType()->isPointerTy()) { 1890 Flags.setPointer(); 1891 Flags.setPointerAddrSpace( 1892 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1893 } 1894 1895 if (NeedsRegBlock) { 1896 Flags.setInConsecutiveRegs(); 1897 if (j == NumValues - 1) 1898 Flags.setInConsecutiveRegsLast(); 1899 } 1900 1901 // Propagate extension type if any 1902 if (ExtendKind == ISD::SIGN_EXTEND) 1903 Flags.setSExt(); 1904 else if (ExtendKind == ISD::ZERO_EXTEND) 1905 Flags.setZExt(); 1906 1907 for (unsigned i = 0; i < NumParts; ++i) { 1908 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1909 VT, /*isfixed=*/true, 0, 0)); 1910 OutVals.push_back(Parts[i]); 1911 } 1912 } 1913 } 1914 } 1915 1916 // Push in swifterror virtual register as the last element of Outs. This makes 1917 // sure swifterror virtual register will be returned in the swifterror 1918 // physical register. 1919 const Function *F = I.getParent()->getParent(); 1920 if (TLI.supportSwiftError() && 1921 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1922 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1923 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1924 Flags.setSwiftError(); 1925 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1926 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1927 true /*isfixed*/, 1 /*origidx*/, 1928 0 /*partOffs*/)); 1929 // Create SDNode for the swifterror virtual register. 1930 OutVals.push_back( 1931 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1932 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1933 EVT(TLI.getPointerTy(DL)))); 1934 } 1935 1936 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1937 CallingConv::ID CallConv = 1938 DAG.getMachineFunction().getFunction().getCallingConv(); 1939 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1940 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1941 1942 // Verify that the target's LowerReturn behaved as expected. 1943 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1944 "LowerReturn didn't return a valid chain!"); 1945 1946 // Update the DAG with the new chain value resulting from return lowering. 1947 DAG.setRoot(Chain); 1948 } 1949 1950 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1951 /// created for it, emit nodes to copy the value into the virtual 1952 /// registers. 1953 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1954 // Skip empty types 1955 if (V->getType()->isEmptyTy()) 1956 return; 1957 1958 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1959 if (VMI != FuncInfo.ValueMap.end()) { 1960 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1961 CopyValueToVirtualRegister(V, VMI->second); 1962 } 1963 } 1964 1965 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1966 /// the current basic block, add it to ValueMap now so that we'll get a 1967 /// CopyTo/FromReg. 1968 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1969 // No need to export constants. 1970 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1971 1972 // Already exported? 1973 if (FuncInfo.isExportedInst(V)) return; 1974 1975 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1976 CopyValueToVirtualRegister(V, Reg); 1977 } 1978 1979 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1980 const BasicBlock *FromBB) { 1981 // The operands of the setcc have to be in this block. We don't know 1982 // how to export them from some other block. 1983 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1984 // Can export from current BB. 1985 if (VI->getParent() == FromBB) 1986 return true; 1987 1988 // Is already exported, noop. 1989 return FuncInfo.isExportedInst(V); 1990 } 1991 1992 // If this is an argument, we can export it if the BB is the entry block or 1993 // if it is already exported. 1994 if (isa<Argument>(V)) { 1995 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1996 return true; 1997 1998 // Otherwise, can only export this if it is already exported. 1999 return FuncInfo.isExportedInst(V); 2000 } 2001 2002 // Otherwise, constants can always be exported. 2003 return true; 2004 } 2005 2006 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2007 BranchProbability 2008 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2009 const MachineBasicBlock *Dst) const { 2010 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2011 const BasicBlock *SrcBB = Src->getBasicBlock(); 2012 const BasicBlock *DstBB = Dst->getBasicBlock(); 2013 if (!BPI) { 2014 // If BPI is not available, set the default probability as 1 / N, where N is 2015 // the number of successors. 2016 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2017 return BranchProbability(1, SuccSize); 2018 } 2019 return BPI->getEdgeProbability(SrcBB, DstBB); 2020 } 2021 2022 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2023 MachineBasicBlock *Dst, 2024 BranchProbability Prob) { 2025 if (!FuncInfo.BPI) 2026 Src->addSuccessorWithoutProb(Dst); 2027 else { 2028 if (Prob.isUnknown()) 2029 Prob = getEdgeProbability(Src, Dst); 2030 Src->addSuccessor(Dst, Prob); 2031 } 2032 } 2033 2034 static bool InBlock(const Value *V, const BasicBlock *BB) { 2035 if (const Instruction *I = dyn_cast<Instruction>(V)) 2036 return I->getParent() == BB; 2037 return true; 2038 } 2039 2040 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2041 /// This function emits a branch and is used at the leaves of an OR or an 2042 /// AND operator tree. 2043 void 2044 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2045 MachineBasicBlock *TBB, 2046 MachineBasicBlock *FBB, 2047 MachineBasicBlock *CurBB, 2048 MachineBasicBlock *SwitchBB, 2049 BranchProbability TProb, 2050 BranchProbability FProb, 2051 bool InvertCond) { 2052 const BasicBlock *BB = CurBB->getBasicBlock(); 2053 2054 // If the leaf of the tree is a comparison, merge the condition into 2055 // the caseblock. 2056 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2057 // The operands of the cmp have to be in this block. We don't know 2058 // how to export them from some other block. If this is the first block 2059 // of the sequence, no exporting is needed. 2060 if (CurBB == SwitchBB || 2061 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2062 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2063 ISD::CondCode Condition; 2064 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2065 ICmpInst::Predicate Pred = 2066 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2067 Condition = getICmpCondCode(Pred); 2068 } else { 2069 const FCmpInst *FC = cast<FCmpInst>(Cond); 2070 FCmpInst::Predicate Pred = 2071 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2072 Condition = getFCmpCondCode(Pred); 2073 if (TM.Options.NoNaNsFPMath) 2074 Condition = getFCmpCodeWithoutNaN(Condition); 2075 } 2076 2077 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2078 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2079 SL->SwitchCases.push_back(CB); 2080 return; 2081 } 2082 } 2083 2084 // Create a CaseBlock record representing this branch. 2085 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2086 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2087 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2088 SL->SwitchCases.push_back(CB); 2089 } 2090 2091 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2092 MachineBasicBlock *TBB, 2093 MachineBasicBlock *FBB, 2094 MachineBasicBlock *CurBB, 2095 MachineBasicBlock *SwitchBB, 2096 Instruction::BinaryOps Opc, 2097 BranchProbability TProb, 2098 BranchProbability FProb, 2099 bool InvertCond) { 2100 // Skip over not part of the tree and remember to invert op and operands at 2101 // next level. 2102 Value *NotCond; 2103 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2104 InBlock(NotCond, CurBB->getBasicBlock())) { 2105 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2106 !InvertCond); 2107 return; 2108 } 2109 2110 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2111 // Compute the effective opcode for Cond, taking into account whether it needs 2112 // to be inverted, e.g. 2113 // and (not (or A, B)), C 2114 // gets lowered as 2115 // and (and (not A, not B), C) 2116 unsigned BOpc = 0; 2117 if (BOp) { 2118 BOpc = BOp->getOpcode(); 2119 if (InvertCond) { 2120 if (BOpc == Instruction::And) 2121 BOpc = Instruction::Or; 2122 else if (BOpc == Instruction::Or) 2123 BOpc = Instruction::And; 2124 } 2125 } 2126 2127 // If this node is not part of the or/and tree, emit it as a branch. 2128 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2129 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2130 BOp->getParent() != CurBB->getBasicBlock() || 2131 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2132 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2133 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2134 TProb, FProb, InvertCond); 2135 return; 2136 } 2137 2138 // Create TmpBB after CurBB. 2139 MachineFunction::iterator BBI(CurBB); 2140 MachineFunction &MF = DAG.getMachineFunction(); 2141 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2142 CurBB->getParent()->insert(++BBI, TmpBB); 2143 2144 if (Opc == Instruction::Or) { 2145 // Codegen X | Y as: 2146 // BB1: 2147 // jmp_if_X TBB 2148 // jmp TmpBB 2149 // TmpBB: 2150 // jmp_if_Y TBB 2151 // jmp FBB 2152 // 2153 2154 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2155 // The requirement is that 2156 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2157 // = TrueProb for original BB. 2158 // Assuming the original probabilities are A and B, one choice is to set 2159 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2160 // A/(1+B) and 2B/(1+B). This choice assumes that 2161 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2162 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2163 // TmpBB, but the math is more complicated. 2164 2165 auto NewTrueProb = TProb / 2; 2166 auto NewFalseProb = TProb / 2 + FProb; 2167 // Emit the LHS condition. 2168 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2169 NewTrueProb, NewFalseProb, InvertCond); 2170 2171 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2172 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2173 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2174 // Emit the RHS condition into TmpBB. 2175 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2176 Probs[0], Probs[1], InvertCond); 2177 } else { 2178 assert(Opc == Instruction::And && "Unknown merge op!"); 2179 // Codegen X & Y as: 2180 // BB1: 2181 // jmp_if_X TmpBB 2182 // jmp FBB 2183 // TmpBB: 2184 // jmp_if_Y TBB 2185 // jmp FBB 2186 // 2187 // This requires creation of TmpBB after CurBB. 2188 2189 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2190 // The requirement is that 2191 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2192 // = FalseProb for original BB. 2193 // Assuming the original probabilities are A and B, one choice is to set 2194 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2195 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2196 // TrueProb for BB1 * FalseProb for TmpBB. 2197 2198 auto NewTrueProb = TProb + FProb / 2; 2199 auto NewFalseProb = FProb / 2; 2200 // Emit the LHS condition. 2201 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2202 NewTrueProb, NewFalseProb, InvertCond); 2203 2204 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2205 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2206 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2207 // Emit the RHS condition into TmpBB. 2208 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2209 Probs[0], Probs[1], InvertCond); 2210 } 2211 } 2212 2213 /// If the set of cases should be emitted as a series of branches, return true. 2214 /// If we should emit this as a bunch of and/or'd together conditions, return 2215 /// false. 2216 bool 2217 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2218 if (Cases.size() != 2) return true; 2219 2220 // If this is two comparisons of the same values or'd or and'd together, they 2221 // will get folded into a single comparison, so don't emit two blocks. 2222 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2223 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2224 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2225 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2226 return false; 2227 } 2228 2229 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2230 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2231 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2232 Cases[0].CC == Cases[1].CC && 2233 isa<Constant>(Cases[0].CmpRHS) && 2234 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2235 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2236 return false; 2237 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2238 return false; 2239 } 2240 2241 return true; 2242 } 2243 2244 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2245 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2246 2247 // Update machine-CFG edges. 2248 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2249 2250 if (I.isUnconditional()) { 2251 // Update machine-CFG edges. 2252 BrMBB->addSuccessor(Succ0MBB); 2253 2254 // If this is not a fall-through branch or optimizations are switched off, 2255 // emit the branch. 2256 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2257 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2258 MVT::Other, getControlRoot(), 2259 DAG.getBasicBlock(Succ0MBB))); 2260 2261 return; 2262 } 2263 2264 // If this condition is one of the special cases we handle, do special stuff 2265 // now. 2266 const Value *CondVal = I.getCondition(); 2267 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2268 2269 // If this is a series of conditions that are or'd or and'd together, emit 2270 // this as a sequence of branches instead of setcc's with and/or operations. 2271 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2272 // unpredictable branches, and vector extracts because those jumps are likely 2273 // expensive for any target), this should improve performance. 2274 // For example, instead of something like: 2275 // cmp A, B 2276 // C = seteq 2277 // cmp D, E 2278 // F = setle 2279 // or C, F 2280 // jnz foo 2281 // Emit: 2282 // cmp A, B 2283 // je foo 2284 // cmp D, E 2285 // jle foo 2286 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2287 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2288 Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1); 2289 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2290 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2291 (Opcode == Instruction::And || Opcode == Instruction::Or) && 2292 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2293 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2294 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2295 Opcode, 2296 getEdgeProbability(BrMBB, Succ0MBB), 2297 getEdgeProbability(BrMBB, Succ1MBB), 2298 /*InvertCond=*/false); 2299 // If the compares in later blocks need to use values not currently 2300 // exported from this block, export them now. This block should always 2301 // be the first entry. 2302 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2303 2304 // Allow some cases to be rejected. 2305 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2306 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2307 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2308 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2309 } 2310 2311 // Emit the branch for this block. 2312 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2313 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2314 return; 2315 } 2316 2317 // Okay, we decided not to do this, remove any inserted MBB's and clear 2318 // SwitchCases. 2319 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2320 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2321 2322 SL->SwitchCases.clear(); 2323 } 2324 } 2325 2326 // Create a CaseBlock record representing this branch. 2327 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2328 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2329 2330 // Use visitSwitchCase to actually insert the fast branch sequence for this 2331 // cond branch. 2332 visitSwitchCase(CB, BrMBB); 2333 } 2334 2335 /// visitSwitchCase - Emits the necessary code to represent a single node in 2336 /// the binary search tree resulting from lowering a switch instruction. 2337 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2338 MachineBasicBlock *SwitchBB) { 2339 SDValue Cond; 2340 SDValue CondLHS = getValue(CB.CmpLHS); 2341 SDLoc dl = CB.DL; 2342 2343 if (CB.CC == ISD::SETTRUE) { 2344 // Branch or fall through to TrueBB. 2345 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2346 SwitchBB->normalizeSuccProbs(); 2347 if (CB.TrueBB != NextBlock(SwitchBB)) { 2348 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2349 DAG.getBasicBlock(CB.TrueBB))); 2350 } 2351 return; 2352 } 2353 2354 auto &TLI = DAG.getTargetLoweringInfo(); 2355 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2356 2357 // Build the setcc now. 2358 if (!CB.CmpMHS) { 2359 // Fold "(X == true)" to X and "(X == false)" to !X to 2360 // handle common cases produced by branch lowering. 2361 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2362 CB.CC == ISD::SETEQ) 2363 Cond = CondLHS; 2364 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2365 CB.CC == ISD::SETEQ) { 2366 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2367 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2368 } else { 2369 SDValue CondRHS = getValue(CB.CmpRHS); 2370 2371 // If a pointer's DAG type is larger than its memory type then the DAG 2372 // values are zero-extended. This breaks signed comparisons so truncate 2373 // back to the underlying type before doing the compare. 2374 if (CondLHS.getValueType() != MemVT) { 2375 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2376 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2377 } 2378 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2379 } 2380 } else { 2381 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2382 2383 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2384 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2385 2386 SDValue CmpOp = getValue(CB.CmpMHS); 2387 EVT VT = CmpOp.getValueType(); 2388 2389 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2390 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2391 ISD::SETLE); 2392 } else { 2393 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2394 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2395 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2396 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2397 } 2398 } 2399 2400 // Update successor info 2401 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2402 // TrueBB and FalseBB are always different unless the incoming IR is 2403 // degenerate. This only happens when running llc on weird IR. 2404 if (CB.TrueBB != CB.FalseBB) 2405 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2406 SwitchBB->normalizeSuccProbs(); 2407 2408 // If the lhs block is the next block, invert the condition so that we can 2409 // fall through to the lhs instead of the rhs block. 2410 if (CB.TrueBB == NextBlock(SwitchBB)) { 2411 std::swap(CB.TrueBB, CB.FalseBB); 2412 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2413 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2414 } 2415 2416 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2417 MVT::Other, getControlRoot(), Cond, 2418 DAG.getBasicBlock(CB.TrueBB)); 2419 2420 // Insert the false branch. Do this even if it's a fall through branch, 2421 // this makes it easier to do DAG optimizations which require inverting 2422 // the branch condition. 2423 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2424 DAG.getBasicBlock(CB.FalseBB)); 2425 2426 DAG.setRoot(BrCond); 2427 } 2428 2429 /// visitJumpTable - Emit JumpTable node in the current MBB 2430 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2431 // Emit the code for the jump table 2432 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2433 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2434 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2435 JT.Reg, PTy); 2436 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2437 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2438 MVT::Other, Index.getValue(1), 2439 Table, Index); 2440 DAG.setRoot(BrJumpTable); 2441 } 2442 2443 /// visitJumpTableHeader - This function emits necessary code to produce index 2444 /// in the JumpTable from switch case. 2445 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2446 JumpTableHeader &JTH, 2447 MachineBasicBlock *SwitchBB) { 2448 SDLoc dl = getCurSDLoc(); 2449 2450 // Subtract the lowest switch case value from the value being switched on. 2451 SDValue SwitchOp = getValue(JTH.SValue); 2452 EVT VT = SwitchOp.getValueType(); 2453 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2454 DAG.getConstant(JTH.First, dl, VT)); 2455 2456 // The SDNode we just created, which holds the value being switched on minus 2457 // the smallest case value, needs to be copied to a virtual register so it 2458 // can be used as an index into the jump table in a subsequent basic block. 2459 // This value may be smaller or larger than the target's pointer type, and 2460 // therefore require extension or truncating. 2461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2462 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2463 2464 unsigned JumpTableReg = 2465 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2466 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2467 JumpTableReg, SwitchOp); 2468 JT.Reg = JumpTableReg; 2469 2470 if (!JTH.OmitRangeCheck) { 2471 // Emit the range check for the jump table, and branch to the default block 2472 // for the switch statement if the value being switched on exceeds the 2473 // largest case in the switch. 2474 SDValue CMP = DAG.getSetCC( 2475 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2476 Sub.getValueType()), 2477 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2478 2479 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2480 MVT::Other, CopyTo, CMP, 2481 DAG.getBasicBlock(JT.Default)); 2482 2483 // Avoid emitting unnecessary branches to the next block. 2484 if (JT.MBB != NextBlock(SwitchBB)) 2485 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2486 DAG.getBasicBlock(JT.MBB)); 2487 2488 DAG.setRoot(BrCond); 2489 } else { 2490 // Avoid emitting unnecessary branches to the next block. 2491 if (JT.MBB != NextBlock(SwitchBB)) 2492 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2493 DAG.getBasicBlock(JT.MBB))); 2494 else 2495 DAG.setRoot(CopyTo); 2496 } 2497 } 2498 2499 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2500 /// variable if there exists one. 2501 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2502 SDValue &Chain) { 2503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2504 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2505 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2506 MachineFunction &MF = DAG.getMachineFunction(); 2507 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2508 MachineSDNode *Node = 2509 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2510 if (Global) { 2511 MachinePointerInfo MPInfo(Global); 2512 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2513 MachineMemOperand::MODereferenceable; 2514 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2515 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2516 DAG.setNodeMemRefs(Node, {MemRef}); 2517 } 2518 if (PtrTy != PtrMemTy) 2519 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2520 return SDValue(Node, 0); 2521 } 2522 2523 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2524 /// tail spliced into a stack protector check success bb. 2525 /// 2526 /// For a high level explanation of how this fits into the stack protector 2527 /// generation see the comment on the declaration of class 2528 /// StackProtectorDescriptor. 2529 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2530 MachineBasicBlock *ParentBB) { 2531 2532 // First create the loads to the guard/stack slot for the comparison. 2533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2534 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2535 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2536 2537 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2538 int FI = MFI.getStackProtectorIndex(); 2539 2540 SDValue Guard; 2541 SDLoc dl = getCurSDLoc(); 2542 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2543 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2544 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2545 2546 // Generate code to load the content of the guard slot. 2547 SDValue GuardVal = DAG.getLoad( 2548 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2549 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2550 MachineMemOperand::MOVolatile); 2551 2552 if (TLI.useStackGuardXorFP()) 2553 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2554 2555 // Retrieve guard check function, nullptr if instrumentation is inlined. 2556 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2557 // The target provides a guard check function to validate the guard value. 2558 // Generate a call to that function with the content of the guard slot as 2559 // argument. 2560 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2561 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2562 2563 TargetLowering::ArgListTy Args; 2564 TargetLowering::ArgListEntry Entry; 2565 Entry.Node = GuardVal; 2566 Entry.Ty = FnTy->getParamType(0); 2567 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2568 Entry.IsInReg = true; 2569 Args.push_back(Entry); 2570 2571 TargetLowering::CallLoweringInfo CLI(DAG); 2572 CLI.setDebugLoc(getCurSDLoc()) 2573 .setChain(DAG.getEntryNode()) 2574 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2575 getValue(GuardCheckFn), std::move(Args)); 2576 2577 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2578 DAG.setRoot(Result.second); 2579 return; 2580 } 2581 2582 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2583 // Otherwise, emit a volatile load to retrieve the stack guard value. 2584 SDValue Chain = DAG.getEntryNode(); 2585 if (TLI.useLoadStackGuardNode()) { 2586 Guard = getLoadStackGuard(DAG, dl, Chain); 2587 } else { 2588 const Value *IRGuard = TLI.getSDagStackGuard(M); 2589 SDValue GuardPtr = getValue(IRGuard); 2590 2591 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2592 MachinePointerInfo(IRGuard, 0), Align, 2593 MachineMemOperand::MOVolatile); 2594 } 2595 2596 // Perform the comparison via a getsetcc. 2597 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2598 *DAG.getContext(), 2599 Guard.getValueType()), 2600 Guard, GuardVal, ISD::SETNE); 2601 2602 // If the guard/stackslot do not equal, branch to failure MBB. 2603 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2604 MVT::Other, GuardVal.getOperand(0), 2605 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2606 // Otherwise branch to success MBB. 2607 SDValue Br = DAG.getNode(ISD::BR, dl, 2608 MVT::Other, BrCond, 2609 DAG.getBasicBlock(SPD.getSuccessMBB())); 2610 2611 DAG.setRoot(Br); 2612 } 2613 2614 /// Codegen the failure basic block for a stack protector check. 2615 /// 2616 /// A failure stack protector machine basic block consists simply of a call to 2617 /// __stack_chk_fail(). 2618 /// 2619 /// For a high level explanation of how this fits into the stack protector 2620 /// generation see the comment on the declaration of class 2621 /// StackProtectorDescriptor. 2622 void 2623 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2625 TargetLowering::MakeLibCallOptions CallOptions; 2626 CallOptions.setDiscardResult(true); 2627 SDValue Chain = 2628 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2629 None, CallOptions, getCurSDLoc()).second; 2630 // On PS4, the "return address" must still be within the calling function, 2631 // even if it's at the very end, so emit an explicit TRAP here. 2632 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2633 if (TM.getTargetTriple().isPS4CPU()) 2634 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2635 // WebAssembly needs an unreachable instruction after a non-returning call, 2636 // because the function return type can be different from __stack_chk_fail's 2637 // return type (void). 2638 if (TM.getTargetTriple().isWasm()) 2639 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2640 2641 DAG.setRoot(Chain); 2642 } 2643 2644 /// visitBitTestHeader - This function emits necessary code to produce value 2645 /// suitable for "bit tests" 2646 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2647 MachineBasicBlock *SwitchBB) { 2648 SDLoc dl = getCurSDLoc(); 2649 2650 // Subtract the minimum value. 2651 SDValue SwitchOp = getValue(B.SValue); 2652 EVT VT = SwitchOp.getValueType(); 2653 SDValue RangeSub = 2654 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2655 2656 // Determine the type of the test operands. 2657 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2658 bool UsePtrType = false; 2659 if (!TLI.isTypeLegal(VT)) { 2660 UsePtrType = true; 2661 } else { 2662 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2663 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2664 // Switch table case range are encoded into series of masks. 2665 // Just use pointer type, it's guaranteed to fit. 2666 UsePtrType = true; 2667 break; 2668 } 2669 } 2670 SDValue Sub = RangeSub; 2671 if (UsePtrType) { 2672 VT = TLI.getPointerTy(DAG.getDataLayout()); 2673 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2674 } 2675 2676 B.RegVT = VT.getSimpleVT(); 2677 B.Reg = FuncInfo.CreateReg(B.RegVT); 2678 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2679 2680 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2681 2682 if (!B.OmitRangeCheck) 2683 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2684 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2685 SwitchBB->normalizeSuccProbs(); 2686 2687 SDValue Root = CopyTo; 2688 if (!B.OmitRangeCheck) { 2689 // Conditional branch to the default block. 2690 SDValue RangeCmp = DAG.getSetCC(dl, 2691 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2692 RangeSub.getValueType()), 2693 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2694 ISD::SETUGT); 2695 2696 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2697 DAG.getBasicBlock(B.Default)); 2698 } 2699 2700 // Avoid emitting unnecessary branches to the next block. 2701 if (MBB != NextBlock(SwitchBB)) 2702 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2703 2704 DAG.setRoot(Root); 2705 } 2706 2707 /// visitBitTestCase - this function produces one "bit test" 2708 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2709 MachineBasicBlock* NextMBB, 2710 BranchProbability BranchProbToNext, 2711 unsigned Reg, 2712 BitTestCase &B, 2713 MachineBasicBlock *SwitchBB) { 2714 SDLoc dl = getCurSDLoc(); 2715 MVT VT = BB.RegVT; 2716 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2717 SDValue Cmp; 2718 unsigned PopCount = countPopulation(B.Mask); 2719 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2720 if (PopCount == 1) { 2721 // Testing for a single bit; just compare the shift count with what it 2722 // would need to be to shift a 1 bit in that position. 2723 Cmp = DAG.getSetCC( 2724 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2725 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2726 ISD::SETEQ); 2727 } else if (PopCount == BB.Range) { 2728 // There is only one zero bit in the range, test for it directly. 2729 Cmp = DAG.getSetCC( 2730 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2731 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2732 ISD::SETNE); 2733 } else { 2734 // Make desired shift 2735 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2736 DAG.getConstant(1, dl, VT), ShiftOp); 2737 2738 // Emit bit tests and jumps 2739 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2740 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2741 Cmp = DAG.getSetCC( 2742 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2743 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2744 } 2745 2746 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2747 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2748 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2749 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2750 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2751 // one as they are relative probabilities (and thus work more like weights), 2752 // and hence we need to normalize them to let the sum of them become one. 2753 SwitchBB->normalizeSuccProbs(); 2754 2755 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2756 MVT::Other, getControlRoot(), 2757 Cmp, DAG.getBasicBlock(B.TargetBB)); 2758 2759 // Avoid emitting unnecessary branches to the next block. 2760 if (NextMBB != NextBlock(SwitchBB)) 2761 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2762 DAG.getBasicBlock(NextMBB)); 2763 2764 DAG.setRoot(BrAnd); 2765 } 2766 2767 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2768 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2769 2770 // Retrieve successors. Look through artificial IR level blocks like 2771 // catchswitch for successors. 2772 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2773 const BasicBlock *EHPadBB = I.getSuccessor(1); 2774 2775 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2776 // have to do anything here to lower funclet bundles. 2777 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2778 LLVMContext::OB_gc_transition, 2779 LLVMContext::OB_gc_live, 2780 LLVMContext::OB_funclet, 2781 LLVMContext::OB_cfguardtarget}) && 2782 "Cannot lower invokes with arbitrary operand bundles yet!"); 2783 2784 const Value *Callee(I.getCalledOperand()); 2785 const Function *Fn = dyn_cast<Function>(Callee); 2786 if (isa<InlineAsm>(Callee)) 2787 visitInlineAsm(I); 2788 else if (Fn && Fn->isIntrinsic()) { 2789 switch (Fn->getIntrinsicID()) { 2790 default: 2791 llvm_unreachable("Cannot invoke this intrinsic"); 2792 case Intrinsic::donothing: 2793 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2794 break; 2795 case Intrinsic::experimental_patchpoint_void: 2796 case Intrinsic::experimental_patchpoint_i64: 2797 visitPatchpoint(I, EHPadBB); 2798 break; 2799 case Intrinsic::experimental_gc_statepoint: 2800 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2801 break; 2802 case Intrinsic::wasm_rethrow_in_catch: { 2803 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2804 // special because it can be invoked, so we manually lower it to a DAG 2805 // node here. 2806 SmallVector<SDValue, 8> Ops; 2807 Ops.push_back(getRoot()); // inchain 2808 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2809 Ops.push_back( 2810 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2811 TLI.getPointerTy(DAG.getDataLayout()))); 2812 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2813 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2814 break; 2815 } 2816 } 2817 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2818 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2819 // Eventually we will support lowering the @llvm.experimental.deoptimize 2820 // intrinsic, and right now there are no plans to support other intrinsics 2821 // with deopt state. 2822 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2823 } else { 2824 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2825 } 2826 2827 // If the value of the invoke is used outside of its defining block, make it 2828 // available as a virtual register. 2829 // We already took care of the exported value for the statepoint instruction 2830 // during call to the LowerStatepoint. 2831 if (!isa<GCStatepointInst>(I)) { 2832 CopyToExportRegsIfNeeded(&I); 2833 } 2834 2835 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2836 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2837 BranchProbability EHPadBBProb = 2838 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2839 : BranchProbability::getZero(); 2840 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2841 2842 // Update successor info. 2843 addSuccessorWithProb(InvokeMBB, Return); 2844 for (auto &UnwindDest : UnwindDests) { 2845 UnwindDest.first->setIsEHPad(); 2846 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2847 } 2848 InvokeMBB->normalizeSuccProbs(); 2849 2850 // Drop into normal successor. 2851 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2852 DAG.getBasicBlock(Return))); 2853 } 2854 2855 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2856 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2857 2858 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2859 // have to do anything here to lower funclet bundles. 2860 assert(!I.hasOperandBundlesOtherThan( 2861 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2862 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2863 2864 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2865 visitInlineAsm(I); 2866 CopyToExportRegsIfNeeded(&I); 2867 2868 // Retrieve successors. 2869 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2870 2871 // Update successor info. 2872 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2873 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2874 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2875 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2876 Target->setIsInlineAsmBrIndirectTarget(); 2877 } 2878 CallBrMBB->normalizeSuccProbs(); 2879 2880 // Drop into default successor. 2881 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2882 MVT::Other, getControlRoot(), 2883 DAG.getBasicBlock(Return))); 2884 } 2885 2886 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2887 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2888 } 2889 2890 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2891 assert(FuncInfo.MBB->isEHPad() && 2892 "Call to landingpad not in landing pad!"); 2893 2894 // If there aren't registers to copy the values into (e.g., during SjLj 2895 // exceptions), then don't bother to create these DAG nodes. 2896 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2897 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2898 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2899 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2900 return; 2901 2902 // If landingpad's return type is token type, we don't create DAG nodes 2903 // for its exception pointer and selector value. The extraction of exception 2904 // pointer or selector value from token type landingpads is not currently 2905 // supported. 2906 if (LP.getType()->isTokenTy()) 2907 return; 2908 2909 SmallVector<EVT, 2> ValueVTs; 2910 SDLoc dl = getCurSDLoc(); 2911 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2912 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2913 2914 // Get the two live-in registers as SDValues. The physregs have already been 2915 // copied into virtual registers. 2916 SDValue Ops[2]; 2917 if (FuncInfo.ExceptionPointerVirtReg) { 2918 Ops[0] = DAG.getZExtOrTrunc( 2919 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2920 FuncInfo.ExceptionPointerVirtReg, 2921 TLI.getPointerTy(DAG.getDataLayout())), 2922 dl, ValueVTs[0]); 2923 } else { 2924 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2925 } 2926 Ops[1] = DAG.getZExtOrTrunc( 2927 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2928 FuncInfo.ExceptionSelectorVirtReg, 2929 TLI.getPointerTy(DAG.getDataLayout())), 2930 dl, ValueVTs[1]); 2931 2932 // Merge into one. 2933 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2934 DAG.getVTList(ValueVTs), Ops); 2935 setValue(&LP, Res); 2936 } 2937 2938 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2939 MachineBasicBlock *Last) { 2940 // Update JTCases. 2941 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2942 if (SL->JTCases[i].first.HeaderBB == First) 2943 SL->JTCases[i].first.HeaderBB = Last; 2944 2945 // Update BitTestCases. 2946 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2947 if (SL->BitTestCases[i].Parent == First) 2948 SL->BitTestCases[i].Parent = Last; 2949 } 2950 2951 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2952 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2953 2954 // Update machine-CFG edges with unique successors. 2955 SmallSet<BasicBlock*, 32> Done; 2956 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2957 BasicBlock *BB = I.getSuccessor(i); 2958 bool Inserted = Done.insert(BB).second; 2959 if (!Inserted) 2960 continue; 2961 2962 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2963 addSuccessorWithProb(IndirectBrMBB, Succ); 2964 } 2965 IndirectBrMBB->normalizeSuccProbs(); 2966 2967 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2968 MVT::Other, getControlRoot(), 2969 getValue(I.getAddress()))); 2970 } 2971 2972 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2973 if (!DAG.getTarget().Options.TrapUnreachable) 2974 return; 2975 2976 // We may be able to ignore unreachable behind a noreturn call. 2977 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2978 const BasicBlock &BB = *I.getParent(); 2979 if (&I != &BB.front()) { 2980 BasicBlock::const_iterator PredI = 2981 std::prev(BasicBlock::const_iterator(&I)); 2982 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2983 if (Call->doesNotReturn()) 2984 return; 2985 } 2986 } 2987 } 2988 2989 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2990 } 2991 2992 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2993 SDNodeFlags Flags; 2994 2995 SDValue Op = getValue(I.getOperand(0)); 2996 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2997 Op, Flags); 2998 setValue(&I, UnNodeValue); 2999 } 3000 3001 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3002 SDNodeFlags Flags; 3003 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3004 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3005 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3006 } 3007 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3008 Flags.setExact(ExactOp->isExact()); 3009 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3010 Flags.copyFMF(*FPOp); 3011 3012 SDValue Op1 = getValue(I.getOperand(0)); 3013 SDValue Op2 = getValue(I.getOperand(1)); 3014 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3015 Op1, Op2, Flags); 3016 setValue(&I, BinNodeValue); 3017 } 3018 3019 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3020 SDValue Op1 = getValue(I.getOperand(0)); 3021 SDValue Op2 = getValue(I.getOperand(1)); 3022 3023 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3024 Op1.getValueType(), DAG.getDataLayout()); 3025 3026 // Coerce the shift amount to the right type if we can. 3027 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3028 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3029 unsigned Op2Size = Op2.getValueSizeInBits(); 3030 SDLoc DL = getCurSDLoc(); 3031 3032 // If the operand is smaller than the shift count type, promote it. 3033 if (ShiftSize > Op2Size) 3034 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3035 3036 // If the operand is larger than the shift count type but the shift 3037 // count type has enough bits to represent any shift value, truncate 3038 // it now. This is a common case and it exposes the truncate to 3039 // optimization early. 3040 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3041 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3042 // Otherwise we'll need to temporarily settle for some other convenient 3043 // type. Type legalization will make adjustments once the shiftee is split. 3044 else 3045 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3046 } 3047 3048 bool nuw = false; 3049 bool nsw = false; 3050 bool exact = false; 3051 3052 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3053 3054 if (const OverflowingBinaryOperator *OFBinOp = 3055 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3056 nuw = OFBinOp->hasNoUnsignedWrap(); 3057 nsw = OFBinOp->hasNoSignedWrap(); 3058 } 3059 if (const PossiblyExactOperator *ExactOp = 3060 dyn_cast<const PossiblyExactOperator>(&I)) 3061 exact = ExactOp->isExact(); 3062 } 3063 SDNodeFlags Flags; 3064 Flags.setExact(exact); 3065 Flags.setNoSignedWrap(nsw); 3066 Flags.setNoUnsignedWrap(nuw); 3067 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3068 Flags); 3069 setValue(&I, Res); 3070 } 3071 3072 void SelectionDAGBuilder::visitSDiv(const User &I) { 3073 SDValue Op1 = getValue(I.getOperand(0)); 3074 SDValue Op2 = getValue(I.getOperand(1)); 3075 3076 SDNodeFlags Flags; 3077 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3078 cast<PossiblyExactOperator>(&I)->isExact()); 3079 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3080 Op2, Flags)); 3081 } 3082 3083 void SelectionDAGBuilder::visitICmp(const User &I) { 3084 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3085 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3086 predicate = IC->getPredicate(); 3087 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3088 predicate = ICmpInst::Predicate(IC->getPredicate()); 3089 SDValue Op1 = getValue(I.getOperand(0)); 3090 SDValue Op2 = getValue(I.getOperand(1)); 3091 ISD::CondCode Opcode = getICmpCondCode(predicate); 3092 3093 auto &TLI = DAG.getTargetLoweringInfo(); 3094 EVT MemVT = 3095 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3096 3097 // If a pointer's DAG type is larger than its memory type then the DAG values 3098 // are zero-extended. This breaks signed comparisons so truncate back to the 3099 // underlying type before doing the compare. 3100 if (Op1.getValueType() != MemVT) { 3101 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3102 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3103 } 3104 3105 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3106 I.getType()); 3107 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3108 } 3109 3110 void SelectionDAGBuilder::visitFCmp(const User &I) { 3111 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3112 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3113 predicate = FC->getPredicate(); 3114 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3115 predicate = FCmpInst::Predicate(FC->getPredicate()); 3116 SDValue Op1 = getValue(I.getOperand(0)); 3117 SDValue Op2 = getValue(I.getOperand(1)); 3118 3119 ISD::CondCode Condition = getFCmpCondCode(predicate); 3120 auto *FPMO = cast<FPMathOperator>(&I); 3121 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3122 Condition = getFCmpCodeWithoutNaN(Condition); 3123 3124 SDNodeFlags Flags; 3125 Flags.copyFMF(*FPMO); 3126 3127 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3128 I.getType()); 3129 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition, Flags)); 3130 } 3131 3132 // Check if the condition of the select has one use or two users that are both 3133 // selects with the same condition. 3134 static bool hasOnlySelectUsers(const Value *Cond) { 3135 return llvm::all_of(Cond->users(), [](const Value *V) { 3136 return isa<SelectInst>(V); 3137 }); 3138 } 3139 3140 void SelectionDAGBuilder::visitSelect(const User &I) { 3141 SmallVector<EVT, 4> ValueVTs; 3142 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3143 ValueVTs); 3144 unsigned NumValues = ValueVTs.size(); 3145 if (NumValues == 0) return; 3146 3147 SmallVector<SDValue, 4> Values(NumValues); 3148 SDValue Cond = getValue(I.getOperand(0)); 3149 SDValue LHSVal = getValue(I.getOperand(1)); 3150 SDValue RHSVal = getValue(I.getOperand(2)); 3151 SmallVector<SDValue, 1> BaseOps(1, Cond); 3152 ISD::NodeType OpCode = 3153 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3154 3155 bool IsUnaryAbs = false; 3156 3157 SDNodeFlags Flags; 3158 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3159 Flags.copyFMF(*FPOp); 3160 3161 // Min/max matching is only viable if all output VTs are the same. 3162 if (is_splat(ValueVTs)) { 3163 EVT VT = ValueVTs[0]; 3164 LLVMContext &Ctx = *DAG.getContext(); 3165 auto &TLI = DAG.getTargetLoweringInfo(); 3166 3167 // We care about the legality of the operation after it has been type 3168 // legalized. 3169 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3170 VT = TLI.getTypeToTransformTo(Ctx, VT); 3171 3172 // If the vselect is legal, assume we want to leave this as a vector setcc + 3173 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3174 // min/max is legal on the scalar type. 3175 bool UseScalarMinMax = VT.isVector() && 3176 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3177 3178 Value *LHS, *RHS; 3179 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3180 ISD::NodeType Opc = ISD::DELETED_NODE; 3181 switch (SPR.Flavor) { 3182 case SPF_UMAX: Opc = ISD::UMAX; break; 3183 case SPF_UMIN: Opc = ISD::UMIN; break; 3184 case SPF_SMAX: Opc = ISD::SMAX; break; 3185 case SPF_SMIN: Opc = ISD::SMIN; break; 3186 case SPF_FMINNUM: 3187 switch (SPR.NaNBehavior) { 3188 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3189 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3190 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3191 case SPNB_RETURNS_ANY: { 3192 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3193 Opc = ISD::FMINNUM; 3194 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3195 Opc = ISD::FMINIMUM; 3196 else if (UseScalarMinMax) 3197 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3198 ISD::FMINNUM : ISD::FMINIMUM; 3199 break; 3200 } 3201 } 3202 break; 3203 case SPF_FMAXNUM: 3204 switch (SPR.NaNBehavior) { 3205 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3206 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3207 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3208 case SPNB_RETURNS_ANY: 3209 3210 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3211 Opc = ISD::FMAXNUM; 3212 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3213 Opc = ISD::FMAXIMUM; 3214 else if (UseScalarMinMax) 3215 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3216 ISD::FMAXNUM : ISD::FMAXIMUM; 3217 break; 3218 } 3219 break; 3220 case SPF_ABS: 3221 IsUnaryAbs = true; 3222 Opc = ISD::ABS; 3223 break; 3224 case SPF_NABS: 3225 // TODO: we need to produce sub(0, abs(X)). 3226 default: break; 3227 } 3228 3229 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3230 (TLI.isOperationLegalOrCustom(Opc, VT) || 3231 (UseScalarMinMax && 3232 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3233 // If the underlying comparison instruction is used by any other 3234 // instruction, the consumed instructions won't be destroyed, so it is 3235 // not profitable to convert to a min/max. 3236 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3237 OpCode = Opc; 3238 LHSVal = getValue(LHS); 3239 RHSVal = getValue(RHS); 3240 BaseOps.clear(); 3241 } 3242 3243 if (IsUnaryAbs) { 3244 OpCode = Opc; 3245 LHSVal = getValue(LHS); 3246 BaseOps.clear(); 3247 } 3248 } 3249 3250 if (IsUnaryAbs) { 3251 for (unsigned i = 0; i != NumValues; ++i) { 3252 Values[i] = 3253 DAG.getNode(OpCode, getCurSDLoc(), 3254 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3255 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3256 } 3257 } else { 3258 for (unsigned i = 0; i != NumValues; ++i) { 3259 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3260 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3261 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3262 Values[i] = DAG.getNode( 3263 OpCode, getCurSDLoc(), 3264 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3265 } 3266 } 3267 3268 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3269 DAG.getVTList(ValueVTs), Values)); 3270 } 3271 3272 void SelectionDAGBuilder::visitTrunc(const User &I) { 3273 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3274 SDValue N = getValue(I.getOperand(0)); 3275 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3276 I.getType()); 3277 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3278 } 3279 3280 void SelectionDAGBuilder::visitZExt(const User &I) { 3281 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3282 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3283 SDValue N = getValue(I.getOperand(0)); 3284 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3285 I.getType()); 3286 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3287 } 3288 3289 void SelectionDAGBuilder::visitSExt(const User &I) { 3290 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3291 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3292 SDValue N = getValue(I.getOperand(0)); 3293 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3294 I.getType()); 3295 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3296 } 3297 3298 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3299 // FPTrunc is never a no-op cast, no need to check 3300 SDValue N = getValue(I.getOperand(0)); 3301 SDLoc dl = getCurSDLoc(); 3302 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3303 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3304 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3305 DAG.getTargetConstant( 3306 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3307 } 3308 3309 void SelectionDAGBuilder::visitFPExt(const User &I) { 3310 // FPExt is never a no-op cast, no need to check 3311 SDValue N = getValue(I.getOperand(0)); 3312 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3313 I.getType()); 3314 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3315 } 3316 3317 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3318 // FPToUI is never a no-op cast, no need to check 3319 SDValue N = getValue(I.getOperand(0)); 3320 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3321 I.getType()); 3322 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3323 } 3324 3325 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3326 // FPToSI is never a no-op cast, no need to check 3327 SDValue N = getValue(I.getOperand(0)); 3328 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3329 I.getType()); 3330 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3331 } 3332 3333 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3334 // UIToFP is never a no-op cast, no need to check 3335 SDValue N = getValue(I.getOperand(0)); 3336 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3337 I.getType()); 3338 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3339 } 3340 3341 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3342 // SIToFP is never a no-op cast, no need to check 3343 SDValue N = getValue(I.getOperand(0)); 3344 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3345 I.getType()); 3346 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3347 } 3348 3349 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3350 // What to do depends on the size of the integer and the size of the pointer. 3351 // We can either truncate, zero extend, or no-op, accordingly. 3352 SDValue N = getValue(I.getOperand(0)); 3353 auto &TLI = DAG.getTargetLoweringInfo(); 3354 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3355 I.getType()); 3356 EVT PtrMemVT = 3357 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3358 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3359 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3360 setValue(&I, N); 3361 } 3362 3363 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3364 // What to do depends on the size of the integer and the size of the pointer. 3365 // We can either truncate, zero extend, or no-op, accordingly. 3366 SDValue N = getValue(I.getOperand(0)); 3367 auto &TLI = DAG.getTargetLoweringInfo(); 3368 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3369 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3370 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3371 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3372 setValue(&I, N); 3373 } 3374 3375 void SelectionDAGBuilder::visitBitCast(const User &I) { 3376 SDValue N = getValue(I.getOperand(0)); 3377 SDLoc dl = getCurSDLoc(); 3378 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3379 I.getType()); 3380 3381 // BitCast assures us that source and destination are the same size so this is 3382 // either a BITCAST or a no-op. 3383 if (DestVT != N.getValueType()) 3384 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3385 DestVT, N)); // convert types. 3386 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3387 // might fold any kind of constant expression to an integer constant and that 3388 // is not what we are looking for. Only recognize a bitcast of a genuine 3389 // constant integer as an opaque constant. 3390 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3391 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3392 /*isOpaque*/true)); 3393 else 3394 setValue(&I, N); // noop cast. 3395 } 3396 3397 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3398 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3399 const Value *SV = I.getOperand(0); 3400 SDValue N = getValue(SV); 3401 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3402 3403 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3404 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3405 3406 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3407 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3408 3409 setValue(&I, N); 3410 } 3411 3412 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3413 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3414 SDValue InVec = getValue(I.getOperand(0)); 3415 SDValue InVal = getValue(I.getOperand(1)); 3416 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3417 TLI.getVectorIdxTy(DAG.getDataLayout())); 3418 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3419 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3420 InVec, InVal, InIdx)); 3421 } 3422 3423 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3424 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3425 SDValue InVec = getValue(I.getOperand(0)); 3426 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3427 TLI.getVectorIdxTy(DAG.getDataLayout())); 3428 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3429 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3430 InVec, InIdx)); 3431 } 3432 3433 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3434 SDValue Src1 = getValue(I.getOperand(0)); 3435 SDValue Src2 = getValue(I.getOperand(1)); 3436 ArrayRef<int> Mask; 3437 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3438 Mask = SVI->getShuffleMask(); 3439 else 3440 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3441 SDLoc DL = getCurSDLoc(); 3442 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3443 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3444 EVT SrcVT = Src1.getValueType(); 3445 3446 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3447 VT.isScalableVector()) { 3448 // Canonical splat form of first element of first input vector. 3449 SDValue FirstElt = 3450 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3451 DAG.getVectorIdxConstant(0, DL)); 3452 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3453 return; 3454 } 3455 3456 // For now, we only handle splats for scalable vectors. 3457 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3458 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3459 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3460 3461 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3462 unsigned MaskNumElts = Mask.size(); 3463 3464 if (SrcNumElts == MaskNumElts) { 3465 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3466 return; 3467 } 3468 3469 // Normalize the shuffle vector since mask and vector length don't match. 3470 if (SrcNumElts < MaskNumElts) { 3471 // Mask is longer than the source vectors. We can use concatenate vector to 3472 // make the mask and vectors lengths match. 3473 3474 if (MaskNumElts % SrcNumElts == 0) { 3475 // Mask length is a multiple of the source vector length. 3476 // Check if the shuffle is some kind of concatenation of the input 3477 // vectors. 3478 unsigned NumConcat = MaskNumElts / SrcNumElts; 3479 bool IsConcat = true; 3480 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3481 for (unsigned i = 0; i != MaskNumElts; ++i) { 3482 int Idx = Mask[i]; 3483 if (Idx < 0) 3484 continue; 3485 // Ensure the indices in each SrcVT sized piece are sequential and that 3486 // the same source is used for the whole piece. 3487 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3488 (ConcatSrcs[i / SrcNumElts] >= 0 && 3489 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3490 IsConcat = false; 3491 break; 3492 } 3493 // Remember which source this index came from. 3494 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3495 } 3496 3497 // The shuffle is concatenating multiple vectors together. Just emit 3498 // a CONCAT_VECTORS operation. 3499 if (IsConcat) { 3500 SmallVector<SDValue, 8> ConcatOps; 3501 for (auto Src : ConcatSrcs) { 3502 if (Src < 0) 3503 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3504 else if (Src == 0) 3505 ConcatOps.push_back(Src1); 3506 else 3507 ConcatOps.push_back(Src2); 3508 } 3509 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3510 return; 3511 } 3512 } 3513 3514 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3515 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3516 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3517 PaddedMaskNumElts); 3518 3519 // Pad both vectors with undefs to make them the same length as the mask. 3520 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3521 3522 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3523 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3524 MOps1[0] = Src1; 3525 MOps2[0] = Src2; 3526 3527 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3528 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3529 3530 // Readjust mask for new input vector length. 3531 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3532 for (unsigned i = 0; i != MaskNumElts; ++i) { 3533 int Idx = Mask[i]; 3534 if (Idx >= (int)SrcNumElts) 3535 Idx -= SrcNumElts - PaddedMaskNumElts; 3536 MappedOps[i] = Idx; 3537 } 3538 3539 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3540 3541 // If the concatenated vector was padded, extract a subvector with the 3542 // correct number of elements. 3543 if (MaskNumElts != PaddedMaskNumElts) 3544 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3545 DAG.getVectorIdxConstant(0, DL)); 3546 3547 setValue(&I, Result); 3548 return; 3549 } 3550 3551 if (SrcNumElts > MaskNumElts) { 3552 // Analyze the access pattern of the vector to see if we can extract 3553 // two subvectors and do the shuffle. 3554 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3555 bool CanExtract = true; 3556 for (int Idx : Mask) { 3557 unsigned Input = 0; 3558 if (Idx < 0) 3559 continue; 3560 3561 if (Idx >= (int)SrcNumElts) { 3562 Input = 1; 3563 Idx -= SrcNumElts; 3564 } 3565 3566 // If all the indices come from the same MaskNumElts sized portion of 3567 // the sources we can use extract. Also make sure the extract wouldn't 3568 // extract past the end of the source. 3569 int NewStartIdx = alignDown(Idx, MaskNumElts); 3570 if (NewStartIdx + MaskNumElts > SrcNumElts || 3571 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3572 CanExtract = false; 3573 // Make sure we always update StartIdx as we use it to track if all 3574 // elements are undef. 3575 StartIdx[Input] = NewStartIdx; 3576 } 3577 3578 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3579 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3580 return; 3581 } 3582 if (CanExtract) { 3583 // Extract appropriate subvector and generate a vector shuffle 3584 for (unsigned Input = 0; Input < 2; ++Input) { 3585 SDValue &Src = Input == 0 ? Src1 : Src2; 3586 if (StartIdx[Input] < 0) 3587 Src = DAG.getUNDEF(VT); 3588 else { 3589 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3590 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3591 } 3592 } 3593 3594 // Calculate new mask. 3595 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3596 for (int &Idx : MappedOps) { 3597 if (Idx >= (int)SrcNumElts) 3598 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3599 else if (Idx >= 0) 3600 Idx -= StartIdx[0]; 3601 } 3602 3603 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3604 return; 3605 } 3606 } 3607 3608 // We can't use either concat vectors or extract subvectors so fall back to 3609 // replacing the shuffle with extract and build vector. 3610 // to insert and build vector. 3611 EVT EltVT = VT.getVectorElementType(); 3612 SmallVector<SDValue,8> Ops; 3613 for (int Idx : Mask) { 3614 SDValue Res; 3615 3616 if (Idx < 0) { 3617 Res = DAG.getUNDEF(EltVT); 3618 } else { 3619 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3620 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3621 3622 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3623 DAG.getVectorIdxConstant(Idx, DL)); 3624 } 3625 3626 Ops.push_back(Res); 3627 } 3628 3629 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3630 } 3631 3632 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3633 ArrayRef<unsigned> Indices; 3634 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3635 Indices = IV->getIndices(); 3636 else 3637 Indices = cast<ConstantExpr>(&I)->getIndices(); 3638 3639 const Value *Op0 = I.getOperand(0); 3640 const Value *Op1 = I.getOperand(1); 3641 Type *AggTy = I.getType(); 3642 Type *ValTy = Op1->getType(); 3643 bool IntoUndef = isa<UndefValue>(Op0); 3644 bool FromUndef = isa<UndefValue>(Op1); 3645 3646 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3647 3648 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3649 SmallVector<EVT, 4> AggValueVTs; 3650 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3651 SmallVector<EVT, 4> ValValueVTs; 3652 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3653 3654 unsigned NumAggValues = AggValueVTs.size(); 3655 unsigned NumValValues = ValValueVTs.size(); 3656 SmallVector<SDValue, 4> Values(NumAggValues); 3657 3658 // Ignore an insertvalue that produces an empty object 3659 if (!NumAggValues) { 3660 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3661 return; 3662 } 3663 3664 SDValue Agg = getValue(Op0); 3665 unsigned i = 0; 3666 // Copy the beginning value(s) from the original aggregate. 3667 for (; i != LinearIndex; ++i) 3668 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3669 SDValue(Agg.getNode(), Agg.getResNo() + i); 3670 // Copy values from the inserted value(s). 3671 if (NumValValues) { 3672 SDValue Val = getValue(Op1); 3673 for (; i != LinearIndex + NumValValues; ++i) 3674 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3675 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3676 } 3677 // Copy remaining value(s) from the original aggregate. 3678 for (; i != NumAggValues; ++i) 3679 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3680 SDValue(Agg.getNode(), Agg.getResNo() + i); 3681 3682 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3683 DAG.getVTList(AggValueVTs), Values)); 3684 } 3685 3686 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3687 ArrayRef<unsigned> Indices; 3688 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3689 Indices = EV->getIndices(); 3690 else 3691 Indices = cast<ConstantExpr>(&I)->getIndices(); 3692 3693 const Value *Op0 = I.getOperand(0); 3694 Type *AggTy = Op0->getType(); 3695 Type *ValTy = I.getType(); 3696 bool OutOfUndef = isa<UndefValue>(Op0); 3697 3698 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3699 3700 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3701 SmallVector<EVT, 4> ValValueVTs; 3702 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3703 3704 unsigned NumValValues = ValValueVTs.size(); 3705 3706 // Ignore a extractvalue that produces an empty object 3707 if (!NumValValues) { 3708 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3709 return; 3710 } 3711 3712 SmallVector<SDValue, 4> Values(NumValValues); 3713 3714 SDValue Agg = getValue(Op0); 3715 // Copy out the selected value(s). 3716 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3717 Values[i - LinearIndex] = 3718 OutOfUndef ? 3719 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3720 SDValue(Agg.getNode(), Agg.getResNo() + i); 3721 3722 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3723 DAG.getVTList(ValValueVTs), Values)); 3724 } 3725 3726 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3727 Value *Op0 = I.getOperand(0); 3728 // Note that the pointer operand may be a vector of pointers. Take the scalar 3729 // element which holds a pointer. 3730 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3731 SDValue N = getValue(Op0); 3732 SDLoc dl = getCurSDLoc(); 3733 auto &TLI = DAG.getTargetLoweringInfo(); 3734 3735 // Normalize Vector GEP - all scalar operands should be converted to the 3736 // splat vector. 3737 bool IsVectorGEP = I.getType()->isVectorTy(); 3738 ElementCount VectorElementCount = 3739 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3740 : ElementCount::getFixed(0); 3741 3742 if (IsVectorGEP && !N.getValueType().isVector()) { 3743 LLVMContext &Context = *DAG.getContext(); 3744 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3745 if (VectorElementCount.isScalable()) 3746 N = DAG.getSplatVector(VT, dl, N); 3747 else 3748 N = DAG.getSplatBuildVector(VT, dl, N); 3749 } 3750 3751 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3752 GTI != E; ++GTI) { 3753 const Value *Idx = GTI.getOperand(); 3754 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3755 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3756 if (Field) { 3757 // N = N + Offset 3758 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3759 3760 // In an inbounds GEP with an offset that is nonnegative even when 3761 // interpreted as signed, assume there is no unsigned overflow. 3762 SDNodeFlags Flags; 3763 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3764 Flags.setNoUnsignedWrap(true); 3765 3766 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3767 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3768 } 3769 } else { 3770 // IdxSize is the width of the arithmetic according to IR semantics. 3771 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3772 // (and fix up the result later). 3773 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3774 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3775 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3776 // We intentionally mask away the high bits here; ElementSize may not 3777 // fit in IdxTy. 3778 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3779 bool ElementScalable = ElementSize.isScalable(); 3780 3781 // If this is a scalar constant or a splat vector of constants, 3782 // handle it quickly. 3783 const auto *C = dyn_cast<Constant>(Idx); 3784 if (C && isa<VectorType>(C->getType())) 3785 C = C->getSplatValue(); 3786 3787 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3788 if (CI && CI->isZero()) 3789 continue; 3790 if (CI && !ElementScalable) { 3791 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3792 LLVMContext &Context = *DAG.getContext(); 3793 SDValue OffsVal; 3794 if (IsVectorGEP) 3795 OffsVal = DAG.getConstant( 3796 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3797 else 3798 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3799 3800 // In an inbounds GEP with an offset that is nonnegative even when 3801 // interpreted as signed, assume there is no unsigned overflow. 3802 SDNodeFlags Flags; 3803 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3804 Flags.setNoUnsignedWrap(true); 3805 3806 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3807 3808 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3809 continue; 3810 } 3811 3812 // N = N + Idx * ElementMul; 3813 SDValue IdxN = getValue(Idx); 3814 3815 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3816 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3817 VectorElementCount); 3818 if (VectorElementCount.isScalable()) 3819 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3820 else 3821 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3822 } 3823 3824 // If the index is smaller or larger than intptr_t, truncate or extend 3825 // it. 3826 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3827 3828 if (ElementScalable) { 3829 EVT VScaleTy = N.getValueType().getScalarType(); 3830 SDValue VScale = DAG.getNode( 3831 ISD::VSCALE, dl, VScaleTy, 3832 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3833 if (IsVectorGEP) 3834 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3835 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3836 } else { 3837 // If this is a multiply by a power of two, turn it into a shl 3838 // immediately. This is a very common case. 3839 if (ElementMul != 1) { 3840 if (ElementMul.isPowerOf2()) { 3841 unsigned Amt = ElementMul.logBase2(); 3842 IdxN = DAG.getNode(ISD::SHL, dl, 3843 N.getValueType(), IdxN, 3844 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3845 } else { 3846 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3847 IdxN.getValueType()); 3848 IdxN = DAG.getNode(ISD::MUL, dl, 3849 N.getValueType(), IdxN, Scale); 3850 } 3851 } 3852 } 3853 3854 N = DAG.getNode(ISD::ADD, dl, 3855 N.getValueType(), N, IdxN); 3856 } 3857 } 3858 3859 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3860 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3861 if (IsVectorGEP) { 3862 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3863 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3864 } 3865 3866 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3867 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3868 3869 setValue(&I, N); 3870 } 3871 3872 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3873 // If this is a fixed sized alloca in the entry block of the function, 3874 // allocate it statically on the stack. 3875 if (FuncInfo.StaticAllocaMap.count(&I)) 3876 return; // getValue will auto-populate this. 3877 3878 SDLoc dl = getCurSDLoc(); 3879 Type *Ty = I.getAllocatedType(); 3880 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3881 auto &DL = DAG.getDataLayout(); 3882 uint64_t TySize = DL.getTypeAllocSize(Ty); 3883 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3884 3885 SDValue AllocSize = getValue(I.getArraySize()); 3886 3887 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3888 if (AllocSize.getValueType() != IntPtr) 3889 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3890 3891 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3892 AllocSize, 3893 DAG.getConstant(TySize, dl, IntPtr)); 3894 3895 // Handle alignment. If the requested alignment is less than or equal to 3896 // the stack alignment, ignore it. If the size is greater than or equal to 3897 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3898 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3899 if (*Alignment <= StackAlign) 3900 Alignment = None; 3901 3902 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3903 // Round the size of the allocation up to the stack alignment size 3904 // by add SA-1 to the size. This doesn't overflow because we're computing 3905 // an address inside an alloca. 3906 SDNodeFlags Flags; 3907 Flags.setNoUnsignedWrap(true); 3908 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3909 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3910 3911 // Mask out the low bits for alignment purposes. 3912 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3913 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3914 3915 SDValue Ops[] = { 3916 getRoot(), AllocSize, 3917 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3918 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3919 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3920 setValue(&I, DSA); 3921 DAG.setRoot(DSA.getValue(1)); 3922 3923 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3924 } 3925 3926 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3927 if (I.isAtomic()) 3928 return visitAtomicLoad(I); 3929 3930 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3931 const Value *SV = I.getOperand(0); 3932 if (TLI.supportSwiftError()) { 3933 // Swifterror values can come from either a function parameter with 3934 // swifterror attribute or an alloca with swifterror attribute. 3935 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3936 if (Arg->hasSwiftErrorAttr()) 3937 return visitLoadFromSwiftError(I); 3938 } 3939 3940 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3941 if (Alloca->isSwiftError()) 3942 return visitLoadFromSwiftError(I); 3943 } 3944 } 3945 3946 SDValue Ptr = getValue(SV); 3947 3948 Type *Ty = I.getType(); 3949 Align Alignment = I.getAlign(); 3950 3951 AAMDNodes AAInfo; 3952 I.getAAMetadata(AAInfo); 3953 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3954 3955 SmallVector<EVT, 4> ValueVTs, MemVTs; 3956 SmallVector<uint64_t, 4> Offsets; 3957 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3958 unsigned NumValues = ValueVTs.size(); 3959 if (NumValues == 0) 3960 return; 3961 3962 bool isVolatile = I.isVolatile(); 3963 3964 SDValue Root; 3965 bool ConstantMemory = false; 3966 if (isVolatile) 3967 // Serialize volatile loads with other side effects. 3968 Root = getRoot(); 3969 else if (NumValues > MaxParallelChains) 3970 Root = getMemoryRoot(); 3971 else if (AA && 3972 AA->pointsToConstantMemory(MemoryLocation( 3973 SV, 3974 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3975 AAInfo))) { 3976 // Do not serialize (non-volatile) loads of constant memory with anything. 3977 Root = DAG.getEntryNode(); 3978 ConstantMemory = true; 3979 } else { 3980 // Do not serialize non-volatile loads against each other. 3981 Root = DAG.getRoot(); 3982 } 3983 3984 SDLoc dl = getCurSDLoc(); 3985 3986 if (isVolatile) 3987 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3988 3989 // An aggregate load cannot wrap around the address space, so offsets to its 3990 // parts don't wrap either. 3991 SDNodeFlags Flags; 3992 Flags.setNoUnsignedWrap(true); 3993 3994 SmallVector<SDValue, 4> Values(NumValues); 3995 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3996 EVT PtrVT = Ptr.getValueType(); 3997 3998 MachineMemOperand::Flags MMOFlags 3999 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4000 4001 unsigned ChainI = 0; 4002 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4003 // Serializing loads here may result in excessive register pressure, and 4004 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4005 // could recover a bit by hoisting nodes upward in the chain by recognizing 4006 // they are side-effect free or do not alias. The optimizer should really 4007 // avoid this case by converting large object/array copies to llvm.memcpy 4008 // (MaxParallelChains should always remain as failsafe). 4009 if (ChainI == MaxParallelChains) { 4010 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4011 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4012 makeArrayRef(Chains.data(), ChainI)); 4013 Root = Chain; 4014 ChainI = 0; 4015 } 4016 SDValue A = DAG.getNode(ISD::ADD, dl, 4017 PtrVT, Ptr, 4018 DAG.getConstant(Offsets[i], dl, PtrVT), 4019 Flags); 4020 4021 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4022 MachinePointerInfo(SV, Offsets[i]), Alignment, 4023 MMOFlags, AAInfo, Ranges); 4024 Chains[ChainI] = L.getValue(1); 4025 4026 if (MemVTs[i] != ValueVTs[i]) 4027 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4028 4029 Values[i] = L; 4030 } 4031 4032 if (!ConstantMemory) { 4033 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4034 makeArrayRef(Chains.data(), ChainI)); 4035 if (isVolatile) 4036 DAG.setRoot(Chain); 4037 else 4038 PendingLoads.push_back(Chain); 4039 } 4040 4041 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4042 DAG.getVTList(ValueVTs), Values)); 4043 } 4044 4045 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4046 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4047 "call visitStoreToSwiftError when backend supports swifterror"); 4048 4049 SmallVector<EVT, 4> ValueVTs; 4050 SmallVector<uint64_t, 4> Offsets; 4051 const Value *SrcV = I.getOperand(0); 4052 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4053 SrcV->getType(), ValueVTs, &Offsets); 4054 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4055 "expect a single EVT for swifterror"); 4056 4057 SDValue Src = getValue(SrcV); 4058 // Create a virtual register, then update the virtual register. 4059 Register VReg = 4060 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4061 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4062 // Chain can be getRoot or getControlRoot. 4063 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4064 SDValue(Src.getNode(), Src.getResNo())); 4065 DAG.setRoot(CopyNode); 4066 } 4067 4068 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4069 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4070 "call visitLoadFromSwiftError when backend supports swifterror"); 4071 4072 assert(!I.isVolatile() && 4073 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4074 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4075 "Support volatile, non temporal, invariant for load_from_swift_error"); 4076 4077 const Value *SV = I.getOperand(0); 4078 Type *Ty = I.getType(); 4079 AAMDNodes AAInfo; 4080 I.getAAMetadata(AAInfo); 4081 assert( 4082 (!AA || 4083 !AA->pointsToConstantMemory(MemoryLocation( 4084 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4085 AAInfo))) && 4086 "load_from_swift_error should not be constant memory"); 4087 4088 SmallVector<EVT, 4> ValueVTs; 4089 SmallVector<uint64_t, 4> Offsets; 4090 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4091 ValueVTs, &Offsets); 4092 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4093 "expect a single EVT for swifterror"); 4094 4095 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4096 SDValue L = DAG.getCopyFromReg( 4097 getRoot(), getCurSDLoc(), 4098 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4099 4100 setValue(&I, L); 4101 } 4102 4103 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4104 if (I.isAtomic()) 4105 return visitAtomicStore(I); 4106 4107 const Value *SrcV = I.getOperand(0); 4108 const Value *PtrV = I.getOperand(1); 4109 4110 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4111 if (TLI.supportSwiftError()) { 4112 // Swifterror values can come from either a function parameter with 4113 // swifterror attribute or an alloca with swifterror attribute. 4114 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4115 if (Arg->hasSwiftErrorAttr()) 4116 return visitStoreToSwiftError(I); 4117 } 4118 4119 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4120 if (Alloca->isSwiftError()) 4121 return visitStoreToSwiftError(I); 4122 } 4123 } 4124 4125 SmallVector<EVT, 4> ValueVTs, MemVTs; 4126 SmallVector<uint64_t, 4> Offsets; 4127 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4128 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4129 unsigned NumValues = ValueVTs.size(); 4130 if (NumValues == 0) 4131 return; 4132 4133 // Get the lowered operands. Note that we do this after 4134 // checking if NumResults is zero, because with zero results 4135 // the operands won't have values in the map. 4136 SDValue Src = getValue(SrcV); 4137 SDValue Ptr = getValue(PtrV); 4138 4139 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4140 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4141 SDLoc dl = getCurSDLoc(); 4142 Align Alignment = I.getAlign(); 4143 AAMDNodes AAInfo; 4144 I.getAAMetadata(AAInfo); 4145 4146 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4147 4148 // An aggregate load cannot wrap around the address space, so offsets to its 4149 // parts don't wrap either. 4150 SDNodeFlags Flags; 4151 Flags.setNoUnsignedWrap(true); 4152 4153 unsigned ChainI = 0; 4154 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4155 // See visitLoad comments. 4156 if (ChainI == MaxParallelChains) { 4157 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4158 makeArrayRef(Chains.data(), ChainI)); 4159 Root = Chain; 4160 ChainI = 0; 4161 } 4162 SDValue Add = 4163 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4164 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4165 if (MemVTs[i] != ValueVTs[i]) 4166 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4167 SDValue St = 4168 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4169 Alignment, MMOFlags, AAInfo); 4170 Chains[ChainI] = St; 4171 } 4172 4173 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4174 makeArrayRef(Chains.data(), ChainI)); 4175 DAG.setRoot(StoreNode); 4176 } 4177 4178 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4179 bool IsCompressing) { 4180 SDLoc sdl = getCurSDLoc(); 4181 4182 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4183 MaybeAlign &Alignment) { 4184 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4185 Src0 = I.getArgOperand(0); 4186 Ptr = I.getArgOperand(1); 4187 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4188 Mask = I.getArgOperand(3); 4189 }; 4190 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4191 MaybeAlign &Alignment) { 4192 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4193 Src0 = I.getArgOperand(0); 4194 Ptr = I.getArgOperand(1); 4195 Mask = I.getArgOperand(2); 4196 Alignment = None; 4197 }; 4198 4199 Value *PtrOperand, *MaskOperand, *Src0Operand; 4200 MaybeAlign Alignment; 4201 if (IsCompressing) 4202 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4203 else 4204 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4205 4206 SDValue Ptr = getValue(PtrOperand); 4207 SDValue Src0 = getValue(Src0Operand); 4208 SDValue Mask = getValue(MaskOperand); 4209 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4210 4211 EVT VT = Src0.getValueType(); 4212 if (!Alignment) 4213 Alignment = DAG.getEVTAlign(VT); 4214 4215 AAMDNodes AAInfo; 4216 I.getAAMetadata(AAInfo); 4217 4218 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4219 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4220 // TODO: Make MachineMemOperands aware of scalable 4221 // vectors. 4222 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4223 SDValue StoreNode = 4224 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4225 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4226 DAG.setRoot(StoreNode); 4227 setValue(&I, StoreNode); 4228 } 4229 4230 // Get a uniform base for the Gather/Scatter intrinsic. 4231 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4232 // We try to represent it as a base pointer + vector of indices. 4233 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4234 // The first operand of the GEP may be a single pointer or a vector of pointers 4235 // Example: 4236 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4237 // or 4238 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4239 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4240 // 4241 // When the first GEP operand is a single pointer - it is the uniform base we 4242 // are looking for. If first operand of the GEP is a splat vector - we 4243 // extract the splat value and use it as a uniform base. 4244 // In all other cases the function returns 'false'. 4245 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4246 ISD::MemIndexType &IndexType, SDValue &Scale, 4247 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4248 SelectionDAG& DAG = SDB->DAG; 4249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4250 const DataLayout &DL = DAG.getDataLayout(); 4251 4252 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4253 4254 // Handle splat constant pointer. 4255 if (auto *C = dyn_cast<Constant>(Ptr)) { 4256 C = C->getSplatValue(); 4257 if (!C) 4258 return false; 4259 4260 Base = SDB->getValue(C); 4261 4262 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4263 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4264 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4265 IndexType = ISD::SIGNED_SCALED; 4266 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4267 return true; 4268 } 4269 4270 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4271 if (!GEP || GEP->getParent() != CurBB) 4272 return false; 4273 4274 if (GEP->getNumOperands() != 2) 4275 return false; 4276 4277 const Value *BasePtr = GEP->getPointerOperand(); 4278 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4279 4280 // Make sure the base is scalar and the index is a vector. 4281 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4282 return false; 4283 4284 Base = SDB->getValue(BasePtr); 4285 Index = SDB->getValue(IndexVal); 4286 IndexType = ISD::SIGNED_SCALED; 4287 Scale = DAG.getTargetConstant( 4288 DL.getTypeAllocSize(GEP->getResultElementType()), 4289 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4290 return true; 4291 } 4292 4293 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4294 SDLoc sdl = getCurSDLoc(); 4295 4296 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4297 const Value *Ptr = I.getArgOperand(1); 4298 SDValue Src0 = getValue(I.getArgOperand(0)); 4299 SDValue Mask = getValue(I.getArgOperand(3)); 4300 EVT VT = Src0.getValueType(); 4301 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4302 ->getMaybeAlignValue() 4303 .getValueOr(DAG.getEVTAlign(VT)); 4304 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4305 4306 AAMDNodes AAInfo; 4307 I.getAAMetadata(AAInfo); 4308 4309 SDValue Base; 4310 SDValue Index; 4311 ISD::MemIndexType IndexType; 4312 SDValue Scale; 4313 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4314 I.getParent()); 4315 4316 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4317 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4318 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4319 // TODO: Make MachineMemOperands aware of scalable 4320 // vectors. 4321 MemoryLocation::UnknownSize, Alignment, AAInfo); 4322 if (!UniformBase) { 4323 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4324 Index = getValue(Ptr); 4325 IndexType = ISD::SIGNED_SCALED; 4326 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4327 } 4328 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4329 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4330 Ops, MMO, IndexType); 4331 DAG.setRoot(Scatter); 4332 setValue(&I, Scatter); 4333 } 4334 4335 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4336 SDLoc sdl = getCurSDLoc(); 4337 4338 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4339 MaybeAlign &Alignment) { 4340 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4341 Ptr = I.getArgOperand(0); 4342 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4343 Mask = I.getArgOperand(2); 4344 Src0 = I.getArgOperand(3); 4345 }; 4346 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4347 MaybeAlign &Alignment) { 4348 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4349 Ptr = I.getArgOperand(0); 4350 Alignment = None; 4351 Mask = I.getArgOperand(1); 4352 Src0 = I.getArgOperand(2); 4353 }; 4354 4355 Value *PtrOperand, *MaskOperand, *Src0Operand; 4356 MaybeAlign Alignment; 4357 if (IsExpanding) 4358 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4359 else 4360 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4361 4362 SDValue Ptr = getValue(PtrOperand); 4363 SDValue Src0 = getValue(Src0Operand); 4364 SDValue Mask = getValue(MaskOperand); 4365 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4366 4367 EVT VT = Src0.getValueType(); 4368 if (!Alignment) 4369 Alignment = DAG.getEVTAlign(VT); 4370 4371 AAMDNodes AAInfo; 4372 I.getAAMetadata(AAInfo); 4373 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4374 4375 // Do not serialize masked loads of constant memory with anything. 4376 MemoryLocation ML; 4377 if (VT.isScalableVector()) 4378 ML = MemoryLocation(PtrOperand); 4379 else 4380 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4381 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4382 AAInfo); 4383 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4384 4385 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4386 4387 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4388 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4389 // TODO: Make MachineMemOperands aware of scalable 4390 // vectors. 4391 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4392 4393 SDValue Load = 4394 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4395 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4396 if (AddToChain) 4397 PendingLoads.push_back(Load.getValue(1)); 4398 setValue(&I, Load); 4399 } 4400 4401 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4402 SDLoc sdl = getCurSDLoc(); 4403 4404 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4405 const Value *Ptr = I.getArgOperand(0); 4406 SDValue Src0 = getValue(I.getArgOperand(3)); 4407 SDValue Mask = getValue(I.getArgOperand(2)); 4408 4409 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4410 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4411 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4412 ->getMaybeAlignValue() 4413 .getValueOr(DAG.getEVTAlign(VT)); 4414 4415 AAMDNodes AAInfo; 4416 I.getAAMetadata(AAInfo); 4417 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4418 4419 SDValue Root = DAG.getRoot(); 4420 SDValue Base; 4421 SDValue Index; 4422 ISD::MemIndexType IndexType; 4423 SDValue Scale; 4424 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4425 I.getParent()); 4426 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4427 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4428 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4429 // TODO: Make MachineMemOperands aware of scalable 4430 // vectors. 4431 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4432 4433 if (!UniformBase) { 4434 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4435 Index = getValue(Ptr); 4436 IndexType = ISD::SIGNED_SCALED; 4437 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4438 } 4439 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4440 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4441 Ops, MMO, IndexType); 4442 4443 PendingLoads.push_back(Gather.getValue(1)); 4444 setValue(&I, Gather); 4445 } 4446 4447 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4448 SDLoc dl = getCurSDLoc(); 4449 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4450 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4451 SyncScope::ID SSID = I.getSyncScopeID(); 4452 4453 SDValue InChain = getRoot(); 4454 4455 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4456 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4457 4458 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4459 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4460 4461 MachineFunction &MF = DAG.getMachineFunction(); 4462 MachineMemOperand *MMO = MF.getMachineMemOperand( 4463 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4464 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4465 FailureOrdering); 4466 4467 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4468 dl, MemVT, VTs, InChain, 4469 getValue(I.getPointerOperand()), 4470 getValue(I.getCompareOperand()), 4471 getValue(I.getNewValOperand()), MMO); 4472 4473 SDValue OutChain = L.getValue(2); 4474 4475 setValue(&I, L); 4476 DAG.setRoot(OutChain); 4477 } 4478 4479 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4480 SDLoc dl = getCurSDLoc(); 4481 ISD::NodeType NT; 4482 switch (I.getOperation()) { 4483 default: llvm_unreachable("Unknown atomicrmw operation"); 4484 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4485 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4486 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4487 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4488 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4489 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4490 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4491 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4492 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4493 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4494 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4495 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4496 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4497 } 4498 AtomicOrdering Ordering = I.getOrdering(); 4499 SyncScope::ID SSID = I.getSyncScopeID(); 4500 4501 SDValue InChain = getRoot(); 4502 4503 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4504 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4505 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4506 4507 MachineFunction &MF = DAG.getMachineFunction(); 4508 MachineMemOperand *MMO = MF.getMachineMemOperand( 4509 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4510 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4511 4512 SDValue L = 4513 DAG.getAtomic(NT, dl, MemVT, InChain, 4514 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4515 MMO); 4516 4517 SDValue OutChain = L.getValue(1); 4518 4519 setValue(&I, L); 4520 DAG.setRoot(OutChain); 4521 } 4522 4523 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4524 SDLoc dl = getCurSDLoc(); 4525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4526 SDValue Ops[3]; 4527 Ops[0] = getRoot(); 4528 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4529 TLI.getFenceOperandTy(DAG.getDataLayout())); 4530 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4531 TLI.getFenceOperandTy(DAG.getDataLayout())); 4532 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4533 } 4534 4535 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4536 SDLoc dl = getCurSDLoc(); 4537 AtomicOrdering Order = I.getOrdering(); 4538 SyncScope::ID SSID = I.getSyncScopeID(); 4539 4540 SDValue InChain = getRoot(); 4541 4542 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4543 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4544 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4545 4546 if (!TLI.supportsUnalignedAtomics() && 4547 I.getAlignment() < MemVT.getSizeInBits() / 8) 4548 report_fatal_error("Cannot generate unaligned atomic load"); 4549 4550 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4551 4552 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4553 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4554 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4555 4556 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4557 4558 SDValue Ptr = getValue(I.getPointerOperand()); 4559 4560 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4561 // TODO: Once this is better exercised by tests, it should be merged with 4562 // the normal path for loads to prevent future divergence. 4563 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4564 if (MemVT != VT) 4565 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4566 4567 setValue(&I, L); 4568 SDValue OutChain = L.getValue(1); 4569 if (!I.isUnordered()) 4570 DAG.setRoot(OutChain); 4571 else 4572 PendingLoads.push_back(OutChain); 4573 return; 4574 } 4575 4576 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4577 Ptr, MMO); 4578 4579 SDValue OutChain = L.getValue(1); 4580 if (MemVT != VT) 4581 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4582 4583 setValue(&I, L); 4584 DAG.setRoot(OutChain); 4585 } 4586 4587 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4588 SDLoc dl = getCurSDLoc(); 4589 4590 AtomicOrdering Ordering = I.getOrdering(); 4591 SyncScope::ID SSID = I.getSyncScopeID(); 4592 4593 SDValue InChain = getRoot(); 4594 4595 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4596 EVT MemVT = 4597 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4598 4599 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4600 report_fatal_error("Cannot generate unaligned atomic store"); 4601 4602 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4603 4604 MachineFunction &MF = DAG.getMachineFunction(); 4605 MachineMemOperand *MMO = MF.getMachineMemOperand( 4606 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4607 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4608 4609 SDValue Val = getValue(I.getValueOperand()); 4610 if (Val.getValueType() != MemVT) 4611 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4612 SDValue Ptr = getValue(I.getPointerOperand()); 4613 4614 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4615 // TODO: Once this is better exercised by tests, it should be merged with 4616 // the normal path for stores to prevent future divergence. 4617 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4618 DAG.setRoot(S); 4619 return; 4620 } 4621 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4622 Ptr, Val, MMO); 4623 4624 4625 DAG.setRoot(OutChain); 4626 } 4627 4628 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4629 /// node. 4630 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4631 unsigned Intrinsic) { 4632 // Ignore the callsite's attributes. A specific call site may be marked with 4633 // readnone, but the lowering code will expect the chain based on the 4634 // definition. 4635 const Function *F = I.getCalledFunction(); 4636 bool HasChain = !F->doesNotAccessMemory(); 4637 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4638 4639 // Build the operand list. 4640 SmallVector<SDValue, 8> Ops; 4641 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4642 if (OnlyLoad) { 4643 // We don't need to serialize loads against other loads. 4644 Ops.push_back(DAG.getRoot()); 4645 } else { 4646 Ops.push_back(getRoot()); 4647 } 4648 } 4649 4650 // Info is set by getTgtMemInstrinsic 4651 TargetLowering::IntrinsicInfo Info; 4652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4653 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4654 DAG.getMachineFunction(), 4655 Intrinsic); 4656 4657 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4658 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4659 Info.opc == ISD::INTRINSIC_W_CHAIN) 4660 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4661 TLI.getPointerTy(DAG.getDataLayout()))); 4662 4663 // Add all operands of the call to the operand list. 4664 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4665 const Value *Arg = I.getArgOperand(i); 4666 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4667 Ops.push_back(getValue(Arg)); 4668 continue; 4669 } 4670 4671 // Use TargetConstant instead of a regular constant for immarg. 4672 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4673 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4674 assert(CI->getBitWidth() <= 64 && 4675 "large intrinsic immediates not handled"); 4676 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4677 } else { 4678 Ops.push_back( 4679 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4680 } 4681 } 4682 4683 SmallVector<EVT, 4> ValueVTs; 4684 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4685 4686 if (HasChain) 4687 ValueVTs.push_back(MVT::Other); 4688 4689 SDVTList VTs = DAG.getVTList(ValueVTs); 4690 4691 // Create the node. 4692 SDValue Result; 4693 if (IsTgtIntrinsic) { 4694 // This is target intrinsic that touches memory 4695 AAMDNodes AAInfo; 4696 I.getAAMetadata(AAInfo); 4697 Result = 4698 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4699 MachinePointerInfo(Info.ptrVal, Info.offset), 4700 Info.align, Info.flags, Info.size, AAInfo); 4701 } else if (!HasChain) { 4702 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4703 } else if (!I.getType()->isVoidTy()) { 4704 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4705 } else { 4706 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4707 } 4708 4709 if (HasChain) { 4710 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4711 if (OnlyLoad) 4712 PendingLoads.push_back(Chain); 4713 else 4714 DAG.setRoot(Chain); 4715 } 4716 4717 if (!I.getType()->isVoidTy()) { 4718 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4719 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4720 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4721 } else 4722 Result = lowerRangeToAssertZExt(DAG, I, Result); 4723 4724 MaybeAlign Alignment = I.getRetAlign(); 4725 if (!Alignment) 4726 Alignment = F->getAttributes().getRetAlignment(); 4727 // Insert `assertalign` node if there's an alignment. 4728 if (InsertAssertAlign && Alignment) { 4729 Result = 4730 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4731 } 4732 4733 setValue(&I, Result); 4734 } 4735 } 4736 4737 /// GetSignificand - Get the significand and build it into a floating-point 4738 /// number with exponent of 1: 4739 /// 4740 /// Op = (Op & 0x007fffff) | 0x3f800000; 4741 /// 4742 /// where Op is the hexadecimal representation of floating point value. 4743 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4744 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4745 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4746 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4747 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4748 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4749 } 4750 4751 /// GetExponent - Get the exponent: 4752 /// 4753 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4754 /// 4755 /// where Op is the hexadecimal representation of floating point value. 4756 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4757 const TargetLowering &TLI, const SDLoc &dl) { 4758 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4759 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4760 SDValue t1 = DAG.getNode( 4761 ISD::SRL, dl, MVT::i32, t0, 4762 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4763 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4764 DAG.getConstant(127, dl, MVT::i32)); 4765 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4766 } 4767 4768 /// getF32Constant - Get 32-bit floating point constant. 4769 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4770 const SDLoc &dl) { 4771 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4772 MVT::f32); 4773 } 4774 4775 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4776 SelectionDAG &DAG) { 4777 // TODO: What fast-math-flags should be set on the floating-point nodes? 4778 4779 // IntegerPartOfX = ((int32_t)(t0); 4780 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4781 4782 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4783 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4784 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4785 4786 // IntegerPartOfX <<= 23; 4787 IntegerPartOfX = DAG.getNode( 4788 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4789 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4790 DAG.getDataLayout()))); 4791 4792 SDValue TwoToFractionalPartOfX; 4793 if (LimitFloatPrecision <= 6) { 4794 // For floating-point precision of 6: 4795 // 4796 // TwoToFractionalPartOfX = 4797 // 0.997535578f + 4798 // (0.735607626f + 0.252464424f * x) * x; 4799 // 4800 // error 0.0144103317, which is 6 bits 4801 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4802 getF32Constant(DAG, 0x3e814304, dl)); 4803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4804 getF32Constant(DAG, 0x3f3c50c8, dl)); 4805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4806 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4807 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4808 } else if (LimitFloatPrecision <= 12) { 4809 // For floating-point precision of 12: 4810 // 4811 // TwoToFractionalPartOfX = 4812 // 0.999892986f + 4813 // (0.696457318f + 4814 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4815 // 4816 // error 0.000107046256, which is 13 to 14 bits 4817 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4818 getF32Constant(DAG, 0x3da235e3, dl)); 4819 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4820 getF32Constant(DAG, 0x3e65b8f3, dl)); 4821 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4822 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4823 getF32Constant(DAG, 0x3f324b07, dl)); 4824 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4825 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4826 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4827 } else { // LimitFloatPrecision <= 18 4828 // For floating-point precision of 18: 4829 // 4830 // TwoToFractionalPartOfX = 4831 // 0.999999982f + 4832 // (0.693148872f + 4833 // (0.240227044f + 4834 // (0.554906021e-1f + 4835 // (0.961591928e-2f + 4836 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4837 // error 2.47208000*10^(-7), which is better than 18 bits 4838 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4839 getF32Constant(DAG, 0x3924b03e, dl)); 4840 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4841 getF32Constant(DAG, 0x3ab24b87, dl)); 4842 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4843 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4844 getF32Constant(DAG, 0x3c1d8c17, dl)); 4845 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4846 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4847 getF32Constant(DAG, 0x3d634a1d, dl)); 4848 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4849 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4850 getF32Constant(DAG, 0x3e75fe14, dl)); 4851 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4852 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4853 getF32Constant(DAG, 0x3f317234, dl)); 4854 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4855 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4856 getF32Constant(DAG, 0x3f800000, dl)); 4857 } 4858 4859 // Add the exponent into the result in integer domain. 4860 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4861 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4862 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4863 } 4864 4865 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4866 /// limited-precision mode. 4867 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4868 const TargetLowering &TLI, SDNodeFlags Flags) { 4869 if (Op.getValueType() == MVT::f32 && 4870 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4871 4872 // Put the exponent in the right bit position for later addition to the 4873 // final result: 4874 // 4875 // t0 = Op * log2(e) 4876 4877 // TODO: What fast-math-flags should be set here? 4878 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4879 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4880 return getLimitedPrecisionExp2(t0, dl, DAG); 4881 } 4882 4883 // No special expansion. 4884 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4885 } 4886 4887 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4888 /// limited-precision mode. 4889 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4890 const TargetLowering &TLI, SDNodeFlags Flags) { 4891 // TODO: What fast-math-flags should be set on the floating-point nodes? 4892 4893 if (Op.getValueType() == MVT::f32 && 4894 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4895 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4896 4897 // Scale the exponent by log(2). 4898 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4899 SDValue LogOfExponent = 4900 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4901 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4902 4903 // Get the significand and build it into a floating-point number with 4904 // exponent of 1. 4905 SDValue X = GetSignificand(DAG, Op1, dl); 4906 4907 SDValue LogOfMantissa; 4908 if (LimitFloatPrecision <= 6) { 4909 // For floating-point precision of 6: 4910 // 4911 // LogofMantissa = 4912 // -1.1609546f + 4913 // (1.4034025f - 0.23903021f * x) * x; 4914 // 4915 // error 0.0034276066, which is better than 8 bits 4916 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4917 getF32Constant(DAG, 0xbe74c456, dl)); 4918 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4919 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4920 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4921 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4922 getF32Constant(DAG, 0x3f949a29, dl)); 4923 } else if (LimitFloatPrecision <= 12) { 4924 // For floating-point precision of 12: 4925 // 4926 // LogOfMantissa = 4927 // -1.7417939f + 4928 // (2.8212026f + 4929 // (-1.4699568f + 4930 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4931 // 4932 // error 0.000061011436, which is 14 bits 4933 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4934 getF32Constant(DAG, 0xbd67b6d6, dl)); 4935 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4936 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4937 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4938 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4939 getF32Constant(DAG, 0x3fbc278b, dl)); 4940 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4941 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4942 getF32Constant(DAG, 0x40348e95, dl)); 4943 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4944 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4945 getF32Constant(DAG, 0x3fdef31a, dl)); 4946 } else { // LimitFloatPrecision <= 18 4947 // For floating-point precision of 18: 4948 // 4949 // LogOfMantissa = 4950 // -2.1072184f + 4951 // (4.2372794f + 4952 // (-3.7029485f + 4953 // (2.2781945f + 4954 // (-0.87823314f + 4955 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4956 // 4957 // error 0.0000023660568, which is better than 18 bits 4958 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4959 getF32Constant(DAG, 0xbc91e5ac, dl)); 4960 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4961 getF32Constant(DAG, 0x3e4350aa, dl)); 4962 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4963 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4964 getF32Constant(DAG, 0x3f60d3e3, dl)); 4965 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4966 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4967 getF32Constant(DAG, 0x4011cdf0, dl)); 4968 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4969 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4970 getF32Constant(DAG, 0x406cfd1c, dl)); 4971 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4972 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4973 getF32Constant(DAG, 0x408797cb, dl)); 4974 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4975 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4976 getF32Constant(DAG, 0x4006dcab, dl)); 4977 } 4978 4979 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4980 } 4981 4982 // No special expansion. 4983 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 4984 } 4985 4986 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4987 /// limited-precision mode. 4988 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4989 const TargetLowering &TLI, SDNodeFlags Flags) { 4990 // TODO: What fast-math-flags should be set on the floating-point nodes? 4991 4992 if (Op.getValueType() == MVT::f32 && 4993 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4994 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4995 4996 // Get the exponent. 4997 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4998 4999 // Get the significand and build it into a floating-point number with 5000 // exponent of 1. 5001 SDValue X = GetSignificand(DAG, Op1, dl); 5002 5003 // Different possible minimax approximations of significand in 5004 // floating-point for various degrees of accuracy over [1,2]. 5005 SDValue Log2ofMantissa; 5006 if (LimitFloatPrecision <= 6) { 5007 // For floating-point precision of 6: 5008 // 5009 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5010 // 5011 // error 0.0049451742, which is more than 7 bits 5012 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5013 getF32Constant(DAG, 0xbeb08fe0, dl)); 5014 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5015 getF32Constant(DAG, 0x40019463, dl)); 5016 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5017 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5018 getF32Constant(DAG, 0x3fd6633d, dl)); 5019 } else if (LimitFloatPrecision <= 12) { 5020 // For floating-point precision of 12: 5021 // 5022 // Log2ofMantissa = 5023 // -2.51285454f + 5024 // (4.07009056f + 5025 // (-2.12067489f + 5026 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5027 // 5028 // error 0.0000876136000, which is better than 13 bits 5029 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5030 getF32Constant(DAG, 0xbda7262e, dl)); 5031 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5032 getF32Constant(DAG, 0x3f25280b, dl)); 5033 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5034 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5035 getF32Constant(DAG, 0x4007b923, dl)); 5036 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5037 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5038 getF32Constant(DAG, 0x40823e2f, dl)); 5039 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5040 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5041 getF32Constant(DAG, 0x4020d29c, dl)); 5042 } else { // LimitFloatPrecision <= 18 5043 // For floating-point precision of 18: 5044 // 5045 // Log2ofMantissa = 5046 // -3.0400495f + 5047 // (6.1129976f + 5048 // (-5.3420409f + 5049 // (3.2865683f + 5050 // (-1.2669343f + 5051 // (0.27515199f - 5052 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5053 // 5054 // error 0.0000018516, which is better than 18 bits 5055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5056 getF32Constant(DAG, 0xbcd2769e, dl)); 5057 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5058 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5060 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5061 getF32Constant(DAG, 0x3fa22ae7, dl)); 5062 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5063 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5064 getF32Constant(DAG, 0x40525723, dl)); 5065 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5066 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5067 getF32Constant(DAG, 0x40aaf200, dl)); 5068 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5069 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5070 getF32Constant(DAG, 0x40c39dad, dl)); 5071 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5072 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5073 getF32Constant(DAG, 0x4042902c, dl)); 5074 } 5075 5076 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5077 } 5078 5079 // No special expansion. 5080 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5081 } 5082 5083 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5084 /// limited-precision mode. 5085 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5086 const TargetLowering &TLI, SDNodeFlags Flags) { 5087 // TODO: What fast-math-flags should be set on the floating-point nodes? 5088 5089 if (Op.getValueType() == MVT::f32 && 5090 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5091 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5092 5093 // Scale the exponent by log10(2) [0.30102999f]. 5094 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5095 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5096 getF32Constant(DAG, 0x3e9a209a, dl)); 5097 5098 // Get the significand and build it into a floating-point number with 5099 // exponent of 1. 5100 SDValue X = GetSignificand(DAG, Op1, dl); 5101 5102 SDValue Log10ofMantissa; 5103 if (LimitFloatPrecision <= 6) { 5104 // For floating-point precision of 6: 5105 // 5106 // Log10ofMantissa = 5107 // -0.50419619f + 5108 // (0.60948995f - 0.10380950f * x) * x; 5109 // 5110 // error 0.0014886165, which is 6 bits 5111 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5112 getF32Constant(DAG, 0xbdd49a13, dl)); 5113 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5114 getF32Constant(DAG, 0x3f1c0789, dl)); 5115 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5116 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5117 getF32Constant(DAG, 0x3f011300, dl)); 5118 } else if (LimitFloatPrecision <= 12) { 5119 // For floating-point precision of 12: 5120 // 5121 // Log10ofMantissa = 5122 // -0.64831180f + 5123 // (0.91751397f + 5124 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5125 // 5126 // error 0.00019228036, which is better than 12 bits 5127 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5128 getF32Constant(DAG, 0x3d431f31, dl)); 5129 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5130 getF32Constant(DAG, 0x3ea21fb2, dl)); 5131 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5132 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5133 getF32Constant(DAG, 0x3f6ae232, dl)); 5134 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5135 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5136 getF32Constant(DAG, 0x3f25f7c3, dl)); 5137 } else { // LimitFloatPrecision <= 18 5138 // For floating-point precision of 18: 5139 // 5140 // Log10ofMantissa = 5141 // -0.84299375f + 5142 // (1.5327582f + 5143 // (-1.0688956f + 5144 // (0.49102474f + 5145 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5146 // 5147 // error 0.0000037995730, which is better than 18 bits 5148 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5149 getF32Constant(DAG, 0x3c5d51ce, dl)); 5150 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5151 getF32Constant(DAG, 0x3e00685a, dl)); 5152 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5153 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5154 getF32Constant(DAG, 0x3efb6798, dl)); 5155 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5156 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5157 getF32Constant(DAG, 0x3f88d192, dl)); 5158 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5159 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5160 getF32Constant(DAG, 0x3fc4316c, dl)); 5161 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5162 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5163 getF32Constant(DAG, 0x3f57ce70, dl)); 5164 } 5165 5166 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5167 } 5168 5169 // No special expansion. 5170 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5171 } 5172 5173 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5174 /// limited-precision mode. 5175 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5176 const TargetLowering &TLI, SDNodeFlags Flags) { 5177 if (Op.getValueType() == MVT::f32 && 5178 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5179 return getLimitedPrecisionExp2(Op, dl, DAG); 5180 5181 // No special expansion. 5182 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5183 } 5184 5185 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5186 /// limited-precision mode with x == 10.0f. 5187 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5188 SelectionDAG &DAG, const TargetLowering &TLI, 5189 SDNodeFlags Flags) { 5190 bool IsExp10 = false; 5191 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5192 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5193 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5194 APFloat Ten(10.0f); 5195 IsExp10 = LHSC->isExactlyValue(Ten); 5196 } 5197 } 5198 5199 // TODO: What fast-math-flags should be set on the FMUL node? 5200 if (IsExp10) { 5201 // Put the exponent in the right bit position for later addition to the 5202 // final result: 5203 // 5204 // #define LOG2OF10 3.3219281f 5205 // t0 = Op * LOG2OF10; 5206 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5207 getF32Constant(DAG, 0x40549a78, dl)); 5208 return getLimitedPrecisionExp2(t0, dl, DAG); 5209 } 5210 5211 // No special expansion. 5212 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5213 } 5214 5215 /// ExpandPowI - Expand a llvm.powi intrinsic. 5216 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5217 SelectionDAG &DAG) { 5218 // If RHS is a constant, we can expand this out to a multiplication tree, 5219 // otherwise we end up lowering to a call to __powidf2 (for example). When 5220 // optimizing for size, we only want to do this if the expansion would produce 5221 // a small number of multiplies, otherwise we do the full expansion. 5222 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5223 // Get the exponent as a positive value. 5224 unsigned Val = RHSC->getSExtValue(); 5225 if ((int)Val < 0) Val = -Val; 5226 5227 // powi(x, 0) -> 1.0 5228 if (Val == 0) 5229 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5230 5231 bool OptForSize = DAG.shouldOptForSize(); 5232 if (!OptForSize || 5233 // If optimizing for size, don't insert too many multiplies. 5234 // This inserts up to 5 multiplies. 5235 countPopulation(Val) + Log2_32(Val) < 7) { 5236 // We use the simple binary decomposition method to generate the multiply 5237 // sequence. There are more optimal ways to do this (for example, 5238 // powi(x,15) generates one more multiply than it should), but this has 5239 // the benefit of being both really simple and much better than a libcall. 5240 SDValue Res; // Logically starts equal to 1.0 5241 SDValue CurSquare = LHS; 5242 // TODO: Intrinsics should have fast-math-flags that propagate to these 5243 // nodes. 5244 while (Val) { 5245 if (Val & 1) { 5246 if (Res.getNode()) 5247 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5248 else 5249 Res = CurSquare; // 1.0*CurSquare. 5250 } 5251 5252 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5253 CurSquare, CurSquare); 5254 Val >>= 1; 5255 } 5256 5257 // If the original was negative, invert the result, producing 1/(x*x*x). 5258 if (RHSC->getSExtValue() < 0) 5259 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5260 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5261 return Res; 5262 } 5263 } 5264 5265 // Otherwise, expand to a libcall. 5266 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5267 } 5268 5269 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5270 SDValue LHS, SDValue RHS, SDValue Scale, 5271 SelectionDAG &DAG, const TargetLowering &TLI) { 5272 EVT VT = LHS.getValueType(); 5273 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5274 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5275 LLVMContext &Ctx = *DAG.getContext(); 5276 5277 // If the type is legal but the operation isn't, this node might survive all 5278 // the way to operation legalization. If we end up there and we do not have 5279 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5280 // node. 5281 5282 // Coax the legalizer into expanding the node during type legalization instead 5283 // by bumping the size by one bit. This will force it to Promote, enabling the 5284 // early expansion and avoiding the need to expand later. 5285 5286 // We don't have to do this if Scale is 0; that can always be expanded, unless 5287 // it's a saturating signed operation. Those can experience true integer 5288 // division overflow, a case which we must avoid. 5289 5290 // FIXME: We wouldn't have to do this (or any of the early 5291 // expansion/promotion) if it was possible to expand a libcall of an 5292 // illegal type during operation legalization. But it's not, so things 5293 // get a bit hacky. 5294 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5295 if ((ScaleInt > 0 || (Saturating && Signed)) && 5296 (TLI.isTypeLegal(VT) || 5297 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5298 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5299 Opcode, VT, ScaleInt); 5300 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5301 EVT PromVT; 5302 if (VT.isScalarInteger()) 5303 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5304 else if (VT.isVector()) { 5305 PromVT = VT.getVectorElementType(); 5306 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5307 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5308 } else 5309 llvm_unreachable("Wrong VT for DIVFIX?"); 5310 if (Signed) { 5311 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5312 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5313 } else { 5314 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5315 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5316 } 5317 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5318 // For saturating operations, we need to shift up the LHS to get the 5319 // proper saturation width, and then shift down again afterwards. 5320 if (Saturating) 5321 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5322 DAG.getConstant(1, DL, ShiftTy)); 5323 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5324 if (Saturating) 5325 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5326 DAG.getConstant(1, DL, ShiftTy)); 5327 return DAG.getZExtOrTrunc(Res, DL, VT); 5328 } 5329 } 5330 5331 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5332 } 5333 5334 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5335 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5336 static void 5337 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5338 const SDValue &N) { 5339 switch (N.getOpcode()) { 5340 case ISD::CopyFromReg: { 5341 SDValue Op = N.getOperand(1); 5342 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5343 Op.getValueType().getSizeInBits()); 5344 return; 5345 } 5346 case ISD::BITCAST: 5347 case ISD::AssertZext: 5348 case ISD::AssertSext: 5349 case ISD::TRUNCATE: 5350 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5351 return; 5352 case ISD::BUILD_PAIR: 5353 case ISD::BUILD_VECTOR: 5354 case ISD::CONCAT_VECTORS: 5355 for (SDValue Op : N->op_values()) 5356 getUnderlyingArgRegs(Regs, Op); 5357 return; 5358 default: 5359 return; 5360 } 5361 } 5362 5363 /// If the DbgValueInst is a dbg_value of a function argument, create the 5364 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5365 /// instruction selection, they will be inserted to the entry BB. 5366 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5367 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5368 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5369 const Argument *Arg = dyn_cast<Argument>(V); 5370 if (!Arg) 5371 return false; 5372 5373 if (!IsDbgDeclare) { 5374 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5375 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5376 // the entry block. 5377 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5378 if (!IsInEntryBlock) 5379 return false; 5380 5381 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5382 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5383 // variable that also is a param. 5384 // 5385 // Although, if we are at the top of the entry block already, we can still 5386 // emit using ArgDbgValue. This might catch some situations when the 5387 // dbg.value refers to an argument that isn't used in the entry block, so 5388 // any CopyToReg node would be optimized out and the only way to express 5389 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5390 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5391 // we should only emit as ArgDbgValue if the Variable is an argument to the 5392 // current function, and the dbg.value intrinsic is found in the entry 5393 // block. 5394 bool VariableIsFunctionInputArg = Variable->isParameter() && 5395 !DL->getInlinedAt(); 5396 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5397 if (!IsInPrologue && !VariableIsFunctionInputArg) 5398 return false; 5399 5400 // Here we assume that a function argument on IR level only can be used to 5401 // describe one input parameter on source level. If we for example have 5402 // source code like this 5403 // 5404 // struct A { long x, y; }; 5405 // void foo(struct A a, long b) { 5406 // ... 5407 // b = a.x; 5408 // ... 5409 // } 5410 // 5411 // and IR like this 5412 // 5413 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5414 // entry: 5415 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5416 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5417 // call void @llvm.dbg.value(metadata i32 %b, "b", 5418 // ... 5419 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5420 // ... 5421 // 5422 // then the last dbg.value is describing a parameter "b" using a value that 5423 // is an argument. But since we already has used %a1 to describe a parameter 5424 // we should not handle that last dbg.value here (that would result in an 5425 // incorrect hoisting of the DBG_VALUE to the function entry). 5426 // Notice that we allow one dbg.value per IR level argument, to accommodate 5427 // for the situation with fragments above. 5428 if (VariableIsFunctionInputArg) { 5429 unsigned ArgNo = Arg->getArgNo(); 5430 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5431 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5432 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5433 return false; 5434 FuncInfo.DescribedArgs.set(ArgNo); 5435 } 5436 } 5437 5438 MachineFunction &MF = DAG.getMachineFunction(); 5439 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5440 5441 bool IsIndirect = false; 5442 Optional<MachineOperand> Op; 5443 // Some arguments' frame index is recorded during argument lowering. 5444 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5445 if (FI != std::numeric_limits<int>::max()) 5446 Op = MachineOperand::CreateFI(FI); 5447 5448 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5449 if (!Op && N.getNode()) { 5450 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5451 Register Reg; 5452 if (ArgRegsAndSizes.size() == 1) 5453 Reg = ArgRegsAndSizes.front().first; 5454 5455 if (Reg && Reg.isVirtual()) { 5456 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5457 Register PR = RegInfo.getLiveInPhysReg(Reg); 5458 if (PR) 5459 Reg = PR; 5460 } 5461 if (Reg) { 5462 Op = MachineOperand::CreateReg(Reg, false); 5463 IsIndirect = IsDbgDeclare; 5464 } 5465 } 5466 5467 if (!Op && N.getNode()) { 5468 // Check if frame index is available. 5469 SDValue LCandidate = peekThroughBitcasts(N); 5470 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5471 if (FrameIndexSDNode *FINode = 5472 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5473 Op = MachineOperand::CreateFI(FINode->getIndex()); 5474 } 5475 5476 if (!Op) { 5477 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5478 auto splitMultiRegDbgValue 5479 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5480 unsigned Offset = 0; 5481 for (auto RegAndSize : SplitRegs) { 5482 // If the expression is already a fragment, the current register 5483 // offset+size might extend beyond the fragment. In this case, only 5484 // the register bits that are inside the fragment are relevant. 5485 int RegFragmentSizeInBits = RegAndSize.second; 5486 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5487 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5488 // The register is entirely outside the expression fragment, 5489 // so is irrelevant for debug info. 5490 if (Offset >= ExprFragmentSizeInBits) 5491 break; 5492 // The register is partially outside the expression fragment, only 5493 // the low bits within the fragment are relevant for debug info. 5494 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5495 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5496 } 5497 } 5498 5499 auto FragmentExpr = DIExpression::createFragmentExpression( 5500 Expr, Offset, RegFragmentSizeInBits); 5501 Offset += RegAndSize.second; 5502 // If a valid fragment expression cannot be created, the variable's 5503 // correct value cannot be determined and so it is set as Undef. 5504 if (!FragmentExpr) { 5505 SDDbgValue *SDV = DAG.getConstantDbgValue( 5506 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5507 DAG.AddDbgValue(SDV, nullptr, false); 5508 continue; 5509 } 5510 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5511 FuncInfo.ArgDbgValues.push_back( 5512 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5513 RegAndSize.first, Variable, *FragmentExpr)); 5514 } 5515 }; 5516 5517 // Check if ValueMap has reg number. 5518 DenseMap<const Value *, Register>::const_iterator 5519 VMI = FuncInfo.ValueMap.find(V); 5520 if (VMI != FuncInfo.ValueMap.end()) { 5521 const auto &TLI = DAG.getTargetLoweringInfo(); 5522 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5523 V->getType(), getABIRegCopyCC(V)); 5524 if (RFV.occupiesMultipleRegs()) { 5525 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5526 return true; 5527 } 5528 5529 Op = MachineOperand::CreateReg(VMI->second, false); 5530 IsIndirect = IsDbgDeclare; 5531 } else if (ArgRegsAndSizes.size() > 1) { 5532 // This was split due to the calling convention, and no virtual register 5533 // mapping exists for the value. 5534 splitMultiRegDbgValue(ArgRegsAndSizes); 5535 return true; 5536 } 5537 } 5538 5539 if (!Op) 5540 return false; 5541 5542 assert(Variable->isValidLocationForIntrinsic(DL) && 5543 "Expected inlined-at fields to agree"); 5544 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5545 FuncInfo.ArgDbgValues.push_back( 5546 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5547 *Op, Variable, Expr)); 5548 5549 return true; 5550 } 5551 5552 /// Return the appropriate SDDbgValue based on N. 5553 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5554 DILocalVariable *Variable, 5555 DIExpression *Expr, 5556 const DebugLoc &dl, 5557 unsigned DbgSDNodeOrder) { 5558 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5559 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5560 // stack slot locations. 5561 // 5562 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5563 // debug values here after optimization: 5564 // 5565 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5566 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5567 // 5568 // Both describe the direct values of their associated variables. 5569 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5570 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5571 } 5572 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5573 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5574 } 5575 5576 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5577 switch (Intrinsic) { 5578 case Intrinsic::smul_fix: 5579 return ISD::SMULFIX; 5580 case Intrinsic::umul_fix: 5581 return ISD::UMULFIX; 5582 case Intrinsic::smul_fix_sat: 5583 return ISD::SMULFIXSAT; 5584 case Intrinsic::umul_fix_sat: 5585 return ISD::UMULFIXSAT; 5586 case Intrinsic::sdiv_fix: 5587 return ISD::SDIVFIX; 5588 case Intrinsic::udiv_fix: 5589 return ISD::UDIVFIX; 5590 case Intrinsic::sdiv_fix_sat: 5591 return ISD::SDIVFIXSAT; 5592 case Intrinsic::udiv_fix_sat: 5593 return ISD::UDIVFIXSAT; 5594 default: 5595 llvm_unreachable("Unhandled fixed point intrinsic"); 5596 } 5597 } 5598 5599 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5600 const char *FunctionName) { 5601 assert(FunctionName && "FunctionName must not be nullptr"); 5602 SDValue Callee = DAG.getExternalSymbol( 5603 FunctionName, 5604 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5605 LowerCallTo(I, Callee, I.isTailCall()); 5606 } 5607 5608 /// Given a @llvm.call.preallocated.setup, return the corresponding 5609 /// preallocated call. 5610 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5611 assert(cast<CallBase>(PreallocatedSetup) 5612 ->getCalledFunction() 5613 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5614 "expected call_preallocated_setup Value"); 5615 for (auto *U : PreallocatedSetup->users()) { 5616 auto *UseCall = cast<CallBase>(U); 5617 const Function *Fn = UseCall->getCalledFunction(); 5618 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5619 return UseCall; 5620 } 5621 } 5622 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5623 } 5624 5625 /// Lower the call to the specified intrinsic function. 5626 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5627 unsigned Intrinsic) { 5628 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5629 SDLoc sdl = getCurSDLoc(); 5630 DebugLoc dl = getCurDebugLoc(); 5631 SDValue Res; 5632 5633 SDNodeFlags Flags; 5634 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5635 Flags.copyFMF(*FPOp); 5636 5637 switch (Intrinsic) { 5638 default: 5639 // By default, turn this into a target intrinsic node. 5640 visitTargetIntrinsic(I, Intrinsic); 5641 return; 5642 case Intrinsic::vscale: { 5643 match(&I, m_VScale(DAG.getDataLayout())); 5644 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5645 setValue(&I, 5646 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5647 return; 5648 } 5649 case Intrinsic::vastart: visitVAStart(I); return; 5650 case Intrinsic::vaend: visitVAEnd(I); return; 5651 case Intrinsic::vacopy: visitVACopy(I); return; 5652 case Intrinsic::returnaddress: 5653 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5654 TLI.getPointerTy(DAG.getDataLayout()), 5655 getValue(I.getArgOperand(0)))); 5656 return; 5657 case Intrinsic::addressofreturnaddress: 5658 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5659 TLI.getPointerTy(DAG.getDataLayout()))); 5660 return; 5661 case Intrinsic::sponentry: 5662 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5663 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5664 return; 5665 case Intrinsic::frameaddress: 5666 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5667 TLI.getFrameIndexTy(DAG.getDataLayout()), 5668 getValue(I.getArgOperand(0)))); 5669 return; 5670 case Intrinsic::read_volatile_register: 5671 case Intrinsic::read_register: { 5672 Value *Reg = I.getArgOperand(0); 5673 SDValue Chain = getRoot(); 5674 SDValue RegName = 5675 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5676 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5677 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5678 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5679 setValue(&I, Res); 5680 DAG.setRoot(Res.getValue(1)); 5681 return; 5682 } 5683 case Intrinsic::write_register: { 5684 Value *Reg = I.getArgOperand(0); 5685 Value *RegValue = I.getArgOperand(1); 5686 SDValue Chain = getRoot(); 5687 SDValue RegName = 5688 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5689 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5690 RegName, getValue(RegValue))); 5691 return; 5692 } 5693 case Intrinsic::memcpy: { 5694 const auto &MCI = cast<MemCpyInst>(I); 5695 SDValue Op1 = getValue(I.getArgOperand(0)); 5696 SDValue Op2 = getValue(I.getArgOperand(1)); 5697 SDValue Op3 = getValue(I.getArgOperand(2)); 5698 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5699 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5700 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5701 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5702 bool isVol = MCI.isVolatile(); 5703 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5704 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5705 // node. 5706 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5707 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5708 /* AlwaysInline */ false, isTC, 5709 MachinePointerInfo(I.getArgOperand(0)), 5710 MachinePointerInfo(I.getArgOperand(1))); 5711 updateDAGForMaybeTailCall(MC); 5712 return; 5713 } 5714 case Intrinsic::memcpy_inline: { 5715 const auto &MCI = cast<MemCpyInlineInst>(I); 5716 SDValue Dst = getValue(I.getArgOperand(0)); 5717 SDValue Src = getValue(I.getArgOperand(1)); 5718 SDValue Size = getValue(I.getArgOperand(2)); 5719 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5720 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5721 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5722 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5723 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5724 bool isVol = MCI.isVolatile(); 5725 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5726 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5727 // node. 5728 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5729 /* AlwaysInline */ true, isTC, 5730 MachinePointerInfo(I.getArgOperand(0)), 5731 MachinePointerInfo(I.getArgOperand(1))); 5732 updateDAGForMaybeTailCall(MC); 5733 return; 5734 } 5735 case Intrinsic::memset: { 5736 const auto &MSI = cast<MemSetInst>(I); 5737 SDValue Op1 = getValue(I.getArgOperand(0)); 5738 SDValue Op2 = getValue(I.getArgOperand(1)); 5739 SDValue Op3 = getValue(I.getArgOperand(2)); 5740 // @llvm.memset defines 0 and 1 to both mean no alignment. 5741 Align Alignment = MSI.getDestAlign().valueOrOne(); 5742 bool isVol = MSI.isVolatile(); 5743 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5744 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5745 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5746 MachinePointerInfo(I.getArgOperand(0))); 5747 updateDAGForMaybeTailCall(MS); 5748 return; 5749 } 5750 case Intrinsic::memmove: { 5751 const auto &MMI = cast<MemMoveInst>(I); 5752 SDValue Op1 = getValue(I.getArgOperand(0)); 5753 SDValue Op2 = getValue(I.getArgOperand(1)); 5754 SDValue Op3 = getValue(I.getArgOperand(2)); 5755 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5756 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5757 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5758 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5759 bool isVol = MMI.isVolatile(); 5760 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5761 // FIXME: Support passing different dest/src alignments to the memmove DAG 5762 // node. 5763 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5764 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5765 isTC, MachinePointerInfo(I.getArgOperand(0)), 5766 MachinePointerInfo(I.getArgOperand(1))); 5767 updateDAGForMaybeTailCall(MM); 5768 return; 5769 } 5770 case Intrinsic::memcpy_element_unordered_atomic: { 5771 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5772 SDValue Dst = getValue(MI.getRawDest()); 5773 SDValue Src = getValue(MI.getRawSource()); 5774 SDValue Length = getValue(MI.getLength()); 5775 5776 unsigned DstAlign = MI.getDestAlignment(); 5777 unsigned SrcAlign = MI.getSourceAlignment(); 5778 Type *LengthTy = MI.getLength()->getType(); 5779 unsigned ElemSz = MI.getElementSizeInBytes(); 5780 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5781 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5782 SrcAlign, Length, LengthTy, ElemSz, isTC, 5783 MachinePointerInfo(MI.getRawDest()), 5784 MachinePointerInfo(MI.getRawSource())); 5785 updateDAGForMaybeTailCall(MC); 5786 return; 5787 } 5788 case Intrinsic::memmove_element_unordered_atomic: { 5789 auto &MI = cast<AtomicMemMoveInst>(I); 5790 SDValue Dst = getValue(MI.getRawDest()); 5791 SDValue Src = getValue(MI.getRawSource()); 5792 SDValue Length = getValue(MI.getLength()); 5793 5794 unsigned DstAlign = MI.getDestAlignment(); 5795 unsigned SrcAlign = MI.getSourceAlignment(); 5796 Type *LengthTy = MI.getLength()->getType(); 5797 unsigned ElemSz = MI.getElementSizeInBytes(); 5798 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5799 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5800 SrcAlign, Length, LengthTy, ElemSz, isTC, 5801 MachinePointerInfo(MI.getRawDest()), 5802 MachinePointerInfo(MI.getRawSource())); 5803 updateDAGForMaybeTailCall(MC); 5804 return; 5805 } 5806 case Intrinsic::memset_element_unordered_atomic: { 5807 auto &MI = cast<AtomicMemSetInst>(I); 5808 SDValue Dst = getValue(MI.getRawDest()); 5809 SDValue Val = getValue(MI.getValue()); 5810 SDValue Length = getValue(MI.getLength()); 5811 5812 unsigned DstAlign = MI.getDestAlignment(); 5813 Type *LengthTy = MI.getLength()->getType(); 5814 unsigned ElemSz = MI.getElementSizeInBytes(); 5815 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5816 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5817 LengthTy, ElemSz, isTC, 5818 MachinePointerInfo(MI.getRawDest())); 5819 updateDAGForMaybeTailCall(MC); 5820 return; 5821 } 5822 case Intrinsic::call_preallocated_setup: { 5823 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5824 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5825 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5826 getRoot(), SrcValue); 5827 setValue(&I, Res); 5828 DAG.setRoot(Res); 5829 return; 5830 } 5831 case Intrinsic::call_preallocated_arg: { 5832 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5833 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5834 SDValue Ops[3]; 5835 Ops[0] = getRoot(); 5836 Ops[1] = SrcValue; 5837 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5838 MVT::i32); // arg index 5839 SDValue Res = DAG.getNode( 5840 ISD::PREALLOCATED_ARG, sdl, 5841 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5842 setValue(&I, Res); 5843 DAG.setRoot(Res.getValue(1)); 5844 return; 5845 } 5846 case Intrinsic::dbg_addr: 5847 case Intrinsic::dbg_declare: { 5848 const auto &DI = cast<DbgVariableIntrinsic>(I); 5849 DILocalVariable *Variable = DI.getVariable(); 5850 DIExpression *Expression = DI.getExpression(); 5851 dropDanglingDebugInfo(Variable, Expression); 5852 assert(Variable && "Missing variable"); 5853 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5854 << "\n"); 5855 // Check if address has undef value. 5856 const Value *Address = DI.getVariableLocation(); 5857 if (!Address || isa<UndefValue>(Address) || 5858 (Address->use_empty() && !isa<Argument>(Address))) { 5859 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5860 << " (bad/undef/unused-arg address)\n"); 5861 return; 5862 } 5863 5864 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5865 5866 // Check if this variable can be described by a frame index, typically 5867 // either as a static alloca or a byval parameter. 5868 int FI = std::numeric_limits<int>::max(); 5869 if (const auto *AI = 5870 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5871 if (AI->isStaticAlloca()) { 5872 auto I = FuncInfo.StaticAllocaMap.find(AI); 5873 if (I != FuncInfo.StaticAllocaMap.end()) 5874 FI = I->second; 5875 } 5876 } else if (const auto *Arg = dyn_cast<Argument>( 5877 Address->stripInBoundsConstantOffsets())) { 5878 FI = FuncInfo.getArgumentFrameIndex(Arg); 5879 } 5880 5881 // llvm.dbg.addr is control dependent and always generates indirect 5882 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5883 // the MachineFunction variable table. 5884 if (FI != std::numeric_limits<int>::max()) { 5885 if (Intrinsic == Intrinsic::dbg_addr) { 5886 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5887 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5888 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5889 } else { 5890 LLVM_DEBUG(dbgs() << "Skipping " << DI 5891 << " (variable info stashed in MF side table)\n"); 5892 } 5893 return; 5894 } 5895 5896 SDValue &N = NodeMap[Address]; 5897 if (!N.getNode() && isa<Argument>(Address)) 5898 // Check unused arguments map. 5899 N = UnusedArgNodeMap[Address]; 5900 SDDbgValue *SDV; 5901 if (N.getNode()) { 5902 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5903 Address = BCI->getOperand(0); 5904 // Parameters are handled specially. 5905 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5906 if (isParameter && FINode) { 5907 // Byval parameter. We have a frame index at this point. 5908 SDV = 5909 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5910 /*IsIndirect*/ true, dl, SDNodeOrder); 5911 } else if (isa<Argument>(Address)) { 5912 // Address is an argument, so try to emit its dbg value using 5913 // virtual register info from the FuncInfo.ValueMap. 5914 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5915 return; 5916 } else { 5917 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5918 true, dl, SDNodeOrder); 5919 } 5920 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5921 } else { 5922 // If Address is an argument then try to emit its dbg value using 5923 // virtual register info from the FuncInfo.ValueMap. 5924 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5925 N)) { 5926 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5927 << " (could not emit func-arg dbg_value)\n"); 5928 } 5929 } 5930 return; 5931 } 5932 case Intrinsic::dbg_label: { 5933 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5934 DILabel *Label = DI.getLabel(); 5935 assert(Label && "Missing label"); 5936 5937 SDDbgLabel *SDV; 5938 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5939 DAG.AddDbgLabel(SDV); 5940 return; 5941 } 5942 case Intrinsic::dbg_value: { 5943 const DbgValueInst &DI = cast<DbgValueInst>(I); 5944 assert(DI.getVariable() && "Missing variable"); 5945 5946 DILocalVariable *Variable = DI.getVariable(); 5947 DIExpression *Expression = DI.getExpression(); 5948 dropDanglingDebugInfo(Variable, Expression); 5949 const Value *V = DI.getValue(); 5950 if (!V) 5951 return; 5952 5953 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5954 SDNodeOrder)) 5955 return; 5956 5957 // TODO: Dangling debug info will eventually either be resolved or produce 5958 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5959 // between the original dbg.value location and its resolved DBG_VALUE, which 5960 // we should ideally fill with an extra Undef DBG_VALUE. 5961 5962 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5963 return; 5964 } 5965 5966 case Intrinsic::eh_typeid_for: { 5967 // Find the type id for the given typeinfo. 5968 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5969 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5970 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5971 setValue(&I, Res); 5972 return; 5973 } 5974 5975 case Intrinsic::eh_return_i32: 5976 case Intrinsic::eh_return_i64: 5977 DAG.getMachineFunction().setCallsEHReturn(true); 5978 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5979 MVT::Other, 5980 getControlRoot(), 5981 getValue(I.getArgOperand(0)), 5982 getValue(I.getArgOperand(1)))); 5983 return; 5984 case Intrinsic::eh_unwind_init: 5985 DAG.getMachineFunction().setCallsUnwindInit(true); 5986 return; 5987 case Intrinsic::eh_dwarf_cfa: 5988 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5989 TLI.getPointerTy(DAG.getDataLayout()), 5990 getValue(I.getArgOperand(0)))); 5991 return; 5992 case Intrinsic::eh_sjlj_callsite: { 5993 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5994 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5995 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5996 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5997 5998 MMI.setCurrentCallSite(CI->getZExtValue()); 5999 return; 6000 } 6001 case Intrinsic::eh_sjlj_functioncontext: { 6002 // Get and store the index of the function context. 6003 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6004 AllocaInst *FnCtx = 6005 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6006 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6007 MFI.setFunctionContextIndex(FI); 6008 return; 6009 } 6010 case Intrinsic::eh_sjlj_setjmp: { 6011 SDValue Ops[2]; 6012 Ops[0] = getRoot(); 6013 Ops[1] = getValue(I.getArgOperand(0)); 6014 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6015 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6016 setValue(&I, Op.getValue(0)); 6017 DAG.setRoot(Op.getValue(1)); 6018 return; 6019 } 6020 case Intrinsic::eh_sjlj_longjmp: 6021 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6022 getRoot(), getValue(I.getArgOperand(0)))); 6023 return; 6024 case Intrinsic::eh_sjlj_setup_dispatch: 6025 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6026 getRoot())); 6027 return; 6028 case Intrinsic::masked_gather: 6029 visitMaskedGather(I); 6030 return; 6031 case Intrinsic::masked_load: 6032 visitMaskedLoad(I); 6033 return; 6034 case Intrinsic::masked_scatter: 6035 visitMaskedScatter(I); 6036 return; 6037 case Intrinsic::masked_store: 6038 visitMaskedStore(I); 6039 return; 6040 case Intrinsic::masked_expandload: 6041 visitMaskedLoad(I, true /* IsExpanding */); 6042 return; 6043 case Intrinsic::masked_compressstore: 6044 visitMaskedStore(I, true /* IsCompressing */); 6045 return; 6046 case Intrinsic::powi: 6047 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6048 getValue(I.getArgOperand(1)), DAG)); 6049 return; 6050 case Intrinsic::log: 6051 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6052 return; 6053 case Intrinsic::log2: 6054 setValue(&I, 6055 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6056 return; 6057 case Intrinsic::log10: 6058 setValue(&I, 6059 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6060 return; 6061 case Intrinsic::exp: 6062 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6063 return; 6064 case Intrinsic::exp2: 6065 setValue(&I, 6066 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6067 return; 6068 case Intrinsic::pow: 6069 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6070 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6071 return; 6072 case Intrinsic::sqrt: 6073 case Intrinsic::fabs: 6074 case Intrinsic::sin: 6075 case Intrinsic::cos: 6076 case Intrinsic::floor: 6077 case Intrinsic::ceil: 6078 case Intrinsic::trunc: 6079 case Intrinsic::rint: 6080 case Intrinsic::nearbyint: 6081 case Intrinsic::round: 6082 case Intrinsic::roundeven: 6083 case Intrinsic::canonicalize: { 6084 unsigned Opcode; 6085 switch (Intrinsic) { 6086 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6087 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6088 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6089 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6090 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6091 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6092 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6093 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6094 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6095 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6096 case Intrinsic::round: Opcode = ISD::FROUND; break; 6097 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6098 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6099 } 6100 6101 setValue(&I, DAG.getNode(Opcode, sdl, 6102 getValue(I.getArgOperand(0)).getValueType(), 6103 getValue(I.getArgOperand(0)), Flags)); 6104 return; 6105 } 6106 case Intrinsic::lround: 6107 case Intrinsic::llround: 6108 case Intrinsic::lrint: 6109 case Intrinsic::llrint: { 6110 unsigned Opcode; 6111 switch (Intrinsic) { 6112 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6113 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6114 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6115 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6116 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6117 } 6118 6119 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6120 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6121 getValue(I.getArgOperand(0)))); 6122 return; 6123 } 6124 case Intrinsic::minnum: 6125 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6126 getValue(I.getArgOperand(0)).getValueType(), 6127 getValue(I.getArgOperand(0)), 6128 getValue(I.getArgOperand(1)), Flags)); 6129 return; 6130 case Intrinsic::maxnum: 6131 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6132 getValue(I.getArgOperand(0)).getValueType(), 6133 getValue(I.getArgOperand(0)), 6134 getValue(I.getArgOperand(1)), Flags)); 6135 return; 6136 case Intrinsic::minimum: 6137 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6138 getValue(I.getArgOperand(0)).getValueType(), 6139 getValue(I.getArgOperand(0)), 6140 getValue(I.getArgOperand(1)), Flags)); 6141 return; 6142 case Intrinsic::maximum: 6143 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6144 getValue(I.getArgOperand(0)).getValueType(), 6145 getValue(I.getArgOperand(0)), 6146 getValue(I.getArgOperand(1)), Flags)); 6147 return; 6148 case Intrinsic::copysign: 6149 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6150 getValue(I.getArgOperand(0)).getValueType(), 6151 getValue(I.getArgOperand(0)), 6152 getValue(I.getArgOperand(1)), Flags)); 6153 return; 6154 case Intrinsic::fma: 6155 setValue(&I, DAG.getNode( 6156 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6157 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6158 getValue(I.getArgOperand(2)), Flags)); 6159 return; 6160 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6161 case Intrinsic::INTRINSIC: 6162 #include "llvm/IR/ConstrainedOps.def" 6163 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6164 return; 6165 case Intrinsic::fmuladd: { 6166 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6167 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6168 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6169 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6170 getValue(I.getArgOperand(0)).getValueType(), 6171 getValue(I.getArgOperand(0)), 6172 getValue(I.getArgOperand(1)), 6173 getValue(I.getArgOperand(2)), Flags)); 6174 } else { 6175 // TODO: Intrinsic calls should have fast-math-flags. 6176 SDValue Mul = DAG.getNode( 6177 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6178 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6179 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6180 getValue(I.getArgOperand(0)).getValueType(), 6181 Mul, getValue(I.getArgOperand(2)), Flags); 6182 setValue(&I, Add); 6183 } 6184 return; 6185 } 6186 case Intrinsic::convert_to_fp16: 6187 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6188 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6189 getValue(I.getArgOperand(0)), 6190 DAG.getTargetConstant(0, sdl, 6191 MVT::i32)))); 6192 return; 6193 case Intrinsic::convert_from_fp16: 6194 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6195 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6196 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6197 getValue(I.getArgOperand(0))))); 6198 return; 6199 case Intrinsic::pcmarker: { 6200 SDValue Tmp = getValue(I.getArgOperand(0)); 6201 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6202 return; 6203 } 6204 case Intrinsic::readcyclecounter: { 6205 SDValue Op = getRoot(); 6206 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6207 DAG.getVTList(MVT::i64, MVT::Other), Op); 6208 setValue(&I, Res); 6209 DAG.setRoot(Res.getValue(1)); 6210 return; 6211 } 6212 case Intrinsic::bitreverse: 6213 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6214 getValue(I.getArgOperand(0)).getValueType(), 6215 getValue(I.getArgOperand(0)))); 6216 return; 6217 case Intrinsic::bswap: 6218 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6219 getValue(I.getArgOperand(0)).getValueType(), 6220 getValue(I.getArgOperand(0)))); 6221 return; 6222 case Intrinsic::cttz: { 6223 SDValue Arg = getValue(I.getArgOperand(0)); 6224 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6225 EVT Ty = Arg.getValueType(); 6226 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6227 sdl, Ty, Arg)); 6228 return; 6229 } 6230 case Intrinsic::ctlz: { 6231 SDValue Arg = getValue(I.getArgOperand(0)); 6232 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6233 EVT Ty = Arg.getValueType(); 6234 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6235 sdl, Ty, Arg)); 6236 return; 6237 } 6238 case Intrinsic::ctpop: { 6239 SDValue Arg = getValue(I.getArgOperand(0)); 6240 EVT Ty = Arg.getValueType(); 6241 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6242 return; 6243 } 6244 case Intrinsic::fshl: 6245 case Intrinsic::fshr: { 6246 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6247 SDValue X = getValue(I.getArgOperand(0)); 6248 SDValue Y = getValue(I.getArgOperand(1)); 6249 SDValue Z = getValue(I.getArgOperand(2)); 6250 EVT VT = X.getValueType(); 6251 6252 if (X == Y) { 6253 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6254 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6255 } else { 6256 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6257 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6258 } 6259 return; 6260 } 6261 case Intrinsic::sadd_sat: { 6262 SDValue Op1 = getValue(I.getArgOperand(0)); 6263 SDValue Op2 = getValue(I.getArgOperand(1)); 6264 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6265 return; 6266 } 6267 case Intrinsic::uadd_sat: { 6268 SDValue Op1 = getValue(I.getArgOperand(0)); 6269 SDValue Op2 = getValue(I.getArgOperand(1)); 6270 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6271 return; 6272 } 6273 case Intrinsic::ssub_sat: { 6274 SDValue Op1 = getValue(I.getArgOperand(0)); 6275 SDValue Op2 = getValue(I.getArgOperand(1)); 6276 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6277 return; 6278 } 6279 case Intrinsic::usub_sat: { 6280 SDValue Op1 = getValue(I.getArgOperand(0)); 6281 SDValue Op2 = getValue(I.getArgOperand(1)); 6282 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6283 return; 6284 } 6285 case Intrinsic::sshl_sat: { 6286 SDValue Op1 = getValue(I.getArgOperand(0)); 6287 SDValue Op2 = getValue(I.getArgOperand(1)); 6288 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6289 return; 6290 } 6291 case Intrinsic::ushl_sat: { 6292 SDValue Op1 = getValue(I.getArgOperand(0)); 6293 SDValue Op2 = getValue(I.getArgOperand(1)); 6294 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6295 return; 6296 } 6297 case Intrinsic::smul_fix: 6298 case Intrinsic::umul_fix: 6299 case Intrinsic::smul_fix_sat: 6300 case Intrinsic::umul_fix_sat: { 6301 SDValue Op1 = getValue(I.getArgOperand(0)); 6302 SDValue Op2 = getValue(I.getArgOperand(1)); 6303 SDValue Op3 = getValue(I.getArgOperand(2)); 6304 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6305 Op1.getValueType(), Op1, Op2, Op3)); 6306 return; 6307 } 6308 case Intrinsic::sdiv_fix: 6309 case Intrinsic::udiv_fix: 6310 case Intrinsic::sdiv_fix_sat: 6311 case Intrinsic::udiv_fix_sat: { 6312 SDValue Op1 = getValue(I.getArgOperand(0)); 6313 SDValue Op2 = getValue(I.getArgOperand(1)); 6314 SDValue Op3 = getValue(I.getArgOperand(2)); 6315 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6316 Op1, Op2, Op3, DAG, TLI)); 6317 return; 6318 } 6319 case Intrinsic::smax: { 6320 SDValue Op1 = getValue(I.getArgOperand(0)); 6321 SDValue Op2 = getValue(I.getArgOperand(1)); 6322 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6323 return; 6324 } 6325 case Intrinsic::smin: { 6326 SDValue Op1 = getValue(I.getArgOperand(0)); 6327 SDValue Op2 = getValue(I.getArgOperand(1)); 6328 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6329 return; 6330 } 6331 case Intrinsic::umax: { 6332 SDValue Op1 = getValue(I.getArgOperand(0)); 6333 SDValue Op2 = getValue(I.getArgOperand(1)); 6334 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6335 return; 6336 } 6337 case Intrinsic::umin: { 6338 SDValue Op1 = getValue(I.getArgOperand(0)); 6339 SDValue Op2 = getValue(I.getArgOperand(1)); 6340 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6341 return; 6342 } 6343 case Intrinsic::abs: { 6344 // TODO: Preserve "int min is poison" arg in SDAG? 6345 SDValue Op1 = getValue(I.getArgOperand(0)); 6346 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6347 return; 6348 } 6349 case Intrinsic::stacksave: { 6350 SDValue Op = getRoot(); 6351 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6352 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6353 setValue(&I, Res); 6354 DAG.setRoot(Res.getValue(1)); 6355 return; 6356 } 6357 case Intrinsic::stackrestore: 6358 Res = getValue(I.getArgOperand(0)); 6359 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6360 return; 6361 case Intrinsic::get_dynamic_area_offset: { 6362 SDValue Op = getRoot(); 6363 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6364 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6365 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6366 // target. 6367 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6368 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6369 " intrinsic!"); 6370 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6371 Op); 6372 DAG.setRoot(Op); 6373 setValue(&I, Res); 6374 return; 6375 } 6376 case Intrinsic::stackguard: { 6377 MachineFunction &MF = DAG.getMachineFunction(); 6378 const Module &M = *MF.getFunction().getParent(); 6379 SDValue Chain = getRoot(); 6380 if (TLI.useLoadStackGuardNode()) { 6381 Res = getLoadStackGuard(DAG, sdl, Chain); 6382 } else { 6383 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6384 const Value *Global = TLI.getSDagStackGuard(M); 6385 Align Align = DL->getPrefTypeAlign(Global->getType()); 6386 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6387 MachinePointerInfo(Global, 0), Align, 6388 MachineMemOperand::MOVolatile); 6389 } 6390 if (TLI.useStackGuardXorFP()) 6391 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6392 DAG.setRoot(Chain); 6393 setValue(&I, Res); 6394 return; 6395 } 6396 case Intrinsic::stackprotector: { 6397 // Emit code into the DAG to store the stack guard onto the stack. 6398 MachineFunction &MF = DAG.getMachineFunction(); 6399 MachineFrameInfo &MFI = MF.getFrameInfo(); 6400 SDValue Src, Chain = getRoot(); 6401 6402 if (TLI.useLoadStackGuardNode()) 6403 Src = getLoadStackGuard(DAG, sdl, Chain); 6404 else 6405 Src = getValue(I.getArgOperand(0)); // The guard's value. 6406 6407 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6408 6409 int FI = FuncInfo.StaticAllocaMap[Slot]; 6410 MFI.setStackProtectorIndex(FI); 6411 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6412 6413 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6414 6415 // Store the stack protector onto the stack. 6416 Res = DAG.getStore( 6417 Chain, sdl, Src, FIN, 6418 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6419 MaybeAlign(), MachineMemOperand::MOVolatile); 6420 setValue(&I, Res); 6421 DAG.setRoot(Res); 6422 return; 6423 } 6424 case Intrinsic::objectsize: 6425 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6426 6427 case Intrinsic::is_constant: 6428 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6429 6430 case Intrinsic::annotation: 6431 case Intrinsic::ptr_annotation: 6432 case Intrinsic::launder_invariant_group: 6433 case Intrinsic::strip_invariant_group: 6434 // Drop the intrinsic, but forward the value 6435 setValue(&I, getValue(I.getOperand(0))); 6436 return; 6437 case Intrinsic::assume: 6438 case Intrinsic::var_annotation: 6439 case Intrinsic::sideeffect: 6440 // Discard annotate attributes, assumptions, and artificial side-effects. 6441 return; 6442 6443 case Intrinsic::codeview_annotation: { 6444 // Emit a label associated with this metadata. 6445 MachineFunction &MF = DAG.getMachineFunction(); 6446 MCSymbol *Label = 6447 MF.getMMI().getContext().createTempSymbol("annotation", true); 6448 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6449 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6450 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6451 DAG.setRoot(Res); 6452 return; 6453 } 6454 6455 case Intrinsic::init_trampoline: { 6456 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6457 6458 SDValue Ops[6]; 6459 Ops[0] = getRoot(); 6460 Ops[1] = getValue(I.getArgOperand(0)); 6461 Ops[2] = getValue(I.getArgOperand(1)); 6462 Ops[3] = getValue(I.getArgOperand(2)); 6463 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6464 Ops[5] = DAG.getSrcValue(F); 6465 6466 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6467 6468 DAG.setRoot(Res); 6469 return; 6470 } 6471 case Intrinsic::adjust_trampoline: 6472 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6473 TLI.getPointerTy(DAG.getDataLayout()), 6474 getValue(I.getArgOperand(0)))); 6475 return; 6476 case Intrinsic::gcroot: { 6477 assert(DAG.getMachineFunction().getFunction().hasGC() && 6478 "only valid in functions with gc specified, enforced by Verifier"); 6479 assert(GFI && "implied by previous"); 6480 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6481 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6482 6483 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6484 GFI->addStackRoot(FI->getIndex(), TypeMap); 6485 return; 6486 } 6487 case Intrinsic::gcread: 6488 case Intrinsic::gcwrite: 6489 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6490 case Intrinsic::flt_rounds: 6491 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6492 setValue(&I, Res); 6493 DAG.setRoot(Res.getValue(1)); 6494 return; 6495 6496 case Intrinsic::expect: 6497 // Just replace __builtin_expect(exp, c) with EXP. 6498 setValue(&I, getValue(I.getArgOperand(0))); 6499 return; 6500 6501 case Intrinsic::debugtrap: 6502 case Intrinsic::trap: { 6503 StringRef TrapFuncName = 6504 I.getAttributes() 6505 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6506 .getValueAsString(); 6507 if (TrapFuncName.empty()) { 6508 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6509 ISD::TRAP : ISD::DEBUGTRAP; 6510 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6511 return; 6512 } 6513 TargetLowering::ArgListTy Args; 6514 6515 TargetLowering::CallLoweringInfo CLI(DAG); 6516 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6517 CallingConv::C, I.getType(), 6518 DAG.getExternalSymbol(TrapFuncName.data(), 6519 TLI.getPointerTy(DAG.getDataLayout())), 6520 std::move(Args)); 6521 6522 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6523 DAG.setRoot(Result.second); 6524 return; 6525 } 6526 6527 case Intrinsic::uadd_with_overflow: 6528 case Intrinsic::sadd_with_overflow: 6529 case Intrinsic::usub_with_overflow: 6530 case Intrinsic::ssub_with_overflow: 6531 case Intrinsic::umul_with_overflow: 6532 case Intrinsic::smul_with_overflow: { 6533 ISD::NodeType Op; 6534 switch (Intrinsic) { 6535 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6536 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6537 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6538 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6539 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6540 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6541 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6542 } 6543 SDValue Op1 = getValue(I.getArgOperand(0)); 6544 SDValue Op2 = getValue(I.getArgOperand(1)); 6545 6546 EVT ResultVT = Op1.getValueType(); 6547 EVT OverflowVT = MVT::i1; 6548 if (ResultVT.isVector()) 6549 OverflowVT = EVT::getVectorVT( 6550 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6551 6552 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6553 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6554 return; 6555 } 6556 case Intrinsic::prefetch: { 6557 SDValue Ops[5]; 6558 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6559 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6560 Ops[0] = DAG.getRoot(); 6561 Ops[1] = getValue(I.getArgOperand(0)); 6562 Ops[2] = getValue(I.getArgOperand(1)); 6563 Ops[3] = getValue(I.getArgOperand(2)); 6564 Ops[4] = getValue(I.getArgOperand(3)); 6565 SDValue Result = DAG.getMemIntrinsicNode( 6566 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6567 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6568 /* align */ None, Flags); 6569 6570 // Chain the prefetch in parallell with any pending loads, to stay out of 6571 // the way of later optimizations. 6572 PendingLoads.push_back(Result); 6573 Result = getRoot(); 6574 DAG.setRoot(Result); 6575 return; 6576 } 6577 case Intrinsic::lifetime_start: 6578 case Intrinsic::lifetime_end: { 6579 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6580 // Stack coloring is not enabled in O0, discard region information. 6581 if (TM.getOptLevel() == CodeGenOpt::None) 6582 return; 6583 6584 const int64_t ObjectSize = 6585 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6586 Value *const ObjectPtr = I.getArgOperand(1); 6587 SmallVector<const Value *, 4> Allocas; 6588 getUnderlyingObjects(ObjectPtr, Allocas); 6589 6590 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6591 E = Allocas.end(); Object != E; ++Object) { 6592 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6593 6594 // Could not find an Alloca. 6595 if (!LifetimeObject) 6596 continue; 6597 6598 // First check that the Alloca is static, otherwise it won't have a 6599 // valid frame index. 6600 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6601 if (SI == FuncInfo.StaticAllocaMap.end()) 6602 return; 6603 6604 const int FrameIndex = SI->second; 6605 int64_t Offset; 6606 if (GetPointerBaseWithConstantOffset( 6607 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6608 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6609 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6610 Offset); 6611 DAG.setRoot(Res); 6612 } 6613 return; 6614 } 6615 case Intrinsic::invariant_start: 6616 // Discard region information. 6617 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6618 return; 6619 case Intrinsic::invariant_end: 6620 // Discard region information. 6621 return; 6622 case Intrinsic::clear_cache: 6623 /// FunctionName may be null. 6624 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6625 lowerCallToExternalSymbol(I, FunctionName); 6626 return; 6627 case Intrinsic::donothing: 6628 // ignore 6629 return; 6630 case Intrinsic::experimental_stackmap: 6631 visitStackmap(I); 6632 return; 6633 case Intrinsic::experimental_patchpoint_void: 6634 case Intrinsic::experimental_patchpoint_i64: 6635 visitPatchpoint(I); 6636 return; 6637 case Intrinsic::experimental_gc_statepoint: 6638 LowerStatepoint(cast<GCStatepointInst>(I)); 6639 return; 6640 case Intrinsic::experimental_gc_result: 6641 visitGCResult(cast<GCResultInst>(I)); 6642 return; 6643 case Intrinsic::experimental_gc_relocate: 6644 visitGCRelocate(cast<GCRelocateInst>(I)); 6645 return; 6646 case Intrinsic::instrprof_increment: 6647 llvm_unreachable("instrprof failed to lower an increment"); 6648 case Intrinsic::instrprof_value_profile: 6649 llvm_unreachable("instrprof failed to lower a value profiling call"); 6650 case Intrinsic::localescape: { 6651 MachineFunction &MF = DAG.getMachineFunction(); 6652 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6653 6654 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6655 // is the same on all targets. 6656 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6657 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6658 if (isa<ConstantPointerNull>(Arg)) 6659 continue; // Skip null pointers. They represent a hole in index space. 6660 AllocaInst *Slot = cast<AllocaInst>(Arg); 6661 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6662 "can only escape static allocas"); 6663 int FI = FuncInfo.StaticAllocaMap[Slot]; 6664 MCSymbol *FrameAllocSym = 6665 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6666 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6667 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6668 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6669 .addSym(FrameAllocSym) 6670 .addFrameIndex(FI); 6671 } 6672 6673 return; 6674 } 6675 6676 case Intrinsic::localrecover: { 6677 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6678 MachineFunction &MF = DAG.getMachineFunction(); 6679 6680 // Get the symbol that defines the frame offset. 6681 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6682 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6683 unsigned IdxVal = 6684 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6685 MCSymbol *FrameAllocSym = 6686 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6687 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6688 6689 Value *FP = I.getArgOperand(1); 6690 SDValue FPVal = getValue(FP); 6691 EVT PtrVT = FPVal.getValueType(); 6692 6693 // Create a MCSymbol for the label to avoid any target lowering 6694 // that would make this PC relative. 6695 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6696 SDValue OffsetVal = 6697 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6698 6699 // Add the offset to the FP. 6700 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6701 setValue(&I, Add); 6702 6703 return; 6704 } 6705 6706 case Intrinsic::eh_exceptionpointer: 6707 case Intrinsic::eh_exceptioncode: { 6708 // Get the exception pointer vreg, copy from it, and resize it to fit. 6709 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6710 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6711 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6712 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6713 SDValue N = 6714 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6715 if (Intrinsic == Intrinsic::eh_exceptioncode) 6716 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6717 setValue(&I, N); 6718 return; 6719 } 6720 case Intrinsic::xray_customevent: { 6721 // Here we want to make sure that the intrinsic behaves as if it has a 6722 // specific calling convention, and only for x86_64. 6723 // FIXME: Support other platforms later. 6724 const auto &Triple = DAG.getTarget().getTargetTriple(); 6725 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6726 return; 6727 6728 SDLoc DL = getCurSDLoc(); 6729 SmallVector<SDValue, 8> Ops; 6730 6731 // We want to say that we always want the arguments in registers. 6732 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6733 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6734 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6735 SDValue Chain = getRoot(); 6736 Ops.push_back(LogEntryVal); 6737 Ops.push_back(StrSizeVal); 6738 Ops.push_back(Chain); 6739 6740 // We need to enforce the calling convention for the callsite, so that 6741 // argument ordering is enforced correctly, and that register allocation can 6742 // see that some registers may be assumed clobbered and have to preserve 6743 // them across calls to the intrinsic. 6744 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6745 DL, NodeTys, Ops); 6746 SDValue patchableNode = SDValue(MN, 0); 6747 DAG.setRoot(patchableNode); 6748 setValue(&I, patchableNode); 6749 return; 6750 } 6751 case Intrinsic::xray_typedevent: { 6752 // Here we want to make sure that the intrinsic behaves as if it has a 6753 // specific calling convention, and only for x86_64. 6754 // FIXME: Support other platforms later. 6755 const auto &Triple = DAG.getTarget().getTargetTriple(); 6756 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6757 return; 6758 6759 SDLoc DL = getCurSDLoc(); 6760 SmallVector<SDValue, 8> Ops; 6761 6762 // We want to say that we always want the arguments in registers. 6763 // It's unclear to me how manipulating the selection DAG here forces callers 6764 // to provide arguments in registers instead of on the stack. 6765 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6766 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6767 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6768 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6769 SDValue Chain = getRoot(); 6770 Ops.push_back(LogTypeId); 6771 Ops.push_back(LogEntryVal); 6772 Ops.push_back(StrSizeVal); 6773 Ops.push_back(Chain); 6774 6775 // We need to enforce the calling convention for the callsite, so that 6776 // argument ordering is enforced correctly, and that register allocation can 6777 // see that some registers may be assumed clobbered and have to preserve 6778 // them across calls to the intrinsic. 6779 MachineSDNode *MN = DAG.getMachineNode( 6780 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6781 SDValue patchableNode = SDValue(MN, 0); 6782 DAG.setRoot(patchableNode); 6783 setValue(&I, patchableNode); 6784 return; 6785 } 6786 case Intrinsic::experimental_deoptimize: 6787 LowerDeoptimizeCall(&I); 6788 return; 6789 6790 case Intrinsic::experimental_vector_reduce_v2_fadd: 6791 case Intrinsic::experimental_vector_reduce_v2_fmul: 6792 case Intrinsic::experimental_vector_reduce_add: 6793 case Intrinsic::experimental_vector_reduce_mul: 6794 case Intrinsic::experimental_vector_reduce_and: 6795 case Intrinsic::experimental_vector_reduce_or: 6796 case Intrinsic::experimental_vector_reduce_xor: 6797 case Intrinsic::experimental_vector_reduce_smax: 6798 case Intrinsic::experimental_vector_reduce_smin: 6799 case Intrinsic::experimental_vector_reduce_umax: 6800 case Intrinsic::experimental_vector_reduce_umin: 6801 case Intrinsic::experimental_vector_reduce_fmax: 6802 case Intrinsic::experimental_vector_reduce_fmin: 6803 visitVectorReduce(I, Intrinsic); 6804 return; 6805 6806 case Intrinsic::icall_branch_funnel: { 6807 SmallVector<SDValue, 16> Ops; 6808 Ops.push_back(getValue(I.getArgOperand(0))); 6809 6810 int64_t Offset; 6811 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6812 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6813 if (!Base) 6814 report_fatal_error( 6815 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6816 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6817 6818 struct BranchFunnelTarget { 6819 int64_t Offset; 6820 SDValue Target; 6821 }; 6822 SmallVector<BranchFunnelTarget, 8> Targets; 6823 6824 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6825 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6826 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6827 if (ElemBase != Base) 6828 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6829 "to the same GlobalValue"); 6830 6831 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6832 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6833 if (!GA) 6834 report_fatal_error( 6835 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6836 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6837 GA->getGlobal(), getCurSDLoc(), 6838 Val.getValueType(), GA->getOffset())}); 6839 } 6840 llvm::sort(Targets, 6841 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6842 return T1.Offset < T2.Offset; 6843 }); 6844 6845 for (auto &T : Targets) { 6846 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6847 Ops.push_back(T.Target); 6848 } 6849 6850 Ops.push_back(DAG.getRoot()); // Chain 6851 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6852 getCurSDLoc(), MVT::Other, Ops), 6853 0); 6854 DAG.setRoot(N); 6855 setValue(&I, N); 6856 HasTailCall = true; 6857 return; 6858 } 6859 6860 case Intrinsic::wasm_landingpad_index: 6861 // Information this intrinsic contained has been transferred to 6862 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6863 // delete it now. 6864 return; 6865 6866 case Intrinsic::aarch64_settag: 6867 case Intrinsic::aarch64_settag_zero: { 6868 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6869 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6870 SDValue Val = TSI.EmitTargetCodeForSetTag( 6871 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6872 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6873 ZeroMemory); 6874 DAG.setRoot(Val); 6875 setValue(&I, Val); 6876 return; 6877 } 6878 case Intrinsic::ptrmask: { 6879 SDValue Ptr = getValue(I.getOperand(0)); 6880 SDValue Const = getValue(I.getOperand(1)); 6881 6882 EVT PtrVT = Ptr.getValueType(); 6883 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 6884 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 6885 return; 6886 } 6887 case Intrinsic::get_active_lane_mask: { 6888 auto DL = getCurSDLoc(); 6889 SDValue Index = getValue(I.getOperand(0)); 6890 SDValue TripCount = getValue(I.getOperand(1)); 6891 Type *ElementTy = I.getOperand(0)->getType(); 6892 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6893 unsigned VecWidth = VT.getVectorNumElements(); 6894 6895 SmallVector<SDValue, 16> OpsTripCount; 6896 SmallVector<SDValue, 16> OpsIndex; 6897 SmallVector<SDValue, 16> OpsStepConstants; 6898 for (unsigned i = 0; i < VecWidth; i++) { 6899 OpsTripCount.push_back(TripCount); 6900 OpsIndex.push_back(Index); 6901 OpsStepConstants.push_back( 6902 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 6903 } 6904 6905 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 6906 6907 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 6908 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 6909 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 6910 SDValue VectorInduction = DAG.getNode( 6911 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 6912 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 6913 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 6914 VectorTripCount, ISD::CondCode::SETULT); 6915 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 6916 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 6917 SetCC)); 6918 return; 6919 } 6920 } 6921 } 6922 6923 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6924 const ConstrainedFPIntrinsic &FPI) { 6925 SDLoc sdl = getCurSDLoc(); 6926 6927 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6928 SmallVector<EVT, 4> ValueVTs; 6929 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6930 ValueVTs.push_back(MVT::Other); // Out chain 6931 6932 // We do not need to serialize constrained FP intrinsics against 6933 // each other or against (nonvolatile) loads, so they can be 6934 // chained like loads. 6935 SDValue Chain = DAG.getRoot(); 6936 SmallVector<SDValue, 4> Opers; 6937 Opers.push_back(Chain); 6938 if (FPI.isUnaryOp()) { 6939 Opers.push_back(getValue(FPI.getArgOperand(0))); 6940 } else if (FPI.isTernaryOp()) { 6941 Opers.push_back(getValue(FPI.getArgOperand(0))); 6942 Opers.push_back(getValue(FPI.getArgOperand(1))); 6943 Opers.push_back(getValue(FPI.getArgOperand(2))); 6944 } else { 6945 Opers.push_back(getValue(FPI.getArgOperand(0))); 6946 Opers.push_back(getValue(FPI.getArgOperand(1))); 6947 } 6948 6949 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6950 assert(Result.getNode()->getNumValues() == 2); 6951 6952 // Push node to the appropriate list so that future instructions can be 6953 // chained up correctly. 6954 SDValue OutChain = Result.getValue(1); 6955 switch (EB) { 6956 case fp::ExceptionBehavior::ebIgnore: 6957 // The only reason why ebIgnore nodes still need to be chained is that 6958 // they might depend on the current rounding mode, and therefore must 6959 // not be moved across instruction that may change that mode. 6960 LLVM_FALLTHROUGH; 6961 case fp::ExceptionBehavior::ebMayTrap: 6962 // These must not be moved across calls or instructions that may change 6963 // floating-point exception masks. 6964 PendingConstrainedFP.push_back(OutChain); 6965 break; 6966 case fp::ExceptionBehavior::ebStrict: 6967 // These must not be moved across calls or instructions that may change 6968 // floating-point exception masks or read floating-point exception flags. 6969 // In addition, they cannot be optimized out even if unused. 6970 PendingConstrainedFPStrict.push_back(OutChain); 6971 break; 6972 } 6973 }; 6974 6975 SDVTList VTs = DAG.getVTList(ValueVTs); 6976 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 6977 6978 SDNodeFlags Flags; 6979 if (EB == fp::ExceptionBehavior::ebIgnore) 6980 Flags.setNoFPExcept(true); 6981 6982 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 6983 Flags.copyFMF(*FPOp); 6984 6985 unsigned Opcode; 6986 switch (FPI.getIntrinsicID()) { 6987 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6988 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6989 case Intrinsic::INTRINSIC: \ 6990 Opcode = ISD::STRICT_##DAGN; \ 6991 break; 6992 #include "llvm/IR/ConstrainedOps.def" 6993 case Intrinsic::experimental_constrained_fmuladd: { 6994 Opcode = ISD::STRICT_FMA; 6995 // Break fmuladd into fmul and fadd. 6996 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 6997 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 6998 ValueVTs[0])) { 6999 Opers.pop_back(); 7000 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7001 pushOutChain(Mul, EB); 7002 Opcode = ISD::STRICT_FADD; 7003 Opers.clear(); 7004 Opers.push_back(Mul.getValue(1)); 7005 Opers.push_back(Mul.getValue(0)); 7006 Opers.push_back(getValue(FPI.getArgOperand(2))); 7007 } 7008 break; 7009 } 7010 } 7011 7012 // A few strict DAG nodes carry additional operands that are not 7013 // set up by the default code above. 7014 switch (Opcode) { 7015 default: break; 7016 case ISD::STRICT_FP_ROUND: 7017 Opers.push_back( 7018 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7019 break; 7020 case ISD::STRICT_FSETCC: 7021 case ISD::STRICT_FSETCCS: { 7022 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7023 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7024 break; 7025 } 7026 } 7027 7028 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7029 pushOutChain(Result, EB); 7030 7031 SDValue FPResult = Result.getValue(0); 7032 setValue(&FPI, FPResult); 7033 } 7034 7035 std::pair<SDValue, SDValue> 7036 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7037 const BasicBlock *EHPadBB) { 7038 MachineFunction &MF = DAG.getMachineFunction(); 7039 MachineModuleInfo &MMI = MF.getMMI(); 7040 MCSymbol *BeginLabel = nullptr; 7041 7042 if (EHPadBB) { 7043 // Insert a label before the invoke call to mark the try range. This can be 7044 // used to detect deletion of the invoke via the MachineModuleInfo. 7045 BeginLabel = MMI.getContext().createTempSymbol(); 7046 7047 // For SjLj, keep track of which landing pads go with which invokes 7048 // so as to maintain the ordering of pads in the LSDA. 7049 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7050 if (CallSiteIndex) { 7051 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7052 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7053 7054 // Now that the call site is handled, stop tracking it. 7055 MMI.setCurrentCallSite(0); 7056 } 7057 7058 // Both PendingLoads and PendingExports must be flushed here; 7059 // this call might not return. 7060 (void)getRoot(); 7061 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7062 7063 CLI.setChain(getRoot()); 7064 } 7065 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7066 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7067 7068 assert((CLI.IsTailCall || Result.second.getNode()) && 7069 "Non-null chain expected with non-tail call!"); 7070 assert((Result.second.getNode() || !Result.first.getNode()) && 7071 "Null value expected with tail call!"); 7072 7073 if (!Result.second.getNode()) { 7074 // As a special case, a null chain means that a tail call has been emitted 7075 // and the DAG root is already updated. 7076 HasTailCall = true; 7077 7078 // Since there's no actual continuation from this block, nothing can be 7079 // relying on us setting vregs for them. 7080 PendingExports.clear(); 7081 } else { 7082 DAG.setRoot(Result.second); 7083 } 7084 7085 if (EHPadBB) { 7086 // Insert a label at the end of the invoke call to mark the try range. This 7087 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7088 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7089 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7090 7091 // Inform MachineModuleInfo of range. 7092 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7093 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7094 // actually use outlined funclets and their LSDA info style. 7095 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7096 assert(CLI.CB); 7097 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7098 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7099 } else if (!isScopedEHPersonality(Pers)) { 7100 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7101 } 7102 } 7103 7104 return Result; 7105 } 7106 7107 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7108 bool isTailCall, 7109 const BasicBlock *EHPadBB) { 7110 auto &DL = DAG.getDataLayout(); 7111 FunctionType *FTy = CB.getFunctionType(); 7112 Type *RetTy = CB.getType(); 7113 7114 TargetLowering::ArgListTy Args; 7115 Args.reserve(CB.arg_size()); 7116 7117 const Value *SwiftErrorVal = nullptr; 7118 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7119 7120 if (isTailCall) { 7121 // Avoid emitting tail calls in functions with the disable-tail-calls 7122 // attribute. 7123 auto *Caller = CB.getParent()->getParent(); 7124 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7125 "true") 7126 isTailCall = false; 7127 7128 // We can't tail call inside a function with a swifterror argument. Lowering 7129 // does not support this yet. It would have to move into the swifterror 7130 // register before the call. 7131 if (TLI.supportSwiftError() && 7132 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7133 isTailCall = false; 7134 } 7135 7136 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7137 TargetLowering::ArgListEntry Entry; 7138 const Value *V = *I; 7139 7140 // Skip empty types 7141 if (V->getType()->isEmptyTy()) 7142 continue; 7143 7144 SDValue ArgNode = getValue(V); 7145 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7146 7147 Entry.setAttributes(&CB, I - CB.arg_begin()); 7148 7149 // Use swifterror virtual register as input to the call. 7150 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7151 SwiftErrorVal = V; 7152 // We find the virtual register for the actual swifterror argument. 7153 // Instead of using the Value, we use the virtual register instead. 7154 Entry.Node = 7155 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7156 EVT(TLI.getPointerTy(DL))); 7157 } 7158 7159 Args.push_back(Entry); 7160 7161 // If we have an explicit sret argument that is an Instruction, (i.e., it 7162 // might point to function-local memory), we can't meaningfully tail-call. 7163 if (Entry.IsSRet && isa<Instruction>(V)) 7164 isTailCall = false; 7165 } 7166 7167 // If call site has a cfguardtarget operand bundle, create and add an 7168 // additional ArgListEntry. 7169 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7170 TargetLowering::ArgListEntry Entry; 7171 Value *V = Bundle->Inputs[0]; 7172 SDValue ArgNode = getValue(V); 7173 Entry.Node = ArgNode; 7174 Entry.Ty = V->getType(); 7175 Entry.IsCFGuardTarget = true; 7176 Args.push_back(Entry); 7177 } 7178 7179 // Check if target-independent constraints permit a tail call here. 7180 // Target-dependent constraints are checked within TLI->LowerCallTo. 7181 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7182 isTailCall = false; 7183 7184 // Disable tail calls if there is an swifterror argument. Targets have not 7185 // been updated to support tail calls. 7186 if (TLI.supportSwiftError() && SwiftErrorVal) 7187 isTailCall = false; 7188 7189 TargetLowering::CallLoweringInfo CLI(DAG); 7190 CLI.setDebugLoc(getCurSDLoc()) 7191 .setChain(getRoot()) 7192 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7193 .setTailCall(isTailCall) 7194 .setConvergent(CB.isConvergent()) 7195 .setIsPreallocated( 7196 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7197 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7198 7199 if (Result.first.getNode()) { 7200 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7201 setValue(&CB, Result.first); 7202 } 7203 7204 // The last element of CLI.InVals has the SDValue for swifterror return. 7205 // Here we copy it to a virtual register and update SwiftErrorMap for 7206 // book-keeping. 7207 if (SwiftErrorVal && TLI.supportSwiftError()) { 7208 // Get the last element of InVals. 7209 SDValue Src = CLI.InVals.back(); 7210 Register VReg = 7211 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7212 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7213 DAG.setRoot(CopyNode); 7214 } 7215 } 7216 7217 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7218 SelectionDAGBuilder &Builder) { 7219 // Check to see if this load can be trivially constant folded, e.g. if the 7220 // input is from a string literal. 7221 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7222 // Cast pointer to the type we really want to load. 7223 Type *LoadTy = 7224 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7225 if (LoadVT.isVector()) 7226 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7227 7228 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7229 PointerType::getUnqual(LoadTy)); 7230 7231 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7232 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7233 return Builder.getValue(LoadCst); 7234 } 7235 7236 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7237 // still constant memory, the input chain can be the entry node. 7238 SDValue Root; 7239 bool ConstantMemory = false; 7240 7241 // Do not serialize (non-volatile) loads of constant memory with anything. 7242 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7243 Root = Builder.DAG.getEntryNode(); 7244 ConstantMemory = true; 7245 } else { 7246 // Do not serialize non-volatile loads against each other. 7247 Root = Builder.DAG.getRoot(); 7248 } 7249 7250 SDValue Ptr = Builder.getValue(PtrVal); 7251 SDValue LoadVal = 7252 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7253 MachinePointerInfo(PtrVal), Align(1)); 7254 7255 if (!ConstantMemory) 7256 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7257 return LoadVal; 7258 } 7259 7260 /// Record the value for an instruction that produces an integer result, 7261 /// converting the type where necessary. 7262 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7263 SDValue Value, 7264 bool IsSigned) { 7265 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7266 I.getType(), true); 7267 if (IsSigned) 7268 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7269 else 7270 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7271 setValue(&I, Value); 7272 } 7273 7274 /// See if we can lower a memcmp call into an optimized form. If so, return 7275 /// true and lower it. Otherwise return false, and it will be lowered like a 7276 /// normal call. 7277 /// The caller already checked that \p I calls the appropriate LibFunc with a 7278 /// correct prototype. 7279 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7280 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7281 const Value *Size = I.getArgOperand(2); 7282 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7283 if (CSize && CSize->getZExtValue() == 0) { 7284 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7285 I.getType(), true); 7286 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7287 return true; 7288 } 7289 7290 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7291 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7292 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7293 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7294 if (Res.first.getNode()) { 7295 processIntegerCallValue(I, Res.first, true); 7296 PendingLoads.push_back(Res.second); 7297 return true; 7298 } 7299 7300 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7301 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7302 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7303 return false; 7304 7305 // If the target has a fast compare for the given size, it will return a 7306 // preferred load type for that size. Require that the load VT is legal and 7307 // that the target supports unaligned loads of that type. Otherwise, return 7308 // INVALID. 7309 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7310 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7311 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7312 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7313 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7314 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7315 // TODO: Check alignment of src and dest ptrs. 7316 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7317 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7318 if (!TLI.isTypeLegal(LVT) || 7319 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7320 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7321 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7322 } 7323 7324 return LVT; 7325 }; 7326 7327 // This turns into unaligned loads. We only do this if the target natively 7328 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7329 // we'll only produce a small number of byte loads. 7330 MVT LoadVT; 7331 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7332 switch (NumBitsToCompare) { 7333 default: 7334 return false; 7335 case 16: 7336 LoadVT = MVT::i16; 7337 break; 7338 case 32: 7339 LoadVT = MVT::i32; 7340 break; 7341 case 64: 7342 case 128: 7343 case 256: 7344 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7345 break; 7346 } 7347 7348 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7349 return false; 7350 7351 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7352 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7353 7354 // Bitcast to a wide integer type if the loads are vectors. 7355 if (LoadVT.isVector()) { 7356 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7357 LoadL = DAG.getBitcast(CmpVT, LoadL); 7358 LoadR = DAG.getBitcast(CmpVT, LoadR); 7359 } 7360 7361 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7362 processIntegerCallValue(I, Cmp, false); 7363 return true; 7364 } 7365 7366 /// See if we can lower a memchr call into an optimized form. If so, return 7367 /// true and lower it. Otherwise return false, and it will be lowered like a 7368 /// normal call. 7369 /// The caller already checked that \p I calls the appropriate LibFunc with a 7370 /// correct prototype. 7371 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7372 const Value *Src = I.getArgOperand(0); 7373 const Value *Char = I.getArgOperand(1); 7374 const Value *Length = I.getArgOperand(2); 7375 7376 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7377 std::pair<SDValue, SDValue> Res = 7378 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7379 getValue(Src), getValue(Char), getValue(Length), 7380 MachinePointerInfo(Src)); 7381 if (Res.first.getNode()) { 7382 setValue(&I, Res.first); 7383 PendingLoads.push_back(Res.second); 7384 return true; 7385 } 7386 7387 return false; 7388 } 7389 7390 /// See if we can lower a mempcpy call into an optimized form. If so, return 7391 /// true and lower it. Otherwise return false, and it will be lowered like a 7392 /// normal call. 7393 /// The caller already checked that \p I calls the appropriate LibFunc with a 7394 /// correct prototype. 7395 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7396 SDValue Dst = getValue(I.getArgOperand(0)); 7397 SDValue Src = getValue(I.getArgOperand(1)); 7398 SDValue Size = getValue(I.getArgOperand(2)); 7399 7400 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7401 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7402 // DAG::getMemcpy needs Alignment to be defined. 7403 Align Alignment = std::min(DstAlign, SrcAlign); 7404 7405 bool isVol = false; 7406 SDLoc sdl = getCurSDLoc(); 7407 7408 // In the mempcpy context we need to pass in a false value for isTailCall 7409 // because the return pointer needs to be adjusted by the size of 7410 // the copied memory. 7411 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7412 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7413 /*isTailCall=*/false, 7414 MachinePointerInfo(I.getArgOperand(0)), 7415 MachinePointerInfo(I.getArgOperand(1))); 7416 assert(MC.getNode() != nullptr && 7417 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7418 DAG.setRoot(MC); 7419 7420 // Check if Size needs to be truncated or extended. 7421 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7422 7423 // Adjust return pointer to point just past the last dst byte. 7424 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7425 Dst, Size); 7426 setValue(&I, DstPlusSize); 7427 return true; 7428 } 7429 7430 /// See if we can lower a strcpy call into an optimized form. If so, return 7431 /// true and lower it, otherwise return false and it will be lowered like a 7432 /// normal call. 7433 /// The caller already checked that \p I calls the appropriate LibFunc with a 7434 /// correct prototype. 7435 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7436 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7437 7438 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7439 std::pair<SDValue, SDValue> Res = 7440 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7441 getValue(Arg0), getValue(Arg1), 7442 MachinePointerInfo(Arg0), 7443 MachinePointerInfo(Arg1), isStpcpy); 7444 if (Res.first.getNode()) { 7445 setValue(&I, Res.first); 7446 DAG.setRoot(Res.second); 7447 return true; 7448 } 7449 7450 return false; 7451 } 7452 7453 /// See if we can lower a strcmp call into an optimized form. If so, return 7454 /// true and lower it, otherwise return false and it will be lowered like a 7455 /// normal call. 7456 /// The caller already checked that \p I calls the appropriate LibFunc with a 7457 /// correct prototype. 7458 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7459 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7460 7461 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7462 std::pair<SDValue, SDValue> Res = 7463 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7464 getValue(Arg0), getValue(Arg1), 7465 MachinePointerInfo(Arg0), 7466 MachinePointerInfo(Arg1)); 7467 if (Res.first.getNode()) { 7468 processIntegerCallValue(I, Res.first, true); 7469 PendingLoads.push_back(Res.second); 7470 return true; 7471 } 7472 7473 return false; 7474 } 7475 7476 /// See if we can lower a strlen call into an optimized form. If so, return 7477 /// true and lower it, otherwise return false and it will be lowered like a 7478 /// normal call. 7479 /// The caller already checked that \p I calls the appropriate LibFunc with a 7480 /// correct prototype. 7481 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7482 const Value *Arg0 = I.getArgOperand(0); 7483 7484 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7485 std::pair<SDValue, SDValue> Res = 7486 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7487 getValue(Arg0), MachinePointerInfo(Arg0)); 7488 if (Res.first.getNode()) { 7489 processIntegerCallValue(I, Res.first, false); 7490 PendingLoads.push_back(Res.second); 7491 return true; 7492 } 7493 7494 return false; 7495 } 7496 7497 /// See if we can lower a strnlen call into an optimized form. If so, return 7498 /// true and lower it, otherwise return false and it will be lowered like a 7499 /// normal call. 7500 /// The caller already checked that \p I calls the appropriate LibFunc with a 7501 /// correct prototype. 7502 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7503 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7504 7505 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7506 std::pair<SDValue, SDValue> Res = 7507 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7508 getValue(Arg0), getValue(Arg1), 7509 MachinePointerInfo(Arg0)); 7510 if (Res.first.getNode()) { 7511 processIntegerCallValue(I, Res.first, false); 7512 PendingLoads.push_back(Res.second); 7513 return true; 7514 } 7515 7516 return false; 7517 } 7518 7519 /// See if we can lower a unary floating-point operation into an SDNode with 7520 /// the specified Opcode. If so, return true and lower it, otherwise return 7521 /// false and it will be lowered like a normal call. 7522 /// The caller already checked that \p I calls the appropriate LibFunc with a 7523 /// correct prototype. 7524 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7525 unsigned Opcode) { 7526 // We already checked this call's prototype; verify it doesn't modify errno. 7527 if (!I.onlyReadsMemory()) 7528 return false; 7529 7530 SDNodeFlags Flags; 7531 Flags.copyFMF(cast<FPMathOperator>(I)); 7532 7533 SDValue Tmp = getValue(I.getArgOperand(0)); 7534 setValue(&I, 7535 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7536 return true; 7537 } 7538 7539 /// See if we can lower a binary floating-point operation into an SDNode with 7540 /// the specified Opcode. If so, return true and lower it. Otherwise return 7541 /// false, and it will be lowered like a normal call. 7542 /// The caller already checked that \p I calls the appropriate LibFunc with a 7543 /// correct prototype. 7544 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7545 unsigned Opcode) { 7546 // We already checked this call's prototype; verify it doesn't modify errno. 7547 if (!I.onlyReadsMemory()) 7548 return false; 7549 7550 SDNodeFlags Flags; 7551 Flags.copyFMF(cast<FPMathOperator>(I)); 7552 7553 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7554 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7555 EVT VT = Tmp0.getValueType(); 7556 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7557 return true; 7558 } 7559 7560 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7561 // Handle inline assembly differently. 7562 if (I.isInlineAsm()) { 7563 visitInlineAsm(I); 7564 return; 7565 } 7566 7567 if (Function *F = I.getCalledFunction()) { 7568 if (F->isDeclaration()) { 7569 // Is this an LLVM intrinsic or a target-specific intrinsic? 7570 unsigned IID = F->getIntrinsicID(); 7571 if (!IID) 7572 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7573 IID = II->getIntrinsicID(F); 7574 7575 if (IID) { 7576 visitIntrinsicCall(I, IID); 7577 return; 7578 } 7579 } 7580 7581 // Check for well-known libc/libm calls. If the function is internal, it 7582 // can't be a library call. Don't do the check if marked as nobuiltin for 7583 // some reason or the call site requires strict floating point semantics. 7584 LibFunc Func; 7585 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7586 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7587 LibInfo->hasOptimizedCodeGen(Func)) { 7588 switch (Func) { 7589 default: break; 7590 case LibFunc_copysign: 7591 case LibFunc_copysignf: 7592 case LibFunc_copysignl: 7593 // We already checked this call's prototype; verify it doesn't modify 7594 // errno. 7595 if (I.onlyReadsMemory()) { 7596 SDValue LHS = getValue(I.getArgOperand(0)); 7597 SDValue RHS = getValue(I.getArgOperand(1)); 7598 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7599 LHS.getValueType(), LHS, RHS)); 7600 return; 7601 } 7602 break; 7603 case LibFunc_fabs: 7604 case LibFunc_fabsf: 7605 case LibFunc_fabsl: 7606 if (visitUnaryFloatCall(I, ISD::FABS)) 7607 return; 7608 break; 7609 case LibFunc_fmin: 7610 case LibFunc_fminf: 7611 case LibFunc_fminl: 7612 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7613 return; 7614 break; 7615 case LibFunc_fmax: 7616 case LibFunc_fmaxf: 7617 case LibFunc_fmaxl: 7618 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7619 return; 7620 break; 7621 case LibFunc_sin: 7622 case LibFunc_sinf: 7623 case LibFunc_sinl: 7624 if (visitUnaryFloatCall(I, ISD::FSIN)) 7625 return; 7626 break; 7627 case LibFunc_cos: 7628 case LibFunc_cosf: 7629 case LibFunc_cosl: 7630 if (visitUnaryFloatCall(I, ISD::FCOS)) 7631 return; 7632 break; 7633 case LibFunc_sqrt: 7634 case LibFunc_sqrtf: 7635 case LibFunc_sqrtl: 7636 case LibFunc_sqrt_finite: 7637 case LibFunc_sqrtf_finite: 7638 case LibFunc_sqrtl_finite: 7639 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7640 return; 7641 break; 7642 case LibFunc_floor: 7643 case LibFunc_floorf: 7644 case LibFunc_floorl: 7645 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7646 return; 7647 break; 7648 case LibFunc_nearbyint: 7649 case LibFunc_nearbyintf: 7650 case LibFunc_nearbyintl: 7651 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7652 return; 7653 break; 7654 case LibFunc_ceil: 7655 case LibFunc_ceilf: 7656 case LibFunc_ceill: 7657 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7658 return; 7659 break; 7660 case LibFunc_rint: 7661 case LibFunc_rintf: 7662 case LibFunc_rintl: 7663 if (visitUnaryFloatCall(I, ISD::FRINT)) 7664 return; 7665 break; 7666 case LibFunc_round: 7667 case LibFunc_roundf: 7668 case LibFunc_roundl: 7669 if (visitUnaryFloatCall(I, ISD::FROUND)) 7670 return; 7671 break; 7672 case LibFunc_trunc: 7673 case LibFunc_truncf: 7674 case LibFunc_truncl: 7675 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7676 return; 7677 break; 7678 case LibFunc_log2: 7679 case LibFunc_log2f: 7680 case LibFunc_log2l: 7681 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7682 return; 7683 break; 7684 case LibFunc_exp2: 7685 case LibFunc_exp2f: 7686 case LibFunc_exp2l: 7687 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7688 return; 7689 break; 7690 case LibFunc_memcmp: 7691 if (visitMemCmpCall(I)) 7692 return; 7693 break; 7694 case LibFunc_mempcpy: 7695 if (visitMemPCpyCall(I)) 7696 return; 7697 break; 7698 case LibFunc_memchr: 7699 if (visitMemChrCall(I)) 7700 return; 7701 break; 7702 case LibFunc_strcpy: 7703 if (visitStrCpyCall(I, false)) 7704 return; 7705 break; 7706 case LibFunc_stpcpy: 7707 if (visitStrCpyCall(I, true)) 7708 return; 7709 break; 7710 case LibFunc_strcmp: 7711 if (visitStrCmpCall(I)) 7712 return; 7713 break; 7714 case LibFunc_strlen: 7715 if (visitStrLenCall(I)) 7716 return; 7717 break; 7718 case LibFunc_strnlen: 7719 if (visitStrNLenCall(I)) 7720 return; 7721 break; 7722 } 7723 } 7724 } 7725 7726 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7727 // have to do anything here to lower funclet bundles. 7728 // CFGuardTarget bundles are lowered in LowerCallTo. 7729 assert(!I.hasOperandBundlesOtherThan( 7730 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7731 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) && 7732 "Cannot lower calls with arbitrary operand bundles!"); 7733 7734 SDValue Callee = getValue(I.getCalledOperand()); 7735 7736 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7737 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7738 else 7739 // Check if we can potentially perform a tail call. More detailed checking 7740 // is be done within LowerCallTo, after more information about the call is 7741 // known. 7742 LowerCallTo(I, Callee, I.isTailCall()); 7743 } 7744 7745 namespace { 7746 7747 /// AsmOperandInfo - This contains information for each constraint that we are 7748 /// lowering. 7749 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7750 public: 7751 /// CallOperand - If this is the result output operand or a clobber 7752 /// this is null, otherwise it is the incoming operand to the CallInst. 7753 /// This gets modified as the asm is processed. 7754 SDValue CallOperand; 7755 7756 /// AssignedRegs - If this is a register or register class operand, this 7757 /// contains the set of register corresponding to the operand. 7758 RegsForValue AssignedRegs; 7759 7760 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7761 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7762 } 7763 7764 /// Whether or not this operand accesses memory 7765 bool hasMemory(const TargetLowering &TLI) const { 7766 // Indirect operand accesses access memory. 7767 if (isIndirect) 7768 return true; 7769 7770 for (const auto &Code : Codes) 7771 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7772 return true; 7773 7774 return false; 7775 } 7776 7777 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7778 /// corresponds to. If there is no Value* for this operand, it returns 7779 /// MVT::Other. 7780 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7781 const DataLayout &DL) const { 7782 if (!CallOperandVal) return MVT::Other; 7783 7784 if (isa<BasicBlock>(CallOperandVal)) 7785 return TLI.getProgramPointerTy(DL); 7786 7787 llvm::Type *OpTy = CallOperandVal->getType(); 7788 7789 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7790 // If this is an indirect operand, the operand is a pointer to the 7791 // accessed type. 7792 if (isIndirect) { 7793 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7794 if (!PtrTy) 7795 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7796 OpTy = PtrTy->getElementType(); 7797 } 7798 7799 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7800 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7801 if (STy->getNumElements() == 1) 7802 OpTy = STy->getElementType(0); 7803 7804 // If OpTy is not a single value, it may be a struct/union that we 7805 // can tile with integers. 7806 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7807 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7808 switch (BitSize) { 7809 default: break; 7810 case 1: 7811 case 8: 7812 case 16: 7813 case 32: 7814 case 64: 7815 case 128: 7816 OpTy = IntegerType::get(Context, BitSize); 7817 break; 7818 } 7819 } 7820 7821 return TLI.getValueType(DL, OpTy, true); 7822 } 7823 }; 7824 7825 7826 } // end anonymous namespace 7827 7828 /// Make sure that the output operand \p OpInfo and its corresponding input 7829 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7830 /// out). 7831 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7832 SDISelAsmOperandInfo &MatchingOpInfo, 7833 SelectionDAG &DAG) { 7834 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7835 return; 7836 7837 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7838 const auto &TLI = DAG.getTargetLoweringInfo(); 7839 7840 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7841 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7842 OpInfo.ConstraintVT); 7843 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7844 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7845 MatchingOpInfo.ConstraintVT); 7846 if ((OpInfo.ConstraintVT.isInteger() != 7847 MatchingOpInfo.ConstraintVT.isInteger()) || 7848 (MatchRC.second != InputRC.second)) { 7849 // FIXME: error out in a more elegant fashion 7850 report_fatal_error("Unsupported asm: input constraint" 7851 " with a matching output constraint of" 7852 " incompatible type!"); 7853 } 7854 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7855 } 7856 7857 /// Get a direct memory input to behave well as an indirect operand. 7858 /// This may introduce stores, hence the need for a \p Chain. 7859 /// \return The (possibly updated) chain. 7860 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7861 SDISelAsmOperandInfo &OpInfo, 7862 SelectionDAG &DAG) { 7863 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7864 7865 // If we don't have an indirect input, put it in the constpool if we can, 7866 // otherwise spill it to a stack slot. 7867 // TODO: This isn't quite right. We need to handle these according to 7868 // the addressing mode that the constraint wants. Also, this may take 7869 // an additional register for the computation and we don't want that 7870 // either. 7871 7872 // If the operand is a float, integer, or vector constant, spill to a 7873 // constant pool entry to get its address. 7874 const Value *OpVal = OpInfo.CallOperandVal; 7875 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7876 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7877 OpInfo.CallOperand = DAG.getConstantPool( 7878 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7879 return Chain; 7880 } 7881 7882 // Otherwise, create a stack slot and emit a store to it before the asm. 7883 Type *Ty = OpVal->getType(); 7884 auto &DL = DAG.getDataLayout(); 7885 uint64_t TySize = DL.getTypeAllocSize(Ty); 7886 MachineFunction &MF = DAG.getMachineFunction(); 7887 int SSFI = MF.getFrameInfo().CreateStackObject( 7888 TySize, DL.getPrefTypeAlign(Ty), false); 7889 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7890 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7891 MachinePointerInfo::getFixedStack(MF, SSFI), 7892 TLI.getMemValueType(DL, Ty)); 7893 OpInfo.CallOperand = StackSlot; 7894 7895 return Chain; 7896 } 7897 7898 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7899 /// specified operand. We prefer to assign virtual registers, to allow the 7900 /// register allocator to handle the assignment process. However, if the asm 7901 /// uses features that we can't model on machineinstrs, we have SDISel do the 7902 /// allocation. This produces generally horrible, but correct, code. 7903 /// 7904 /// OpInfo describes the operand 7905 /// RefOpInfo describes the matching operand if any, the operand otherwise 7906 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7907 SDISelAsmOperandInfo &OpInfo, 7908 SDISelAsmOperandInfo &RefOpInfo) { 7909 LLVMContext &Context = *DAG.getContext(); 7910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7911 7912 MachineFunction &MF = DAG.getMachineFunction(); 7913 SmallVector<unsigned, 4> Regs; 7914 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7915 7916 // No work to do for memory operations. 7917 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7918 return; 7919 7920 // If this is a constraint for a single physreg, or a constraint for a 7921 // register class, find it. 7922 unsigned AssignedReg; 7923 const TargetRegisterClass *RC; 7924 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7925 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7926 // RC is unset only on failure. Return immediately. 7927 if (!RC) 7928 return; 7929 7930 // Get the actual register value type. This is important, because the user 7931 // may have asked for (e.g.) the AX register in i32 type. We need to 7932 // remember that AX is actually i16 to get the right extension. 7933 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7934 7935 if (OpInfo.ConstraintVT != MVT::Other) { 7936 // If this is an FP operand in an integer register (or visa versa), or more 7937 // generally if the operand value disagrees with the register class we plan 7938 // to stick it in, fix the operand type. 7939 // 7940 // If this is an input value, the bitcast to the new type is done now. 7941 // Bitcast for output value is done at the end of visitInlineAsm(). 7942 if ((OpInfo.Type == InlineAsm::isOutput || 7943 OpInfo.Type == InlineAsm::isInput) && 7944 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7945 // Try to convert to the first EVT that the reg class contains. If the 7946 // types are identical size, use a bitcast to convert (e.g. two differing 7947 // vector types). Note: output bitcast is done at the end of 7948 // visitInlineAsm(). 7949 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7950 // Exclude indirect inputs while they are unsupported because the code 7951 // to perform the load is missing and thus OpInfo.CallOperand still 7952 // refers to the input address rather than the pointed-to value. 7953 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7954 OpInfo.CallOperand = 7955 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7956 OpInfo.ConstraintVT = RegVT; 7957 // If the operand is an FP value and we want it in integer registers, 7958 // use the corresponding integer type. This turns an f64 value into 7959 // i64, which can be passed with two i32 values on a 32-bit machine. 7960 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7961 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7962 if (OpInfo.Type == InlineAsm::isInput) 7963 OpInfo.CallOperand = 7964 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7965 OpInfo.ConstraintVT = VT; 7966 } 7967 } 7968 } 7969 7970 // No need to allocate a matching input constraint since the constraint it's 7971 // matching to has already been allocated. 7972 if (OpInfo.isMatchingInputConstraint()) 7973 return; 7974 7975 EVT ValueVT = OpInfo.ConstraintVT; 7976 if (OpInfo.ConstraintVT == MVT::Other) 7977 ValueVT = RegVT; 7978 7979 // Initialize NumRegs. 7980 unsigned NumRegs = 1; 7981 if (OpInfo.ConstraintVT != MVT::Other) 7982 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7983 7984 // If this is a constraint for a specific physical register, like {r17}, 7985 // assign it now. 7986 7987 // If this associated to a specific register, initialize iterator to correct 7988 // place. If virtual, make sure we have enough registers 7989 7990 // Initialize iterator if necessary 7991 TargetRegisterClass::iterator I = RC->begin(); 7992 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7993 7994 // Do not check for single registers. 7995 if (AssignedReg) { 7996 for (; *I != AssignedReg; ++I) 7997 assert(I != RC->end() && "AssignedReg should be member of RC"); 7998 } 7999 8000 for (; NumRegs; --NumRegs, ++I) { 8001 assert(I != RC->end() && "Ran out of registers to allocate!"); 8002 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8003 Regs.push_back(R); 8004 } 8005 8006 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8007 } 8008 8009 static unsigned 8010 findMatchingInlineAsmOperand(unsigned OperandNo, 8011 const std::vector<SDValue> &AsmNodeOperands) { 8012 // Scan until we find the definition we already emitted of this operand. 8013 unsigned CurOp = InlineAsm::Op_FirstOperand; 8014 for (; OperandNo; --OperandNo) { 8015 // Advance to the next operand. 8016 unsigned OpFlag = 8017 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8018 assert((InlineAsm::isRegDefKind(OpFlag) || 8019 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8020 InlineAsm::isMemKind(OpFlag)) && 8021 "Skipped past definitions?"); 8022 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8023 } 8024 return CurOp; 8025 } 8026 8027 namespace { 8028 8029 class ExtraFlags { 8030 unsigned Flags = 0; 8031 8032 public: 8033 explicit ExtraFlags(const CallBase &Call) { 8034 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8035 if (IA->hasSideEffects()) 8036 Flags |= InlineAsm::Extra_HasSideEffects; 8037 if (IA->isAlignStack()) 8038 Flags |= InlineAsm::Extra_IsAlignStack; 8039 if (Call.isConvergent()) 8040 Flags |= InlineAsm::Extra_IsConvergent; 8041 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8042 } 8043 8044 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8045 // Ideally, we would only check against memory constraints. However, the 8046 // meaning of an Other constraint can be target-specific and we can't easily 8047 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8048 // for Other constraints as well. 8049 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8050 OpInfo.ConstraintType == TargetLowering::C_Other) { 8051 if (OpInfo.Type == InlineAsm::isInput) 8052 Flags |= InlineAsm::Extra_MayLoad; 8053 else if (OpInfo.Type == InlineAsm::isOutput) 8054 Flags |= InlineAsm::Extra_MayStore; 8055 else if (OpInfo.Type == InlineAsm::isClobber) 8056 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8057 } 8058 } 8059 8060 unsigned get() const { return Flags; } 8061 }; 8062 8063 } // end anonymous namespace 8064 8065 /// visitInlineAsm - Handle a call to an InlineAsm object. 8066 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8067 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8068 8069 /// ConstraintOperands - Information about all of the constraints. 8070 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8071 8072 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8073 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8074 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8075 8076 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8077 // AsmDialect, MayLoad, MayStore). 8078 bool HasSideEffect = IA->hasSideEffects(); 8079 ExtraFlags ExtraInfo(Call); 8080 8081 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8082 unsigned ResNo = 0; // ResNo - The result number of the next output. 8083 unsigned NumMatchingOps = 0; 8084 for (auto &T : TargetConstraints) { 8085 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8086 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8087 8088 // Compute the value type for each operand. 8089 if (OpInfo.Type == InlineAsm::isInput || 8090 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8091 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8092 8093 // Process the call argument. BasicBlocks are labels, currently appearing 8094 // only in asm's. 8095 if (isa<CallBrInst>(Call) && 8096 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8097 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8098 NumMatchingOps) && 8099 (NumMatchingOps == 0 || 8100 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8101 NumMatchingOps))) { 8102 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8103 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8104 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8105 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8106 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8107 } else { 8108 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8109 } 8110 8111 OpInfo.ConstraintVT = 8112 OpInfo 8113 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8114 .getSimpleVT(); 8115 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8116 // The return value of the call is this value. As such, there is no 8117 // corresponding argument. 8118 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8119 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8120 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8121 DAG.getDataLayout(), STy->getElementType(ResNo)); 8122 } else { 8123 assert(ResNo == 0 && "Asm only has one result!"); 8124 OpInfo.ConstraintVT = 8125 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8126 } 8127 ++ResNo; 8128 } else { 8129 OpInfo.ConstraintVT = MVT::Other; 8130 } 8131 8132 if (OpInfo.hasMatchingInput()) 8133 ++NumMatchingOps; 8134 8135 if (!HasSideEffect) 8136 HasSideEffect = OpInfo.hasMemory(TLI); 8137 8138 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8139 // FIXME: Could we compute this on OpInfo rather than T? 8140 8141 // Compute the constraint code and ConstraintType to use. 8142 TLI.ComputeConstraintToUse(T, SDValue()); 8143 8144 if (T.ConstraintType == TargetLowering::C_Immediate && 8145 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8146 // We've delayed emitting a diagnostic like the "n" constraint because 8147 // inlining could cause an integer showing up. 8148 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8149 "' expects an integer constant " 8150 "expression"); 8151 8152 ExtraInfo.update(T); 8153 } 8154 8155 8156 // We won't need to flush pending loads if this asm doesn't touch 8157 // memory and is nonvolatile. 8158 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8159 8160 bool IsCallBr = isa<CallBrInst>(Call); 8161 if (IsCallBr) { 8162 // If this is a callbr we need to flush pending exports since inlineasm_br 8163 // is a terminator. We need to do this before nodes are glued to 8164 // the inlineasm_br node. 8165 Chain = getControlRoot(); 8166 } 8167 8168 // Second pass over the constraints: compute which constraint option to use. 8169 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8170 // If this is an output operand with a matching input operand, look up the 8171 // matching input. If their types mismatch, e.g. one is an integer, the 8172 // other is floating point, or their sizes are different, flag it as an 8173 // error. 8174 if (OpInfo.hasMatchingInput()) { 8175 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8176 patchMatchingInput(OpInfo, Input, DAG); 8177 } 8178 8179 // Compute the constraint code and ConstraintType to use. 8180 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8181 8182 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8183 OpInfo.Type == InlineAsm::isClobber) 8184 continue; 8185 8186 // If this is a memory input, and if the operand is not indirect, do what we 8187 // need to provide an address for the memory input. 8188 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8189 !OpInfo.isIndirect) { 8190 assert((OpInfo.isMultipleAlternative || 8191 (OpInfo.Type == InlineAsm::isInput)) && 8192 "Can only indirectify direct input operands!"); 8193 8194 // Memory operands really want the address of the value. 8195 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8196 8197 // There is no longer a Value* corresponding to this operand. 8198 OpInfo.CallOperandVal = nullptr; 8199 8200 // It is now an indirect operand. 8201 OpInfo.isIndirect = true; 8202 } 8203 8204 } 8205 8206 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8207 std::vector<SDValue> AsmNodeOperands; 8208 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8209 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8210 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8211 8212 // If we have a !srcloc metadata node associated with it, we want to attach 8213 // this to the ultimately generated inline asm machineinstr. To do this, we 8214 // pass in the third operand as this (potentially null) inline asm MDNode. 8215 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8216 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8217 8218 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8219 // bits as operand 3. 8220 AsmNodeOperands.push_back(DAG.getTargetConstant( 8221 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8222 8223 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8224 // this, assign virtual and physical registers for inputs and otput. 8225 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8226 // Assign Registers. 8227 SDISelAsmOperandInfo &RefOpInfo = 8228 OpInfo.isMatchingInputConstraint() 8229 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8230 : OpInfo; 8231 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8232 8233 auto DetectWriteToReservedRegister = [&]() { 8234 const MachineFunction &MF = DAG.getMachineFunction(); 8235 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8236 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8237 if (Register::isPhysicalRegister(Reg) && 8238 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8239 const char *RegName = TRI.getName(Reg); 8240 emitInlineAsmError(Call, "write to reserved register '" + 8241 Twine(RegName) + "'"); 8242 return true; 8243 } 8244 } 8245 return false; 8246 }; 8247 8248 switch (OpInfo.Type) { 8249 case InlineAsm::isOutput: 8250 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8251 unsigned ConstraintID = 8252 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8253 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8254 "Failed to convert memory constraint code to constraint id."); 8255 8256 // Add information to the INLINEASM node to know about this output. 8257 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8258 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8259 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8260 MVT::i32)); 8261 AsmNodeOperands.push_back(OpInfo.CallOperand); 8262 } else { 8263 // Otherwise, this outputs to a register (directly for C_Register / 8264 // C_RegisterClass, and a target-defined fashion for 8265 // C_Immediate/C_Other). Find a register that we can use. 8266 if (OpInfo.AssignedRegs.Regs.empty()) { 8267 emitInlineAsmError( 8268 Call, "couldn't allocate output register for constraint '" + 8269 Twine(OpInfo.ConstraintCode) + "'"); 8270 return; 8271 } 8272 8273 if (DetectWriteToReservedRegister()) 8274 return; 8275 8276 // Add information to the INLINEASM node to know that this register is 8277 // set. 8278 OpInfo.AssignedRegs.AddInlineAsmOperands( 8279 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8280 : InlineAsm::Kind_RegDef, 8281 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8282 } 8283 break; 8284 8285 case InlineAsm::isInput: { 8286 SDValue InOperandVal = OpInfo.CallOperand; 8287 8288 if (OpInfo.isMatchingInputConstraint()) { 8289 // If this is required to match an output register we have already set, 8290 // just use its register. 8291 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8292 AsmNodeOperands); 8293 unsigned OpFlag = 8294 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8295 if (InlineAsm::isRegDefKind(OpFlag) || 8296 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8297 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8298 if (OpInfo.isIndirect) { 8299 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8300 emitInlineAsmError(Call, "inline asm not supported yet: " 8301 "don't know how to handle tied " 8302 "indirect register inputs"); 8303 return; 8304 } 8305 8306 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8307 SmallVector<unsigned, 4> Regs; 8308 8309 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8310 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8311 MachineRegisterInfo &RegInfo = 8312 DAG.getMachineFunction().getRegInfo(); 8313 for (unsigned i = 0; i != NumRegs; ++i) 8314 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8315 } else { 8316 emitInlineAsmError(Call, 8317 "inline asm error: This value type register " 8318 "class is not natively supported!"); 8319 return; 8320 } 8321 8322 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8323 8324 SDLoc dl = getCurSDLoc(); 8325 // Use the produced MatchedRegs object to 8326 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8327 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8328 true, OpInfo.getMatchedOperand(), dl, 8329 DAG, AsmNodeOperands); 8330 break; 8331 } 8332 8333 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8334 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8335 "Unexpected number of operands"); 8336 // Add information to the INLINEASM node to know about this input. 8337 // See InlineAsm.h isUseOperandTiedToDef. 8338 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8339 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8340 OpInfo.getMatchedOperand()); 8341 AsmNodeOperands.push_back(DAG.getTargetConstant( 8342 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8343 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8344 break; 8345 } 8346 8347 // Treat indirect 'X' constraint as memory. 8348 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8349 OpInfo.isIndirect) 8350 OpInfo.ConstraintType = TargetLowering::C_Memory; 8351 8352 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8353 OpInfo.ConstraintType == TargetLowering::C_Other) { 8354 std::vector<SDValue> Ops; 8355 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8356 Ops, DAG); 8357 if (Ops.empty()) { 8358 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8359 if (isa<ConstantSDNode>(InOperandVal)) { 8360 emitInlineAsmError(Call, "value out of range for constraint '" + 8361 Twine(OpInfo.ConstraintCode) + "'"); 8362 return; 8363 } 8364 8365 emitInlineAsmError(Call, 8366 "invalid operand for inline asm constraint '" + 8367 Twine(OpInfo.ConstraintCode) + "'"); 8368 return; 8369 } 8370 8371 // Add information to the INLINEASM node to know about this input. 8372 unsigned ResOpType = 8373 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8374 AsmNodeOperands.push_back(DAG.getTargetConstant( 8375 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8376 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8377 break; 8378 } 8379 8380 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8381 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8382 assert(InOperandVal.getValueType() == 8383 TLI.getPointerTy(DAG.getDataLayout()) && 8384 "Memory operands expect pointer values"); 8385 8386 unsigned ConstraintID = 8387 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8388 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8389 "Failed to convert memory constraint code to constraint id."); 8390 8391 // Add information to the INLINEASM node to know about this input. 8392 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8393 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8394 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8395 getCurSDLoc(), 8396 MVT::i32)); 8397 AsmNodeOperands.push_back(InOperandVal); 8398 break; 8399 } 8400 8401 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8402 OpInfo.ConstraintType == TargetLowering::C_Register) && 8403 "Unknown constraint type!"); 8404 8405 // TODO: Support this. 8406 if (OpInfo.isIndirect) { 8407 emitInlineAsmError( 8408 Call, "Don't know how to handle indirect register inputs yet " 8409 "for constraint '" + 8410 Twine(OpInfo.ConstraintCode) + "'"); 8411 return; 8412 } 8413 8414 // Copy the input into the appropriate registers. 8415 if (OpInfo.AssignedRegs.Regs.empty()) { 8416 emitInlineAsmError(Call, 8417 "couldn't allocate input reg for constraint '" + 8418 Twine(OpInfo.ConstraintCode) + "'"); 8419 return; 8420 } 8421 8422 if (DetectWriteToReservedRegister()) 8423 return; 8424 8425 SDLoc dl = getCurSDLoc(); 8426 8427 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8428 &Call); 8429 8430 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8431 dl, DAG, AsmNodeOperands); 8432 break; 8433 } 8434 case InlineAsm::isClobber: 8435 // Add the clobbered value to the operand list, so that the register 8436 // allocator is aware that the physreg got clobbered. 8437 if (!OpInfo.AssignedRegs.Regs.empty()) 8438 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8439 false, 0, getCurSDLoc(), DAG, 8440 AsmNodeOperands); 8441 break; 8442 } 8443 } 8444 8445 // Finish up input operands. Set the input chain and add the flag last. 8446 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8447 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8448 8449 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8450 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8451 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8452 Flag = Chain.getValue(1); 8453 8454 // Do additional work to generate outputs. 8455 8456 SmallVector<EVT, 1> ResultVTs; 8457 SmallVector<SDValue, 1> ResultValues; 8458 SmallVector<SDValue, 8> OutChains; 8459 8460 llvm::Type *CallResultType = Call.getType(); 8461 ArrayRef<Type *> ResultTypes; 8462 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8463 ResultTypes = StructResult->elements(); 8464 else if (!CallResultType->isVoidTy()) 8465 ResultTypes = makeArrayRef(CallResultType); 8466 8467 auto CurResultType = ResultTypes.begin(); 8468 auto handleRegAssign = [&](SDValue V) { 8469 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8470 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8471 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8472 ++CurResultType; 8473 // If the type of the inline asm call site return value is different but has 8474 // same size as the type of the asm output bitcast it. One example of this 8475 // is for vectors with different width / number of elements. This can 8476 // happen for register classes that can contain multiple different value 8477 // types. The preg or vreg allocated may not have the same VT as was 8478 // expected. 8479 // 8480 // This can also happen for a return value that disagrees with the register 8481 // class it is put in, eg. a double in a general-purpose register on a 8482 // 32-bit machine. 8483 if (ResultVT != V.getValueType() && 8484 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8485 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8486 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8487 V.getValueType().isInteger()) { 8488 // If a result value was tied to an input value, the computed result 8489 // may have a wider width than the expected result. Extract the 8490 // relevant portion. 8491 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8492 } 8493 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8494 ResultVTs.push_back(ResultVT); 8495 ResultValues.push_back(V); 8496 }; 8497 8498 // Deal with output operands. 8499 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8500 if (OpInfo.Type == InlineAsm::isOutput) { 8501 SDValue Val; 8502 // Skip trivial output operands. 8503 if (OpInfo.AssignedRegs.Regs.empty()) 8504 continue; 8505 8506 switch (OpInfo.ConstraintType) { 8507 case TargetLowering::C_Register: 8508 case TargetLowering::C_RegisterClass: 8509 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8510 Chain, &Flag, &Call); 8511 break; 8512 case TargetLowering::C_Immediate: 8513 case TargetLowering::C_Other: 8514 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8515 OpInfo, DAG); 8516 break; 8517 case TargetLowering::C_Memory: 8518 break; // Already handled. 8519 case TargetLowering::C_Unknown: 8520 assert(false && "Unexpected unknown constraint"); 8521 } 8522 8523 // Indirect output manifest as stores. Record output chains. 8524 if (OpInfo.isIndirect) { 8525 const Value *Ptr = OpInfo.CallOperandVal; 8526 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8527 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8528 MachinePointerInfo(Ptr)); 8529 OutChains.push_back(Store); 8530 } else { 8531 // generate CopyFromRegs to associated registers. 8532 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8533 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8534 for (const SDValue &V : Val->op_values()) 8535 handleRegAssign(V); 8536 } else 8537 handleRegAssign(Val); 8538 } 8539 } 8540 } 8541 8542 // Set results. 8543 if (!ResultValues.empty()) { 8544 assert(CurResultType == ResultTypes.end() && 8545 "Mismatch in number of ResultTypes"); 8546 assert(ResultValues.size() == ResultTypes.size() && 8547 "Mismatch in number of output operands in asm result"); 8548 8549 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8550 DAG.getVTList(ResultVTs), ResultValues); 8551 setValue(&Call, V); 8552 } 8553 8554 // Collect store chains. 8555 if (!OutChains.empty()) 8556 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8557 8558 // Only Update Root if inline assembly has a memory effect. 8559 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8560 DAG.setRoot(Chain); 8561 } 8562 8563 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8564 const Twine &Message) { 8565 LLVMContext &Ctx = *DAG.getContext(); 8566 Ctx.emitError(&Call, Message); 8567 8568 // Make sure we leave the DAG in a valid state 8569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8570 SmallVector<EVT, 1> ValueVTs; 8571 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8572 8573 if (ValueVTs.empty()) 8574 return; 8575 8576 SmallVector<SDValue, 1> Ops; 8577 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8578 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8579 8580 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8581 } 8582 8583 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8584 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8585 MVT::Other, getRoot(), 8586 getValue(I.getArgOperand(0)), 8587 DAG.getSrcValue(I.getArgOperand(0)))); 8588 } 8589 8590 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8591 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8592 const DataLayout &DL = DAG.getDataLayout(); 8593 SDValue V = DAG.getVAArg( 8594 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8595 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8596 DL.getABITypeAlign(I.getType()).value()); 8597 DAG.setRoot(V.getValue(1)); 8598 8599 if (I.getType()->isPointerTy()) 8600 V = DAG.getPtrExtOrTrunc( 8601 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8602 setValue(&I, V); 8603 } 8604 8605 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8606 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8607 MVT::Other, getRoot(), 8608 getValue(I.getArgOperand(0)), 8609 DAG.getSrcValue(I.getArgOperand(0)))); 8610 } 8611 8612 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8613 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8614 MVT::Other, getRoot(), 8615 getValue(I.getArgOperand(0)), 8616 getValue(I.getArgOperand(1)), 8617 DAG.getSrcValue(I.getArgOperand(0)), 8618 DAG.getSrcValue(I.getArgOperand(1)))); 8619 } 8620 8621 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8622 const Instruction &I, 8623 SDValue Op) { 8624 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8625 if (!Range) 8626 return Op; 8627 8628 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8629 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8630 return Op; 8631 8632 APInt Lo = CR.getUnsignedMin(); 8633 if (!Lo.isMinValue()) 8634 return Op; 8635 8636 APInt Hi = CR.getUnsignedMax(); 8637 unsigned Bits = std::max(Hi.getActiveBits(), 8638 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8639 8640 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8641 8642 SDLoc SL = getCurSDLoc(); 8643 8644 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8645 DAG.getValueType(SmallVT)); 8646 unsigned NumVals = Op.getNode()->getNumValues(); 8647 if (NumVals == 1) 8648 return ZExt; 8649 8650 SmallVector<SDValue, 4> Ops; 8651 8652 Ops.push_back(ZExt); 8653 for (unsigned I = 1; I != NumVals; ++I) 8654 Ops.push_back(Op.getValue(I)); 8655 8656 return DAG.getMergeValues(Ops, SL); 8657 } 8658 8659 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8660 /// the call being lowered. 8661 /// 8662 /// This is a helper for lowering intrinsics that follow a target calling 8663 /// convention or require stack pointer adjustment. Only a subset of the 8664 /// intrinsic's operands need to participate in the calling convention. 8665 void SelectionDAGBuilder::populateCallLoweringInfo( 8666 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8667 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8668 bool IsPatchPoint) { 8669 TargetLowering::ArgListTy Args; 8670 Args.reserve(NumArgs); 8671 8672 // Populate the argument list. 8673 // Attributes for args start at offset 1, after the return attribute. 8674 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8675 ArgI != ArgE; ++ArgI) { 8676 const Value *V = Call->getOperand(ArgI); 8677 8678 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8679 8680 TargetLowering::ArgListEntry Entry; 8681 Entry.Node = getValue(V); 8682 Entry.Ty = V->getType(); 8683 Entry.setAttributes(Call, ArgI); 8684 Args.push_back(Entry); 8685 } 8686 8687 CLI.setDebugLoc(getCurSDLoc()) 8688 .setChain(getRoot()) 8689 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8690 .setDiscardResult(Call->use_empty()) 8691 .setIsPatchPoint(IsPatchPoint) 8692 .setIsPreallocated( 8693 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8694 } 8695 8696 /// Add a stack map intrinsic call's live variable operands to a stackmap 8697 /// or patchpoint target node's operand list. 8698 /// 8699 /// Constants are converted to TargetConstants purely as an optimization to 8700 /// avoid constant materialization and register allocation. 8701 /// 8702 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8703 /// generate addess computation nodes, and so FinalizeISel can convert the 8704 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8705 /// address materialization and register allocation, but may also be required 8706 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8707 /// alloca in the entry block, then the runtime may assume that the alloca's 8708 /// StackMap location can be read immediately after compilation and that the 8709 /// location is valid at any point during execution (this is similar to the 8710 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8711 /// only available in a register, then the runtime would need to trap when 8712 /// execution reaches the StackMap in order to read the alloca's location. 8713 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8714 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8715 SelectionDAGBuilder &Builder) { 8716 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8717 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8718 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8719 Ops.push_back( 8720 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8721 Ops.push_back( 8722 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8723 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8724 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8725 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8726 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8727 } else 8728 Ops.push_back(OpVal); 8729 } 8730 } 8731 8732 /// Lower llvm.experimental.stackmap directly to its target opcode. 8733 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8734 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8735 // [live variables...]) 8736 8737 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8738 8739 SDValue Chain, InFlag, Callee, NullPtr; 8740 SmallVector<SDValue, 32> Ops; 8741 8742 SDLoc DL = getCurSDLoc(); 8743 Callee = getValue(CI.getCalledOperand()); 8744 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8745 8746 // The stackmap intrinsic only records the live variables (the arguments 8747 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8748 // intrinsic, this won't be lowered to a function call. This means we don't 8749 // have to worry about calling conventions and target specific lowering code. 8750 // Instead we perform the call lowering right here. 8751 // 8752 // chain, flag = CALLSEQ_START(chain, 0, 0) 8753 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8754 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8755 // 8756 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8757 InFlag = Chain.getValue(1); 8758 8759 // Add the <id> and <numBytes> constants. 8760 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8761 Ops.push_back(DAG.getTargetConstant( 8762 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8763 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8764 Ops.push_back(DAG.getTargetConstant( 8765 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8766 MVT::i32)); 8767 8768 // Push live variables for the stack map. 8769 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8770 8771 // We are not pushing any register mask info here on the operands list, 8772 // because the stackmap doesn't clobber anything. 8773 8774 // Push the chain and the glue flag. 8775 Ops.push_back(Chain); 8776 Ops.push_back(InFlag); 8777 8778 // Create the STACKMAP node. 8779 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8780 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8781 Chain = SDValue(SM, 0); 8782 InFlag = Chain.getValue(1); 8783 8784 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8785 8786 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8787 8788 // Set the root to the target-lowered call chain. 8789 DAG.setRoot(Chain); 8790 8791 // Inform the Frame Information that we have a stackmap in this function. 8792 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8793 } 8794 8795 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8796 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8797 const BasicBlock *EHPadBB) { 8798 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8799 // i32 <numBytes>, 8800 // i8* <target>, 8801 // i32 <numArgs>, 8802 // [Args...], 8803 // [live variables...]) 8804 8805 CallingConv::ID CC = CB.getCallingConv(); 8806 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8807 bool HasDef = !CB.getType()->isVoidTy(); 8808 SDLoc dl = getCurSDLoc(); 8809 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8810 8811 // Handle immediate and symbolic callees. 8812 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8813 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8814 /*isTarget=*/true); 8815 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8816 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8817 SDLoc(SymbolicCallee), 8818 SymbolicCallee->getValueType(0)); 8819 8820 // Get the real number of arguments participating in the call <numArgs> 8821 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8822 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8823 8824 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8825 // Intrinsics include all meta-operands up to but not including CC. 8826 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8827 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8828 "Not enough arguments provided to the patchpoint intrinsic"); 8829 8830 // For AnyRegCC the arguments are lowered later on manually. 8831 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8832 Type *ReturnTy = 8833 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8834 8835 TargetLowering::CallLoweringInfo CLI(DAG); 8836 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8837 ReturnTy, true); 8838 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8839 8840 SDNode *CallEnd = Result.second.getNode(); 8841 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8842 CallEnd = CallEnd->getOperand(0).getNode(); 8843 8844 /// Get a call instruction from the call sequence chain. 8845 /// Tail calls are not allowed. 8846 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8847 "Expected a callseq node."); 8848 SDNode *Call = CallEnd->getOperand(0).getNode(); 8849 bool HasGlue = Call->getGluedNode(); 8850 8851 // Replace the target specific call node with the patchable intrinsic. 8852 SmallVector<SDValue, 8> Ops; 8853 8854 // Add the <id> and <numBytes> constants. 8855 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8856 Ops.push_back(DAG.getTargetConstant( 8857 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8858 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8859 Ops.push_back(DAG.getTargetConstant( 8860 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8861 MVT::i32)); 8862 8863 // Add the callee. 8864 Ops.push_back(Callee); 8865 8866 // Adjust <numArgs> to account for any arguments that have been passed on the 8867 // stack instead. 8868 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8869 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8870 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8871 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8872 8873 // Add the calling convention 8874 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8875 8876 // Add the arguments we omitted previously. The register allocator should 8877 // place these in any free register. 8878 if (IsAnyRegCC) 8879 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8880 Ops.push_back(getValue(CB.getArgOperand(i))); 8881 8882 // Push the arguments from the call instruction up to the register mask. 8883 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8884 Ops.append(Call->op_begin() + 2, e); 8885 8886 // Push live variables for the stack map. 8887 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8888 8889 // Push the register mask info. 8890 if (HasGlue) 8891 Ops.push_back(*(Call->op_end()-2)); 8892 else 8893 Ops.push_back(*(Call->op_end()-1)); 8894 8895 // Push the chain (this is originally the first operand of the call, but 8896 // becomes now the last or second to last operand). 8897 Ops.push_back(*(Call->op_begin())); 8898 8899 // Push the glue flag (last operand). 8900 if (HasGlue) 8901 Ops.push_back(*(Call->op_end()-1)); 8902 8903 SDVTList NodeTys; 8904 if (IsAnyRegCC && HasDef) { 8905 // Create the return types based on the intrinsic definition 8906 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8907 SmallVector<EVT, 3> ValueVTs; 8908 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8909 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8910 8911 // There is always a chain and a glue type at the end 8912 ValueVTs.push_back(MVT::Other); 8913 ValueVTs.push_back(MVT::Glue); 8914 NodeTys = DAG.getVTList(ValueVTs); 8915 } else 8916 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8917 8918 // Replace the target specific call node with a PATCHPOINT node. 8919 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8920 dl, NodeTys, Ops); 8921 8922 // Update the NodeMap. 8923 if (HasDef) { 8924 if (IsAnyRegCC) 8925 setValue(&CB, SDValue(MN, 0)); 8926 else 8927 setValue(&CB, Result.first); 8928 } 8929 8930 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8931 // call sequence. Furthermore the location of the chain and glue can change 8932 // when the AnyReg calling convention is used and the intrinsic returns a 8933 // value. 8934 if (IsAnyRegCC && HasDef) { 8935 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8936 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8937 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8938 } else 8939 DAG.ReplaceAllUsesWith(Call, MN); 8940 DAG.DeleteNode(Call); 8941 8942 // Inform the Frame Information that we have a patchpoint in this function. 8943 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8944 } 8945 8946 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8947 unsigned Intrinsic) { 8948 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8949 SDValue Op1 = getValue(I.getArgOperand(0)); 8950 SDValue Op2; 8951 if (I.getNumArgOperands() > 1) 8952 Op2 = getValue(I.getArgOperand(1)); 8953 SDLoc dl = getCurSDLoc(); 8954 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8955 SDValue Res; 8956 SDNodeFlags SDFlags; 8957 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 8958 SDFlags.copyFMF(*FPMO); 8959 8960 switch (Intrinsic) { 8961 case Intrinsic::experimental_vector_reduce_v2_fadd: 8962 if (SDFlags.hasAllowReassociation()) 8963 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8964 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 8965 SDFlags); 8966 else 8967 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2, SDFlags); 8968 break; 8969 case Intrinsic::experimental_vector_reduce_v2_fmul: 8970 if (SDFlags.hasAllowReassociation()) 8971 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8972 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 8973 SDFlags); 8974 else 8975 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2, SDFlags); 8976 break; 8977 case Intrinsic::experimental_vector_reduce_add: 8978 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8979 break; 8980 case Intrinsic::experimental_vector_reduce_mul: 8981 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8982 break; 8983 case Intrinsic::experimental_vector_reduce_and: 8984 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8985 break; 8986 case Intrinsic::experimental_vector_reduce_or: 8987 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8988 break; 8989 case Intrinsic::experimental_vector_reduce_xor: 8990 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8991 break; 8992 case Intrinsic::experimental_vector_reduce_smax: 8993 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8994 break; 8995 case Intrinsic::experimental_vector_reduce_smin: 8996 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8997 break; 8998 case Intrinsic::experimental_vector_reduce_umax: 8999 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9000 break; 9001 case Intrinsic::experimental_vector_reduce_umin: 9002 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9003 break; 9004 case Intrinsic::experimental_vector_reduce_fmax: 9005 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9006 break; 9007 case Intrinsic::experimental_vector_reduce_fmin: 9008 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9009 break; 9010 default: 9011 llvm_unreachable("Unhandled vector reduce intrinsic"); 9012 } 9013 setValue(&I, Res); 9014 } 9015 9016 /// Returns an AttributeList representing the attributes applied to the return 9017 /// value of the given call. 9018 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9019 SmallVector<Attribute::AttrKind, 2> Attrs; 9020 if (CLI.RetSExt) 9021 Attrs.push_back(Attribute::SExt); 9022 if (CLI.RetZExt) 9023 Attrs.push_back(Attribute::ZExt); 9024 if (CLI.IsInReg) 9025 Attrs.push_back(Attribute::InReg); 9026 9027 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9028 Attrs); 9029 } 9030 9031 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9032 /// implementation, which just calls LowerCall. 9033 /// FIXME: When all targets are 9034 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9035 std::pair<SDValue, SDValue> 9036 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9037 // Handle the incoming return values from the call. 9038 CLI.Ins.clear(); 9039 Type *OrigRetTy = CLI.RetTy; 9040 SmallVector<EVT, 4> RetTys; 9041 SmallVector<uint64_t, 4> Offsets; 9042 auto &DL = CLI.DAG.getDataLayout(); 9043 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9044 9045 if (CLI.IsPostTypeLegalization) { 9046 // If we are lowering a libcall after legalization, split the return type. 9047 SmallVector<EVT, 4> OldRetTys; 9048 SmallVector<uint64_t, 4> OldOffsets; 9049 RetTys.swap(OldRetTys); 9050 Offsets.swap(OldOffsets); 9051 9052 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9053 EVT RetVT = OldRetTys[i]; 9054 uint64_t Offset = OldOffsets[i]; 9055 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9056 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9057 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9058 RetTys.append(NumRegs, RegisterVT); 9059 for (unsigned j = 0; j != NumRegs; ++j) 9060 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9061 } 9062 } 9063 9064 SmallVector<ISD::OutputArg, 4> Outs; 9065 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9066 9067 bool CanLowerReturn = 9068 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9069 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9070 9071 SDValue DemoteStackSlot; 9072 int DemoteStackIdx = -100; 9073 if (!CanLowerReturn) { 9074 // FIXME: equivalent assert? 9075 // assert(!CS.hasInAllocaArgument() && 9076 // "sret demotion is incompatible with inalloca"); 9077 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9078 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9079 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9080 DemoteStackIdx = 9081 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9082 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9083 DL.getAllocaAddrSpace()); 9084 9085 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9086 ArgListEntry Entry; 9087 Entry.Node = DemoteStackSlot; 9088 Entry.Ty = StackSlotPtrType; 9089 Entry.IsSExt = false; 9090 Entry.IsZExt = false; 9091 Entry.IsInReg = false; 9092 Entry.IsSRet = true; 9093 Entry.IsNest = false; 9094 Entry.IsByVal = false; 9095 Entry.IsByRef = false; 9096 Entry.IsReturned = false; 9097 Entry.IsSwiftSelf = false; 9098 Entry.IsSwiftError = false; 9099 Entry.IsCFGuardTarget = false; 9100 Entry.Alignment = Alignment; 9101 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9102 CLI.NumFixedArgs += 1; 9103 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9104 9105 // sret demotion isn't compatible with tail-calls, since the sret argument 9106 // points into the callers stack frame. 9107 CLI.IsTailCall = false; 9108 } else { 9109 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9110 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9111 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9112 ISD::ArgFlagsTy Flags; 9113 if (NeedsRegBlock) { 9114 Flags.setInConsecutiveRegs(); 9115 if (I == RetTys.size() - 1) 9116 Flags.setInConsecutiveRegsLast(); 9117 } 9118 EVT VT = RetTys[I]; 9119 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9120 CLI.CallConv, VT); 9121 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9122 CLI.CallConv, VT); 9123 for (unsigned i = 0; i != NumRegs; ++i) { 9124 ISD::InputArg MyFlags; 9125 MyFlags.Flags = Flags; 9126 MyFlags.VT = RegisterVT; 9127 MyFlags.ArgVT = VT; 9128 MyFlags.Used = CLI.IsReturnValueUsed; 9129 if (CLI.RetTy->isPointerTy()) { 9130 MyFlags.Flags.setPointer(); 9131 MyFlags.Flags.setPointerAddrSpace( 9132 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9133 } 9134 if (CLI.RetSExt) 9135 MyFlags.Flags.setSExt(); 9136 if (CLI.RetZExt) 9137 MyFlags.Flags.setZExt(); 9138 if (CLI.IsInReg) 9139 MyFlags.Flags.setInReg(); 9140 CLI.Ins.push_back(MyFlags); 9141 } 9142 } 9143 } 9144 9145 // We push in swifterror return as the last element of CLI.Ins. 9146 ArgListTy &Args = CLI.getArgs(); 9147 if (supportSwiftError()) { 9148 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9149 if (Args[i].IsSwiftError) { 9150 ISD::InputArg MyFlags; 9151 MyFlags.VT = getPointerTy(DL); 9152 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9153 MyFlags.Flags.setSwiftError(); 9154 CLI.Ins.push_back(MyFlags); 9155 } 9156 } 9157 } 9158 9159 // Handle all of the outgoing arguments. 9160 CLI.Outs.clear(); 9161 CLI.OutVals.clear(); 9162 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9163 SmallVector<EVT, 4> ValueVTs; 9164 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9165 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9166 Type *FinalType = Args[i].Ty; 9167 if (Args[i].IsByVal) 9168 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9169 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9170 FinalType, CLI.CallConv, CLI.IsVarArg); 9171 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9172 ++Value) { 9173 EVT VT = ValueVTs[Value]; 9174 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9175 SDValue Op = SDValue(Args[i].Node.getNode(), 9176 Args[i].Node.getResNo() + Value); 9177 ISD::ArgFlagsTy Flags; 9178 9179 // Certain targets (such as MIPS), may have a different ABI alignment 9180 // for a type depending on the context. Give the target a chance to 9181 // specify the alignment it wants. 9182 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9183 9184 if (Args[i].Ty->isPointerTy()) { 9185 Flags.setPointer(); 9186 Flags.setPointerAddrSpace( 9187 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9188 } 9189 if (Args[i].IsZExt) 9190 Flags.setZExt(); 9191 if (Args[i].IsSExt) 9192 Flags.setSExt(); 9193 if (Args[i].IsInReg) { 9194 // If we are using vectorcall calling convention, a structure that is 9195 // passed InReg - is surely an HVA 9196 if (CLI.CallConv == CallingConv::X86_VectorCall && 9197 isa<StructType>(FinalType)) { 9198 // The first value of a structure is marked 9199 if (0 == Value) 9200 Flags.setHvaStart(); 9201 Flags.setHva(); 9202 } 9203 // Set InReg Flag 9204 Flags.setInReg(); 9205 } 9206 if (Args[i].IsSRet) 9207 Flags.setSRet(); 9208 if (Args[i].IsSwiftSelf) 9209 Flags.setSwiftSelf(); 9210 if (Args[i].IsSwiftError) 9211 Flags.setSwiftError(); 9212 if (Args[i].IsCFGuardTarget) 9213 Flags.setCFGuardTarget(); 9214 if (Args[i].IsByVal) 9215 Flags.setByVal(); 9216 if (Args[i].IsByRef) 9217 Flags.setByRef(); 9218 if (Args[i].IsPreallocated) { 9219 Flags.setPreallocated(); 9220 // Set the byval flag for CCAssignFn callbacks that don't know about 9221 // preallocated. This way we can know how many bytes we should've 9222 // allocated and how many bytes a callee cleanup function will pop. If 9223 // we port preallocated to more targets, we'll have to add custom 9224 // preallocated handling in the various CC lowering callbacks. 9225 Flags.setByVal(); 9226 } 9227 if (Args[i].IsInAlloca) { 9228 Flags.setInAlloca(); 9229 // Set the byval flag for CCAssignFn callbacks that don't know about 9230 // inalloca. This way we can know how many bytes we should've allocated 9231 // and how many bytes a callee cleanup function will pop. If we port 9232 // inalloca to more targets, we'll have to add custom inalloca handling 9233 // in the various CC lowering callbacks. 9234 Flags.setByVal(); 9235 } 9236 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9237 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9238 Type *ElementTy = Ty->getElementType(); 9239 9240 unsigned FrameSize = DL.getTypeAllocSize( 9241 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9242 Flags.setByValSize(FrameSize); 9243 9244 // info is not there but there are cases it cannot get right. 9245 Align FrameAlign; 9246 if (auto MA = Args[i].Alignment) 9247 FrameAlign = *MA; 9248 else 9249 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9250 Flags.setByValAlign(FrameAlign); 9251 } 9252 if (Args[i].IsNest) 9253 Flags.setNest(); 9254 if (NeedsRegBlock) 9255 Flags.setInConsecutiveRegs(); 9256 Flags.setOrigAlign(OriginalAlignment); 9257 9258 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9259 CLI.CallConv, VT); 9260 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9261 CLI.CallConv, VT); 9262 SmallVector<SDValue, 4> Parts(NumParts); 9263 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9264 9265 if (Args[i].IsSExt) 9266 ExtendKind = ISD::SIGN_EXTEND; 9267 else if (Args[i].IsZExt) 9268 ExtendKind = ISD::ZERO_EXTEND; 9269 9270 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9271 // for now. 9272 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9273 CanLowerReturn) { 9274 assert((CLI.RetTy == Args[i].Ty || 9275 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9276 CLI.RetTy->getPointerAddressSpace() == 9277 Args[i].Ty->getPointerAddressSpace())) && 9278 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9279 // Before passing 'returned' to the target lowering code, ensure that 9280 // either the register MVT and the actual EVT are the same size or that 9281 // the return value and argument are extended in the same way; in these 9282 // cases it's safe to pass the argument register value unchanged as the 9283 // return register value (although it's at the target's option whether 9284 // to do so) 9285 // TODO: allow code generation to take advantage of partially preserved 9286 // registers rather than clobbering the entire register when the 9287 // parameter extension method is not compatible with the return 9288 // extension method 9289 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9290 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9291 CLI.RetZExt == Args[i].IsZExt)) 9292 Flags.setReturned(); 9293 } 9294 9295 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9296 CLI.CallConv, ExtendKind); 9297 9298 for (unsigned j = 0; j != NumParts; ++j) { 9299 // if it isn't first piece, alignment must be 1 9300 // For scalable vectors the scalable part is currently handled 9301 // by individual targets, so we just use the known minimum size here. 9302 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9303 i < CLI.NumFixedArgs, i, 9304 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9305 if (NumParts > 1 && j == 0) 9306 MyFlags.Flags.setSplit(); 9307 else if (j != 0) { 9308 MyFlags.Flags.setOrigAlign(Align(1)); 9309 if (j == NumParts - 1) 9310 MyFlags.Flags.setSplitEnd(); 9311 } 9312 9313 CLI.Outs.push_back(MyFlags); 9314 CLI.OutVals.push_back(Parts[j]); 9315 } 9316 9317 if (NeedsRegBlock && Value == NumValues - 1) 9318 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9319 } 9320 } 9321 9322 SmallVector<SDValue, 4> InVals; 9323 CLI.Chain = LowerCall(CLI, InVals); 9324 9325 // Update CLI.InVals to use outside of this function. 9326 CLI.InVals = InVals; 9327 9328 // Verify that the target's LowerCall behaved as expected. 9329 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9330 "LowerCall didn't return a valid chain!"); 9331 assert((!CLI.IsTailCall || InVals.empty()) && 9332 "LowerCall emitted a return value for a tail call!"); 9333 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9334 "LowerCall didn't emit the correct number of values!"); 9335 9336 // For a tail call, the return value is merely live-out and there aren't 9337 // any nodes in the DAG representing it. Return a special value to 9338 // indicate that a tail call has been emitted and no more Instructions 9339 // should be processed in the current block. 9340 if (CLI.IsTailCall) { 9341 CLI.DAG.setRoot(CLI.Chain); 9342 return std::make_pair(SDValue(), SDValue()); 9343 } 9344 9345 #ifndef NDEBUG 9346 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9347 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9348 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9349 "LowerCall emitted a value with the wrong type!"); 9350 } 9351 #endif 9352 9353 SmallVector<SDValue, 4> ReturnValues; 9354 if (!CanLowerReturn) { 9355 // The instruction result is the result of loading from the 9356 // hidden sret parameter. 9357 SmallVector<EVT, 1> PVTs; 9358 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9359 9360 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9361 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9362 EVT PtrVT = PVTs[0]; 9363 9364 unsigned NumValues = RetTys.size(); 9365 ReturnValues.resize(NumValues); 9366 SmallVector<SDValue, 4> Chains(NumValues); 9367 9368 // An aggregate return value cannot wrap around the address space, so 9369 // offsets to its parts don't wrap either. 9370 SDNodeFlags Flags; 9371 Flags.setNoUnsignedWrap(true); 9372 9373 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9374 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9375 for (unsigned i = 0; i < NumValues; ++i) { 9376 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9377 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9378 PtrVT), Flags); 9379 SDValue L = CLI.DAG.getLoad( 9380 RetTys[i], CLI.DL, CLI.Chain, Add, 9381 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9382 DemoteStackIdx, Offsets[i]), 9383 HiddenSRetAlign); 9384 ReturnValues[i] = L; 9385 Chains[i] = L.getValue(1); 9386 } 9387 9388 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9389 } else { 9390 // Collect the legal value parts into potentially illegal values 9391 // that correspond to the original function's return values. 9392 Optional<ISD::NodeType> AssertOp; 9393 if (CLI.RetSExt) 9394 AssertOp = ISD::AssertSext; 9395 else if (CLI.RetZExt) 9396 AssertOp = ISD::AssertZext; 9397 unsigned CurReg = 0; 9398 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9399 EVT VT = RetTys[I]; 9400 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9401 CLI.CallConv, VT); 9402 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9403 CLI.CallConv, VT); 9404 9405 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9406 NumRegs, RegisterVT, VT, nullptr, 9407 CLI.CallConv, AssertOp)); 9408 CurReg += NumRegs; 9409 } 9410 9411 // For a function returning void, there is no return value. We can't create 9412 // such a node, so we just return a null return value in that case. In 9413 // that case, nothing will actually look at the value. 9414 if (ReturnValues.empty()) 9415 return std::make_pair(SDValue(), CLI.Chain); 9416 } 9417 9418 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9419 CLI.DAG.getVTList(RetTys), ReturnValues); 9420 return std::make_pair(Res, CLI.Chain); 9421 } 9422 9423 void TargetLowering::LowerOperationWrapper(SDNode *N, 9424 SmallVectorImpl<SDValue> &Results, 9425 SelectionDAG &DAG) const { 9426 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9427 Results.push_back(Res); 9428 } 9429 9430 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9431 llvm_unreachable("LowerOperation not implemented for this target!"); 9432 } 9433 9434 void 9435 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9436 SDValue Op = getNonRegisterValue(V); 9437 assert((Op.getOpcode() != ISD::CopyFromReg || 9438 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9439 "Copy from a reg to the same reg!"); 9440 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9441 9442 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9443 // If this is an InlineAsm we have to match the registers required, not the 9444 // notional registers required by the type. 9445 9446 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9447 None); // This is not an ABI copy. 9448 SDValue Chain = DAG.getEntryNode(); 9449 9450 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9451 FuncInfo.PreferredExtendType.end()) 9452 ? ISD::ANY_EXTEND 9453 : FuncInfo.PreferredExtendType[V]; 9454 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9455 PendingExports.push_back(Chain); 9456 } 9457 9458 #include "llvm/CodeGen/SelectionDAGISel.h" 9459 9460 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9461 /// entry block, return true. This includes arguments used by switches, since 9462 /// the switch may expand into multiple basic blocks. 9463 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9464 // With FastISel active, we may be splitting blocks, so force creation 9465 // of virtual registers for all non-dead arguments. 9466 if (FastISel) 9467 return A->use_empty(); 9468 9469 const BasicBlock &Entry = A->getParent()->front(); 9470 for (const User *U : A->users()) 9471 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9472 return false; // Use not in entry block. 9473 9474 return true; 9475 } 9476 9477 using ArgCopyElisionMapTy = 9478 DenseMap<const Argument *, 9479 std::pair<const AllocaInst *, const StoreInst *>>; 9480 9481 /// Scan the entry block of the function in FuncInfo for arguments that look 9482 /// like copies into a local alloca. Record any copied arguments in 9483 /// ArgCopyElisionCandidates. 9484 static void 9485 findArgumentCopyElisionCandidates(const DataLayout &DL, 9486 FunctionLoweringInfo *FuncInfo, 9487 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9488 // Record the state of every static alloca used in the entry block. Argument 9489 // allocas are all used in the entry block, so we need approximately as many 9490 // entries as we have arguments. 9491 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9492 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9493 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9494 StaticAllocas.reserve(NumArgs * 2); 9495 9496 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9497 if (!V) 9498 return nullptr; 9499 V = V->stripPointerCasts(); 9500 const auto *AI = dyn_cast<AllocaInst>(V); 9501 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9502 return nullptr; 9503 auto Iter = StaticAllocas.insert({AI, Unknown}); 9504 return &Iter.first->second; 9505 }; 9506 9507 // Look for stores of arguments to static allocas. Look through bitcasts and 9508 // GEPs to handle type coercions, as long as the alloca is fully initialized 9509 // by the store. Any non-store use of an alloca escapes it and any subsequent 9510 // unanalyzed store might write it. 9511 // FIXME: Handle structs initialized with multiple stores. 9512 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9513 // Look for stores, and handle non-store uses conservatively. 9514 const auto *SI = dyn_cast<StoreInst>(&I); 9515 if (!SI) { 9516 // We will look through cast uses, so ignore them completely. 9517 if (I.isCast()) 9518 continue; 9519 // Ignore debug info intrinsics, they don't escape or store to allocas. 9520 if (isa<DbgInfoIntrinsic>(I)) 9521 continue; 9522 // This is an unknown instruction. Assume it escapes or writes to all 9523 // static alloca operands. 9524 for (const Use &U : I.operands()) { 9525 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9526 *Info = StaticAllocaInfo::Clobbered; 9527 } 9528 continue; 9529 } 9530 9531 // If the stored value is a static alloca, mark it as escaped. 9532 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9533 *Info = StaticAllocaInfo::Clobbered; 9534 9535 // Check if the destination is a static alloca. 9536 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9537 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9538 if (!Info) 9539 continue; 9540 const AllocaInst *AI = cast<AllocaInst>(Dst); 9541 9542 // Skip allocas that have been initialized or clobbered. 9543 if (*Info != StaticAllocaInfo::Unknown) 9544 continue; 9545 9546 // Check if the stored value is an argument, and that this store fully 9547 // initializes the alloca. Don't elide copies from the same argument twice. 9548 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9549 const auto *Arg = dyn_cast<Argument>(Val); 9550 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9551 Arg->getType()->isEmptyTy() || 9552 DL.getTypeStoreSize(Arg->getType()) != 9553 DL.getTypeAllocSize(AI->getAllocatedType()) || 9554 ArgCopyElisionCandidates.count(Arg)) { 9555 *Info = StaticAllocaInfo::Clobbered; 9556 continue; 9557 } 9558 9559 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9560 << '\n'); 9561 9562 // Mark this alloca and store for argument copy elision. 9563 *Info = StaticAllocaInfo::Elidable; 9564 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9565 9566 // Stop scanning if we've seen all arguments. This will happen early in -O0 9567 // builds, which is useful, because -O0 builds have large entry blocks and 9568 // many allocas. 9569 if (ArgCopyElisionCandidates.size() == NumArgs) 9570 break; 9571 } 9572 } 9573 9574 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9575 /// ArgVal is a load from a suitable fixed stack object. 9576 static void tryToElideArgumentCopy( 9577 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9578 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9579 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9580 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9581 SDValue ArgVal, bool &ArgHasUses) { 9582 // Check if this is a load from a fixed stack object. 9583 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9584 if (!LNode) 9585 return; 9586 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9587 if (!FINode) 9588 return; 9589 9590 // Check that the fixed stack object is the right size and alignment. 9591 // Look at the alignment that the user wrote on the alloca instead of looking 9592 // at the stack object. 9593 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9594 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9595 const AllocaInst *AI = ArgCopyIter->second.first; 9596 int FixedIndex = FINode->getIndex(); 9597 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9598 int OldIndex = AllocaIndex; 9599 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9600 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9601 LLVM_DEBUG( 9602 dbgs() << " argument copy elision failed due to bad fixed stack " 9603 "object size\n"); 9604 return; 9605 } 9606 Align RequiredAlignment = AI->getAlign(); 9607 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9608 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9609 "greater than stack argument alignment (" 9610 << DebugStr(RequiredAlignment) << " vs " 9611 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9612 return; 9613 } 9614 9615 // Perform the elision. Delete the old stack object and replace its only use 9616 // in the variable info map. Mark the stack object as mutable. 9617 LLVM_DEBUG({ 9618 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9619 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9620 << '\n'; 9621 }); 9622 MFI.RemoveStackObject(OldIndex); 9623 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9624 AllocaIndex = FixedIndex; 9625 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9626 Chains.push_back(ArgVal.getValue(1)); 9627 9628 // Avoid emitting code for the store implementing the copy. 9629 const StoreInst *SI = ArgCopyIter->second.second; 9630 ElidedArgCopyInstrs.insert(SI); 9631 9632 // Check for uses of the argument again so that we can avoid exporting ArgVal 9633 // if it is't used by anything other than the store. 9634 for (const Value *U : Arg.users()) { 9635 if (U != SI) { 9636 ArgHasUses = true; 9637 break; 9638 } 9639 } 9640 } 9641 9642 void SelectionDAGISel::LowerArguments(const Function &F) { 9643 SelectionDAG &DAG = SDB->DAG; 9644 SDLoc dl = SDB->getCurSDLoc(); 9645 const DataLayout &DL = DAG.getDataLayout(); 9646 SmallVector<ISD::InputArg, 16> Ins; 9647 9648 // In Naked functions we aren't going to save any registers. 9649 if (F.hasFnAttribute(Attribute::Naked)) 9650 return; 9651 9652 if (!FuncInfo->CanLowerReturn) { 9653 // Put in an sret pointer parameter before all the other parameters. 9654 SmallVector<EVT, 1> ValueVTs; 9655 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9656 F.getReturnType()->getPointerTo( 9657 DAG.getDataLayout().getAllocaAddrSpace()), 9658 ValueVTs); 9659 9660 // NOTE: Assuming that a pointer will never break down to more than one VT 9661 // or one register. 9662 ISD::ArgFlagsTy Flags; 9663 Flags.setSRet(); 9664 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9665 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9666 ISD::InputArg::NoArgIndex, 0); 9667 Ins.push_back(RetArg); 9668 } 9669 9670 // Look for stores of arguments to static allocas. Mark such arguments with a 9671 // flag to ask the target to give us the memory location of that argument if 9672 // available. 9673 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9674 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9675 ArgCopyElisionCandidates); 9676 9677 // Set up the incoming argument description vector. 9678 for (const Argument &Arg : F.args()) { 9679 unsigned ArgNo = Arg.getArgNo(); 9680 SmallVector<EVT, 4> ValueVTs; 9681 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9682 bool isArgValueUsed = !Arg.use_empty(); 9683 unsigned PartBase = 0; 9684 Type *FinalType = Arg.getType(); 9685 if (Arg.hasAttribute(Attribute::ByVal)) 9686 FinalType = Arg.getParamByValType(); 9687 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9688 FinalType, F.getCallingConv(), F.isVarArg()); 9689 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9690 Value != NumValues; ++Value) { 9691 EVT VT = ValueVTs[Value]; 9692 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9693 ISD::ArgFlagsTy Flags; 9694 9695 // Certain targets (such as MIPS), may have a different ABI alignment 9696 // for a type depending on the context. Give the target a chance to 9697 // specify the alignment it wants. 9698 const Align OriginalAlignment( 9699 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9700 9701 if (Arg.getType()->isPointerTy()) { 9702 Flags.setPointer(); 9703 Flags.setPointerAddrSpace( 9704 cast<PointerType>(Arg.getType())->getAddressSpace()); 9705 } 9706 if (Arg.hasAttribute(Attribute::ZExt)) 9707 Flags.setZExt(); 9708 if (Arg.hasAttribute(Attribute::SExt)) 9709 Flags.setSExt(); 9710 if (Arg.hasAttribute(Attribute::InReg)) { 9711 // If we are using vectorcall calling convention, a structure that is 9712 // passed InReg - is surely an HVA 9713 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9714 isa<StructType>(Arg.getType())) { 9715 // The first value of a structure is marked 9716 if (0 == Value) 9717 Flags.setHvaStart(); 9718 Flags.setHva(); 9719 } 9720 // Set InReg Flag 9721 Flags.setInReg(); 9722 } 9723 if (Arg.hasAttribute(Attribute::StructRet)) 9724 Flags.setSRet(); 9725 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9726 Flags.setSwiftSelf(); 9727 if (Arg.hasAttribute(Attribute::SwiftError)) 9728 Flags.setSwiftError(); 9729 if (Arg.hasAttribute(Attribute::ByVal)) 9730 Flags.setByVal(); 9731 if (Arg.hasAttribute(Attribute::ByRef)) 9732 Flags.setByRef(); 9733 if (Arg.hasAttribute(Attribute::InAlloca)) { 9734 Flags.setInAlloca(); 9735 // Set the byval flag for CCAssignFn callbacks that don't know about 9736 // inalloca. This way we can know how many bytes we should've allocated 9737 // and how many bytes a callee cleanup function will pop. If we port 9738 // inalloca to more targets, we'll have to add custom inalloca handling 9739 // in the various CC lowering callbacks. 9740 Flags.setByVal(); 9741 } 9742 if (Arg.hasAttribute(Attribute::Preallocated)) { 9743 Flags.setPreallocated(); 9744 // Set the byval flag for CCAssignFn callbacks that don't know about 9745 // preallocated. This way we can know how many bytes we should've 9746 // allocated and how many bytes a callee cleanup function will pop. If 9747 // we port preallocated to more targets, we'll have to add custom 9748 // preallocated handling in the various CC lowering callbacks. 9749 Flags.setByVal(); 9750 } 9751 9752 Type *ArgMemTy = nullptr; 9753 if (F.getCallingConv() == CallingConv::X86_INTR) { 9754 // IA Interrupt passes frame (1st parameter) by value in the stack. 9755 if (ArgNo == 0) { 9756 Flags.setByVal(); 9757 // FIXME: Dependence on pointee element type. See bug 46672. 9758 ArgMemTy = Arg.getType()->getPointerElementType(); 9759 } 9760 } 9761 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 9762 Flags.isByRef()) { 9763 if (!ArgMemTy) 9764 ArgMemTy = Arg.getPointeeInMemoryValueType(); 9765 9766 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 9767 9768 // For in-memory arguments, size and alignment should be passed from FE. 9769 // BE will guess if this info is not there but there are cases it cannot 9770 // get right. 9771 MaybeAlign MemAlign = Arg.getParamAlign(); 9772 if (!MemAlign) 9773 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 9774 9775 if (Flags.isByRef()) { 9776 Flags.setByRefSize(MemSize); 9777 Flags.setByRefAlign(*MemAlign); 9778 } else { 9779 Flags.setByValSize(MemSize); 9780 Flags.setByValAlign(*MemAlign); 9781 } 9782 } 9783 9784 if (Arg.hasAttribute(Attribute::Nest)) 9785 Flags.setNest(); 9786 if (NeedsRegBlock) 9787 Flags.setInConsecutiveRegs(); 9788 Flags.setOrigAlign(OriginalAlignment); 9789 if (ArgCopyElisionCandidates.count(&Arg)) 9790 Flags.setCopyElisionCandidate(); 9791 if (Arg.hasAttribute(Attribute::Returned)) 9792 Flags.setReturned(); 9793 9794 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9795 *CurDAG->getContext(), F.getCallingConv(), VT); 9796 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9797 *CurDAG->getContext(), F.getCallingConv(), VT); 9798 for (unsigned i = 0; i != NumRegs; ++i) { 9799 // For scalable vectors, use the minimum size; individual targets 9800 // are responsible for handling scalable vector arguments and 9801 // return values. 9802 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9803 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9804 if (NumRegs > 1 && i == 0) 9805 MyFlags.Flags.setSplit(); 9806 // if it isn't first piece, alignment must be 1 9807 else if (i > 0) { 9808 MyFlags.Flags.setOrigAlign(Align(1)); 9809 if (i == NumRegs - 1) 9810 MyFlags.Flags.setSplitEnd(); 9811 } 9812 Ins.push_back(MyFlags); 9813 } 9814 if (NeedsRegBlock && Value == NumValues - 1) 9815 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9816 PartBase += VT.getStoreSize().getKnownMinSize(); 9817 } 9818 } 9819 9820 // Call the target to set up the argument values. 9821 SmallVector<SDValue, 8> InVals; 9822 SDValue NewRoot = TLI->LowerFormalArguments( 9823 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9824 9825 // Verify that the target's LowerFormalArguments behaved as expected. 9826 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9827 "LowerFormalArguments didn't return a valid chain!"); 9828 assert(InVals.size() == Ins.size() && 9829 "LowerFormalArguments didn't emit the correct number of values!"); 9830 LLVM_DEBUG({ 9831 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9832 assert(InVals[i].getNode() && 9833 "LowerFormalArguments emitted a null value!"); 9834 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9835 "LowerFormalArguments emitted a value with the wrong type!"); 9836 } 9837 }); 9838 9839 // Update the DAG with the new chain value resulting from argument lowering. 9840 DAG.setRoot(NewRoot); 9841 9842 // Set up the argument values. 9843 unsigned i = 0; 9844 if (!FuncInfo->CanLowerReturn) { 9845 // Create a virtual register for the sret pointer, and put in a copy 9846 // from the sret argument into it. 9847 SmallVector<EVT, 1> ValueVTs; 9848 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9849 F.getReturnType()->getPointerTo( 9850 DAG.getDataLayout().getAllocaAddrSpace()), 9851 ValueVTs); 9852 MVT VT = ValueVTs[0].getSimpleVT(); 9853 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9854 Optional<ISD::NodeType> AssertOp = None; 9855 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9856 nullptr, F.getCallingConv(), AssertOp); 9857 9858 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9859 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9860 Register SRetReg = 9861 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9862 FuncInfo->DemoteRegister = SRetReg; 9863 NewRoot = 9864 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9865 DAG.setRoot(NewRoot); 9866 9867 // i indexes lowered arguments. Bump it past the hidden sret argument. 9868 ++i; 9869 } 9870 9871 SmallVector<SDValue, 4> Chains; 9872 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9873 for (const Argument &Arg : F.args()) { 9874 SmallVector<SDValue, 4> ArgValues; 9875 SmallVector<EVT, 4> ValueVTs; 9876 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9877 unsigned NumValues = ValueVTs.size(); 9878 if (NumValues == 0) 9879 continue; 9880 9881 bool ArgHasUses = !Arg.use_empty(); 9882 9883 // Elide the copying store if the target loaded this argument from a 9884 // suitable fixed stack object. 9885 if (Ins[i].Flags.isCopyElisionCandidate()) { 9886 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9887 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9888 InVals[i], ArgHasUses); 9889 } 9890 9891 // If this argument is unused then remember its value. It is used to generate 9892 // debugging information. 9893 bool isSwiftErrorArg = 9894 TLI->supportSwiftError() && 9895 Arg.hasAttribute(Attribute::SwiftError); 9896 if (!ArgHasUses && !isSwiftErrorArg) { 9897 SDB->setUnusedArgValue(&Arg, InVals[i]); 9898 9899 // Also remember any frame index for use in FastISel. 9900 if (FrameIndexSDNode *FI = 9901 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9902 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9903 } 9904 9905 for (unsigned Val = 0; Val != NumValues; ++Val) { 9906 EVT VT = ValueVTs[Val]; 9907 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9908 F.getCallingConv(), VT); 9909 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9910 *CurDAG->getContext(), F.getCallingConv(), VT); 9911 9912 // Even an apparent 'unused' swifterror argument needs to be returned. So 9913 // we do generate a copy for it that can be used on return from the 9914 // function. 9915 if (ArgHasUses || isSwiftErrorArg) { 9916 Optional<ISD::NodeType> AssertOp; 9917 if (Arg.hasAttribute(Attribute::SExt)) 9918 AssertOp = ISD::AssertSext; 9919 else if (Arg.hasAttribute(Attribute::ZExt)) 9920 AssertOp = ISD::AssertZext; 9921 9922 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9923 PartVT, VT, nullptr, 9924 F.getCallingConv(), AssertOp)); 9925 } 9926 9927 i += NumParts; 9928 } 9929 9930 // We don't need to do anything else for unused arguments. 9931 if (ArgValues.empty()) 9932 continue; 9933 9934 // Note down frame index. 9935 if (FrameIndexSDNode *FI = 9936 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9937 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9938 9939 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9940 SDB->getCurSDLoc()); 9941 9942 SDB->setValue(&Arg, Res); 9943 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9944 // We want to associate the argument with the frame index, among 9945 // involved operands, that correspond to the lowest address. The 9946 // getCopyFromParts function, called earlier, is swapping the order of 9947 // the operands to BUILD_PAIR depending on endianness. The result of 9948 // that swapping is that the least significant bits of the argument will 9949 // be in the first operand of the BUILD_PAIR node, and the most 9950 // significant bits will be in the second operand. 9951 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9952 if (LoadSDNode *LNode = 9953 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9954 if (FrameIndexSDNode *FI = 9955 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9956 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9957 } 9958 9959 // Analyses past this point are naive and don't expect an assertion. 9960 if (Res.getOpcode() == ISD::AssertZext) 9961 Res = Res.getOperand(0); 9962 9963 // Update the SwiftErrorVRegDefMap. 9964 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9965 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9966 if (Register::isVirtualRegister(Reg)) 9967 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9968 Reg); 9969 } 9970 9971 // If this argument is live outside of the entry block, insert a copy from 9972 // wherever we got it to the vreg that other BB's will reference it as. 9973 if (Res.getOpcode() == ISD::CopyFromReg) { 9974 // If we can, though, try to skip creating an unnecessary vreg. 9975 // FIXME: This isn't very clean... it would be nice to make this more 9976 // general. 9977 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9978 if (Register::isVirtualRegister(Reg)) { 9979 FuncInfo->ValueMap[&Arg] = Reg; 9980 continue; 9981 } 9982 } 9983 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9984 FuncInfo->InitializeRegForValue(&Arg); 9985 SDB->CopyToExportRegsIfNeeded(&Arg); 9986 } 9987 } 9988 9989 if (!Chains.empty()) { 9990 Chains.push_back(NewRoot); 9991 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9992 } 9993 9994 DAG.setRoot(NewRoot); 9995 9996 assert(i == InVals.size() && "Argument register count mismatch!"); 9997 9998 // If any argument copy elisions occurred and we have debug info, update the 9999 // stale frame indices used in the dbg.declare variable info table. 10000 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10001 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10002 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10003 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10004 if (I != ArgCopyElisionFrameIndexMap.end()) 10005 VI.Slot = I->second; 10006 } 10007 } 10008 10009 // Finally, if the target has anything special to do, allow it to do so. 10010 emitFunctionEntryCode(); 10011 } 10012 10013 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10014 /// ensure constants are generated when needed. Remember the virtual registers 10015 /// that need to be added to the Machine PHI nodes as input. We cannot just 10016 /// directly add them, because expansion might result in multiple MBB's for one 10017 /// BB. As such, the start of the BB might correspond to a different MBB than 10018 /// the end. 10019 void 10020 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10021 const Instruction *TI = LLVMBB->getTerminator(); 10022 10023 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10024 10025 // Check PHI nodes in successors that expect a value to be available from this 10026 // block. 10027 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10028 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10029 if (!isa<PHINode>(SuccBB->begin())) continue; 10030 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10031 10032 // If this terminator has multiple identical successors (common for 10033 // switches), only handle each succ once. 10034 if (!SuccsHandled.insert(SuccMBB).second) 10035 continue; 10036 10037 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10038 10039 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10040 // nodes and Machine PHI nodes, but the incoming operands have not been 10041 // emitted yet. 10042 for (const PHINode &PN : SuccBB->phis()) { 10043 // Ignore dead phi's. 10044 if (PN.use_empty()) 10045 continue; 10046 10047 // Skip empty types 10048 if (PN.getType()->isEmptyTy()) 10049 continue; 10050 10051 unsigned Reg; 10052 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10053 10054 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10055 unsigned &RegOut = ConstantsOut[C]; 10056 if (RegOut == 0) { 10057 RegOut = FuncInfo.CreateRegs(C); 10058 CopyValueToVirtualRegister(C, RegOut); 10059 } 10060 Reg = RegOut; 10061 } else { 10062 DenseMap<const Value *, Register>::iterator I = 10063 FuncInfo.ValueMap.find(PHIOp); 10064 if (I != FuncInfo.ValueMap.end()) 10065 Reg = I->second; 10066 else { 10067 assert(isa<AllocaInst>(PHIOp) && 10068 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10069 "Didn't codegen value into a register!??"); 10070 Reg = FuncInfo.CreateRegs(PHIOp); 10071 CopyValueToVirtualRegister(PHIOp, Reg); 10072 } 10073 } 10074 10075 // Remember that this register needs to added to the machine PHI node as 10076 // the input for this MBB. 10077 SmallVector<EVT, 4> ValueVTs; 10078 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10079 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10080 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10081 EVT VT = ValueVTs[vti]; 10082 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10083 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10084 FuncInfo.PHINodesToUpdate.push_back( 10085 std::make_pair(&*MBBI++, Reg + i)); 10086 Reg += NumRegisters; 10087 } 10088 } 10089 } 10090 10091 ConstantsOut.clear(); 10092 } 10093 10094 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10095 /// is 0. 10096 MachineBasicBlock * 10097 SelectionDAGBuilder::StackProtectorDescriptor:: 10098 AddSuccessorMBB(const BasicBlock *BB, 10099 MachineBasicBlock *ParentMBB, 10100 bool IsLikely, 10101 MachineBasicBlock *SuccMBB) { 10102 // If SuccBB has not been created yet, create it. 10103 if (!SuccMBB) { 10104 MachineFunction *MF = ParentMBB->getParent(); 10105 MachineFunction::iterator BBI(ParentMBB); 10106 SuccMBB = MF->CreateMachineBasicBlock(BB); 10107 MF->insert(++BBI, SuccMBB); 10108 } 10109 // Add it as a successor of ParentMBB. 10110 ParentMBB->addSuccessor( 10111 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10112 return SuccMBB; 10113 } 10114 10115 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10116 MachineFunction::iterator I(MBB); 10117 if (++I == FuncInfo.MF->end()) 10118 return nullptr; 10119 return &*I; 10120 } 10121 10122 /// During lowering new call nodes can be created (such as memset, etc.). 10123 /// Those will become new roots of the current DAG, but complications arise 10124 /// when they are tail calls. In such cases, the call lowering will update 10125 /// the root, but the builder still needs to know that a tail call has been 10126 /// lowered in order to avoid generating an additional return. 10127 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10128 // If the node is null, we do have a tail call. 10129 if (MaybeTC.getNode() != nullptr) 10130 DAG.setRoot(MaybeTC); 10131 else 10132 HasTailCall = true; 10133 } 10134 10135 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10136 MachineBasicBlock *SwitchMBB, 10137 MachineBasicBlock *DefaultMBB) { 10138 MachineFunction *CurMF = FuncInfo.MF; 10139 MachineBasicBlock *NextMBB = nullptr; 10140 MachineFunction::iterator BBI(W.MBB); 10141 if (++BBI != FuncInfo.MF->end()) 10142 NextMBB = &*BBI; 10143 10144 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10145 10146 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10147 10148 if (Size == 2 && W.MBB == SwitchMBB) { 10149 // If any two of the cases has the same destination, and if one value 10150 // is the same as the other, but has one bit unset that the other has set, 10151 // use bit manipulation to do two compares at once. For example: 10152 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10153 // TODO: This could be extended to merge any 2 cases in switches with 3 10154 // cases. 10155 // TODO: Handle cases where W.CaseBB != SwitchBB. 10156 CaseCluster &Small = *W.FirstCluster; 10157 CaseCluster &Big = *W.LastCluster; 10158 10159 if (Small.Low == Small.High && Big.Low == Big.High && 10160 Small.MBB == Big.MBB) { 10161 const APInt &SmallValue = Small.Low->getValue(); 10162 const APInt &BigValue = Big.Low->getValue(); 10163 10164 // Check that there is only one bit different. 10165 APInt CommonBit = BigValue ^ SmallValue; 10166 if (CommonBit.isPowerOf2()) { 10167 SDValue CondLHS = getValue(Cond); 10168 EVT VT = CondLHS.getValueType(); 10169 SDLoc DL = getCurSDLoc(); 10170 10171 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10172 DAG.getConstant(CommonBit, DL, VT)); 10173 SDValue Cond = DAG.getSetCC( 10174 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10175 ISD::SETEQ); 10176 10177 // Update successor info. 10178 // Both Small and Big will jump to Small.BB, so we sum up the 10179 // probabilities. 10180 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10181 if (BPI) 10182 addSuccessorWithProb( 10183 SwitchMBB, DefaultMBB, 10184 // The default destination is the first successor in IR. 10185 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10186 else 10187 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10188 10189 // Insert the true branch. 10190 SDValue BrCond = 10191 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10192 DAG.getBasicBlock(Small.MBB)); 10193 // Insert the false branch. 10194 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10195 DAG.getBasicBlock(DefaultMBB)); 10196 10197 DAG.setRoot(BrCond); 10198 return; 10199 } 10200 } 10201 } 10202 10203 if (TM.getOptLevel() != CodeGenOpt::None) { 10204 // Here, we order cases by probability so the most likely case will be 10205 // checked first. However, two clusters can have the same probability in 10206 // which case their relative ordering is non-deterministic. So we use Low 10207 // as a tie-breaker as clusters are guaranteed to never overlap. 10208 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10209 [](const CaseCluster &a, const CaseCluster &b) { 10210 return a.Prob != b.Prob ? 10211 a.Prob > b.Prob : 10212 a.Low->getValue().slt(b.Low->getValue()); 10213 }); 10214 10215 // Rearrange the case blocks so that the last one falls through if possible 10216 // without changing the order of probabilities. 10217 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10218 --I; 10219 if (I->Prob > W.LastCluster->Prob) 10220 break; 10221 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10222 std::swap(*I, *W.LastCluster); 10223 break; 10224 } 10225 } 10226 } 10227 10228 // Compute total probability. 10229 BranchProbability DefaultProb = W.DefaultProb; 10230 BranchProbability UnhandledProbs = DefaultProb; 10231 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10232 UnhandledProbs += I->Prob; 10233 10234 MachineBasicBlock *CurMBB = W.MBB; 10235 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10236 bool FallthroughUnreachable = false; 10237 MachineBasicBlock *Fallthrough; 10238 if (I == W.LastCluster) { 10239 // For the last cluster, fall through to the default destination. 10240 Fallthrough = DefaultMBB; 10241 FallthroughUnreachable = isa<UnreachableInst>( 10242 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10243 } else { 10244 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10245 CurMF->insert(BBI, Fallthrough); 10246 // Put Cond in a virtual register to make it available from the new blocks. 10247 ExportFromCurrentBlock(Cond); 10248 } 10249 UnhandledProbs -= I->Prob; 10250 10251 switch (I->Kind) { 10252 case CC_JumpTable: { 10253 // FIXME: Optimize away range check based on pivot comparisons. 10254 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10255 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10256 10257 // The jump block hasn't been inserted yet; insert it here. 10258 MachineBasicBlock *JumpMBB = JT->MBB; 10259 CurMF->insert(BBI, JumpMBB); 10260 10261 auto JumpProb = I->Prob; 10262 auto FallthroughProb = UnhandledProbs; 10263 10264 // If the default statement is a target of the jump table, we evenly 10265 // distribute the default probability to successors of CurMBB. Also 10266 // update the probability on the edge from JumpMBB to Fallthrough. 10267 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10268 SE = JumpMBB->succ_end(); 10269 SI != SE; ++SI) { 10270 if (*SI == DefaultMBB) { 10271 JumpProb += DefaultProb / 2; 10272 FallthroughProb -= DefaultProb / 2; 10273 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10274 JumpMBB->normalizeSuccProbs(); 10275 break; 10276 } 10277 } 10278 10279 if (FallthroughUnreachable) { 10280 // Skip the range check if the fallthrough block is unreachable. 10281 JTH->OmitRangeCheck = true; 10282 } 10283 10284 if (!JTH->OmitRangeCheck) 10285 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10286 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10287 CurMBB->normalizeSuccProbs(); 10288 10289 // The jump table header will be inserted in our current block, do the 10290 // range check, and fall through to our fallthrough block. 10291 JTH->HeaderBB = CurMBB; 10292 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10293 10294 // If we're in the right place, emit the jump table header right now. 10295 if (CurMBB == SwitchMBB) { 10296 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10297 JTH->Emitted = true; 10298 } 10299 break; 10300 } 10301 case CC_BitTests: { 10302 // FIXME: Optimize away range check based on pivot comparisons. 10303 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10304 10305 // The bit test blocks haven't been inserted yet; insert them here. 10306 for (BitTestCase &BTC : BTB->Cases) 10307 CurMF->insert(BBI, BTC.ThisBB); 10308 10309 // Fill in fields of the BitTestBlock. 10310 BTB->Parent = CurMBB; 10311 BTB->Default = Fallthrough; 10312 10313 BTB->DefaultProb = UnhandledProbs; 10314 // If the cases in bit test don't form a contiguous range, we evenly 10315 // distribute the probability on the edge to Fallthrough to two 10316 // successors of CurMBB. 10317 if (!BTB->ContiguousRange) { 10318 BTB->Prob += DefaultProb / 2; 10319 BTB->DefaultProb -= DefaultProb / 2; 10320 } 10321 10322 if (FallthroughUnreachable) { 10323 // Skip the range check if the fallthrough block is unreachable. 10324 BTB->OmitRangeCheck = true; 10325 } 10326 10327 // If we're in the right place, emit the bit test header right now. 10328 if (CurMBB == SwitchMBB) { 10329 visitBitTestHeader(*BTB, SwitchMBB); 10330 BTB->Emitted = true; 10331 } 10332 break; 10333 } 10334 case CC_Range: { 10335 const Value *RHS, *LHS, *MHS; 10336 ISD::CondCode CC; 10337 if (I->Low == I->High) { 10338 // Check Cond == I->Low. 10339 CC = ISD::SETEQ; 10340 LHS = Cond; 10341 RHS=I->Low; 10342 MHS = nullptr; 10343 } else { 10344 // Check I->Low <= Cond <= I->High. 10345 CC = ISD::SETLE; 10346 LHS = I->Low; 10347 MHS = Cond; 10348 RHS = I->High; 10349 } 10350 10351 // If Fallthrough is unreachable, fold away the comparison. 10352 if (FallthroughUnreachable) 10353 CC = ISD::SETTRUE; 10354 10355 // The false probability is the sum of all unhandled cases. 10356 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10357 getCurSDLoc(), I->Prob, UnhandledProbs); 10358 10359 if (CurMBB == SwitchMBB) 10360 visitSwitchCase(CB, SwitchMBB); 10361 else 10362 SL->SwitchCases.push_back(CB); 10363 10364 break; 10365 } 10366 } 10367 CurMBB = Fallthrough; 10368 } 10369 } 10370 10371 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10372 CaseClusterIt First, 10373 CaseClusterIt Last) { 10374 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10375 if (X.Prob != CC.Prob) 10376 return X.Prob > CC.Prob; 10377 10378 // Ties are broken by comparing the case value. 10379 return X.Low->getValue().slt(CC.Low->getValue()); 10380 }); 10381 } 10382 10383 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10384 const SwitchWorkListItem &W, 10385 Value *Cond, 10386 MachineBasicBlock *SwitchMBB) { 10387 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10388 "Clusters not sorted?"); 10389 10390 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10391 10392 // Balance the tree based on branch probabilities to create a near-optimal (in 10393 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10394 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10395 CaseClusterIt LastLeft = W.FirstCluster; 10396 CaseClusterIt FirstRight = W.LastCluster; 10397 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10398 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10399 10400 // Move LastLeft and FirstRight towards each other from opposite directions to 10401 // find a partitioning of the clusters which balances the probability on both 10402 // sides. If LeftProb and RightProb are equal, alternate which side is 10403 // taken to ensure 0-probability nodes are distributed evenly. 10404 unsigned I = 0; 10405 while (LastLeft + 1 < FirstRight) { 10406 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10407 LeftProb += (++LastLeft)->Prob; 10408 else 10409 RightProb += (--FirstRight)->Prob; 10410 I++; 10411 } 10412 10413 while (true) { 10414 // Our binary search tree differs from a typical BST in that ours can have up 10415 // to three values in each leaf. The pivot selection above doesn't take that 10416 // into account, which means the tree might require more nodes and be less 10417 // efficient. We compensate for this here. 10418 10419 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10420 unsigned NumRight = W.LastCluster - FirstRight + 1; 10421 10422 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10423 // If one side has less than 3 clusters, and the other has more than 3, 10424 // consider taking a cluster from the other side. 10425 10426 if (NumLeft < NumRight) { 10427 // Consider moving the first cluster on the right to the left side. 10428 CaseCluster &CC = *FirstRight; 10429 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10430 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10431 if (LeftSideRank <= RightSideRank) { 10432 // Moving the cluster to the left does not demote it. 10433 ++LastLeft; 10434 ++FirstRight; 10435 continue; 10436 } 10437 } else { 10438 assert(NumRight < NumLeft); 10439 // Consider moving the last element on the left to the right side. 10440 CaseCluster &CC = *LastLeft; 10441 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10442 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10443 if (RightSideRank <= LeftSideRank) { 10444 // Moving the cluster to the right does not demot it. 10445 --LastLeft; 10446 --FirstRight; 10447 continue; 10448 } 10449 } 10450 } 10451 break; 10452 } 10453 10454 assert(LastLeft + 1 == FirstRight); 10455 assert(LastLeft >= W.FirstCluster); 10456 assert(FirstRight <= W.LastCluster); 10457 10458 // Use the first element on the right as pivot since we will make less-than 10459 // comparisons against it. 10460 CaseClusterIt PivotCluster = FirstRight; 10461 assert(PivotCluster > W.FirstCluster); 10462 assert(PivotCluster <= W.LastCluster); 10463 10464 CaseClusterIt FirstLeft = W.FirstCluster; 10465 CaseClusterIt LastRight = W.LastCluster; 10466 10467 const ConstantInt *Pivot = PivotCluster->Low; 10468 10469 // New blocks will be inserted immediately after the current one. 10470 MachineFunction::iterator BBI(W.MBB); 10471 ++BBI; 10472 10473 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10474 // we can branch to its destination directly if it's squeezed exactly in 10475 // between the known lower bound and Pivot - 1. 10476 MachineBasicBlock *LeftMBB; 10477 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10478 FirstLeft->Low == W.GE && 10479 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10480 LeftMBB = FirstLeft->MBB; 10481 } else { 10482 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10483 FuncInfo.MF->insert(BBI, LeftMBB); 10484 WorkList.push_back( 10485 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10486 // Put Cond in a virtual register to make it available from the new blocks. 10487 ExportFromCurrentBlock(Cond); 10488 } 10489 10490 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10491 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10492 // directly if RHS.High equals the current upper bound. 10493 MachineBasicBlock *RightMBB; 10494 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10495 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10496 RightMBB = FirstRight->MBB; 10497 } else { 10498 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10499 FuncInfo.MF->insert(BBI, RightMBB); 10500 WorkList.push_back( 10501 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10502 // Put Cond in a virtual register to make it available from the new blocks. 10503 ExportFromCurrentBlock(Cond); 10504 } 10505 10506 // Create the CaseBlock record that will be used to lower the branch. 10507 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10508 getCurSDLoc(), LeftProb, RightProb); 10509 10510 if (W.MBB == SwitchMBB) 10511 visitSwitchCase(CB, SwitchMBB); 10512 else 10513 SL->SwitchCases.push_back(CB); 10514 } 10515 10516 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10517 // from the swith statement. 10518 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10519 BranchProbability PeeledCaseProb) { 10520 if (PeeledCaseProb == BranchProbability::getOne()) 10521 return BranchProbability::getZero(); 10522 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10523 10524 uint32_t Numerator = CaseProb.getNumerator(); 10525 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10526 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10527 } 10528 10529 // Try to peel the top probability case if it exceeds the threshold. 10530 // Return current MachineBasicBlock for the switch statement if the peeling 10531 // does not occur. 10532 // If the peeling is performed, return the newly created MachineBasicBlock 10533 // for the peeled switch statement. Also update Clusters to remove the peeled 10534 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10535 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10536 const SwitchInst &SI, CaseClusterVector &Clusters, 10537 BranchProbability &PeeledCaseProb) { 10538 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10539 // Don't perform if there is only one cluster or optimizing for size. 10540 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10541 TM.getOptLevel() == CodeGenOpt::None || 10542 SwitchMBB->getParent()->getFunction().hasMinSize()) 10543 return SwitchMBB; 10544 10545 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10546 unsigned PeeledCaseIndex = 0; 10547 bool SwitchPeeled = false; 10548 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10549 CaseCluster &CC = Clusters[Index]; 10550 if (CC.Prob < TopCaseProb) 10551 continue; 10552 TopCaseProb = CC.Prob; 10553 PeeledCaseIndex = Index; 10554 SwitchPeeled = true; 10555 } 10556 if (!SwitchPeeled) 10557 return SwitchMBB; 10558 10559 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10560 << TopCaseProb << "\n"); 10561 10562 // Record the MBB for the peeled switch statement. 10563 MachineFunction::iterator BBI(SwitchMBB); 10564 ++BBI; 10565 MachineBasicBlock *PeeledSwitchMBB = 10566 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10567 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10568 10569 ExportFromCurrentBlock(SI.getCondition()); 10570 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10571 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10572 nullptr, nullptr, TopCaseProb.getCompl()}; 10573 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10574 10575 Clusters.erase(PeeledCaseIt); 10576 for (CaseCluster &CC : Clusters) { 10577 LLVM_DEBUG( 10578 dbgs() << "Scale the probablity for one cluster, before scaling: " 10579 << CC.Prob << "\n"); 10580 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10581 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10582 } 10583 PeeledCaseProb = TopCaseProb; 10584 return PeeledSwitchMBB; 10585 } 10586 10587 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10588 // Extract cases from the switch. 10589 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10590 CaseClusterVector Clusters; 10591 Clusters.reserve(SI.getNumCases()); 10592 for (auto I : SI.cases()) { 10593 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10594 const ConstantInt *CaseVal = I.getCaseValue(); 10595 BranchProbability Prob = 10596 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10597 : BranchProbability(1, SI.getNumCases() + 1); 10598 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10599 } 10600 10601 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10602 10603 // Cluster adjacent cases with the same destination. We do this at all 10604 // optimization levels because it's cheap to do and will make codegen faster 10605 // if there are many clusters. 10606 sortAndRangeify(Clusters); 10607 10608 // The branch probablity of the peeled case. 10609 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10610 MachineBasicBlock *PeeledSwitchMBB = 10611 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10612 10613 // If there is only the default destination, jump there directly. 10614 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10615 if (Clusters.empty()) { 10616 assert(PeeledSwitchMBB == SwitchMBB); 10617 SwitchMBB->addSuccessor(DefaultMBB); 10618 if (DefaultMBB != NextBlock(SwitchMBB)) { 10619 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10620 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10621 } 10622 return; 10623 } 10624 10625 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10626 SL->findBitTestClusters(Clusters, &SI); 10627 10628 LLVM_DEBUG({ 10629 dbgs() << "Case clusters: "; 10630 for (const CaseCluster &C : Clusters) { 10631 if (C.Kind == CC_JumpTable) 10632 dbgs() << "JT:"; 10633 if (C.Kind == CC_BitTests) 10634 dbgs() << "BT:"; 10635 10636 C.Low->getValue().print(dbgs(), true); 10637 if (C.Low != C.High) { 10638 dbgs() << '-'; 10639 C.High->getValue().print(dbgs(), true); 10640 } 10641 dbgs() << ' '; 10642 } 10643 dbgs() << '\n'; 10644 }); 10645 10646 assert(!Clusters.empty()); 10647 SwitchWorkList WorkList; 10648 CaseClusterIt First = Clusters.begin(); 10649 CaseClusterIt Last = Clusters.end() - 1; 10650 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10651 // Scale the branchprobability for DefaultMBB if the peel occurs and 10652 // DefaultMBB is not replaced. 10653 if (PeeledCaseProb != BranchProbability::getZero() && 10654 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10655 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10656 WorkList.push_back( 10657 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10658 10659 while (!WorkList.empty()) { 10660 SwitchWorkListItem W = WorkList.back(); 10661 WorkList.pop_back(); 10662 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10663 10664 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10665 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10666 // For optimized builds, lower large range as a balanced binary tree. 10667 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10668 continue; 10669 } 10670 10671 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10672 } 10673 } 10674 10675 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10676 SmallVector<EVT, 4> ValueVTs; 10677 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10678 ValueVTs); 10679 unsigned NumValues = ValueVTs.size(); 10680 if (NumValues == 0) return; 10681 10682 SmallVector<SDValue, 4> Values(NumValues); 10683 SDValue Op = getValue(I.getOperand(0)); 10684 10685 for (unsigned i = 0; i != NumValues; ++i) 10686 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10687 SDValue(Op.getNode(), Op.getResNo() + i)); 10688 10689 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10690 DAG.getVTList(ValueVTs), Values)); 10691 } 10692