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 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 155 const SDValue *Parts, unsigned NumParts, 156 MVT PartVT, EVT ValueVT, const Value *V, 157 Optional<CallingConv::ID> CC); 158 159 /// getCopyFromParts - Create a value that contains the specified legal parts 160 /// combined into the value they represent. If the parts combine to a type 161 /// larger than ValueVT then AssertOp can be used to specify whether the extra 162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 163 /// (ISD::AssertSext). 164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 165 const SDValue *Parts, unsigned NumParts, 166 MVT PartVT, EVT ValueVT, const Value *V, 167 Optional<CallingConv::ID> CC = None, 168 Optional<ISD::NodeType> AssertOp = None) { 169 // Let the target assemble the parts if it wants to 170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 171 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts, 172 PartVT, ValueVT, CC)) 173 return Val; 174 175 if (ValueVT.isVector()) 176 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 177 CC); 178 179 assert(NumParts > 0 && "No parts to assemble!"); 180 SDValue Val = Parts[0]; 181 182 if (NumParts > 1) { 183 // Assemble the value from multiple parts. 184 if (ValueVT.isInteger()) { 185 unsigned PartBits = PartVT.getSizeInBits(); 186 unsigned ValueBits = ValueVT.getSizeInBits(); 187 188 // Assemble the power of 2 part. 189 unsigned RoundParts = 190 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 191 unsigned RoundBits = PartBits * RoundParts; 192 EVT RoundVT = RoundBits == ValueBits ? 193 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 194 SDValue Lo, Hi; 195 196 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 197 198 if (RoundParts > 2) { 199 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 200 PartVT, HalfVT, V); 201 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 202 RoundParts / 2, PartVT, HalfVT, V); 203 } else { 204 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 205 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 206 } 207 208 if (DAG.getDataLayout().isBigEndian()) 209 std::swap(Lo, Hi); 210 211 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 212 213 if (RoundParts < NumParts) { 214 // Assemble the trailing non-power-of-2 part. 215 unsigned OddParts = NumParts - RoundParts; 216 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 217 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 218 OddVT, V, CC); 219 220 // Combine the round and odd parts. 221 Lo = Val; 222 if (DAG.getDataLayout().isBigEndian()) 223 std::swap(Lo, Hi); 224 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 225 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 226 Hi = 227 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 228 DAG.getConstant(Lo.getValueSizeInBits(), DL, 229 TLI.getPointerTy(DAG.getDataLayout()))); 230 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 231 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 232 } 233 } else if (PartVT.isFloatingPoint()) { 234 // FP split into multiple FP parts (for ppcf128) 235 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 236 "Unexpected split"); 237 SDValue Lo, Hi; 238 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 239 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 240 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 241 std::swap(Lo, Hi); 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 243 } else { 244 // FP split into integer parts (soft fp) 245 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 246 !PartVT.isVector() && "Unexpected split"); 247 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 248 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 249 } 250 } 251 252 // There is now one part, held in Val. Correct it to match ValueVT. 253 // PartEVT is the type of the register class that holds the value. 254 // ValueVT is the type of the inline asm operation. 255 EVT PartEVT = Val.getValueType(); 256 257 if (PartEVT == ValueVT) 258 return Val; 259 260 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 261 ValueVT.bitsLT(PartEVT)) { 262 // For an FP value in an integer part, we need to truncate to the right 263 // width first. 264 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 265 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 266 } 267 268 // Handle types that have the same size. 269 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 270 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 271 272 // Handle types with different sizes. 273 if (PartEVT.isInteger() && ValueVT.isInteger()) { 274 if (ValueVT.bitsLT(PartEVT)) { 275 // For a truncate, see if we have any information to 276 // indicate whether the truncated bits will always be 277 // zero or sign-extension. 278 if (AssertOp.hasValue()) 279 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 280 DAG.getValueType(ValueVT)); 281 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 282 } 283 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 284 } 285 286 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 287 // FP_ROUND's are always exact here. 288 if (ValueVT.bitsLT(Val.getValueType())) 289 return DAG.getNode( 290 ISD::FP_ROUND, DL, ValueVT, Val, 291 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 292 293 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 294 } 295 296 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 297 // then truncating. 298 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 299 ValueVT.bitsLT(PartEVT)) { 300 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 301 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 302 } 303 304 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 305 } 306 307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 308 const Twine &ErrMsg) { 309 const Instruction *I = dyn_cast_or_null<Instruction>(V); 310 if (!V) 311 return Ctx.emitError(ErrMsg); 312 313 const char *AsmError = ", possible invalid constraint for vector type"; 314 if (const CallInst *CI = dyn_cast<CallInst>(I)) 315 if (CI->isInlineAsm()) 316 return Ctx.emitError(I, ErrMsg + AsmError); 317 318 return Ctx.emitError(I, ErrMsg); 319 } 320 321 /// getCopyFromPartsVector - Create a value that contains the specified legal 322 /// parts combined into the value they represent. If the parts combine to a 323 /// type larger than ValueVT then AssertOp can be used to specify whether the 324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 325 /// ValueVT (ISD::AssertSext). 326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 327 const SDValue *Parts, unsigned NumParts, 328 MVT PartVT, EVT ValueVT, const Value *V, 329 Optional<CallingConv::ID> CallConv) { 330 assert(ValueVT.isVector() && "Not a vector value"); 331 assert(NumParts > 0 && "No parts to assemble!"); 332 const bool IsABIRegCopy = CallConv.hasValue(); 333 334 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 335 SDValue Val = Parts[0]; 336 337 // Handle a multi-element vector. 338 if (NumParts > 1) { 339 EVT IntermediateVT; 340 MVT RegisterVT; 341 unsigned NumIntermediates; 342 unsigned NumRegs; 343 344 if (IsABIRegCopy) { 345 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 346 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 347 NumIntermediates, RegisterVT); 348 } else { 349 NumRegs = 350 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 351 NumIntermediates, RegisterVT); 352 } 353 354 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 355 NumParts = NumRegs; // Silence a compiler warning. 356 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 357 assert(RegisterVT.getSizeInBits() == 358 Parts[0].getSimpleValueType().getSizeInBits() && 359 "Part type sizes don't match!"); 360 361 // Assemble the parts into intermediate operands. 362 SmallVector<SDValue, 8> Ops(NumIntermediates); 363 if (NumIntermediates == NumParts) { 364 // If the register was not expanded, truncate or copy the value, 365 // as appropriate. 366 for (unsigned i = 0; i != NumParts; ++i) 367 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 368 PartVT, IntermediateVT, V, CallConv); 369 } else if (NumParts > 0) { 370 // If the intermediate type was expanded, build the intermediate 371 // operands from the parts. 372 assert(NumParts % NumIntermediates == 0 && 373 "Must expand into a divisible number of parts!"); 374 unsigned Factor = NumParts / NumIntermediates; 375 for (unsigned i = 0; i != NumIntermediates; ++i) 376 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 377 PartVT, IntermediateVT, V, CallConv); 378 } 379 380 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 381 // intermediate operands. 382 EVT BuiltVectorTy = 383 IntermediateVT.isVector() 384 ? EVT::getVectorVT( 385 *DAG.getContext(), IntermediateVT.getScalarType(), 386 IntermediateVT.getVectorElementCount() * NumParts) 387 : EVT::getVectorVT(*DAG.getContext(), 388 IntermediateVT.getScalarType(), 389 NumIntermediates); 390 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 391 : ISD::BUILD_VECTOR, 392 DL, BuiltVectorTy, Ops); 393 } 394 395 // There is now one part, held in Val. Correct it to match ValueVT. 396 EVT PartEVT = Val.getValueType(); 397 398 if (PartEVT == ValueVT) 399 return Val; 400 401 if (PartEVT.isVector()) { 402 // If the element type of the source/dest vectors are the same, but the 403 // parts vector has more elements than the value vector, then we have a 404 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 405 // elements we want. 406 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 407 assert((PartEVT.getVectorElementCount().getKnownMinValue() > 408 ValueVT.getVectorElementCount().getKnownMinValue()) && 409 (PartEVT.getVectorElementCount().isScalable() == 410 ValueVT.getVectorElementCount().isScalable()) && 411 "Cannot narrow, it would be a lossy transformation"); 412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 413 DAG.getVectorIdxConstant(0, DL)); 414 } 415 416 // Vector/Vector bitcast. 417 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 419 420 assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() && 421 "Cannot handle this kind of promotion"); 422 // Promoted vector extract 423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 424 425 } 426 427 // Trivial bitcast if the types are the same size and the destination 428 // vector type is legal. 429 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 430 TLI.isTypeLegal(ValueVT)) 431 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 432 433 if (ValueVT.getVectorNumElements() != 1) { 434 // Certain ABIs require that vectors are passed as integers. For vectors 435 // are the same size, this is an obvious bitcast. 436 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 } else if (ValueVT.bitsLT(PartEVT)) { 439 // Bitcast Val back the original type and extract the corresponding 440 // vector we want. 441 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 442 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 443 ValueVT.getVectorElementType(), Elts); 444 Val = DAG.getBitcast(WiderVecType, Val); 445 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 446 DAG.getVectorIdxConstant(0, DL)); 447 } 448 449 diagnosePossiblyInvalidConstraint( 450 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 451 return DAG.getUNDEF(ValueVT); 452 } 453 454 // Handle cases such as i8 -> <1 x i1> 455 EVT ValueSVT = ValueVT.getVectorElementType(); 456 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) { 457 if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits()) 458 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val); 459 else 460 Val = ValueVT.isFloatingPoint() 461 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 462 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 463 } 464 465 return DAG.getBuildVector(ValueVT, DL, Val); 466 } 467 468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 469 SDValue Val, SDValue *Parts, unsigned NumParts, 470 MVT PartVT, const Value *V, 471 Optional<CallingConv::ID> CallConv); 472 473 /// getCopyToParts - Create a series of nodes that contain the specified value 474 /// split into legal parts. If the parts contain more bits than Val, then, for 475 /// integers, ExtendKind can be used to specify how to generate the extra bits. 476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 477 SDValue *Parts, unsigned NumParts, MVT PartVT, 478 const Value *V, 479 Optional<CallingConv::ID> CallConv = None, 480 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 481 // Let the target split the parts if it wants to 482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 483 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT, 484 CallConv)) 485 return; 486 EVT ValueVT = Val.getValueType(); 487 488 // Handle the vector case separately. 489 if (ValueVT.isVector()) 490 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 491 CallConv); 492 493 unsigned PartBits = PartVT.getSizeInBits(); 494 unsigned OrigNumParts = NumParts; 495 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 496 "Copying to an illegal type!"); 497 498 if (NumParts == 0) 499 return; 500 501 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 502 EVT PartEVT = PartVT; 503 if (PartEVT == ValueVT) { 504 assert(NumParts == 1 && "No-op copy with multiple parts!"); 505 Parts[0] = Val; 506 return; 507 } 508 509 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 510 // If the parts cover more bits than the value has, promote the value. 511 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 512 assert(NumParts == 1 && "Do not know what to promote to!"); 513 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 514 } else { 515 if (ValueVT.isFloatingPoint()) { 516 // FP values need to be bitcast, then extended if they are being put 517 // into a larger container. 518 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 519 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 520 } 521 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 522 ValueVT.isInteger() && 523 "Unknown mismatch!"); 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 525 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 526 if (PartVT == MVT::x86mmx) 527 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 528 } 529 } else if (PartBits == ValueVT.getSizeInBits()) { 530 // Different types of the same size. 531 assert(NumParts == 1 && PartEVT != ValueVT); 532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 533 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 534 // If the parts cover less bits than value has, truncate the value. 535 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 536 ValueVT.isInteger() && 537 "Unknown mismatch!"); 538 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 539 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 540 if (PartVT == MVT::x86mmx) 541 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 542 } 543 544 // The value may have changed - recompute ValueVT. 545 ValueVT = Val.getValueType(); 546 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 547 "Failed to tile the value with PartVT!"); 548 549 if (NumParts == 1) { 550 if (PartEVT != ValueVT) { 551 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 552 "scalar-to-vector conversion failed"); 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } 555 556 Parts[0] = Val; 557 return; 558 } 559 560 // Expand the value into multiple parts. 561 if (NumParts & (NumParts - 1)) { 562 // The number of parts is not a power of 2. Split off and copy the tail. 563 assert(PartVT.isInteger() && ValueVT.isInteger() && 564 "Do not know what to expand to!"); 565 unsigned RoundParts = 1 << Log2_32(NumParts); 566 unsigned RoundBits = RoundParts * PartBits; 567 unsigned OddParts = NumParts - RoundParts; 568 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 569 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 570 571 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 572 CallConv); 573 574 if (DAG.getDataLayout().isBigEndian()) 575 // The odd parts were reversed by getCopyToParts - unreverse them. 576 std::reverse(Parts + RoundParts, Parts + NumParts); 577 578 NumParts = RoundParts; 579 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 580 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 581 } 582 583 // The number of parts is a power of 2. Repeatedly bisect the value using 584 // EXTRACT_ELEMENT. 585 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 586 EVT::getIntegerVT(*DAG.getContext(), 587 ValueVT.getSizeInBits()), 588 Val); 589 590 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 591 for (unsigned i = 0; i < NumParts; i += StepSize) { 592 unsigned ThisBits = StepSize * PartBits / 2; 593 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 594 SDValue &Part0 = Parts[i]; 595 SDValue &Part1 = Parts[i+StepSize/2]; 596 597 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 598 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 599 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 600 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 601 602 if (ThisBits == PartBits && ThisVT != PartVT) { 603 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 604 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 605 } 606 } 607 } 608 609 if (DAG.getDataLayout().isBigEndian()) 610 std::reverse(Parts, Parts + OrigNumParts); 611 } 612 613 static SDValue widenVectorToPartType(SelectionDAG &DAG, 614 SDValue Val, const SDLoc &DL, EVT PartVT) { 615 if (!PartVT.isFixedLengthVector()) 616 return SDValue(); 617 618 EVT ValueVT = Val.getValueType(); 619 unsigned PartNumElts = PartVT.getVectorNumElements(); 620 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 621 if (PartNumElts > ValueNumElts && 622 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 623 EVT ElementVT = PartVT.getVectorElementType(); 624 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 625 // undef elements. 626 SmallVector<SDValue, 16> Ops; 627 DAG.ExtractVectorElements(Val, Ops); 628 SDValue EltUndef = DAG.getUNDEF(ElementVT); 629 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 630 Ops.push_back(EltUndef); 631 632 // FIXME: Use CONCAT for 2x -> 4x. 633 return DAG.getBuildVector(PartVT, DL, Ops); 634 } 635 636 return SDValue(); 637 } 638 639 /// getCopyToPartsVector - Create a series of nodes that contain the specified 640 /// value split into legal parts. 641 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 642 SDValue Val, SDValue *Parts, unsigned NumParts, 643 MVT PartVT, const Value *V, 644 Optional<CallingConv::ID> CallConv) { 645 EVT ValueVT = Val.getValueType(); 646 assert(ValueVT.isVector() && "Not a vector"); 647 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 648 const bool IsABIRegCopy = CallConv.hasValue(); 649 650 if (NumParts == 1) { 651 EVT PartEVT = PartVT; 652 if (PartEVT == ValueVT) { 653 // Nothing to do. 654 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 655 // Bitconvert vector->vector case. 656 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 657 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 658 Val = Widened; 659 } else if (PartVT.isVector() && 660 PartEVT.getVectorElementType().bitsGE( 661 ValueVT.getVectorElementType()) && 662 PartEVT.getVectorElementCount() == 663 ValueVT.getVectorElementCount()) { 664 665 // Promoted vector extract 666 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 667 } else { 668 if (ValueVT.getVectorElementCount().isScalar()) { 669 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 670 DAG.getVectorIdxConstant(0, DL)); 671 } else { 672 uint64_t ValueSize = ValueVT.getFixedSizeInBits(); 673 assert(PartVT.getFixedSizeInBits() > ValueSize && 674 "lossy conversion of vector to scalar type"); 675 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize); 676 Val = DAG.getBitcast(IntermediateType, Val); 677 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 678 } 679 } 680 681 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 682 Parts[0] = Val; 683 return; 684 } 685 686 // Handle a multi-element vector. 687 EVT IntermediateVT; 688 MVT RegisterVT; 689 unsigned NumIntermediates; 690 unsigned NumRegs; 691 if (IsABIRegCopy) { 692 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 693 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 694 NumIntermediates, RegisterVT); 695 } else { 696 NumRegs = 697 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 698 NumIntermediates, RegisterVT); 699 } 700 701 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 702 NumParts = NumRegs; // Silence a compiler warning. 703 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 704 705 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && 706 "Mixing scalable and fixed vectors when copying in parts"); 707 708 Optional<ElementCount> DestEltCnt; 709 710 if (IntermediateVT.isVector()) 711 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates; 712 else 713 DestEltCnt = ElementCount::getFixed(NumIntermediates); 714 715 EVT BuiltVectorTy = EVT::getVectorVT( 716 *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue()); 717 if (ValueVT != BuiltVectorTy) { 718 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 719 Val = Widened; 720 721 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 722 } 723 724 // Split the vector into intermediate operands. 725 SmallVector<SDValue, 8> Ops(NumIntermediates); 726 for (unsigned i = 0; i != NumIntermediates; ++i) { 727 if (IntermediateVT.isVector()) { 728 // This does something sensible for scalable vectors - see the 729 // definition of EXTRACT_SUBVECTOR for further details. 730 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements(); 731 Ops[i] = 732 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 733 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL)); 734 } else { 735 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 736 DAG.getVectorIdxConstant(i, DL)); 737 } 738 } 739 740 // Split the intermediate operands into legal parts. 741 if (NumParts == NumIntermediates) { 742 // If the register was not expanded, promote or copy the value, 743 // as appropriate. 744 for (unsigned i = 0; i != NumParts; ++i) 745 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 746 } else if (NumParts > 0) { 747 // If the intermediate type was expanded, split each the value into 748 // legal parts. 749 assert(NumIntermediates != 0 && "division by zero"); 750 assert(NumParts % NumIntermediates == 0 && 751 "Must expand into a divisible number of parts!"); 752 unsigned Factor = NumParts / NumIntermediates; 753 for (unsigned i = 0; i != NumIntermediates; ++i) 754 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 755 CallConv); 756 } 757 } 758 759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 760 EVT valuevt, Optional<CallingConv::ID> CC) 761 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 762 RegCount(1, regs.size()), CallConv(CC) {} 763 764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 765 const DataLayout &DL, unsigned Reg, Type *Ty, 766 Optional<CallingConv::ID> CC) { 767 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 768 769 CallConv = CC; 770 771 for (EVT ValueVT : ValueVTs) { 772 unsigned NumRegs = 773 isABIMangled() 774 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 775 : TLI.getNumRegisters(Context, ValueVT); 776 MVT RegisterVT = 777 isABIMangled() 778 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 779 : TLI.getRegisterType(Context, ValueVT); 780 for (unsigned i = 0; i != NumRegs; ++i) 781 Regs.push_back(Reg + i); 782 RegVTs.push_back(RegisterVT); 783 RegCount.push_back(NumRegs); 784 Reg += NumRegs; 785 } 786 } 787 788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 789 FunctionLoweringInfo &FuncInfo, 790 const SDLoc &dl, SDValue &Chain, 791 SDValue *Flag, const Value *V) const { 792 // A Value with type {} or [0 x %t] needs no registers. 793 if (ValueVTs.empty()) 794 return SDValue(); 795 796 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 797 798 // Assemble the legal parts into the final values. 799 SmallVector<SDValue, 4> Values(ValueVTs.size()); 800 SmallVector<SDValue, 8> Parts; 801 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 802 // Copy the legal parts from the registers. 803 EVT ValueVT = ValueVTs[Value]; 804 unsigned NumRegs = RegCount[Value]; 805 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 806 *DAG.getContext(), 807 CallConv.getValue(), RegVTs[Value]) 808 : RegVTs[Value]; 809 810 Parts.resize(NumRegs); 811 for (unsigned i = 0; i != NumRegs; ++i) { 812 SDValue P; 813 if (!Flag) { 814 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 815 } else { 816 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 817 *Flag = P.getValue(2); 818 } 819 820 Chain = P.getValue(1); 821 Parts[i] = P; 822 823 // If the source register was virtual and if we know something about it, 824 // add an assert node. 825 if (!Register::isVirtualRegister(Regs[Part + i]) || 826 !RegisterVT.isInteger()) 827 continue; 828 829 const FunctionLoweringInfo::LiveOutInfo *LOI = 830 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 831 if (!LOI) 832 continue; 833 834 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 835 unsigned NumSignBits = LOI->NumSignBits; 836 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 837 838 if (NumZeroBits == RegSize) { 839 // The current value is a zero. 840 // Explicitly express that as it would be easier for 841 // optimizations to kick in. 842 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 843 continue; 844 } 845 846 // FIXME: We capture more information than the dag can represent. For 847 // now, just use the tightest assertzext/assertsext possible. 848 bool isSExt; 849 EVT FromVT(MVT::Other); 850 if (NumZeroBits) { 851 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 852 isSExt = false; 853 } else if (NumSignBits > 1) { 854 FromVT = 855 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 856 isSExt = true; 857 } else { 858 continue; 859 } 860 // Add an assertion node. 861 assert(FromVT != MVT::Other); 862 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 863 RegisterVT, P, DAG.getValueType(FromVT)); 864 } 865 866 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 867 RegisterVT, ValueVT, V, CallConv); 868 Part += NumRegs; 869 Parts.clear(); 870 } 871 872 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 873 } 874 875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 876 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 877 const Value *V, 878 ISD::NodeType PreferredExtendType) const { 879 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 880 ISD::NodeType ExtendKind = PreferredExtendType; 881 882 // Get the list of the values's legal parts. 883 unsigned NumRegs = Regs.size(); 884 SmallVector<SDValue, 8> Parts(NumRegs); 885 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 886 unsigned NumParts = RegCount[Value]; 887 888 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 889 *DAG.getContext(), 890 CallConv.getValue(), RegVTs[Value]) 891 : RegVTs[Value]; 892 893 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 894 ExtendKind = ISD::ZERO_EXTEND; 895 896 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 897 NumParts, RegisterVT, V, CallConv, ExtendKind); 898 Part += NumParts; 899 } 900 901 // Copy the parts into the registers. 902 SmallVector<SDValue, 8> Chains(NumRegs); 903 for (unsigned i = 0; i != NumRegs; ++i) { 904 SDValue Part; 905 if (!Flag) { 906 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 907 } else { 908 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 909 *Flag = Part.getValue(1); 910 } 911 912 Chains[i] = Part.getValue(0); 913 } 914 915 if (NumRegs == 1 || Flag) 916 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 917 // flagged to it. That is the CopyToReg nodes and the user are considered 918 // a single scheduling unit. If we create a TokenFactor and return it as 919 // chain, then the TokenFactor is both a predecessor (operand) of the 920 // user as well as a successor (the TF operands are flagged to the user). 921 // c1, f1 = CopyToReg 922 // c2, f2 = CopyToReg 923 // c3 = TokenFactor c1, c2 924 // ... 925 // = op c3, ..., f2 926 Chain = Chains[NumRegs-1]; 927 else 928 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 929 } 930 931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 932 unsigned MatchingIdx, const SDLoc &dl, 933 SelectionDAG &DAG, 934 std::vector<SDValue> &Ops) const { 935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 936 937 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 938 if (HasMatching) 939 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 940 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 941 // Put the register class of the virtual registers in the flag word. That 942 // way, later passes can recompute register class constraints for inline 943 // assembly as well as normal instructions. 944 // Don't do this for tied operands that can use the regclass information 945 // from the def. 946 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 947 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 948 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 949 } 950 951 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 952 Ops.push_back(Res); 953 954 if (Code == InlineAsm::Kind_Clobber) { 955 // Clobbers should always have a 1:1 mapping with registers, and may 956 // reference registers that have illegal (e.g. vector) types. Hence, we 957 // shouldn't try to apply any sort of splitting logic to them. 958 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 959 "No 1:1 mapping from clobbers to regs?"); 960 Register SP = TLI.getStackPointerRegisterToSaveRestore(); 961 (void)SP; 962 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 963 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 964 assert( 965 (Regs[I] != SP || 966 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 967 "If we clobbered the stack pointer, MFI should know about it."); 968 } 969 return; 970 } 971 972 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 973 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 974 MVT RegisterVT = RegVTs[Value]; 975 for (unsigned i = 0; i != NumRegs; ++i) { 976 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 977 unsigned TheReg = Regs[Reg++]; 978 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 979 } 980 } 981 } 982 983 SmallVector<std::pair<unsigned, unsigned>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 986 unsigned I = 0; 987 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 988 unsigned RegCount = std::get<0>(CountAndVT); 989 MVT RegisterVT = std::get<1>(CountAndVT); 990 unsigned RegisterSize = RegisterVT.getSizeInBits(); 991 for (unsigned E = I + RegCount; I != E; ++I) 992 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 993 } 994 return OutVec; 995 } 996 997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 998 const TargetLibraryInfo *li) { 999 AA = aa; 1000 GFI = gfi; 1001 LibInfo = li; 1002 DL = &DAG.getDataLayout(); 1003 Context = DAG.getContext(); 1004 LPadToCallSiteMap.clear(); 1005 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1006 } 1007 1008 void SelectionDAGBuilder::clear() { 1009 NodeMap.clear(); 1010 UnusedArgNodeMap.clear(); 1011 PendingLoads.clear(); 1012 PendingExports.clear(); 1013 PendingConstrainedFP.clear(); 1014 PendingConstrainedFPStrict.clear(); 1015 CurInst = nullptr; 1016 HasTailCall = false; 1017 SDNodeOrder = LowestSDNodeOrder; 1018 StatepointLowering.clear(); 1019 } 1020 1021 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1022 DanglingDebugInfoMap.clear(); 1023 } 1024 1025 // Update DAG root to include dependencies on Pending chains. 1026 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) { 1027 SDValue Root = DAG.getRoot(); 1028 1029 if (Pending.empty()) 1030 return Root; 1031 1032 // Add current root to PendingChains, unless we already indirectly 1033 // depend on it. 1034 if (Root.getOpcode() != ISD::EntryToken) { 1035 unsigned i = 0, e = Pending.size(); 1036 for (; i != e; ++i) { 1037 assert(Pending[i].getNode()->getNumOperands() > 1); 1038 if (Pending[i].getNode()->getOperand(0) == Root) 1039 break; // Don't add the root if we already indirectly depend on it. 1040 } 1041 1042 if (i == e) 1043 Pending.push_back(Root); 1044 } 1045 1046 if (Pending.size() == 1) 1047 Root = Pending[0]; 1048 else 1049 Root = DAG.getTokenFactor(getCurSDLoc(), Pending); 1050 1051 DAG.setRoot(Root); 1052 Pending.clear(); 1053 return Root; 1054 } 1055 1056 SDValue SelectionDAGBuilder::getMemoryRoot() { 1057 return updateRoot(PendingLoads); 1058 } 1059 1060 SDValue SelectionDAGBuilder::getRoot() { 1061 // Chain up all pending constrained intrinsics together with all 1062 // pending loads, by simply appending them to PendingLoads and 1063 // then calling getMemoryRoot(). 1064 PendingLoads.reserve(PendingLoads.size() + 1065 PendingConstrainedFP.size() + 1066 PendingConstrainedFPStrict.size()); 1067 PendingLoads.append(PendingConstrainedFP.begin(), 1068 PendingConstrainedFP.end()); 1069 PendingLoads.append(PendingConstrainedFPStrict.begin(), 1070 PendingConstrainedFPStrict.end()); 1071 PendingConstrainedFP.clear(); 1072 PendingConstrainedFPStrict.clear(); 1073 return getMemoryRoot(); 1074 } 1075 1076 SDValue SelectionDAGBuilder::getControlRoot() { 1077 // We need to emit pending fpexcept.strict constrained intrinsics, 1078 // so append them to the PendingExports list. 1079 PendingExports.append(PendingConstrainedFPStrict.begin(), 1080 PendingConstrainedFPStrict.end()); 1081 PendingConstrainedFPStrict.clear(); 1082 return updateRoot(PendingExports); 1083 } 1084 1085 void SelectionDAGBuilder::visit(const Instruction &I) { 1086 // Set up outgoing PHI node register values before emitting the terminator. 1087 if (I.isTerminator()) { 1088 HandlePHINodesInSuccessorBlocks(I.getParent()); 1089 } 1090 1091 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1092 if (!isa<DbgInfoIntrinsic>(I)) 1093 ++SDNodeOrder; 1094 1095 CurInst = &I; 1096 1097 visit(I.getOpcode(), I); 1098 1099 if (!I.isTerminator() && !HasTailCall && 1100 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally 1101 CopyToExportRegsIfNeeded(&I); 1102 1103 CurInst = nullptr; 1104 } 1105 1106 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1107 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1108 } 1109 1110 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1111 // Note: this doesn't use InstVisitor, because it has to work with 1112 // ConstantExpr's in addition to instructions. 1113 switch (Opcode) { 1114 default: llvm_unreachable("Unknown instruction type encountered!"); 1115 // Build the switch statement using the Instruction.def file. 1116 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1117 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1118 #include "llvm/IR/Instruction.def" 1119 } 1120 } 1121 1122 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1123 const DIExpression *Expr) { 1124 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1125 const DbgValueInst *DI = DDI.getDI(); 1126 DIVariable *DanglingVariable = DI->getVariable(); 1127 DIExpression *DanglingExpr = DI->getExpression(); 1128 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1129 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1130 return true; 1131 } 1132 return false; 1133 }; 1134 1135 for (auto &DDIMI : DanglingDebugInfoMap) { 1136 DanglingDebugInfoVector &DDIV = DDIMI.second; 1137 1138 // If debug info is to be dropped, run it through final checks to see 1139 // whether it can be salvaged. 1140 for (auto &DDI : DDIV) 1141 if (isMatchingDbgValue(DDI)) 1142 salvageUnresolvedDbgValue(DDI); 1143 1144 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1145 } 1146 } 1147 1148 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1149 // generate the debug data structures now that we've seen its definition. 1150 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1151 SDValue Val) { 1152 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1153 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1154 return; 1155 1156 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1157 for (auto &DDI : DDIV) { 1158 const DbgValueInst *DI = DDI.getDI(); 1159 assert(DI && "Ill-formed DanglingDebugInfo"); 1160 DebugLoc dl = DDI.getdl(); 1161 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1162 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1163 DILocalVariable *Variable = DI->getVariable(); 1164 DIExpression *Expr = DI->getExpression(); 1165 assert(Variable->isValidLocationForIntrinsic(dl) && 1166 "Expected inlined-at fields to agree"); 1167 SDDbgValue *SDV; 1168 if (Val.getNode()) { 1169 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1170 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1171 // we couldn't resolve it directly when examining the DbgValue intrinsic 1172 // in the first place we should not be more successful here). Unless we 1173 // have some test case that prove this to be correct we should avoid 1174 // calling EmitFuncArgumentDbgValue here. 1175 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1176 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1177 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1178 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1179 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1180 // inserted after the definition of Val when emitting the instructions 1181 // after ISel. An alternative could be to teach 1182 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1183 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1184 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1185 << ValSDNodeOrder << "\n"); 1186 SDV = getDbgValue(Val, Variable, Expr, dl, 1187 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1188 DAG.AddDbgValue(SDV, Val.getNode(), false); 1189 } else 1190 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1191 << "in EmitFuncArgumentDbgValue\n"); 1192 } else { 1193 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1194 auto Undef = 1195 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1196 auto SDV = 1197 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1198 DAG.AddDbgValue(SDV, nullptr, false); 1199 } 1200 } 1201 DDIV.clear(); 1202 } 1203 1204 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1205 Value *V = DDI.getDI()->getValue(); 1206 DILocalVariable *Var = DDI.getDI()->getVariable(); 1207 DIExpression *Expr = DDI.getDI()->getExpression(); 1208 DebugLoc DL = DDI.getdl(); 1209 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1210 unsigned SDOrder = DDI.getSDNodeOrder(); 1211 1212 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1213 // that DW_OP_stack_value is desired. 1214 assert(isa<DbgValueInst>(DDI.getDI())); 1215 bool StackValue = true; 1216 1217 // Can this Value can be encoded without any further work? 1218 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1219 return; 1220 1221 // Attempt to salvage back through as many instructions as possible. Bail if 1222 // a non-instruction is seen, such as a constant expression or global 1223 // variable. FIXME: Further work could recover those too. 1224 while (isa<Instruction>(V)) { 1225 Instruction &VAsInst = *cast<Instruction>(V); 1226 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1227 1228 // If we cannot salvage any further, and haven't yet found a suitable debug 1229 // expression, bail out. 1230 if (!NewExpr) 1231 break; 1232 1233 // New value and expr now represent this debuginfo. 1234 V = VAsInst.getOperand(0); 1235 Expr = NewExpr; 1236 1237 // Some kind of simplification occurred: check whether the operand of the 1238 // salvaged debug expression can be encoded in this DAG. 1239 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1240 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1241 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1242 return; 1243 } 1244 } 1245 1246 // This was the final opportunity to salvage this debug information, and it 1247 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1248 // any earlier variable location. 1249 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1250 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1251 DAG.AddDbgValue(SDV, nullptr, false); 1252 1253 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1254 << "\n"); 1255 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1256 << "\n"); 1257 } 1258 1259 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1260 DIExpression *Expr, DebugLoc dl, 1261 DebugLoc InstDL, unsigned Order) { 1262 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1263 SDDbgValue *SDV; 1264 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1265 isa<ConstantPointerNull>(V)) { 1266 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1267 DAG.AddDbgValue(SDV, nullptr, false); 1268 return true; 1269 } 1270 1271 // If the Value is a frame index, we can create a FrameIndex debug value 1272 // without relying on the DAG at all. 1273 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1274 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1275 if (SI != FuncInfo.StaticAllocaMap.end()) { 1276 auto SDV = 1277 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1278 /*IsIndirect*/ false, dl, SDNodeOrder); 1279 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1280 // is still available even if the SDNode gets optimized out. 1281 DAG.AddDbgValue(SDV, nullptr, false); 1282 return true; 1283 } 1284 } 1285 1286 // Do not use getValue() in here; we don't want to generate code at 1287 // this point if it hasn't been done yet. 1288 SDValue N = NodeMap[V]; 1289 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1290 N = UnusedArgNodeMap[V]; 1291 if (N.getNode()) { 1292 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1293 return true; 1294 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1295 DAG.AddDbgValue(SDV, N.getNode(), false); 1296 return true; 1297 } 1298 1299 // Special rules apply for the first dbg.values of parameter variables in a 1300 // function. Identify them by the fact they reference Argument Values, that 1301 // they're parameters, and they are parameters of the current function. We 1302 // need to let them dangle until they get an SDNode. 1303 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1304 !InstDL.getInlinedAt(); 1305 if (!IsParamOfFunc) { 1306 // The value is not used in this block yet (or it would have an SDNode). 1307 // We still want the value to appear for the user if possible -- if it has 1308 // an associated VReg, we can refer to that instead. 1309 auto VMI = FuncInfo.ValueMap.find(V); 1310 if (VMI != FuncInfo.ValueMap.end()) { 1311 unsigned Reg = VMI->second; 1312 // If this is a PHI node, it may be split up into several MI PHI nodes 1313 // (in FunctionLoweringInfo::set). 1314 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1315 V->getType(), None); 1316 if (RFV.occupiesMultipleRegs()) { 1317 unsigned Offset = 0; 1318 unsigned BitsToDescribe = 0; 1319 if (auto VarSize = Var->getSizeInBits()) 1320 BitsToDescribe = *VarSize; 1321 if (auto Fragment = Expr->getFragmentInfo()) 1322 BitsToDescribe = Fragment->SizeInBits; 1323 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1324 unsigned RegisterSize = RegAndSize.second; 1325 // Bail out if all bits are described already. 1326 if (Offset >= BitsToDescribe) 1327 break; 1328 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1329 ? BitsToDescribe - Offset 1330 : RegisterSize; 1331 auto FragmentExpr = DIExpression::createFragmentExpression( 1332 Expr, Offset, FragmentSize); 1333 if (!FragmentExpr) 1334 continue; 1335 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1336 false, dl, SDNodeOrder); 1337 DAG.AddDbgValue(SDV, nullptr, false); 1338 Offset += RegisterSize; 1339 } 1340 } else { 1341 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1342 DAG.AddDbgValue(SDV, nullptr, false); 1343 } 1344 return true; 1345 } 1346 } 1347 1348 return false; 1349 } 1350 1351 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1352 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1353 for (auto &Pair : DanglingDebugInfoMap) 1354 for (auto &DDI : Pair.second) 1355 salvageUnresolvedDbgValue(DDI); 1356 clearDanglingDebugInfo(); 1357 } 1358 1359 /// getCopyFromRegs - If there was virtual register allocated for the value V 1360 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1361 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1362 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1363 SDValue Result; 1364 1365 if (It != FuncInfo.ValueMap.end()) { 1366 Register InReg = It->second; 1367 1368 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1369 DAG.getDataLayout(), InReg, Ty, 1370 None); // This is not an ABI copy. 1371 SDValue Chain = DAG.getEntryNode(); 1372 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1373 V); 1374 resolveDanglingDebugInfo(V, Result); 1375 } 1376 1377 return Result; 1378 } 1379 1380 /// getValue - Return an SDValue for the given Value. 1381 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1382 // If we already have an SDValue for this value, use it. It's important 1383 // to do this first, so that we don't create a CopyFromReg if we already 1384 // have a regular SDValue. 1385 SDValue &N = NodeMap[V]; 1386 if (N.getNode()) return N; 1387 1388 // If there's a virtual register allocated and initialized for this 1389 // value, use it. 1390 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1391 return copyFromReg; 1392 1393 // Otherwise create a new SDValue and remember it. 1394 SDValue Val = getValueImpl(V); 1395 NodeMap[V] = Val; 1396 resolveDanglingDebugInfo(V, Val); 1397 return Val; 1398 } 1399 1400 /// getNonRegisterValue - Return an SDValue for the given Value, but 1401 /// don't look in FuncInfo.ValueMap for a virtual register. 1402 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1403 // If we already have an SDValue for this value, use it. 1404 SDValue &N = NodeMap[V]; 1405 if (N.getNode()) { 1406 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1407 // Remove the debug location from the node as the node is about to be used 1408 // in a location which may differ from the original debug location. This 1409 // is relevant to Constant and ConstantFP nodes because they can appear 1410 // as constant expressions inside PHI nodes. 1411 N->setDebugLoc(DebugLoc()); 1412 } 1413 return N; 1414 } 1415 1416 // Otherwise create a new SDValue and remember it. 1417 SDValue Val = getValueImpl(V); 1418 NodeMap[V] = Val; 1419 resolveDanglingDebugInfo(V, Val); 1420 return Val; 1421 } 1422 1423 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1424 /// Create an SDValue for the given value. 1425 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1426 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1427 1428 if (const Constant *C = dyn_cast<Constant>(V)) { 1429 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1430 1431 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1432 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1433 1434 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1435 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1436 1437 if (isa<ConstantPointerNull>(C)) { 1438 unsigned AS = V->getType()->getPointerAddressSpace(); 1439 return DAG.getConstant(0, getCurSDLoc(), 1440 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1441 } 1442 1443 if (match(C, m_VScale(DAG.getDataLayout()))) 1444 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1445 1446 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1447 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1448 1449 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1450 return DAG.getUNDEF(VT); 1451 1452 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1453 visit(CE->getOpcode(), *CE); 1454 SDValue N1 = NodeMap[V]; 1455 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1456 return N1; 1457 } 1458 1459 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1460 SmallVector<SDValue, 4> Constants; 1461 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1462 OI != OE; ++OI) { 1463 SDNode *Val = getValue(*OI).getNode(); 1464 // If the operand is an empty aggregate, there are no values. 1465 if (!Val) continue; 1466 // Add each leaf value from the operand to the Constants list 1467 // to form a flattened list of all the values. 1468 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1469 Constants.push_back(SDValue(Val, i)); 1470 } 1471 1472 return DAG.getMergeValues(Constants, getCurSDLoc()); 1473 } 1474 1475 if (const ConstantDataSequential *CDS = 1476 dyn_cast<ConstantDataSequential>(C)) { 1477 SmallVector<SDValue, 4> Ops; 1478 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1479 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1480 // Add each leaf value from the operand to the Constants list 1481 // to form a flattened list of all the values. 1482 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1483 Ops.push_back(SDValue(Val, i)); 1484 } 1485 1486 if (isa<ArrayType>(CDS->getType())) 1487 return DAG.getMergeValues(Ops, getCurSDLoc()); 1488 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1489 } 1490 1491 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1492 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1493 "Unknown struct or array constant!"); 1494 1495 SmallVector<EVT, 4> ValueVTs; 1496 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1497 unsigned NumElts = ValueVTs.size(); 1498 if (NumElts == 0) 1499 return SDValue(); // empty struct 1500 SmallVector<SDValue, 4> Constants(NumElts); 1501 for (unsigned i = 0; i != NumElts; ++i) { 1502 EVT EltVT = ValueVTs[i]; 1503 if (isa<UndefValue>(C)) 1504 Constants[i] = DAG.getUNDEF(EltVT); 1505 else if (EltVT.isFloatingPoint()) 1506 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1507 else 1508 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1509 } 1510 1511 return DAG.getMergeValues(Constants, getCurSDLoc()); 1512 } 1513 1514 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1515 return DAG.getBlockAddress(BA, VT); 1516 1517 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1518 return getValue(Equiv->getGlobalValue()); 1519 1520 VectorType *VecTy = cast<VectorType>(V->getType()); 1521 1522 // Now that we know the number and type of the elements, get that number of 1523 // elements into the Ops array based on what kind of constant it is. 1524 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1525 SmallVector<SDValue, 16> Ops; 1526 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1527 for (unsigned i = 0; i != NumElements; ++i) 1528 Ops.push_back(getValue(CV->getOperand(i))); 1529 1530 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1531 } else if (isa<ConstantAggregateZero>(C)) { 1532 EVT EltVT = 1533 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1534 1535 SDValue Op; 1536 if (EltVT.isFloatingPoint()) 1537 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1538 else 1539 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1540 1541 if (isa<ScalableVectorType>(VecTy)) 1542 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1543 else { 1544 SmallVector<SDValue, 16> Ops; 1545 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1546 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1547 } 1548 } 1549 llvm_unreachable("Unknown vector constant"); 1550 } 1551 1552 // If this is a static alloca, generate it as the frameindex instead of 1553 // computation. 1554 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1555 DenseMap<const AllocaInst*, int>::iterator SI = 1556 FuncInfo.StaticAllocaMap.find(AI); 1557 if (SI != FuncInfo.StaticAllocaMap.end()) 1558 return DAG.getFrameIndex(SI->second, 1559 TLI.getFrameIndexTy(DAG.getDataLayout())); 1560 } 1561 1562 // If this is an instruction which fast-isel has deferred, select it now. 1563 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1564 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1565 1566 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1567 Inst->getType(), None); 1568 SDValue Chain = DAG.getEntryNode(); 1569 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1570 } 1571 1572 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1573 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1574 } 1575 llvm_unreachable("Can't get register for value!"); 1576 } 1577 1578 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1579 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1580 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1581 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1582 bool IsSEH = isAsynchronousEHPersonality(Pers); 1583 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1584 if (!IsSEH) 1585 CatchPadMBB->setIsEHScopeEntry(); 1586 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1587 if (IsMSVCCXX || IsCoreCLR) 1588 CatchPadMBB->setIsEHFuncletEntry(); 1589 } 1590 1591 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1592 // Update machine-CFG edge. 1593 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1594 FuncInfo.MBB->addSuccessor(TargetMBB); 1595 1596 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1597 bool IsSEH = isAsynchronousEHPersonality(Pers); 1598 if (IsSEH) { 1599 // If this is not a fall-through branch or optimizations are switched off, 1600 // emit the branch. 1601 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1602 TM.getOptLevel() == CodeGenOpt::None) 1603 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1604 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1605 return; 1606 } 1607 1608 // Figure out the funclet membership for the catchret's successor. 1609 // This will be used by the FuncletLayout pass to determine how to order the 1610 // BB's. 1611 // A 'catchret' returns to the outer scope's color. 1612 Value *ParentPad = I.getCatchSwitchParentPad(); 1613 const BasicBlock *SuccessorColor; 1614 if (isa<ConstantTokenNone>(ParentPad)) 1615 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1616 else 1617 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1618 assert(SuccessorColor && "No parent funclet for catchret!"); 1619 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1620 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1621 1622 // Create the terminator node. 1623 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1624 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1625 DAG.getBasicBlock(SuccessorColorMBB)); 1626 DAG.setRoot(Ret); 1627 } 1628 1629 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1630 // Don't emit any special code for the cleanuppad instruction. It just marks 1631 // the start of an EH scope/funclet. 1632 FuncInfo.MBB->setIsEHScopeEntry(); 1633 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1634 if (Pers != EHPersonality::Wasm_CXX) { 1635 FuncInfo.MBB->setIsEHFuncletEntry(); 1636 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1637 } 1638 } 1639 1640 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1641 // the control flow always stops at the single catch pad, as it does for a 1642 // cleanup pad. In case the exception caught is not of the types the catch pad 1643 // catches, it will be rethrown by a rethrow. 1644 static void findWasmUnwindDestinations( 1645 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1646 BranchProbability Prob, 1647 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1648 &UnwindDests) { 1649 while (EHPadBB) { 1650 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1651 if (isa<CleanupPadInst>(Pad)) { 1652 // Stop on cleanup pads. 1653 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1654 UnwindDests.back().first->setIsEHScopeEntry(); 1655 break; 1656 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1657 // Add the catchpad handlers to the possible destinations. We don't 1658 // continue to the unwind destination of the catchswitch for wasm. 1659 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1660 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1661 UnwindDests.back().first->setIsEHScopeEntry(); 1662 } 1663 break; 1664 } else { 1665 continue; 1666 } 1667 } 1668 } 1669 1670 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1671 /// many places it could ultimately go. In the IR, we have a single unwind 1672 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1673 /// This function skips over imaginary basic blocks that hold catchswitch 1674 /// instructions, and finds all the "real" machine 1675 /// basic block destinations. As those destinations may not be successors of 1676 /// EHPadBB, here we also calculate the edge probability to those destinations. 1677 /// The passed-in Prob is the edge probability to EHPadBB. 1678 static void findUnwindDestinations( 1679 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1680 BranchProbability Prob, 1681 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1682 &UnwindDests) { 1683 EHPersonality Personality = 1684 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1685 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1686 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1687 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1688 bool IsSEH = isAsynchronousEHPersonality(Personality); 1689 1690 if (IsWasmCXX) { 1691 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1692 assert(UnwindDests.size() <= 1 && 1693 "There should be at most one unwind destination for wasm"); 1694 return; 1695 } 1696 1697 while (EHPadBB) { 1698 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1699 BasicBlock *NewEHPadBB = nullptr; 1700 if (isa<LandingPadInst>(Pad)) { 1701 // Stop on landingpads. They are not funclets. 1702 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1703 break; 1704 } else if (isa<CleanupPadInst>(Pad)) { 1705 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1706 // personalities. 1707 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1708 UnwindDests.back().first->setIsEHScopeEntry(); 1709 UnwindDests.back().first->setIsEHFuncletEntry(); 1710 break; 1711 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1712 // Add the catchpad handlers to the possible destinations. 1713 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1714 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1715 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1716 if (IsMSVCCXX || IsCoreCLR) 1717 UnwindDests.back().first->setIsEHFuncletEntry(); 1718 if (!IsSEH) 1719 UnwindDests.back().first->setIsEHScopeEntry(); 1720 } 1721 NewEHPadBB = CatchSwitch->getUnwindDest(); 1722 } else { 1723 continue; 1724 } 1725 1726 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1727 if (BPI && NewEHPadBB) 1728 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1729 EHPadBB = NewEHPadBB; 1730 } 1731 } 1732 1733 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1734 // Update successor info. 1735 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1736 auto UnwindDest = I.getUnwindDest(); 1737 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1738 BranchProbability UnwindDestProb = 1739 (BPI && UnwindDest) 1740 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1741 : BranchProbability::getZero(); 1742 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1743 for (auto &UnwindDest : UnwindDests) { 1744 UnwindDest.first->setIsEHPad(); 1745 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1746 } 1747 FuncInfo.MBB->normalizeSuccProbs(); 1748 1749 // Create the terminator node. 1750 SDValue Ret = 1751 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1752 DAG.setRoot(Ret); 1753 } 1754 1755 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1756 report_fatal_error("visitCatchSwitch not yet implemented!"); 1757 } 1758 1759 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1760 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1761 auto &DL = DAG.getDataLayout(); 1762 SDValue Chain = getControlRoot(); 1763 SmallVector<ISD::OutputArg, 8> Outs; 1764 SmallVector<SDValue, 8> OutVals; 1765 1766 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1767 // lower 1768 // 1769 // %val = call <ty> @llvm.experimental.deoptimize() 1770 // ret <ty> %val 1771 // 1772 // differently. 1773 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1774 LowerDeoptimizingReturn(); 1775 return; 1776 } 1777 1778 if (!FuncInfo.CanLowerReturn) { 1779 unsigned DemoteReg = FuncInfo.DemoteRegister; 1780 const Function *F = I.getParent()->getParent(); 1781 1782 // Emit a store of the return value through the virtual register. 1783 // Leave Outs empty so that LowerReturn won't try to load return 1784 // registers the usual way. 1785 SmallVector<EVT, 1> PtrValueVTs; 1786 ComputeValueVTs(TLI, DL, 1787 F->getReturnType()->getPointerTo( 1788 DAG.getDataLayout().getAllocaAddrSpace()), 1789 PtrValueVTs); 1790 1791 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1792 DemoteReg, PtrValueVTs[0]); 1793 SDValue RetOp = getValue(I.getOperand(0)); 1794 1795 SmallVector<EVT, 4> ValueVTs, MemVTs; 1796 SmallVector<uint64_t, 4> Offsets; 1797 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1798 &Offsets); 1799 unsigned NumValues = ValueVTs.size(); 1800 1801 SmallVector<SDValue, 4> Chains(NumValues); 1802 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1803 for (unsigned i = 0; i != NumValues; ++i) { 1804 // An aggregate return value cannot wrap around the address space, so 1805 // offsets to its parts don't wrap either. 1806 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1807 TypeSize::Fixed(Offsets[i])); 1808 1809 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1810 if (MemVTs[i] != ValueVTs[i]) 1811 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1812 Chains[i] = DAG.getStore( 1813 Chain, getCurSDLoc(), Val, 1814 // FIXME: better loc info would be nice. 1815 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1816 commonAlignment(BaseAlign, Offsets[i])); 1817 } 1818 1819 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1820 MVT::Other, Chains); 1821 } else if (I.getNumOperands() != 0) { 1822 SmallVector<EVT, 4> ValueVTs; 1823 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1824 unsigned NumValues = ValueVTs.size(); 1825 if (NumValues) { 1826 SDValue RetOp = getValue(I.getOperand(0)); 1827 1828 const Function *F = I.getParent()->getParent(); 1829 1830 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1831 I.getOperand(0)->getType(), F->getCallingConv(), 1832 /*IsVarArg*/ false); 1833 1834 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1835 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1836 Attribute::SExt)) 1837 ExtendKind = ISD::SIGN_EXTEND; 1838 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1839 Attribute::ZExt)) 1840 ExtendKind = ISD::ZERO_EXTEND; 1841 1842 LLVMContext &Context = F->getContext(); 1843 bool RetInReg = F->getAttributes().hasAttribute( 1844 AttributeList::ReturnIndex, Attribute::InReg); 1845 1846 for (unsigned j = 0; j != NumValues; ++j) { 1847 EVT VT = ValueVTs[j]; 1848 1849 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1850 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1851 1852 CallingConv::ID CC = F->getCallingConv(); 1853 1854 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1855 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1856 SmallVector<SDValue, 4> Parts(NumParts); 1857 getCopyToParts(DAG, getCurSDLoc(), 1858 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1859 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1860 1861 // 'inreg' on function refers to return value 1862 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1863 if (RetInReg) 1864 Flags.setInReg(); 1865 1866 if (I.getOperand(0)->getType()->isPointerTy()) { 1867 Flags.setPointer(); 1868 Flags.setPointerAddrSpace( 1869 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1870 } 1871 1872 if (NeedsRegBlock) { 1873 Flags.setInConsecutiveRegs(); 1874 if (j == NumValues - 1) 1875 Flags.setInConsecutiveRegsLast(); 1876 } 1877 1878 // Propagate extension type if any 1879 if (ExtendKind == ISD::SIGN_EXTEND) 1880 Flags.setSExt(); 1881 else if (ExtendKind == ISD::ZERO_EXTEND) 1882 Flags.setZExt(); 1883 1884 for (unsigned i = 0; i < NumParts; ++i) { 1885 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1886 VT, /*isfixed=*/true, 0, 0)); 1887 OutVals.push_back(Parts[i]); 1888 } 1889 } 1890 } 1891 } 1892 1893 // Push in swifterror virtual register as the last element of Outs. This makes 1894 // sure swifterror virtual register will be returned in the swifterror 1895 // physical register. 1896 const Function *F = I.getParent()->getParent(); 1897 if (TLI.supportSwiftError() && 1898 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1899 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1900 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1901 Flags.setSwiftError(); 1902 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1903 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1904 true /*isfixed*/, 1 /*origidx*/, 1905 0 /*partOffs*/)); 1906 // Create SDNode for the swifterror virtual register. 1907 OutVals.push_back( 1908 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1909 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1910 EVT(TLI.getPointerTy(DL)))); 1911 } 1912 1913 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1914 CallingConv::ID CallConv = 1915 DAG.getMachineFunction().getFunction().getCallingConv(); 1916 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1917 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1918 1919 // Verify that the target's LowerReturn behaved as expected. 1920 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1921 "LowerReturn didn't return a valid chain!"); 1922 1923 // Update the DAG with the new chain value resulting from return lowering. 1924 DAG.setRoot(Chain); 1925 } 1926 1927 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1928 /// created for it, emit nodes to copy the value into the virtual 1929 /// registers. 1930 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1931 // Skip empty types 1932 if (V->getType()->isEmptyTy()) 1933 return; 1934 1935 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1936 if (VMI != FuncInfo.ValueMap.end()) { 1937 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1938 CopyValueToVirtualRegister(V, VMI->second); 1939 } 1940 } 1941 1942 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1943 /// the current basic block, add it to ValueMap now so that we'll get a 1944 /// CopyTo/FromReg. 1945 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1946 // No need to export constants. 1947 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1948 1949 // Already exported? 1950 if (FuncInfo.isExportedInst(V)) return; 1951 1952 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1953 CopyValueToVirtualRegister(V, Reg); 1954 } 1955 1956 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1957 const BasicBlock *FromBB) { 1958 // The operands of the setcc have to be in this block. We don't know 1959 // how to export them from some other block. 1960 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1961 // Can export from current BB. 1962 if (VI->getParent() == FromBB) 1963 return true; 1964 1965 // Is already exported, noop. 1966 return FuncInfo.isExportedInst(V); 1967 } 1968 1969 // If this is an argument, we can export it if the BB is the entry block or 1970 // if it is already exported. 1971 if (isa<Argument>(V)) { 1972 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1973 return true; 1974 1975 // Otherwise, can only export this if it is already exported. 1976 return FuncInfo.isExportedInst(V); 1977 } 1978 1979 // Otherwise, constants can always be exported. 1980 return true; 1981 } 1982 1983 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1984 BranchProbability 1985 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1986 const MachineBasicBlock *Dst) const { 1987 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1988 const BasicBlock *SrcBB = Src->getBasicBlock(); 1989 const BasicBlock *DstBB = Dst->getBasicBlock(); 1990 if (!BPI) { 1991 // If BPI is not available, set the default probability as 1 / N, where N is 1992 // the number of successors. 1993 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1994 return BranchProbability(1, SuccSize); 1995 } 1996 return BPI->getEdgeProbability(SrcBB, DstBB); 1997 } 1998 1999 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2000 MachineBasicBlock *Dst, 2001 BranchProbability Prob) { 2002 if (!FuncInfo.BPI) 2003 Src->addSuccessorWithoutProb(Dst); 2004 else { 2005 if (Prob.isUnknown()) 2006 Prob = getEdgeProbability(Src, Dst); 2007 Src->addSuccessor(Dst, Prob); 2008 } 2009 } 2010 2011 static bool InBlock(const Value *V, const BasicBlock *BB) { 2012 if (const Instruction *I = dyn_cast<Instruction>(V)) 2013 return I->getParent() == BB; 2014 return true; 2015 } 2016 2017 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2018 /// This function emits a branch and is used at the leaves of an OR or an 2019 /// AND operator tree. 2020 void 2021 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2022 MachineBasicBlock *TBB, 2023 MachineBasicBlock *FBB, 2024 MachineBasicBlock *CurBB, 2025 MachineBasicBlock *SwitchBB, 2026 BranchProbability TProb, 2027 BranchProbability FProb, 2028 bool InvertCond) { 2029 const BasicBlock *BB = CurBB->getBasicBlock(); 2030 2031 // If the leaf of the tree is a comparison, merge the condition into 2032 // the caseblock. 2033 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2034 // The operands of the cmp have to be in this block. We don't know 2035 // how to export them from some other block. If this is the first block 2036 // of the sequence, no exporting is needed. 2037 if (CurBB == SwitchBB || 2038 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2039 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2040 ISD::CondCode Condition; 2041 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2042 ICmpInst::Predicate Pred = 2043 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2044 Condition = getICmpCondCode(Pred); 2045 } else { 2046 const FCmpInst *FC = cast<FCmpInst>(Cond); 2047 FCmpInst::Predicate Pred = 2048 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2049 Condition = getFCmpCondCode(Pred); 2050 if (TM.Options.NoNaNsFPMath) 2051 Condition = getFCmpCodeWithoutNaN(Condition); 2052 } 2053 2054 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2055 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2056 SL->SwitchCases.push_back(CB); 2057 return; 2058 } 2059 } 2060 2061 // Create a CaseBlock record representing this branch. 2062 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2063 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2064 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2065 SL->SwitchCases.push_back(CB); 2066 } 2067 2068 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2069 MachineBasicBlock *TBB, 2070 MachineBasicBlock *FBB, 2071 MachineBasicBlock *CurBB, 2072 MachineBasicBlock *SwitchBB, 2073 Instruction::BinaryOps Opc, 2074 BranchProbability TProb, 2075 BranchProbability FProb, 2076 bool InvertCond) { 2077 // Skip over not part of the tree and remember to invert op and operands at 2078 // next level. 2079 Value *NotCond; 2080 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2081 InBlock(NotCond, CurBB->getBasicBlock())) { 2082 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2083 !InvertCond); 2084 return; 2085 } 2086 2087 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2088 // Compute the effective opcode for Cond, taking into account whether it needs 2089 // to be inverted, e.g. 2090 // and (not (or A, B)), C 2091 // gets lowered as 2092 // and (and (not A, not B), C) 2093 unsigned BOpc = 0; 2094 if (BOp) { 2095 BOpc = BOp->getOpcode(); 2096 if (InvertCond) { 2097 if (BOpc == Instruction::And) 2098 BOpc = Instruction::Or; 2099 else if (BOpc == Instruction::Or) 2100 BOpc = Instruction::And; 2101 } 2102 } 2103 2104 // If this node is not part of the or/and tree, emit it as a branch. 2105 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2106 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2107 BOp->getParent() != CurBB->getBasicBlock() || 2108 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2109 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2110 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2111 TProb, FProb, InvertCond); 2112 return; 2113 } 2114 2115 // Create TmpBB after CurBB. 2116 MachineFunction::iterator BBI(CurBB); 2117 MachineFunction &MF = DAG.getMachineFunction(); 2118 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2119 CurBB->getParent()->insert(++BBI, TmpBB); 2120 2121 if (Opc == Instruction::Or) { 2122 // Codegen X | Y as: 2123 // BB1: 2124 // jmp_if_X TBB 2125 // jmp TmpBB 2126 // TmpBB: 2127 // jmp_if_Y TBB 2128 // jmp FBB 2129 // 2130 2131 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2132 // The requirement is that 2133 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2134 // = TrueProb for original BB. 2135 // Assuming the original probabilities are A and B, one choice is to set 2136 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2137 // A/(1+B) and 2B/(1+B). This choice assumes that 2138 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2139 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2140 // TmpBB, but the math is more complicated. 2141 2142 auto NewTrueProb = TProb / 2; 2143 auto NewFalseProb = TProb / 2 + FProb; 2144 // Emit the LHS condition. 2145 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2146 NewTrueProb, NewFalseProb, InvertCond); 2147 2148 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2149 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2150 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2151 // Emit the RHS condition into TmpBB. 2152 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2153 Probs[0], Probs[1], InvertCond); 2154 } else { 2155 assert(Opc == Instruction::And && "Unknown merge op!"); 2156 // Codegen X & Y as: 2157 // BB1: 2158 // jmp_if_X TmpBB 2159 // jmp FBB 2160 // TmpBB: 2161 // jmp_if_Y TBB 2162 // jmp FBB 2163 // 2164 // This requires creation of TmpBB after CurBB. 2165 2166 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2167 // The requirement is that 2168 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2169 // = FalseProb for original BB. 2170 // Assuming the original probabilities are A and B, one choice is to set 2171 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2172 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2173 // TrueProb for BB1 * FalseProb for TmpBB. 2174 2175 auto NewTrueProb = TProb + FProb / 2; 2176 auto NewFalseProb = FProb / 2; 2177 // Emit the LHS condition. 2178 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2179 NewTrueProb, NewFalseProb, InvertCond); 2180 2181 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2182 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2183 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2184 // Emit the RHS condition into TmpBB. 2185 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2186 Probs[0], Probs[1], InvertCond); 2187 } 2188 } 2189 2190 /// If the set of cases should be emitted as a series of branches, return true. 2191 /// If we should emit this as a bunch of and/or'd together conditions, return 2192 /// false. 2193 bool 2194 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2195 if (Cases.size() != 2) return true; 2196 2197 // If this is two comparisons of the same values or'd or and'd together, they 2198 // will get folded into a single comparison, so don't emit two blocks. 2199 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2200 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2201 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2202 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2203 return false; 2204 } 2205 2206 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2207 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2208 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2209 Cases[0].CC == Cases[1].CC && 2210 isa<Constant>(Cases[0].CmpRHS) && 2211 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2212 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2213 return false; 2214 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2215 return false; 2216 } 2217 2218 return true; 2219 } 2220 2221 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2222 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2223 2224 // Update machine-CFG edges. 2225 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2226 2227 if (I.isUnconditional()) { 2228 // Update machine-CFG edges. 2229 BrMBB->addSuccessor(Succ0MBB); 2230 2231 // If this is not a fall-through branch or optimizations are switched off, 2232 // emit the branch. 2233 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2234 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2235 MVT::Other, getControlRoot(), 2236 DAG.getBasicBlock(Succ0MBB))); 2237 2238 return; 2239 } 2240 2241 // If this condition is one of the special cases we handle, do special stuff 2242 // now. 2243 const Value *CondVal = I.getCondition(); 2244 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2245 2246 // If this is a series of conditions that are or'd or and'd together, emit 2247 // this as a sequence of branches instead of setcc's with and/or operations. 2248 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2249 // unpredictable branches, and vector extracts because those jumps are likely 2250 // expensive for any target), this should improve performance. 2251 // For example, instead of something like: 2252 // cmp A, B 2253 // C = seteq 2254 // cmp D, E 2255 // F = setle 2256 // or C, F 2257 // jnz foo 2258 // Emit: 2259 // cmp A, B 2260 // je foo 2261 // cmp D, E 2262 // jle foo 2263 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2264 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2265 Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1); 2266 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2267 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2268 (Opcode == Instruction::And || Opcode == Instruction::Or) && 2269 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2270 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2271 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2272 Opcode, 2273 getEdgeProbability(BrMBB, Succ0MBB), 2274 getEdgeProbability(BrMBB, Succ1MBB), 2275 /*InvertCond=*/false); 2276 // If the compares in later blocks need to use values not currently 2277 // exported from this block, export them now. This block should always 2278 // be the first entry. 2279 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2280 2281 // Allow some cases to be rejected. 2282 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2283 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2284 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2285 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2286 } 2287 2288 // Emit the branch for this block. 2289 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2290 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2291 return; 2292 } 2293 2294 // Okay, we decided not to do this, remove any inserted MBB's and clear 2295 // SwitchCases. 2296 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2297 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2298 2299 SL->SwitchCases.clear(); 2300 } 2301 } 2302 2303 // Create a CaseBlock record representing this branch. 2304 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2305 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2306 2307 // Use visitSwitchCase to actually insert the fast branch sequence for this 2308 // cond branch. 2309 visitSwitchCase(CB, BrMBB); 2310 } 2311 2312 /// visitSwitchCase - Emits the necessary code to represent a single node in 2313 /// the binary search tree resulting from lowering a switch instruction. 2314 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2315 MachineBasicBlock *SwitchBB) { 2316 SDValue Cond; 2317 SDValue CondLHS = getValue(CB.CmpLHS); 2318 SDLoc dl = CB.DL; 2319 2320 if (CB.CC == ISD::SETTRUE) { 2321 // Branch or fall through to TrueBB. 2322 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2323 SwitchBB->normalizeSuccProbs(); 2324 if (CB.TrueBB != NextBlock(SwitchBB)) { 2325 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2326 DAG.getBasicBlock(CB.TrueBB))); 2327 } 2328 return; 2329 } 2330 2331 auto &TLI = DAG.getTargetLoweringInfo(); 2332 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2333 2334 // Build the setcc now. 2335 if (!CB.CmpMHS) { 2336 // Fold "(X == true)" to X and "(X == false)" to !X to 2337 // handle common cases produced by branch lowering. 2338 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2339 CB.CC == ISD::SETEQ) 2340 Cond = CondLHS; 2341 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2342 CB.CC == ISD::SETEQ) { 2343 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2344 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2345 } else { 2346 SDValue CondRHS = getValue(CB.CmpRHS); 2347 2348 // If a pointer's DAG type is larger than its memory type then the DAG 2349 // values are zero-extended. This breaks signed comparisons so truncate 2350 // back to the underlying type before doing the compare. 2351 if (CondLHS.getValueType() != MemVT) { 2352 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2353 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2354 } 2355 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2356 } 2357 } else { 2358 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2359 2360 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2361 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2362 2363 SDValue CmpOp = getValue(CB.CmpMHS); 2364 EVT VT = CmpOp.getValueType(); 2365 2366 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2367 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2368 ISD::SETLE); 2369 } else { 2370 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2371 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2372 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2373 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2374 } 2375 } 2376 2377 // Update successor info 2378 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2379 // TrueBB and FalseBB are always different unless the incoming IR is 2380 // degenerate. This only happens when running llc on weird IR. 2381 if (CB.TrueBB != CB.FalseBB) 2382 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2383 SwitchBB->normalizeSuccProbs(); 2384 2385 // If the lhs block is the next block, invert the condition so that we can 2386 // fall through to the lhs instead of the rhs block. 2387 if (CB.TrueBB == NextBlock(SwitchBB)) { 2388 std::swap(CB.TrueBB, CB.FalseBB); 2389 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2390 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2391 } 2392 2393 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2394 MVT::Other, getControlRoot(), Cond, 2395 DAG.getBasicBlock(CB.TrueBB)); 2396 2397 // Insert the false branch. Do this even if it's a fall through branch, 2398 // this makes it easier to do DAG optimizations which require inverting 2399 // the branch condition. 2400 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2401 DAG.getBasicBlock(CB.FalseBB)); 2402 2403 DAG.setRoot(BrCond); 2404 } 2405 2406 /// visitJumpTable - Emit JumpTable node in the current MBB 2407 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2408 // Emit the code for the jump table 2409 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2410 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2411 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2412 JT.Reg, PTy); 2413 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2414 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2415 MVT::Other, Index.getValue(1), 2416 Table, Index); 2417 DAG.setRoot(BrJumpTable); 2418 } 2419 2420 /// visitJumpTableHeader - This function emits necessary code to produce index 2421 /// in the JumpTable from switch case. 2422 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2423 JumpTableHeader &JTH, 2424 MachineBasicBlock *SwitchBB) { 2425 SDLoc dl = getCurSDLoc(); 2426 2427 // Subtract the lowest switch case value from the value being switched on. 2428 SDValue SwitchOp = getValue(JTH.SValue); 2429 EVT VT = SwitchOp.getValueType(); 2430 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2431 DAG.getConstant(JTH.First, dl, VT)); 2432 2433 // The SDNode we just created, which holds the value being switched on minus 2434 // the smallest case value, needs to be copied to a virtual register so it 2435 // can be used as an index into the jump table in a subsequent basic block. 2436 // This value may be smaller or larger than the target's pointer type, and 2437 // therefore require extension or truncating. 2438 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2439 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2440 2441 unsigned JumpTableReg = 2442 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2443 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2444 JumpTableReg, SwitchOp); 2445 JT.Reg = JumpTableReg; 2446 2447 if (!JTH.OmitRangeCheck) { 2448 // Emit the range check for the jump table, and branch to the default block 2449 // for the switch statement if the value being switched on exceeds the 2450 // largest case in the switch. 2451 SDValue CMP = DAG.getSetCC( 2452 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2453 Sub.getValueType()), 2454 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2455 2456 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2457 MVT::Other, CopyTo, CMP, 2458 DAG.getBasicBlock(JT.Default)); 2459 2460 // Avoid emitting unnecessary branches to the next block. 2461 if (JT.MBB != NextBlock(SwitchBB)) 2462 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2463 DAG.getBasicBlock(JT.MBB)); 2464 2465 DAG.setRoot(BrCond); 2466 } else { 2467 // Avoid emitting unnecessary branches to the next block. 2468 if (JT.MBB != NextBlock(SwitchBB)) 2469 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2470 DAG.getBasicBlock(JT.MBB))); 2471 else 2472 DAG.setRoot(CopyTo); 2473 } 2474 } 2475 2476 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2477 /// variable if there exists one. 2478 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2479 SDValue &Chain) { 2480 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2481 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2482 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2483 MachineFunction &MF = DAG.getMachineFunction(); 2484 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2485 MachineSDNode *Node = 2486 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2487 if (Global) { 2488 MachinePointerInfo MPInfo(Global); 2489 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2490 MachineMemOperand::MODereferenceable; 2491 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2492 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2493 DAG.setNodeMemRefs(Node, {MemRef}); 2494 } 2495 if (PtrTy != PtrMemTy) 2496 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2497 return SDValue(Node, 0); 2498 } 2499 2500 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2501 /// tail spliced into a stack protector check success bb. 2502 /// 2503 /// For a high level explanation of how this fits into the stack protector 2504 /// generation see the comment on the declaration of class 2505 /// StackProtectorDescriptor. 2506 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2507 MachineBasicBlock *ParentBB) { 2508 2509 // First create the loads to the guard/stack slot for the comparison. 2510 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2511 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2512 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2513 2514 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2515 int FI = MFI.getStackProtectorIndex(); 2516 2517 SDValue Guard; 2518 SDLoc dl = getCurSDLoc(); 2519 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2520 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2521 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2522 2523 // Generate code to load the content of the guard slot. 2524 SDValue GuardVal = DAG.getLoad( 2525 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2526 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2527 MachineMemOperand::MOVolatile); 2528 2529 if (TLI.useStackGuardXorFP()) 2530 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2531 2532 // Retrieve guard check function, nullptr if instrumentation is inlined. 2533 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2534 // The target provides a guard check function to validate the guard value. 2535 // Generate a call to that function with the content of the guard slot as 2536 // argument. 2537 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2538 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2539 2540 TargetLowering::ArgListTy Args; 2541 TargetLowering::ArgListEntry Entry; 2542 Entry.Node = GuardVal; 2543 Entry.Ty = FnTy->getParamType(0); 2544 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2545 Entry.IsInReg = true; 2546 Args.push_back(Entry); 2547 2548 TargetLowering::CallLoweringInfo CLI(DAG); 2549 CLI.setDebugLoc(getCurSDLoc()) 2550 .setChain(DAG.getEntryNode()) 2551 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2552 getValue(GuardCheckFn), std::move(Args)); 2553 2554 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2555 DAG.setRoot(Result.second); 2556 return; 2557 } 2558 2559 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2560 // Otherwise, emit a volatile load to retrieve the stack guard value. 2561 SDValue Chain = DAG.getEntryNode(); 2562 if (TLI.useLoadStackGuardNode()) { 2563 Guard = getLoadStackGuard(DAG, dl, Chain); 2564 } else { 2565 const Value *IRGuard = TLI.getSDagStackGuard(M); 2566 SDValue GuardPtr = getValue(IRGuard); 2567 2568 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2569 MachinePointerInfo(IRGuard, 0), Align, 2570 MachineMemOperand::MOVolatile); 2571 } 2572 2573 // Perform the comparison via a getsetcc. 2574 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2575 *DAG.getContext(), 2576 Guard.getValueType()), 2577 Guard, GuardVal, ISD::SETNE); 2578 2579 // If the guard/stackslot do not equal, branch to failure MBB. 2580 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2581 MVT::Other, GuardVal.getOperand(0), 2582 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2583 // Otherwise branch to success MBB. 2584 SDValue Br = DAG.getNode(ISD::BR, dl, 2585 MVT::Other, BrCond, 2586 DAG.getBasicBlock(SPD.getSuccessMBB())); 2587 2588 DAG.setRoot(Br); 2589 } 2590 2591 /// Codegen the failure basic block for a stack protector check. 2592 /// 2593 /// A failure stack protector machine basic block consists simply of a call to 2594 /// __stack_chk_fail(). 2595 /// 2596 /// For a high level explanation of how this fits into the stack protector 2597 /// generation see the comment on the declaration of class 2598 /// StackProtectorDescriptor. 2599 void 2600 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2602 TargetLowering::MakeLibCallOptions CallOptions; 2603 CallOptions.setDiscardResult(true); 2604 SDValue Chain = 2605 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2606 None, CallOptions, getCurSDLoc()).second; 2607 // On PS4, the "return address" must still be within the calling function, 2608 // even if it's at the very end, so emit an explicit TRAP here. 2609 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2610 if (TM.getTargetTriple().isPS4CPU()) 2611 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2612 // WebAssembly needs an unreachable instruction after a non-returning call, 2613 // because the function return type can be different from __stack_chk_fail's 2614 // return type (void). 2615 if (TM.getTargetTriple().isWasm()) 2616 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2617 2618 DAG.setRoot(Chain); 2619 } 2620 2621 /// visitBitTestHeader - This function emits necessary code to produce value 2622 /// suitable for "bit tests" 2623 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2624 MachineBasicBlock *SwitchBB) { 2625 SDLoc dl = getCurSDLoc(); 2626 2627 // Subtract the minimum value. 2628 SDValue SwitchOp = getValue(B.SValue); 2629 EVT VT = SwitchOp.getValueType(); 2630 SDValue RangeSub = 2631 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2632 2633 // Determine the type of the test operands. 2634 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2635 bool UsePtrType = false; 2636 if (!TLI.isTypeLegal(VT)) { 2637 UsePtrType = true; 2638 } else { 2639 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2640 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2641 // Switch table case range are encoded into series of masks. 2642 // Just use pointer type, it's guaranteed to fit. 2643 UsePtrType = true; 2644 break; 2645 } 2646 } 2647 SDValue Sub = RangeSub; 2648 if (UsePtrType) { 2649 VT = TLI.getPointerTy(DAG.getDataLayout()); 2650 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2651 } 2652 2653 B.RegVT = VT.getSimpleVT(); 2654 B.Reg = FuncInfo.CreateReg(B.RegVT); 2655 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2656 2657 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2658 2659 if (!B.OmitRangeCheck) 2660 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2661 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2662 SwitchBB->normalizeSuccProbs(); 2663 2664 SDValue Root = CopyTo; 2665 if (!B.OmitRangeCheck) { 2666 // Conditional branch to the default block. 2667 SDValue RangeCmp = DAG.getSetCC(dl, 2668 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2669 RangeSub.getValueType()), 2670 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2671 ISD::SETUGT); 2672 2673 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2674 DAG.getBasicBlock(B.Default)); 2675 } 2676 2677 // Avoid emitting unnecessary branches to the next block. 2678 if (MBB != NextBlock(SwitchBB)) 2679 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2680 2681 DAG.setRoot(Root); 2682 } 2683 2684 /// visitBitTestCase - this function produces one "bit test" 2685 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2686 MachineBasicBlock* NextMBB, 2687 BranchProbability BranchProbToNext, 2688 unsigned Reg, 2689 BitTestCase &B, 2690 MachineBasicBlock *SwitchBB) { 2691 SDLoc dl = getCurSDLoc(); 2692 MVT VT = BB.RegVT; 2693 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2694 SDValue Cmp; 2695 unsigned PopCount = countPopulation(B.Mask); 2696 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2697 if (PopCount == 1) { 2698 // Testing for a single bit; just compare the shift count with what it 2699 // would need to be to shift a 1 bit in that position. 2700 Cmp = DAG.getSetCC( 2701 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2702 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2703 ISD::SETEQ); 2704 } else if (PopCount == BB.Range) { 2705 // There is only one zero bit in the range, test for it directly. 2706 Cmp = DAG.getSetCC( 2707 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2708 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2709 ISD::SETNE); 2710 } else { 2711 // Make desired shift 2712 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2713 DAG.getConstant(1, dl, VT), ShiftOp); 2714 2715 // Emit bit tests and jumps 2716 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2717 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2718 Cmp = DAG.getSetCC( 2719 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2720 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2721 } 2722 2723 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2724 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2725 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2726 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2727 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2728 // one as they are relative probabilities (and thus work more like weights), 2729 // and hence we need to normalize them to let the sum of them become one. 2730 SwitchBB->normalizeSuccProbs(); 2731 2732 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2733 MVT::Other, getControlRoot(), 2734 Cmp, DAG.getBasicBlock(B.TargetBB)); 2735 2736 // Avoid emitting unnecessary branches to the next block. 2737 if (NextMBB != NextBlock(SwitchBB)) 2738 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2739 DAG.getBasicBlock(NextMBB)); 2740 2741 DAG.setRoot(BrAnd); 2742 } 2743 2744 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2745 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2746 2747 // Retrieve successors. Look through artificial IR level blocks like 2748 // catchswitch for successors. 2749 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2750 const BasicBlock *EHPadBB = I.getSuccessor(1); 2751 2752 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2753 // have to do anything here to lower funclet bundles. 2754 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2755 LLVMContext::OB_gc_transition, 2756 LLVMContext::OB_gc_live, 2757 LLVMContext::OB_funclet, 2758 LLVMContext::OB_cfguardtarget}) && 2759 "Cannot lower invokes with arbitrary operand bundles yet!"); 2760 2761 const Value *Callee(I.getCalledOperand()); 2762 const Function *Fn = dyn_cast<Function>(Callee); 2763 if (isa<InlineAsm>(Callee)) 2764 visitInlineAsm(I); 2765 else if (Fn && Fn->isIntrinsic()) { 2766 switch (Fn->getIntrinsicID()) { 2767 default: 2768 llvm_unreachable("Cannot invoke this intrinsic"); 2769 case Intrinsic::donothing: 2770 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2771 break; 2772 case Intrinsic::experimental_patchpoint_void: 2773 case Intrinsic::experimental_patchpoint_i64: 2774 visitPatchpoint(I, EHPadBB); 2775 break; 2776 case Intrinsic::experimental_gc_statepoint: 2777 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2778 break; 2779 case Intrinsic::wasm_rethrow_in_catch: { 2780 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2781 // special because it can be invoked, so we manually lower it to a DAG 2782 // node here. 2783 SmallVector<SDValue, 8> Ops; 2784 Ops.push_back(getRoot()); // inchain 2785 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2786 Ops.push_back( 2787 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2788 TLI.getPointerTy(DAG.getDataLayout()))); 2789 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2790 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2791 break; 2792 } 2793 } 2794 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2795 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2796 // Eventually we will support lowering the @llvm.experimental.deoptimize 2797 // intrinsic, and right now there are no plans to support other intrinsics 2798 // with deopt state. 2799 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2800 } else { 2801 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2802 } 2803 2804 // If the value of the invoke is used outside of its defining block, make it 2805 // available as a virtual register. 2806 // We already took care of the exported value for the statepoint instruction 2807 // during call to the LowerStatepoint. 2808 if (!isa<GCStatepointInst>(I)) { 2809 CopyToExportRegsIfNeeded(&I); 2810 } 2811 2812 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2813 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2814 BranchProbability EHPadBBProb = 2815 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2816 : BranchProbability::getZero(); 2817 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2818 2819 // Update successor info. 2820 addSuccessorWithProb(InvokeMBB, Return); 2821 for (auto &UnwindDest : UnwindDests) { 2822 UnwindDest.first->setIsEHPad(); 2823 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2824 } 2825 InvokeMBB->normalizeSuccProbs(); 2826 2827 // Drop into normal successor. 2828 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2829 DAG.getBasicBlock(Return))); 2830 } 2831 2832 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2833 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2834 2835 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2836 // have to do anything here to lower funclet bundles. 2837 assert(!I.hasOperandBundlesOtherThan( 2838 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2839 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2840 2841 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2842 visitInlineAsm(I); 2843 CopyToExportRegsIfNeeded(&I); 2844 2845 // Retrieve successors. 2846 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2847 2848 // Update successor info. 2849 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2850 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2851 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2852 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2853 Target->setIsInlineAsmBrIndirectTarget(); 2854 } 2855 CallBrMBB->normalizeSuccProbs(); 2856 2857 // Drop into default successor. 2858 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2859 MVT::Other, getControlRoot(), 2860 DAG.getBasicBlock(Return))); 2861 } 2862 2863 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2864 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2865 } 2866 2867 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2868 assert(FuncInfo.MBB->isEHPad() && 2869 "Call to landingpad not in landing pad!"); 2870 2871 // If there aren't registers to copy the values into (e.g., during SjLj 2872 // exceptions), then don't bother to create these DAG nodes. 2873 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2874 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2875 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2876 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2877 return; 2878 2879 // If landingpad's return type is token type, we don't create DAG nodes 2880 // for its exception pointer and selector value. The extraction of exception 2881 // pointer or selector value from token type landingpads is not currently 2882 // supported. 2883 if (LP.getType()->isTokenTy()) 2884 return; 2885 2886 SmallVector<EVT, 2> ValueVTs; 2887 SDLoc dl = getCurSDLoc(); 2888 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2889 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2890 2891 // Get the two live-in registers as SDValues. The physregs have already been 2892 // copied into virtual registers. 2893 SDValue Ops[2]; 2894 if (FuncInfo.ExceptionPointerVirtReg) { 2895 Ops[0] = DAG.getZExtOrTrunc( 2896 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2897 FuncInfo.ExceptionPointerVirtReg, 2898 TLI.getPointerTy(DAG.getDataLayout())), 2899 dl, ValueVTs[0]); 2900 } else { 2901 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2902 } 2903 Ops[1] = DAG.getZExtOrTrunc( 2904 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2905 FuncInfo.ExceptionSelectorVirtReg, 2906 TLI.getPointerTy(DAG.getDataLayout())), 2907 dl, ValueVTs[1]); 2908 2909 // Merge into one. 2910 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2911 DAG.getVTList(ValueVTs), Ops); 2912 setValue(&LP, Res); 2913 } 2914 2915 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2916 MachineBasicBlock *Last) { 2917 // Update JTCases. 2918 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2919 if (SL->JTCases[i].first.HeaderBB == First) 2920 SL->JTCases[i].first.HeaderBB = Last; 2921 2922 // Update BitTestCases. 2923 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2924 if (SL->BitTestCases[i].Parent == First) 2925 SL->BitTestCases[i].Parent = Last; 2926 } 2927 2928 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2929 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2930 2931 // Update machine-CFG edges with unique successors. 2932 SmallSet<BasicBlock*, 32> Done; 2933 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2934 BasicBlock *BB = I.getSuccessor(i); 2935 bool Inserted = Done.insert(BB).second; 2936 if (!Inserted) 2937 continue; 2938 2939 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2940 addSuccessorWithProb(IndirectBrMBB, Succ); 2941 } 2942 IndirectBrMBB->normalizeSuccProbs(); 2943 2944 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2945 MVT::Other, getControlRoot(), 2946 getValue(I.getAddress()))); 2947 } 2948 2949 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2950 if (!DAG.getTarget().Options.TrapUnreachable) 2951 return; 2952 2953 // We may be able to ignore unreachable behind a noreturn call. 2954 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2955 const BasicBlock &BB = *I.getParent(); 2956 if (&I != &BB.front()) { 2957 BasicBlock::const_iterator PredI = 2958 std::prev(BasicBlock::const_iterator(&I)); 2959 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2960 if (Call->doesNotReturn()) 2961 return; 2962 } 2963 } 2964 } 2965 2966 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2967 } 2968 2969 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2970 SDNodeFlags Flags; 2971 2972 SDValue Op = getValue(I.getOperand(0)); 2973 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2974 Op, Flags); 2975 setValue(&I, UnNodeValue); 2976 } 2977 2978 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2979 SDNodeFlags Flags; 2980 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2981 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2982 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2983 } 2984 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 2985 Flags.setExact(ExactOp->isExact()); 2986 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 2987 Flags.copyFMF(*FPOp); 2988 2989 SDValue Op1 = getValue(I.getOperand(0)); 2990 SDValue Op2 = getValue(I.getOperand(1)); 2991 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2992 Op1, Op2, Flags); 2993 setValue(&I, BinNodeValue); 2994 } 2995 2996 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2997 SDValue Op1 = getValue(I.getOperand(0)); 2998 SDValue Op2 = getValue(I.getOperand(1)); 2999 3000 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3001 Op1.getValueType(), DAG.getDataLayout()); 3002 3003 // Coerce the shift amount to the right type if we can. 3004 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3005 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3006 unsigned Op2Size = Op2.getValueSizeInBits(); 3007 SDLoc DL = getCurSDLoc(); 3008 3009 // If the operand is smaller than the shift count type, promote it. 3010 if (ShiftSize > Op2Size) 3011 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3012 3013 // If the operand is larger than the shift count type but the shift 3014 // count type has enough bits to represent any shift value, truncate 3015 // it now. This is a common case and it exposes the truncate to 3016 // optimization early. 3017 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3018 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3019 // Otherwise we'll need to temporarily settle for some other convenient 3020 // type. Type legalization will make adjustments once the shiftee is split. 3021 else 3022 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3023 } 3024 3025 bool nuw = false; 3026 bool nsw = false; 3027 bool exact = false; 3028 3029 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3030 3031 if (const OverflowingBinaryOperator *OFBinOp = 3032 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3033 nuw = OFBinOp->hasNoUnsignedWrap(); 3034 nsw = OFBinOp->hasNoSignedWrap(); 3035 } 3036 if (const PossiblyExactOperator *ExactOp = 3037 dyn_cast<const PossiblyExactOperator>(&I)) 3038 exact = ExactOp->isExact(); 3039 } 3040 SDNodeFlags Flags; 3041 Flags.setExact(exact); 3042 Flags.setNoSignedWrap(nsw); 3043 Flags.setNoUnsignedWrap(nuw); 3044 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3045 Flags); 3046 setValue(&I, Res); 3047 } 3048 3049 void SelectionDAGBuilder::visitSDiv(const User &I) { 3050 SDValue Op1 = getValue(I.getOperand(0)); 3051 SDValue Op2 = getValue(I.getOperand(1)); 3052 3053 SDNodeFlags Flags; 3054 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3055 cast<PossiblyExactOperator>(&I)->isExact()); 3056 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3057 Op2, Flags)); 3058 } 3059 3060 void SelectionDAGBuilder::visitICmp(const User &I) { 3061 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3062 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3063 predicate = IC->getPredicate(); 3064 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3065 predicate = ICmpInst::Predicate(IC->getPredicate()); 3066 SDValue Op1 = getValue(I.getOperand(0)); 3067 SDValue Op2 = getValue(I.getOperand(1)); 3068 ISD::CondCode Opcode = getICmpCondCode(predicate); 3069 3070 auto &TLI = DAG.getTargetLoweringInfo(); 3071 EVT MemVT = 3072 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3073 3074 // If a pointer's DAG type is larger than its memory type then the DAG values 3075 // are zero-extended. This breaks signed comparisons so truncate back to the 3076 // underlying type before doing the compare. 3077 if (Op1.getValueType() != MemVT) { 3078 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3079 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3080 } 3081 3082 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3083 I.getType()); 3084 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3085 } 3086 3087 void SelectionDAGBuilder::visitFCmp(const User &I) { 3088 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3089 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3090 predicate = FC->getPredicate(); 3091 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3092 predicate = FCmpInst::Predicate(FC->getPredicate()); 3093 SDValue Op1 = getValue(I.getOperand(0)); 3094 SDValue Op2 = getValue(I.getOperand(1)); 3095 3096 ISD::CondCode Condition = getFCmpCondCode(predicate); 3097 auto *FPMO = cast<FPMathOperator>(&I); 3098 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3099 Condition = getFCmpCodeWithoutNaN(Condition); 3100 3101 SDNodeFlags Flags; 3102 Flags.copyFMF(*FPMO); 3103 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3104 3105 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3106 I.getType()); 3107 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3108 } 3109 3110 // Check if the condition of the select has one use or two users that are both 3111 // selects with the same condition. 3112 static bool hasOnlySelectUsers(const Value *Cond) { 3113 return llvm::all_of(Cond->users(), [](const Value *V) { 3114 return isa<SelectInst>(V); 3115 }); 3116 } 3117 3118 void SelectionDAGBuilder::visitSelect(const User &I) { 3119 SmallVector<EVT, 4> ValueVTs; 3120 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3121 ValueVTs); 3122 unsigned NumValues = ValueVTs.size(); 3123 if (NumValues == 0) return; 3124 3125 SmallVector<SDValue, 4> Values(NumValues); 3126 SDValue Cond = getValue(I.getOperand(0)); 3127 SDValue LHSVal = getValue(I.getOperand(1)); 3128 SDValue RHSVal = getValue(I.getOperand(2)); 3129 SmallVector<SDValue, 1> BaseOps(1, Cond); 3130 ISD::NodeType OpCode = 3131 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3132 3133 bool IsUnaryAbs = false; 3134 3135 SDNodeFlags Flags; 3136 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3137 Flags.copyFMF(*FPOp); 3138 3139 // Min/max matching is only viable if all output VTs are the same. 3140 if (is_splat(ValueVTs)) { 3141 EVT VT = ValueVTs[0]; 3142 LLVMContext &Ctx = *DAG.getContext(); 3143 auto &TLI = DAG.getTargetLoweringInfo(); 3144 3145 // We care about the legality of the operation after it has been type 3146 // legalized. 3147 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3148 VT = TLI.getTypeToTransformTo(Ctx, VT); 3149 3150 // If the vselect is legal, assume we want to leave this as a vector setcc + 3151 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3152 // min/max is legal on the scalar type. 3153 bool UseScalarMinMax = VT.isVector() && 3154 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3155 3156 Value *LHS, *RHS; 3157 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3158 ISD::NodeType Opc = ISD::DELETED_NODE; 3159 switch (SPR.Flavor) { 3160 case SPF_UMAX: Opc = ISD::UMAX; break; 3161 case SPF_UMIN: Opc = ISD::UMIN; break; 3162 case SPF_SMAX: Opc = ISD::SMAX; break; 3163 case SPF_SMIN: Opc = ISD::SMIN; break; 3164 case SPF_FMINNUM: 3165 switch (SPR.NaNBehavior) { 3166 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3167 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3168 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3169 case SPNB_RETURNS_ANY: { 3170 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3171 Opc = ISD::FMINNUM; 3172 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3173 Opc = ISD::FMINIMUM; 3174 else if (UseScalarMinMax) 3175 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3176 ISD::FMINNUM : ISD::FMINIMUM; 3177 break; 3178 } 3179 } 3180 break; 3181 case SPF_FMAXNUM: 3182 switch (SPR.NaNBehavior) { 3183 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3184 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3185 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3186 case SPNB_RETURNS_ANY: 3187 3188 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3189 Opc = ISD::FMAXNUM; 3190 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3191 Opc = ISD::FMAXIMUM; 3192 else if (UseScalarMinMax) 3193 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3194 ISD::FMAXNUM : ISD::FMAXIMUM; 3195 break; 3196 } 3197 break; 3198 case SPF_ABS: 3199 IsUnaryAbs = true; 3200 Opc = ISD::ABS; 3201 break; 3202 case SPF_NABS: 3203 // TODO: we need to produce sub(0, abs(X)). 3204 default: break; 3205 } 3206 3207 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3208 (TLI.isOperationLegalOrCustom(Opc, VT) || 3209 (UseScalarMinMax && 3210 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3211 // If the underlying comparison instruction is used by any other 3212 // instruction, the consumed instructions won't be destroyed, so it is 3213 // not profitable to convert to a min/max. 3214 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3215 OpCode = Opc; 3216 LHSVal = getValue(LHS); 3217 RHSVal = getValue(RHS); 3218 BaseOps.clear(); 3219 } 3220 3221 if (IsUnaryAbs) { 3222 OpCode = Opc; 3223 LHSVal = getValue(LHS); 3224 BaseOps.clear(); 3225 } 3226 } 3227 3228 if (IsUnaryAbs) { 3229 for (unsigned i = 0; i != NumValues; ++i) { 3230 Values[i] = 3231 DAG.getNode(OpCode, getCurSDLoc(), 3232 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3233 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3234 } 3235 } else { 3236 for (unsigned i = 0; i != NumValues; ++i) { 3237 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3238 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3239 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3240 Values[i] = DAG.getNode( 3241 OpCode, getCurSDLoc(), 3242 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3243 } 3244 } 3245 3246 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3247 DAG.getVTList(ValueVTs), Values)); 3248 } 3249 3250 void SelectionDAGBuilder::visitTrunc(const User &I) { 3251 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3252 SDValue N = getValue(I.getOperand(0)); 3253 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3254 I.getType()); 3255 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3256 } 3257 3258 void SelectionDAGBuilder::visitZExt(const User &I) { 3259 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3260 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3261 SDValue N = getValue(I.getOperand(0)); 3262 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3263 I.getType()); 3264 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3265 } 3266 3267 void SelectionDAGBuilder::visitSExt(const User &I) { 3268 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3269 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3270 SDValue N = getValue(I.getOperand(0)); 3271 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3272 I.getType()); 3273 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3274 } 3275 3276 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3277 // FPTrunc is never a no-op cast, no need to check 3278 SDValue N = getValue(I.getOperand(0)); 3279 SDLoc dl = getCurSDLoc(); 3280 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3281 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3282 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3283 DAG.getTargetConstant( 3284 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3285 } 3286 3287 void SelectionDAGBuilder::visitFPExt(const User &I) { 3288 // FPExt is never a no-op cast, no need to check 3289 SDValue N = getValue(I.getOperand(0)); 3290 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3291 I.getType()); 3292 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3293 } 3294 3295 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3296 // FPToUI is never a no-op cast, no need to check 3297 SDValue N = getValue(I.getOperand(0)); 3298 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3299 I.getType()); 3300 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3301 } 3302 3303 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3304 // FPToSI is never a no-op cast, no need to check 3305 SDValue N = getValue(I.getOperand(0)); 3306 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3307 I.getType()); 3308 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3309 } 3310 3311 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3312 // UIToFP is never a no-op cast, no need to check 3313 SDValue N = getValue(I.getOperand(0)); 3314 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3315 I.getType()); 3316 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3317 } 3318 3319 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3320 // SIToFP is never a no-op cast, no need to check 3321 SDValue N = getValue(I.getOperand(0)); 3322 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3323 I.getType()); 3324 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3325 } 3326 3327 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3328 // What to do depends on the size of the integer and the size of the pointer. 3329 // We can either truncate, zero extend, or no-op, accordingly. 3330 SDValue N = getValue(I.getOperand(0)); 3331 auto &TLI = DAG.getTargetLoweringInfo(); 3332 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3333 I.getType()); 3334 EVT PtrMemVT = 3335 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3336 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3337 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3338 setValue(&I, N); 3339 } 3340 3341 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3342 // What to do depends on the size of the integer and the size of the pointer. 3343 // We can either truncate, zero extend, or no-op, accordingly. 3344 SDValue N = getValue(I.getOperand(0)); 3345 auto &TLI = DAG.getTargetLoweringInfo(); 3346 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3347 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3348 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3349 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3350 setValue(&I, N); 3351 } 3352 3353 void SelectionDAGBuilder::visitBitCast(const User &I) { 3354 SDValue N = getValue(I.getOperand(0)); 3355 SDLoc dl = getCurSDLoc(); 3356 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3357 I.getType()); 3358 3359 // BitCast assures us that source and destination are the same size so this is 3360 // either a BITCAST or a no-op. 3361 if (DestVT != N.getValueType()) 3362 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3363 DestVT, N)); // convert types. 3364 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3365 // might fold any kind of constant expression to an integer constant and that 3366 // is not what we are looking for. Only recognize a bitcast of a genuine 3367 // constant integer as an opaque constant. 3368 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3369 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3370 /*isOpaque*/true)); 3371 else 3372 setValue(&I, N); // noop cast. 3373 } 3374 3375 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3376 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3377 const Value *SV = I.getOperand(0); 3378 SDValue N = getValue(SV); 3379 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3380 3381 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3382 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3383 3384 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3385 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3386 3387 setValue(&I, N); 3388 } 3389 3390 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3391 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3392 SDValue InVec = getValue(I.getOperand(0)); 3393 SDValue InVal = getValue(I.getOperand(1)); 3394 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3395 TLI.getVectorIdxTy(DAG.getDataLayout())); 3396 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3397 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3398 InVec, InVal, InIdx)); 3399 } 3400 3401 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3402 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3403 SDValue InVec = getValue(I.getOperand(0)); 3404 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3405 TLI.getVectorIdxTy(DAG.getDataLayout())); 3406 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3407 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3408 InVec, InIdx)); 3409 } 3410 3411 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3412 SDValue Src1 = getValue(I.getOperand(0)); 3413 SDValue Src2 = getValue(I.getOperand(1)); 3414 ArrayRef<int> Mask; 3415 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3416 Mask = SVI->getShuffleMask(); 3417 else 3418 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3419 SDLoc DL = getCurSDLoc(); 3420 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3421 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3422 EVT SrcVT = Src1.getValueType(); 3423 3424 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3425 VT.isScalableVector()) { 3426 // Canonical splat form of first element of first input vector. 3427 SDValue FirstElt = 3428 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3429 DAG.getVectorIdxConstant(0, DL)); 3430 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3431 return; 3432 } 3433 3434 // For now, we only handle splats for scalable vectors. 3435 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3436 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3437 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3438 3439 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3440 unsigned MaskNumElts = Mask.size(); 3441 3442 if (SrcNumElts == MaskNumElts) { 3443 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3444 return; 3445 } 3446 3447 // Normalize the shuffle vector since mask and vector length don't match. 3448 if (SrcNumElts < MaskNumElts) { 3449 // Mask is longer than the source vectors. We can use concatenate vector to 3450 // make the mask and vectors lengths match. 3451 3452 if (MaskNumElts % SrcNumElts == 0) { 3453 // Mask length is a multiple of the source vector length. 3454 // Check if the shuffle is some kind of concatenation of the input 3455 // vectors. 3456 unsigned NumConcat = MaskNumElts / SrcNumElts; 3457 bool IsConcat = true; 3458 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3459 for (unsigned i = 0; i != MaskNumElts; ++i) { 3460 int Idx = Mask[i]; 3461 if (Idx < 0) 3462 continue; 3463 // Ensure the indices in each SrcVT sized piece are sequential and that 3464 // the same source is used for the whole piece. 3465 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3466 (ConcatSrcs[i / SrcNumElts] >= 0 && 3467 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3468 IsConcat = false; 3469 break; 3470 } 3471 // Remember which source this index came from. 3472 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3473 } 3474 3475 // The shuffle is concatenating multiple vectors together. Just emit 3476 // a CONCAT_VECTORS operation. 3477 if (IsConcat) { 3478 SmallVector<SDValue, 8> ConcatOps; 3479 for (auto Src : ConcatSrcs) { 3480 if (Src < 0) 3481 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3482 else if (Src == 0) 3483 ConcatOps.push_back(Src1); 3484 else 3485 ConcatOps.push_back(Src2); 3486 } 3487 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3488 return; 3489 } 3490 } 3491 3492 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3493 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3494 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3495 PaddedMaskNumElts); 3496 3497 // Pad both vectors with undefs to make them the same length as the mask. 3498 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3499 3500 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3501 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3502 MOps1[0] = Src1; 3503 MOps2[0] = Src2; 3504 3505 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3506 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3507 3508 // Readjust mask for new input vector length. 3509 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3510 for (unsigned i = 0; i != MaskNumElts; ++i) { 3511 int Idx = Mask[i]; 3512 if (Idx >= (int)SrcNumElts) 3513 Idx -= SrcNumElts - PaddedMaskNumElts; 3514 MappedOps[i] = Idx; 3515 } 3516 3517 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3518 3519 // If the concatenated vector was padded, extract a subvector with the 3520 // correct number of elements. 3521 if (MaskNumElts != PaddedMaskNumElts) 3522 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3523 DAG.getVectorIdxConstant(0, DL)); 3524 3525 setValue(&I, Result); 3526 return; 3527 } 3528 3529 if (SrcNumElts > MaskNumElts) { 3530 // Analyze the access pattern of the vector to see if we can extract 3531 // two subvectors and do the shuffle. 3532 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3533 bool CanExtract = true; 3534 for (int Idx : Mask) { 3535 unsigned Input = 0; 3536 if (Idx < 0) 3537 continue; 3538 3539 if (Idx >= (int)SrcNumElts) { 3540 Input = 1; 3541 Idx -= SrcNumElts; 3542 } 3543 3544 // If all the indices come from the same MaskNumElts sized portion of 3545 // the sources we can use extract. Also make sure the extract wouldn't 3546 // extract past the end of the source. 3547 int NewStartIdx = alignDown(Idx, MaskNumElts); 3548 if (NewStartIdx + MaskNumElts > SrcNumElts || 3549 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3550 CanExtract = false; 3551 // Make sure we always update StartIdx as we use it to track if all 3552 // elements are undef. 3553 StartIdx[Input] = NewStartIdx; 3554 } 3555 3556 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3557 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3558 return; 3559 } 3560 if (CanExtract) { 3561 // Extract appropriate subvector and generate a vector shuffle 3562 for (unsigned Input = 0; Input < 2; ++Input) { 3563 SDValue &Src = Input == 0 ? Src1 : Src2; 3564 if (StartIdx[Input] < 0) 3565 Src = DAG.getUNDEF(VT); 3566 else { 3567 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3568 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3569 } 3570 } 3571 3572 // Calculate new mask. 3573 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3574 for (int &Idx : MappedOps) { 3575 if (Idx >= (int)SrcNumElts) 3576 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3577 else if (Idx >= 0) 3578 Idx -= StartIdx[0]; 3579 } 3580 3581 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3582 return; 3583 } 3584 } 3585 3586 // We can't use either concat vectors or extract subvectors so fall back to 3587 // replacing the shuffle with extract and build vector. 3588 // to insert and build vector. 3589 EVT EltVT = VT.getVectorElementType(); 3590 SmallVector<SDValue,8> Ops; 3591 for (int Idx : Mask) { 3592 SDValue Res; 3593 3594 if (Idx < 0) { 3595 Res = DAG.getUNDEF(EltVT); 3596 } else { 3597 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3598 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3599 3600 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3601 DAG.getVectorIdxConstant(Idx, DL)); 3602 } 3603 3604 Ops.push_back(Res); 3605 } 3606 3607 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3608 } 3609 3610 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3611 ArrayRef<unsigned> Indices; 3612 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3613 Indices = IV->getIndices(); 3614 else 3615 Indices = cast<ConstantExpr>(&I)->getIndices(); 3616 3617 const Value *Op0 = I.getOperand(0); 3618 const Value *Op1 = I.getOperand(1); 3619 Type *AggTy = I.getType(); 3620 Type *ValTy = Op1->getType(); 3621 bool IntoUndef = isa<UndefValue>(Op0); 3622 bool FromUndef = isa<UndefValue>(Op1); 3623 3624 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3625 3626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3627 SmallVector<EVT, 4> AggValueVTs; 3628 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3629 SmallVector<EVT, 4> ValValueVTs; 3630 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3631 3632 unsigned NumAggValues = AggValueVTs.size(); 3633 unsigned NumValValues = ValValueVTs.size(); 3634 SmallVector<SDValue, 4> Values(NumAggValues); 3635 3636 // Ignore an insertvalue that produces an empty object 3637 if (!NumAggValues) { 3638 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3639 return; 3640 } 3641 3642 SDValue Agg = getValue(Op0); 3643 unsigned i = 0; 3644 // Copy the beginning value(s) from the original aggregate. 3645 for (; i != LinearIndex; ++i) 3646 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3647 SDValue(Agg.getNode(), Agg.getResNo() + i); 3648 // Copy values from the inserted value(s). 3649 if (NumValValues) { 3650 SDValue Val = getValue(Op1); 3651 for (; i != LinearIndex + NumValValues; ++i) 3652 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3653 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3654 } 3655 // Copy remaining value(s) from the original aggregate. 3656 for (; i != NumAggValues; ++i) 3657 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3658 SDValue(Agg.getNode(), Agg.getResNo() + i); 3659 3660 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3661 DAG.getVTList(AggValueVTs), Values)); 3662 } 3663 3664 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3665 ArrayRef<unsigned> Indices; 3666 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3667 Indices = EV->getIndices(); 3668 else 3669 Indices = cast<ConstantExpr>(&I)->getIndices(); 3670 3671 const Value *Op0 = I.getOperand(0); 3672 Type *AggTy = Op0->getType(); 3673 Type *ValTy = I.getType(); 3674 bool OutOfUndef = isa<UndefValue>(Op0); 3675 3676 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3677 3678 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3679 SmallVector<EVT, 4> ValValueVTs; 3680 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3681 3682 unsigned NumValValues = ValValueVTs.size(); 3683 3684 // Ignore a extractvalue that produces an empty object 3685 if (!NumValValues) { 3686 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3687 return; 3688 } 3689 3690 SmallVector<SDValue, 4> Values(NumValValues); 3691 3692 SDValue Agg = getValue(Op0); 3693 // Copy out the selected value(s). 3694 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3695 Values[i - LinearIndex] = 3696 OutOfUndef ? 3697 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3698 SDValue(Agg.getNode(), Agg.getResNo() + i); 3699 3700 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3701 DAG.getVTList(ValValueVTs), Values)); 3702 } 3703 3704 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3705 Value *Op0 = I.getOperand(0); 3706 // Note that the pointer operand may be a vector of pointers. Take the scalar 3707 // element which holds a pointer. 3708 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3709 SDValue N = getValue(Op0); 3710 SDLoc dl = getCurSDLoc(); 3711 auto &TLI = DAG.getTargetLoweringInfo(); 3712 3713 // Normalize Vector GEP - all scalar operands should be converted to the 3714 // splat vector. 3715 bool IsVectorGEP = I.getType()->isVectorTy(); 3716 ElementCount VectorElementCount = 3717 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3718 : ElementCount::getFixed(0); 3719 3720 if (IsVectorGEP && !N.getValueType().isVector()) { 3721 LLVMContext &Context = *DAG.getContext(); 3722 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3723 if (VectorElementCount.isScalable()) 3724 N = DAG.getSplatVector(VT, dl, N); 3725 else 3726 N = DAG.getSplatBuildVector(VT, dl, N); 3727 } 3728 3729 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3730 GTI != E; ++GTI) { 3731 const Value *Idx = GTI.getOperand(); 3732 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3733 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3734 if (Field) { 3735 // N = N + Offset 3736 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3737 3738 // In an inbounds GEP with an offset that is nonnegative even when 3739 // interpreted as signed, assume there is no unsigned overflow. 3740 SDNodeFlags Flags; 3741 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3742 Flags.setNoUnsignedWrap(true); 3743 3744 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3745 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3746 } 3747 } else { 3748 // IdxSize is the width of the arithmetic according to IR semantics. 3749 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3750 // (and fix up the result later). 3751 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3752 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3753 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3754 // We intentionally mask away the high bits here; ElementSize may not 3755 // fit in IdxTy. 3756 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3757 bool ElementScalable = ElementSize.isScalable(); 3758 3759 // If this is a scalar constant or a splat vector of constants, 3760 // handle it quickly. 3761 const auto *C = dyn_cast<Constant>(Idx); 3762 if (C && isa<VectorType>(C->getType())) 3763 C = C->getSplatValue(); 3764 3765 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3766 if (CI && CI->isZero()) 3767 continue; 3768 if (CI && !ElementScalable) { 3769 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3770 LLVMContext &Context = *DAG.getContext(); 3771 SDValue OffsVal; 3772 if (IsVectorGEP) 3773 OffsVal = DAG.getConstant( 3774 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3775 else 3776 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3777 3778 // In an inbounds GEP with an offset that is nonnegative even when 3779 // interpreted as signed, assume there is no unsigned overflow. 3780 SDNodeFlags Flags; 3781 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3782 Flags.setNoUnsignedWrap(true); 3783 3784 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3785 3786 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3787 continue; 3788 } 3789 3790 // N = N + Idx * ElementMul; 3791 SDValue IdxN = getValue(Idx); 3792 3793 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3794 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3795 VectorElementCount); 3796 if (VectorElementCount.isScalable()) 3797 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3798 else 3799 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3800 } 3801 3802 // If the index is smaller or larger than intptr_t, truncate or extend 3803 // it. 3804 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3805 3806 if (ElementScalable) { 3807 EVT VScaleTy = N.getValueType().getScalarType(); 3808 SDValue VScale = DAG.getNode( 3809 ISD::VSCALE, dl, VScaleTy, 3810 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3811 if (IsVectorGEP) 3812 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3813 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3814 } else { 3815 // If this is a multiply by a power of two, turn it into a shl 3816 // immediately. This is a very common case. 3817 if (ElementMul != 1) { 3818 if (ElementMul.isPowerOf2()) { 3819 unsigned Amt = ElementMul.logBase2(); 3820 IdxN = DAG.getNode(ISD::SHL, dl, 3821 N.getValueType(), IdxN, 3822 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3823 } else { 3824 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3825 IdxN.getValueType()); 3826 IdxN = DAG.getNode(ISD::MUL, dl, 3827 N.getValueType(), IdxN, Scale); 3828 } 3829 } 3830 } 3831 3832 N = DAG.getNode(ISD::ADD, dl, 3833 N.getValueType(), N, IdxN); 3834 } 3835 } 3836 3837 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3838 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3839 if (IsVectorGEP) { 3840 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3841 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3842 } 3843 3844 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3845 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3846 3847 setValue(&I, N); 3848 } 3849 3850 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3851 // If this is a fixed sized alloca in the entry block of the function, 3852 // allocate it statically on the stack. 3853 if (FuncInfo.StaticAllocaMap.count(&I)) 3854 return; // getValue will auto-populate this. 3855 3856 SDLoc dl = getCurSDLoc(); 3857 Type *Ty = I.getAllocatedType(); 3858 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3859 auto &DL = DAG.getDataLayout(); 3860 uint64_t TySize = DL.getTypeAllocSize(Ty); 3861 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3862 3863 SDValue AllocSize = getValue(I.getArraySize()); 3864 3865 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3866 if (AllocSize.getValueType() != IntPtr) 3867 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3868 3869 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3870 AllocSize, 3871 DAG.getConstant(TySize, dl, IntPtr)); 3872 3873 // Handle alignment. If the requested alignment is less than or equal to 3874 // the stack alignment, ignore it. If the size is greater than or equal to 3875 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3876 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3877 if (*Alignment <= StackAlign) 3878 Alignment = None; 3879 3880 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3881 // Round the size of the allocation up to the stack alignment size 3882 // by add SA-1 to the size. This doesn't overflow because we're computing 3883 // an address inside an alloca. 3884 SDNodeFlags Flags; 3885 Flags.setNoUnsignedWrap(true); 3886 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3887 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3888 3889 // Mask out the low bits for alignment purposes. 3890 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3891 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3892 3893 SDValue Ops[] = { 3894 getRoot(), AllocSize, 3895 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3896 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3897 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3898 setValue(&I, DSA); 3899 DAG.setRoot(DSA.getValue(1)); 3900 3901 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3902 } 3903 3904 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3905 if (I.isAtomic()) 3906 return visitAtomicLoad(I); 3907 3908 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3909 const Value *SV = I.getOperand(0); 3910 if (TLI.supportSwiftError()) { 3911 // Swifterror values can come from either a function parameter with 3912 // swifterror attribute or an alloca with swifterror attribute. 3913 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3914 if (Arg->hasSwiftErrorAttr()) 3915 return visitLoadFromSwiftError(I); 3916 } 3917 3918 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3919 if (Alloca->isSwiftError()) 3920 return visitLoadFromSwiftError(I); 3921 } 3922 } 3923 3924 SDValue Ptr = getValue(SV); 3925 3926 Type *Ty = I.getType(); 3927 Align Alignment = I.getAlign(); 3928 3929 AAMDNodes AAInfo; 3930 I.getAAMetadata(AAInfo); 3931 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3932 3933 SmallVector<EVT, 4> ValueVTs, MemVTs; 3934 SmallVector<uint64_t, 4> Offsets; 3935 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3936 unsigned NumValues = ValueVTs.size(); 3937 if (NumValues == 0) 3938 return; 3939 3940 bool isVolatile = I.isVolatile(); 3941 3942 SDValue Root; 3943 bool ConstantMemory = false; 3944 if (isVolatile) 3945 // Serialize volatile loads with other side effects. 3946 Root = getRoot(); 3947 else if (NumValues > MaxParallelChains) 3948 Root = getMemoryRoot(); 3949 else if (AA && 3950 AA->pointsToConstantMemory(MemoryLocation( 3951 SV, 3952 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3953 AAInfo))) { 3954 // Do not serialize (non-volatile) loads of constant memory with anything. 3955 Root = DAG.getEntryNode(); 3956 ConstantMemory = true; 3957 } else { 3958 // Do not serialize non-volatile loads against each other. 3959 Root = DAG.getRoot(); 3960 } 3961 3962 SDLoc dl = getCurSDLoc(); 3963 3964 if (isVolatile) 3965 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3966 3967 // An aggregate load cannot wrap around the address space, so offsets to its 3968 // parts don't wrap either. 3969 SDNodeFlags Flags; 3970 Flags.setNoUnsignedWrap(true); 3971 3972 SmallVector<SDValue, 4> Values(NumValues); 3973 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3974 EVT PtrVT = Ptr.getValueType(); 3975 3976 MachineMemOperand::Flags MMOFlags 3977 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 3978 3979 unsigned ChainI = 0; 3980 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3981 // Serializing loads here may result in excessive register pressure, and 3982 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3983 // could recover a bit by hoisting nodes upward in the chain by recognizing 3984 // they are side-effect free or do not alias. The optimizer should really 3985 // avoid this case by converting large object/array copies to llvm.memcpy 3986 // (MaxParallelChains should always remain as failsafe). 3987 if (ChainI == MaxParallelChains) { 3988 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3989 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3990 makeArrayRef(Chains.data(), ChainI)); 3991 Root = Chain; 3992 ChainI = 0; 3993 } 3994 SDValue A = DAG.getNode(ISD::ADD, dl, 3995 PtrVT, Ptr, 3996 DAG.getConstant(Offsets[i], dl, PtrVT), 3997 Flags); 3998 3999 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4000 MachinePointerInfo(SV, Offsets[i]), Alignment, 4001 MMOFlags, AAInfo, Ranges); 4002 Chains[ChainI] = L.getValue(1); 4003 4004 if (MemVTs[i] != ValueVTs[i]) 4005 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4006 4007 Values[i] = L; 4008 } 4009 4010 if (!ConstantMemory) { 4011 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4012 makeArrayRef(Chains.data(), ChainI)); 4013 if (isVolatile) 4014 DAG.setRoot(Chain); 4015 else 4016 PendingLoads.push_back(Chain); 4017 } 4018 4019 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4020 DAG.getVTList(ValueVTs), Values)); 4021 } 4022 4023 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4024 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4025 "call visitStoreToSwiftError when backend supports swifterror"); 4026 4027 SmallVector<EVT, 4> ValueVTs; 4028 SmallVector<uint64_t, 4> Offsets; 4029 const Value *SrcV = I.getOperand(0); 4030 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4031 SrcV->getType(), ValueVTs, &Offsets); 4032 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4033 "expect a single EVT for swifterror"); 4034 4035 SDValue Src = getValue(SrcV); 4036 // Create a virtual register, then update the virtual register. 4037 Register VReg = 4038 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4039 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4040 // Chain can be getRoot or getControlRoot. 4041 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4042 SDValue(Src.getNode(), Src.getResNo())); 4043 DAG.setRoot(CopyNode); 4044 } 4045 4046 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4047 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4048 "call visitLoadFromSwiftError when backend supports swifterror"); 4049 4050 assert(!I.isVolatile() && 4051 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4052 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4053 "Support volatile, non temporal, invariant for load_from_swift_error"); 4054 4055 const Value *SV = I.getOperand(0); 4056 Type *Ty = I.getType(); 4057 AAMDNodes AAInfo; 4058 I.getAAMetadata(AAInfo); 4059 assert( 4060 (!AA || 4061 !AA->pointsToConstantMemory(MemoryLocation( 4062 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4063 AAInfo))) && 4064 "load_from_swift_error should not be constant memory"); 4065 4066 SmallVector<EVT, 4> ValueVTs; 4067 SmallVector<uint64_t, 4> Offsets; 4068 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4069 ValueVTs, &Offsets); 4070 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4071 "expect a single EVT for swifterror"); 4072 4073 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4074 SDValue L = DAG.getCopyFromReg( 4075 getRoot(), getCurSDLoc(), 4076 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4077 4078 setValue(&I, L); 4079 } 4080 4081 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4082 if (I.isAtomic()) 4083 return visitAtomicStore(I); 4084 4085 const Value *SrcV = I.getOperand(0); 4086 const Value *PtrV = I.getOperand(1); 4087 4088 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4089 if (TLI.supportSwiftError()) { 4090 // Swifterror values can come from either a function parameter with 4091 // swifterror attribute or an alloca with swifterror attribute. 4092 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4093 if (Arg->hasSwiftErrorAttr()) 4094 return visitStoreToSwiftError(I); 4095 } 4096 4097 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4098 if (Alloca->isSwiftError()) 4099 return visitStoreToSwiftError(I); 4100 } 4101 } 4102 4103 SmallVector<EVT, 4> ValueVTs, MemVTs; 4104 SmallVector<uint64_t, 4> Offsets; 4105 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4106 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4107 unsigned NumValues = ValueVTs.size(); 4108 if (NumValues == 0) 4109 return; 4110 4111 // Get the lowered operands. Note that we do this after 4112 // checking if NumResults is zero, because with zero results 4113 // the operands won't have values in the map. 4114 SDValue Src = getValue(SrcV); 4115 SDValue Ptr = getValue(PtrV); 4116 4117 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4118 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4119 SDLoc dl = getCurSDLoc(); 4120 Align Alignment = I.getAlign(); 4121 AAMDNodes AAInfo; 4122 I.getAAMetadata(AAInfo); 4123 4124 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4125 4126 // An aggregate load cannot wrap around the address space, so offsets to its 4127 // parts don't wrap either. 4128 SDNodeFlags Flags; 4129 Flags.setNoUnsignedWrap(true); 4130 4131 unsigned ChainI = 0; 4132 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4133 // See visitLoad comments. 4134 if (ChainI == MaxParallelChains) { 4135 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4136 makeArrayRef(Chains.data(), ChainI)); 4137 Root = Chain; 4138 ChainI = 0; 4139 } 4140 SDValue Add = 4141 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4142 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4143 if (MemVTs[i] != ValueVTs[i]) 4144 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4145 SDValue St = 4146 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4147 Alignment, MMOFlags, AAInfo); 4148 Chains[ChainI] = St; 4149 } 4150 4151 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4152 makeArrayRef(Chains.data(), ChainI)); 4153 DAG.setRoot(StoreNode); 4154 } 4155 4156 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4157 bool IsCompressing) { 4158 SDLoc sdl = getCurSDLoc(); 4159 4160 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4161 MaybeAlign &Alignment) { 4162 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4163 Src0 = I.getArgOperand(0); 4164 Ptr = I.getArgOperand(1); 4165 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4166 Mask = I.getArgOperand(3); 4167 }; 4168 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4169 MaybeAlign &Alignment) { 4170 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4171 Src0 = I.getArgOperand(0); 4172 Ptr = I.getArgOperand(1); 4173 Mask = I.getArgOperand(2); 4174 Alignment = None; 4175 }; 4176 4177 Value *PtrOperand, *MaskOperand, *Src0Operand; 4178 MaybeAlign Alignment; 4179 if (IsCompressing) 4180 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4181 else 4182 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4183 4184 SDValue Ptr = getValue(PtrOperand); 4185 SDValue Src0 = getValue(Src0Operand); 4186 SDValue Mask = getValue(MaskOperand); 4187 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4188 4189 EVT VT = Src0.getValueType(); 4190 if (!Alignment) 4191 Alignment = DAG.getEVTAlign(VT); 4192 4193 AAMDNodes AAInfo; 4194 I.getAAMetadata(AAInfo); 4195 4196 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4197 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4198 // TODO: Make MachineMemOperands aware of scalable 4199 // vectors. 4200 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4201 SDValue StoreNode = 4202 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4203 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4204 DAG.setRoot(StoreNode); 4205 setValue(&I, StoreNode); 4206 } 4207 4208 // Get a uniform base for the Gather/Scatter intrinsic. 4209 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4210 // We try to represent it as a base pointer + vector of indices. 4211 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4212 // The first operand of the GEP may be a single pointer or a vector of pointers 4213 // Example: 4214 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4215 // or 4216 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4217 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4218 // 4219 // When the first GEP operand is a single pointer - it is the uniform base we 4220 // are looking for. If first operand of the GEP is a splat vector - we 4221 // extract the splat value and use it as a uniform base. 4222 // In all other cases the function returns 'false'. 4223 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4224 ISD::MemIndexType &IndexType, SDValue &Scale, 4225 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4226 SelectionDAG& DAG = SDB->DAG; 4227 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4228 const DataLayout &DL = DAG.getDataLayout(); 4229 4230 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4231 4232 // Handle splat constant pointer. 4233 if (auto *C = dyn_cast<Constant>(Ptr)) { 4234 C = C->getSplatValue(); 4235 if (!C) 4236 return false; 4237 4238 Base = SDB->getValue(C); 4239 4240 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4241 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4242 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4243 IndexType = ISD::SIGNED_SCALED; 4244 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4245 return true; 4246 } 4247 4248 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4249 if (!GEP || GEP->getParent() != CurBB) 4250 return false; 4251 4252 if (GEP->getNumOperands() != 2) 4253 return false; 4254 4255 const Value *BasePtr = GEP->getPointerOperand(); 4256 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4257 4258 // Make sure the base is scalar and the index is a vector. 4259 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4260 return false; 4261 4262 Base = SDB->getValue(BasePtr); 4263 Index = SDB->getValue(IndexVal); 4264 IndexType = ISD::SIGNED_SCALED; 4265 Scale = DAG.getTargetConstant( 4266 DL.getTypeAllocSize(GEP->getResultElementType()), 4267 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4268 return true; 4269 } 4270 4271 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4272 SDLoc sdl = getCurSDLoc(); 4273 4274 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4275 const Value *Ptr = I.getArgOperand(1); 4276 SDValue Src0 = getValue(I.getArgOperand(0)); 4277 SDValue Mask = getValue(I.getArgOperand(3)); 4278 EVT VT = Src0.getValueType(); 4279 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4280 ->getMaybeAlignValue() 4281 .getValueOr(DAG.getEVTAlign(VT)); 4282 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4283 4284 AAMDNodes AAInfo; 4285 I.getAAMetadata(AAInfo); 4286 4287 SDValue Base; 4288 SDValue Index; 4289 ISD::MemIndexType IndexType; 4290 SDValue Scale; 4291 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4292 I.getParent()); 4293 4294 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4295 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4296 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4297 // TODO: Make MachineMemOperands aware of scalable 4298 // vectors. 4299 MemoryLocation::UnknownSize, Alignment, AAInfo); 4300 if (!UniformBase) { 4301 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4302 Index = getValue(Ptr); 4303 IndexType = ISD::SIGNED_UNSCALED; 4304 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4305 } 4306 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4307 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4308 Ops, MMO, IndexType, false); 4309 DAG.setRoot(Scatter); 4310 setValue(&I, Scatter); 4311 } 4312 4313 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4314 SDLoc sdl = getCurSDLoc(); 4315 4316 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4317 MaybeAlign &Alignment) { 4318 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4319 Ptr = I.getArgOperand(0); 4320 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4321 Mask = I.getArgOperand(2); 4322 Src0 = I.getArgOperand(3); 4323 }; 4324 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4325 MaybeAlign &Alignment) { 4326 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4327 Ptr = I.getArgOperand(0); 4328 Alignment = None; 4329 Mask = I.getArgOperand(1); 4330 Src0 = I.getArgOperand(2); 4331 }; 4332 4333 Value *PtrOperand, *MaskOperand, *Src0Operand; 4334 MaybeAlign Alignment; 4335 if (IsExpanding) 4336 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4337 else 4338 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4339 4340 SDValue Ptr = getValue(PtrOperand); 4341 SDValue Src0 = getValue(Src0Operand); 4342 SDValue Mask = getValue(MaskOperand); 4343 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4344 4345 EVT VT = Src0.getValueType(); 4346 if (!Alignment) 4347 Alignment = DAG.getEVTAlign(VT); 4348 4349 AAMDNodes AAInfo; 4350 I.getAAMetadata(AAInfo); 4351 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4352 4353 // Do not serialize masked loads of constant memory with anything. 4354 MemoryLocation ML; 4355 if (VT.isScalableVector()) 4356 ML = MemoryLocation(PtrOperand, LocationSize::unknown()); 4357 else 4358 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4359 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4360 AAInfo); 4361 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4362 4363 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4364 4365 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4366 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4367 // TODO: Make MachineMemOperands aware of scalable 4368 // vectors. 4369 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4370 4371 SDValue Load = 4372 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4373 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4374 if (AddToChain) 4375 PendingLoads.push_back(Load.getValue(1)); 4376 setValue(&I, Load); 4377 } 4378 4379 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4380 SDLoc sdl = getCurSDLoc(); 4381 4382 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4383 const Value *Ptr = I.getArgOperand(0); 4384 SDValue Src0 = getValue(I.getArgOperand(3)); 4385 SDValue Mask = getValue(I.getArgOperand(2)); 4386 4387 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4388 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4389 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4390 ->getMaybeAlignValue() 4391 .getValueOr(DAG.getEVTAlign(VT)); 4392 4393 AAMDNodes AAInfo; 4394 I.getAAMetadata(AAInfo); 4395 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4396 4397 SDValue Root = DAG.getRoot(); 4398 SDValue Base; 4399 SDValue Index; 4400 ISD::MemIndexType IndexType; 4401 SDValue Scale; 4402 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4403 I.getParent()); 4404 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4405 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4406 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4407 // TODO: Make MachineMemOperands aware of scalable 4408 // vectors. 4409 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4410 4411 if (!UniformBase) { 4412 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4413 Index = getValue(Ptr); 4414 IndexType = ISD::SIGNED_SCALED; 4415 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4416 } 4417 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4418 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4419 Ops, MMO, IndexType); 4420 4421 PendingLoads.push_back(Gather.getValue(1)); 4422 setValue(&I, Gather); 4423 } 4424 4425 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4426 SDLoc dl = getCurSDLoc(); 4427 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4428 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4429 SyncScope::ID SSID = I.getSyncScopeID(); 4430 4431 SDValue InChain = getRoot(); 4432 4433 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4434 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4435 4436 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4437 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4438 4439 MachineFunction &MF = DAG.getMachineFunction(); 4440 MachineMemOperand *MMO = MF.getMachineMemOperand( 4441 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4442 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4443 FailureOrdering); 4444 4445 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4446 dl, MemVT, VTs, InChain, 4447 getValue(I.getPointerOperand()), 4448 getValue(I.getCompareOperand()), 4449 getValue(I.getNewValOperand()), MMO); 4450 4451 SDValue OutChain = L.getValue(2); 4452 4453 setValue(&I, L); 4454 DAG.setRoot(OutChain); 4455 } 4456 4457 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4458 SDLoc dl = getCurSDLoc(); 4459 ISD::NodeType NT; 4460 switch (I.getOperation()) { 4461 default: llvm_unreachable("Unknown atomicrmw operation"); 4462 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4463 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4464 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4465 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4466 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4467 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4468 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4469 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4470 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4471 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4472 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4473 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4474 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4475 } 4476 AtomicOrdering Ordering = I.getOrdering(); 4477 SyncScope::ID SSID = I.getSyncScopeID(); 4478 4479 SDValue InChain = getRoot(); 4480 4481 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4482 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4483 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4484 4485 MachineFunction &MF = DAG.getMachineFunction(); 4486 MachineMemOperand *MMO = MF.getMachineMemOperand( 4487 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4488 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4489 4490 SDValue L = 4491 DAG.getAtomic(NT, dl, MemVT, InChain, 4492 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4493 MMO); 4494 4495 SDValue OutChain = L.getValue(1); 4496 4497 setValue(&I, L); 4498 DAG.setRoot(OutChain); 4499 } 4500 4501 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4502 SDLoc dl = getCurSDLoc(); 4503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4504 SDValue Ops[3]; 4505 Ops[0] = getRoot(); 4506 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4507 TLI.getFenceOperandTy(DAG.getDataLayout())); 4508 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4509 TLI.getFenceOperandTy(DAG.getDataLayout())); 4510 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4511 } 4512 4513 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4514 SDLoc dl = getCurSDLoc(); 4515 AtomicOrdering Order = I.getOrdering(); 4516 SyncScope::ID SSID = I.getSyncScopeID(); 4517 4518 SDValue InChain = getRoot(); 4519 4520 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4521 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4522 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4523 4524 if (!TLI.supportsUnalignedAtomics() && 4525 I.getAlignment() < MemVT.getSizeInBits() / 8) 4526 report_fatal_error("Cannot generate unaligned atomic load"); 4527 4528 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4529 4530 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4531 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4532 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4533 4534 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4535 4536 SDValue Ptr = getValue(I.getPointerOperand()); 4537 4538 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4539 // TODO: Once this is better exercised by tests, it should be merged with 4540 // the normal path for loads to prevent future divergence. 4541 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4542 if (MemVT != VT) 4543 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4544 4545 setValue(&I, L); 4546 SDValue OutChain = L.getValue(1); 4547 if (!I.isUnordered()) 4548 DAG.setRoot(OutChain); 4549 else 4550 PendingLoads.push_back(OutChain); 4551 return; 4552 } 4553 4554 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4555 Ptr, MMO); 4556 4557 SDValue OutChain = L.getValue(1); 4558 if (MemVT != VT) 4559 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4560 4561 setValue(&I, L); 4562 DAG.setRoot(OutChain); 4563 } 4564 4565 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4566 SDLoc dl = getCurSDLoc(); 4567 4568 AtomicOrdering Ordering = I.getOrdering(); 4569 SyncScope::ID SSID = I.getSyncScopeID(); 4570 4571 SDValue InChain = getRoot(); 4572 4573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4574 EVT MemVT = 4575 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4576 4577 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4578 report_fatal_error("Cannot generate unaligned atomic store"); 4579 4580 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4581 4582 MachineFunction &MF = DAG.getMachineFunction(); 4583 MachineMemOperand *MMO = MF.getMachineMemOperand( 4584 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4585 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4586 4587 SDValue Val = getValue(I.getValueOperand()); 4588 if (Val.getValueType() != MemVT) 4589 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4590 SDValue Ptr = getValue(I.getPointerOperand()); 4591 4592 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4593 // TODO: Once this is better exercised by tests, it should be merged with 4594 // the normal path for stores to prevent future divergence. 4595 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4596 DAG.setRoot(S); 4597 return; 4598 } 4599 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4600 Ptr, Val, MMO); 4601 4602 4603 DAG.setRoot(OutChain); 4604 } 4605 4606 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4607 /// node. 4608 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4609 unsigned Intrinsic) { 4610 // Ignore the callsite's attributes. A specific call site may be marked with 4611 // readnone, but the lowering code will expect the chain based on the 4612 // definition. 4613 const Function *F = I.getCalledFunction(); 4614 bool HasChain = !F->doesNotAccessMemory(); 4615 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4616 4617 // Build the operand list. 4618 SmallVector<SDValue, 8> Ops; 4619 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4620 if (OnlyLoad) { 4621 // We don't need to serialize loads against other loads. 4622 Ops.push_back(DAG.getRoot()); 4623 } else { 4624 Ops.push_back(getRoot()); 4625 } 4626 } 4627 4628 // Info is set by getTgtMemInstrinsic 4629 TargetLowering::IntrinsicInfo Info; 4630 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4631 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4632 DAG.getMachineFunction(), 4633 Intrinsic); 4634 4635 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4636 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4637 Info.opc == ISD::INTRINSIC_W_CHAIN) 4638 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4639 TLI.getPointerTy(DAG.getDataLayout()))); 4640 4641 // Add all operands of the call to the operand list. 4642 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4643 const Value *Arg = I.getArgOperand(i); 4644 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4645 Ops.push_back(getValue(Arg)); 4646 continue; 4647 } 4648 4649 // Use TargetConstant instead of a regular constant for immarg. 4650 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4651 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4652 assert(CI->getBitWidth() <= 64 && 4653 "large intrinsic immediates not handled"); 4654 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4655 } else { 4656 Ops.push_back( 4657 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4658 } 4659 } 4660 4661 SmallVector<EVT, 4> ValueVTs; 4662 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4663 4664 if (HasChain) 4665 ValueVTs.push_back(MVT::Other); 4666 4667 SDVTList VTs = DAG.getVTList(ValueVTs); 4668 4669 // Create the node. 4670 SDValue Result; 4671 if (IsTgtIntrinsic) { 4672 // This is target intrinsic that touches memory 4673 AAMDNodes AAInfo; 4674 I.getAAMetadata(AAInfo); 4675 Result = 4676 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4677 MachinePointerInfo(Info.ptrVal, Info.offset), 4678 Info.align, Info.flags, Info.size, AAInfo); 4679 } else if (!HasChain) { 4680 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4681 } else if (!I.getType()->isVoidTy()) { 4682 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4683 } else { 4684 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4685 } 4686 4687 if (HasChain) { 4688 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4689 if (OnlyLoad) 4690 PendingLoads.push_back(Chain); 4691 else 4692 DAG.setRoot(Chain); 4693 } 4694 4695 if (!I.getType()->isVoidTy()) { 4696 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4697 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4698 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4699 } else 4700 Result = lowerRangeToAssertZExt(DAG, I, Result); 4701 4702 MaybeAlign Alignment = I.getRetAlign(); 4703 if (!Alignment) 4704 Alignment = F->getAttributes().getRetAlignment(); 4705 // Insert `assertalign` node if there's an alignment. 4706 if (InsertAssertAlign && Alignment) { 4707 Result = 4708 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4709 } 4710 4711 setValue(&I, Result); 4712 } 4713 } 4714 4715 /// GetSignificand - Get the significand and build it into a floating-point 4716 /// number with exponent of 1: 4717 /// 4718 /// Op = (Op & 0x007fffff) | 0x3f800000; 4719 /// 4720 /// where Op is the hexadecimal representation of floating point value. 4721 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4722 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4723 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4724 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4725 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4726 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4727 } 4728 4729 /// GetExponent - Get the exponent: 4730 /// 4731 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4732 /// 4733 /// where Op is the hexadecimal representation of floating point value. 4734 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4735 const TargetLowering &TLI, const SDLoc &dl) { 4736 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4737 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4738 SDValue t1 = DAG.getNode( 4739 ISD::SRL, dl, MVT::i32, t0, 4740 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4741 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4742 DAG.getConstant(127, dl, MVT::i32)); 4743 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4744 } 4745 4746 /// getF32Constant - Get 32-bit floating point constant. 4747 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4748 const SDLoc &dl) { 4749 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4750 MVT::f32); 4751 } 4752 4753 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4754 SelectionDAG &DAG) { 4755 // TODO: What fast-math-flags should be set on the floating-point nodes? 4756 4757 // IntegerPartOfX = ((int32_t)(t0); 4758 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4759 4760 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4761 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4762 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4763 4764 // IntegerPartOfX <<= 23; 4765 IntegerPartOfX = DAG.getNode( 4766 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4767 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4768 DAG.getDataLayout()))); 4769 4770 SDValue TwoToFractionalPartOfX; 4771 if (LimitFloatPrecision <= 6) { 4772 // For floating-point precision of 6: 4773 // 4774 // TwoToFractionalPartOfX = 4775 // 0.997535578f + 4776 // (0.735607626f + 0.252464424f * x) * x; 4777 // 4778 // error 0.0144103317, which is 6 bits 4779 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4780 getF32Constant(DAG, 0x3e814304, dl)); 4781 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4782 getF32Constant(DAG, 0x3f3c50c8, dl)); 4783 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4784 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4785 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4786 } else if (LimitFloatPrecision <= 12) { 4787 // For floating-point precision of 12: 4788 // 4789 // TwoToFractionalPartOfX = 4790 // 0.999892986f + 4791 // (0.696457318f + 4792 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4793 // 4794 // error 0.000107046256, which is 13 to 14 bits 4795 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4796 getF32Constant(DAG, 0x3da235e3, dl)); 4797 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4798 getF32Constant(DAG, 0x3e65b8f3, dl)); 4799 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4800 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4801 getF32Constant(DAG, 0x3f324b07, dl)); 4802 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4803 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4804 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4805 } else { // LimitFloatPrecision <= 18 4806 // For floating-point precision of 18: 4807 // 4808 // TwoToFractionalPartOfX = 4809 // 0.999999982f + 4810 // (0.693148872f + 4811 // (0.240227044f + 4812 // (0.554906021e-1f + 4813 // (0.961591928e-2f + 4814 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4815 // error 2.47208000*10^(-7), which is better than 18 bits 4816 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4817 getF32Constant(DAG, 0x3924b03e, dl)); 4818 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4819 getF32Constant(DAG, 0x3ab24b87, dl)); 4820 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4821 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4822 getF32Constant(DAG, 0x3c1d8c17, dl)); 4823 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4824 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4825 getF32Constant(DAG, 0x3d634a1d, dl)); 4826 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4827 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4828 getF32Constant(DAG, 0x3e75fe14, dl)); 4829 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4830 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4831 getF32Constant(DAG, 0x3f317234, dl)); 4832 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4833 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4834 getF32Constant(DAG, 0x3f800000, dl)); 4835 } 4836 4837 // Add the exponent into the result in integer domain. 4838 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4839 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4840 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4841 } 4842 4843 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4844 /// limited-precision mode. 4845 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4846 const TargetLowering &TLI, SDNodeFlags Flags) { 4847 if (Op.getValueType() == MVT::f32 && 4848 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4849 4850 // Put the exponent in the right bit position for later addition to the 4851 // final result: 4852 // 4853 // t0 = Op * log2(e) 4854 4855 // TODO: What fast-math-flags should be set here? 4856 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4857 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4858 return getLimitedPrecisionExp2(t0, dl, DAG); 4859 } 4860 4861 // No special expansion. 4862 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4863 } 4864 4865 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4866 /// limited-precision mode. 4867 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4868 const TargetLowering &TLI, SDNodeFlags Flags) { 4869 // TODO: What fast-math-flags should be set on the floating-point nodes? 4870 4871 if (Op.getValueType() == MVT::f32 && 4872 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4873 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4874 4875 // Scale the exponent by log(2). 4876 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4877 SDValue LogOfExponent = 4878 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4879 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4880 4881 // Get the significand and build it into a floating-point number with 4882 // exponent of 1. 4883 SDValue X = GetSignificand(DAG, Op1, dl); 4884 4885 SDValue LogOfMantissa; 4886 if (LimitFloatPrecision <= 6) { 4887 // For floating-point precision of 6: 4888 // 4889 // LogofMantissa = 4890 // -1.1609546f + 4891 // (1.4034025f - 0.23903021f * x) * x; 4892 // 4893 // error 0.0034276066, which is better than 8 bits 4894 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4895 getF32Constant(DAG, 0xbe74c456, dl)); 4896 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4897 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4898 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4899 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4900 getF32Constant(DAG, 0x3f949a29, dl)); 4901 } else if (LimitFloatPrecision <= 12) { 4902 // For floating-point precision of 12: 4903 // 4904 // LogOfMantissa = 4905 // -1.7417939f + 4906 // (2.8212026f + 4907 // (-1.4699568f + 4908 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4909 // 4910 // error 0.000061011436, which is 14 bits 4911 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4912 getF32Constant(DAG, 0xbd67b6d6, dl)); 4913 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4914 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4915 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4916 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4917 getF32Constant(DAG, 0x3fbc278b, dl)); 4918 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4919 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4920 getF32Constant(DAG, 0x40348e95, dl)); 4921 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4922 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4923 getF32Constant(DAG, 0x3fdef31a, dl)); 4924 } else { // LimitFloatPrecision <= 18 4925 // For floating-point precision of 18: 4926 // 4927 // LogOfMantissa = 4928 // -2.1072184f + 4929 // (4.2372794f + 4930 // (-3.7029485f + 4931 // (2.2781945f + 4932 // (-0.87823314f + 4933 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4934 // 4935 // error 0.0000023660568, which is better than 18 bits 4936 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4937 getF32Constant(DAG, 0xbc91e5ac, dl)); 4938 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4939 getF32Constant(DAG, 0x3e4350aa, dl)); 4940 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4941 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4942 getF32Constant(DAG, 0x3f60d3e3, dl)); 4943 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4944 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4945 getF32Constant(DAG, 0x4011cdf0, dl)); 4946 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4947 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4948 getF32Constant(DAG, 0x406cfd1c, dl)); 4949 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4950 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4951 getF32Constant(DAG, 0x408797cb, dl)); 4952 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4953 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4954 getF32Constant(DAG, 0x4006dcab, dl)); 4955 } 4956 4957 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4958 } 4959 4960 // No special expansion. 4961 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 4962 } 4963 4964 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4965 /// limited-precision mode. 4966 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4967 const TargetLowering &TLI, SDNodeFlags Flags) { 4968 // TODO: What fast-math-flags should be set on the floating-point nodes? 4969 4970 if (Op.getValueType() == MVT::f32 && 4971 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4972 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4973 4974 // Get the exponent. 4975 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4976 4977 // Get the significand and build it into a floating-point number with 4978 // exponent of 1. 4979 SDValue X = GetSignificand(DAG, Op1, dl); 4980 4981 // Different possible minimax approximations of significand in 4982 // floating-point for various degrees of accuracy over [1,2]. 4983 SDValue Log2ofMantissa; 4984 if (LimitFloatPrecision <= 6) { 4985 // For floating-point precision of 6: 4986 // 4987 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4988 // 4989 // error 0.0049451742, which is more than 7 bits 4990 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4991 getF32Constant(DAG, 0xbeb08fe0, dl)); 4992 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4993 getF32Constant(DAG, 0x40019463, dl)); 4994 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4995 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4996 getF32Constant(DAG, 0x3fd6633d, dl)); 4997 } else if (LimitFloatPrecision <= 12) { 4998 // For floating-point precision of 12: 4999 // 5000 // Log2ofMantissa = 5001 // -2.51285454f + 5002 // (4.07009056f + 5003 // (-2.12067489f + 5004 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5005 // 5006 // error 0.0000876136000, which is better than 13 bits 5007 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5008 getF32Constant(DAG, 0xbda7262e, dl)); 5009 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5010 getF32Constant(DAG, 0x3f25280b, dl)); 5011 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5012 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5013 getF32Constant(DAG, 0x4007b923, dl)); 5014 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5015 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5016 getF32Constant(DAG, 0x40823e2f, dl)); 5017 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5018 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5019 getF32Constant(DAG, 0x4020d29c, dl)); 5020 } else { // LimitFloatPrecision <= 18 5021 // For floating-point precision of 18: 5022 // 5023 // Log2ofMantissa = 5024 // -3.0400495f + 5025 // (6.1129976f + 5026 // (-5.3420409f + 5027 // (3.2865683f + 5028 // (-1.2669343f + 5029 // (0.27515199f - 5030 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5031 // 5032 // error 0.0000018516, which is better than 18 bits 5033 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5034 getF32Constant(DAG, 0xbcd2769e, dl)); 5035 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5036 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5037 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5038 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5039 getF32Constant(DAG, 0x3fa22ae7, dl)); 5040 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5041 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5042 getF32Constant(DAG, 0x40525723, dl)); 5043 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5044 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5045 getF32Constant(DAG, 0x40aaf200, dl)); 5046 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5047 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5048 getF32Constant(DAG, 0x40c39dad, dl)); 5049 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5050 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5051 getF32Constant(DAG, 0x4042902c, dl)); 5052 } 5053 5054 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5055 } 5056 5057 // No special expansion. 5058 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5059 } 5060 5061 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5062 /// limited-precision mode. 5063 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5064 const TargetLowering &TLI, SDNodeFlags Flags) { 5065 // TODO: What fast-math-flags should be set on the floating-point nodes? 5066 5067 if (Op.getValueType() == MVT::f32 && 5068 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5069 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5070 5071 // Scale the exponent by log10(2) [0.30102999f]. 5072 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5073 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5074 getF32Constant(DAG, 0x3e9a209a, dl)); 5075 5076 // Get the significand and build it into a floating-point number with 5077 // exponent of 1. 5078 SDValue X = GetSignificand(DAG, Op1, dl); 5079 5080 SDValue Log10ofMantissa; 5081 if (LimitFloatPrecision <= 6) { 5082 // For floating-point precision of 6: 5083 // 5084 // Log10ofMantissa = 5085 // -0.50419619f + 5086 // (0.60948995f - 0.10380950f * x) * x; 5087 // 5088 // error 0.0014886165, which is 6 bits 5089 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5090 getF32Constant(DAG, 0xbdd49a13, dl)); 5091 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5092 getF32Constant(DAG, 0x3f1c0789, dl)); 5093 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5094 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5095 getF32Constant(DAG, 0x3f011300, dl)); 5096 } else if (LimitFloatPrecision <= 12) { 5097 // For floating-point precision of 12: 5098 // 5099 // Log10ofMantissa = 5100 // -0.64831180f + 5101 // (0.91751397f + 5102 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5103 // 5104 // error 0.00019228036, which is better than 12 bits 5105 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5106 getF32Constant(DAG, 0x3d431f31, dl)); 5107 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5108 getF32Constant(DAG, 0x3ea21fb2, dl)); 5109 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5110 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5111 getF32Constant(DAG, 0x3f6ae232, dl)); 5112 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5113 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5114 getF32Constant(DAG, 0x3f25f7c3, dl)); 5115 } else { // LimitFloatPrecision <= 18 5116 // For floating-point precision of 18: 5117 // 5118 // Log10ofMantissa = 5119 // -0.84299375f + 5120 // (1.5327582f + 5121 // (-1.0688956f + 5122 // (0.49102474f + 5123 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5124 // 5125 // error 0.0000037995730, which is better than 18 bits 5126 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5127 getF32Constant(DAG, 0x3c5d51ce, dl)); 5128 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5129 getF32Constant(DAG, 0x3e00685a, dl)); 5130 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5131 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5132 getF32Constant(DAG, 0x3efb6798, dl)); 5133 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5134 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5135 getF32Constant(DAG, 0x3f88d192, dl)); 5136 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5137 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5138 getF32Constant(DAG, 0x3fc4316c, dl)); 5139 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5140 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5141 getF32Constant(DAG, 0x3f57ce70, dl)); 5142 } 5143 5144 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5145 } 5146 5147 // No special expansion. 5148 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5149 } 5150 5151 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5152 /// limited-precision mode. 5153 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5154 const TargetLowering &TLI, SDNodeFlags Flags) { 5155 if (Op.getValueType() == MVT::f32 && 5156 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5157 return getLimitedPrecisionExp2(Op, dl, DAG); 5158 5159 // No special expansion. 5160 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5161 } 5162 5163 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5164 /// limited-precision mode with x == 10.0f. 5165 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5166 SelectionDAG &DAG, const TargetLowering &TLI, 5167 SDNodeFlags Flags) { 5168 bool IsExp10 = false; 5169 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5170 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5171 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5172 APFloat Ten(10.0f); 5173 IsExp10 = LHSC->isExactlyValue(Ten); 5174 } 5175 } 5176 5177 // TODO: What fast-math-flags should be set on the FMUL node? 5178 if (IsExp10) { 5179 // Put the exponent in the right bit position for later addition to the 5180 // final result: 5181 // 5182 // #define LOG2OF10 3.3219281f 5183 // t0 = Op * LOG2OF10; 5184 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5185 getF32Constant(DAG, 0x40549a78, dl)); 5186 return getLimitedPrecisionExp2(t0, dl, DAG); 5187 } 5188 5189 // No special expansion. 5190 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5191 } 5192 5193 /// ExpandPowI - Expand a llvm.powi intrinsic. 5194 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5195 SelectionDAG &DAG) { 5196 // If RHS is a constant, we can expand this out to a multiplication tree, 5197 // otherwise we end up lowering to a call to __powidf2 (for example). When 5198 // optimizing for size, we only want to do this if the expansion would produce 5199 // a small number of multiplies, otherwise we do the full expansion. 5200 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5201 // Get the exponent as a positive value. 5202 unsigned Val = RHSC->getSExtValue(); 5203 if ((int)Val < 0) Val = -Val; 5204 5205 // powi(x, 0) -> 1.0 5206 if (Val == 0) 5207 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5208 5209 bool OptForSize = DAG.shouldOptForSize(); 5210 if (!OptForSize || 5211 // If optimizing for size, don't insert too many multiplies. 5212 // This inserts up to 5 multiplies. 5213 countPopulation(Val) + Log2_32(Val) < 7) { 5214 // We use the simple binary decomposition method to generate the multiply 5215 // sequence. There are more optimal ways to do this (for example, 5216 // powi(x,15) generates one more multiply than it should), but this has 5217 // the benefit of being both really simple and much better than a libcall. 5218 SDValue Res; // Logically starts equal to 1.0 5219 SDValue CurSquare = LHS; 5220 // TODO: Intrinsics should have fast-math-flags that propagate to these 5221 // nodes. 5222 while (Val) { 5223 if (Val & 1) { 5224 if (Res.getNode()) 5225 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5226 else 5227 Res = CurSquare; // 1.0*CurSquare. 5228 } 5229 5230 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5231 CurSquare, CurSquare); 5232 Val >>= 1; 5233 } 5234 5235 // If the original was negative, invert the result, producing 1/(x*x*x). 5236 if (RHSC->getSExtValue() < 0) 5237 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5238 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5239 return Res; 5240 } 5241 } 5242 5243 // Otherwise, expand to a libcall. 5244 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5245 } 5246 5247 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5248 SDValue LHS, SDValue RHS, SDValue Scale, 5249 SelectionDAG &DAG, const TargetLowering &TLI) { 5250 EVT VT = LHS.getValueType(); 5251 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5252 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5253 LLVMContext &Ctx = *DAG.getContext(); 5254 5255 // If the type is legal but the operation isn't, this node might survive all 5256 // the way to operation legalization. If we end up there and we do not have 5257 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5258 // node. 5259 5260 // Coax the legalizer into expanding the node during type legalization instead 5261 // by bumping the size by one bit. This will force it to Promote, enabling the 5262 // early expansion and avoiding the need to expand later. 5263 5264 // We don't have to do this if Scale is 0; that can always be expanded, unless 5265 // it's a saturating signed operation. Those can experience true integer 5266 // division overflow, a case which we must avoid. 5267 5268 // FIXME: We wouldn't have to do this (or any of the early 5269 // expansion/promotion) if it was possible to expand a libcall of an 5270 // illegal type during operation legalization. But it's not, so things 5271 // get a bit hacky. 5272 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5273 if ((ScaleInt > 0 || (Saturating && Signed)) && 5274 (TLI.isTypeLegal(VT) || 5275 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5276 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5277 Opcode, VT, ScaleInt); 5278 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5279 EVT PromVT; 5280 if (VT.isScalarInteger()) 5281 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5282 else if (VT.isVector()) { 5283 PromVT = VT.getVectorElementType(); 5284 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5285 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5286 } else 5287 llvm_unreachable("Wrong VT for DIVFIX?"); 5288 if (Signed) { 5289 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5290 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5291 } else { 5292 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5293 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5294 } 5295 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5296 // For saturating operations, we need to shift up the LHS to get the 5297 // proper saturation width, and then shift down again afterwards. 5298 if (Saturating) 5299 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5300 DAG.getConstant(1, DL, ShiftTy)); 5301 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5302 if (Saturating) 5303 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5304 DAG.getConstant(1, DL, ShiftTy)); 5305 return DAG.getZExtOrTrunc(Res, DL, VT); 5306 } 5307 } 5308 5309 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5310 } 5311 5312 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5313 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5314 static void 5315 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5316 const SDValue &N) { 5317 switch (N.getOpcode()) { 5318 case ISD::CopyFromReg: { 5319 SDValue Op = N.getOperand(1); 5320 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5321 Op.getValueType().getSizeInBits()); 5322 return; 5323 } 5324 case ISD::BITCAST: 5325 case ISD::AssertZext: 5326 case ISD::AssertSext: 5327 case ISD::TRUNCATE: 5328 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5329 return; 5330 case ISD::BUILD_PAIR: 5331 case ISD::BUILD_VECTOR: 5332 case ISD::CONCAT_VECTORS: 5333 for (SDValue Op : N->op_values()) 5334 getUnderlyingArgRegs(Regs, Op); 5335 return; 5336 default: 5337 return; 5338 } 5339 } 5340 5341 /// If the DbgValueInst is a dbg_value of a function argument, create the 5342 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5343 /// instruction selection, they will be inserted to the entry BB. 5344 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5345 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5346 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5347 const Argument *Arg = dyn_cast<Argument>(V); 5348 if (!Arg) 5349 return false; 5350 5351 if (!IsDbgDeclare) { 5352 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5353 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5354 // the entry block. 5355 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5356 if (!IsInEntryBlock) 5357 return false; 5358 5359 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5360 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5361 // variable that also is a param. 5362 // 5363 // Although, if we are at the top of the entry block already, we can still 5364 // emit using ArgDbgValue. This might catch some situations when the 5365 // dbg.value refers to an argument that isn't used in the entry block, so 5366 // any CopyToReg node would be optimized out and the only way to express 5367 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5368 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5369 // we should only emit as ArgDbgValue if the Variable is an argument to the 5370 // current function, and the dbg.value intrinsic is found in the entry 5371 // block. 5372 bool VariableIsFunctionInputArg = Variable->isParameter() && 5373 !DL->getInlinedAt(); 5374 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5375 if (!IsInPrologue && !VariableIsFunctionInputArg) 5376 return false; 5377 5378 // Here we assume that a function argument on IR level only can be used to 5379 // describe one input parameter on source level. If we for example have 5380 // source code like this 5381 // 5382 // struct A { long x, y; }; 5383 // void foo(struct A a, long b) { 5384 // ... 5385 // b = a.x; 5386 // ... 5387 // } 5388 // 5389 // and IR like this 5390 // 5391 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5392 // entry: 5393 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5394 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5395 // call void @llvm.dbg.value(metadata i32 %b, "b", 5396 // ... 5397 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5398 // ... 5399 // 5400 // then the last dbg.value is describing a parameter "b" using a value that 5401 // is an argument. But since we already has used %a1 to describe a parameter 5402 // we should not handle that last dbg.value here (that would result in an 5403 // incorrect hoisting of the DBG_VALUE to the function entry). 5404 // Notice that we allow one dbg.value per IR level argument, to accommodate 5405 // for the situation with fragments above. 5406 if (VariableIsFunctionInputArg) { 5407 unsigned ArgNo = Arg->getArgNo(); 5408 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5409 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5410 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5411 return false; 5412 FuncInfo.DescribedArgs.set(ArgNo); 5413 } 5414 } 5415 5416 MachineFunction &MF = DAG.getMachineFunction(); 5417 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5418 5419 bool IsIndirect = false; 5420 Optional<MachineOperand> Op; 5421 // Some arguments' frame index is recorded during argument lowering. 5422 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5423 if (FI != std::numeric_limits<int>::max()) 5424 Op = MachineOperand::CreateFI(FI); 5425 5426 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5427 if (!Op && N.getNode()) { 5428 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5429 Register Reg; 5430 if (ArgRegsAndSizes.size() == 1) 5431 Reg = ArgRegsAndSizes.front().first; 5432 5433 if (Reg && Reg.isVirtual()) { 5434 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5435 Register PR = RegInfo.getLiveInPhysReg(Reg); 5436 if (PR) 5437 Reg = PR; 5438 } 5439 if (Reg) { 5440 Op = MachineOperand::CreateReg(Reg, false); 5441 IsIndirect = IsDbgDeclare; 5442 } 5443 } 5444 5445 if (!Op && N.getNode()) { 5446 // Check if frame index is available. 5447 SDValue LCandidate = peekThroughBitcasts(N); 5448 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5449 if (FrameIndexSDNode *FINode = 5450 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5451 Op = MachineOperand::CreateFI(FINode->getIndex()); 5452 } 5453 5454 if (!Op) { 5455 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5456 auto splitMultiRegDbgValue 5457 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5458 unsigned Offset = 0; 5459 for (auto RegAndSize : SplitRegs) { 5460 // If the expression is already a fragment, the current register 5461 // offset+size might extend beyond the fragment. In this case, only 5462 // the register bits that are inside the fragment are relevant. 5463 int RegFragmentSizeInBits = RegAndSize.second; 5464 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5465 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5466 // The register is entirely outside the expression fragment, 5467 // so is irrelevant for debug info. 5468 if (Offset >= ExprFragmentSizeInBits) 5469 break; 5470 // The register is partially outside the expression fragment, only 5471 // the low bits within the fragment are relevant for debug info. 5472 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5473 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5474 } 5475 } 5476 5477 auto FragmentExpr = DIExpression::createFragmentExpression( 5478 Expr, Offset, RegFragmentSizeInBits); 5479 Offset += RegAndSize.second; 5480 // If a valid fragment expression cannot be created, the variable's 5481 // correct value cannot be determined and so it is set as Undef. 5482 if (!FragmentExpr) { 5483 SDDbgValue *SDV = DAG.getConstantDbgValue( 5484 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5485 DAG.AddDbgValue(SDV, nullptr, false); 5486 continue; 5487 } 5488 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5489 FuncInfo.ArgDbgValues.push_back( 5490 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5491 RegAndSize.first, Variable, *FragmentExpr)); 5492 } 5493 }; 5494 5495 // Check if ValueMap has reg number. 5496 DenseMap<const Value *, Register>::const_iterator 5497 VMI = FuncInfo.ValueMap.find(V); 5498 if (VMI != FuncInfo.ValueMap.end()) { 5499 const auto &TLI = DAG.getTargetLoweringInfo(); 5500 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5501 V->getType(), None); 5502 if (RFV.occupiesMultipleRegs()) { 5503 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5504 return true; 5505 } 5506 5507 Op = MachineOperand::CreateReg(VMI->second, false); 5508 IsIndirect = IsDbgDeclare; 5509 } else if (ArgRegsAndSizes.size() > 1) { 5510 // This was split due to the calling convention, and no virtual register 5511 // mapping exists for the value. 5512 splitMultiRegDbgValue(ArgRegsAndSizes); 5513 return true; 5514 } 5515 } 5516 5517 if (!Op) 5518 return false; 5519 5520 assert(Variable->isValidLocationForIntrinsic(DL) && 5521 "Expected inlined-at fields to agree"); 5522 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5523 FuncInfo.ArgDbgValues.push_back( 5524 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5525 *Op, Variable, Expr)); 5526 5527 return true; 5528 } 5529 5530 /// Return the appropriate SDDbgValue based on N. 5531 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5532 DILocalVariable *Variable, 5533 DIExpression *Expr, 5534 const DebugLoc &dl, 5535 unsigned DbgSDNodeOrder) { 5536 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5537 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5538 // stack slot locations. 5539 // 5540 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5541 // debug values here after optimization: 5542 // 5543 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5544 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5545 // 5546 // Both describe the direct values of their associated variables. 5547 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5548 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5549 } 5550 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5551 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5552 } 5553 5554 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5555 switch (Intrinsic) { 5556 case Intrinsic::smul_fix: 5557 return ISD::SMULFIX; 5558 case Intrinsic::umul_fix: 5559 return ISD::UMULFIX; 5560 case Intrinsic::smul_fix_sat: 5561 return ISD::SMULFIXSAT; 5562 case Intrinsic::umul_fix_sat: 5563 return ISD::UMULFIXSAT; 5564 case Intrinsic::sdiv_fix: 5565 return ISD::SDIVFIX; 5566 case Intrinsic::udiv_fix: 5567 return ISD::UDIVFIX; 5568 case Intrinsic::sdiv_fix_sat: 5569 return ISD::SDIVFIXSAT; 5570 case Intrinsic::udiv_fix_sat: 5571 return ISD::UDIVFIXSAT; 5572 default: 5573 llvm_unreachable("Unhandled fixed point intrinsic"); 5574 } 5575 } 5576 5577 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5578 const char *FunctionName) { 5579 assert(FunctionName && "FunctionName must not be nullptr"); 5580 SDValue Callee = DAG.getExternalSymbol( 5581 FunctionName, 5582 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5583 LowerCallTo(I, Callee, I.isTailCall()); 5584 } 5585 5586 /// Given a @llvm.call.preallocated.setup, return the corresponding 5587 /// preallocated call. 5588 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5589 assert(cast<CallBase>(PreallocatedSetup) 5590 ->getCalledFunction() 5591 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5592 "expected call_preallocated_setup Value"); 5593 for (auto *U : PreallocatedSetup->users()) { 5594 auto *UseCall = cast<CallBase>(U); 5595 const Function *Fn = UseCall->getCalledFunction(); 5596 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5597 return UseCall; 5598 } 5599 } 5600 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5601 } 5602 5603 /// Lower the call to the specified intrinsic function. 5604 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5605 unsigned Intrinsic) { 5606 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5607 SDLoc sdl = getCurSDLoc(); 5608 DebugLoc dl = getCurDebugLoc(); 5609 SDValue Res; 5610 5611 SDNodeFlags Flags; 5612 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5613 Flags.copyFMF(*FPOp); 5614 5615 switch (Intrinsic) { 5616 default: 5617 // By default, turn this into a target intrinsic node. 5618 visitTargetIntrinsic(I, Intrinsic); 5619 return; 5620 case Intrinsic::vscale: { 5621 match(&I, m_VScale(DAG.getDataLayout())); 5622 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5623 setValue(&I, 5624 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5625 return; 5626 } 5627 case Intrinsic::vastart: visitVAStart(I); return; 5628 case Intrinsic::vaend: visitVAEnd(I); return; 5629 case Intrinsic::vacopy: visitVACopy(I); return; 5630 case Intrinsic::returnaddress: 5631 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5632 TLI.getPointerTy(DAG.getDataLayout()), 5633 getValue(I.getArgOperand(0)))); 5634 return; 5635 case Intrinsic::addressofreturnaddress: 5636 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5637 TLI.getPointerTy(DAG.getDataLayout()))); 5638 return; 5639 case Intrinsic::sponentry: 5640 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5641 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5642 return; 5643 case Intrinsic::frameaddress: 5644 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5645 TLI.getFrameIndexTy(DAG.getDataLayout()), 5646 getValue(I.getArgOperand(0)))); 5647 return; 5648 case Intrinsic::read_volatile_register: 5649 case Intrinsic::read_register: { 5650 Value *Reg = I.getArgOperand(0); 5651 SDValue Chain = getRoot(); 5652 SDValue RegName = 5653 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5654 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5655 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5656 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5657 setValue(&I, Res); 5658 DAG.setRoot(Res.getValue(1)); 5659 return; 5660 } 5661 case Intrinsic::write_register: { 5662 Value *Reg = I.getArgOperand(0); 5663 Value *RegValue = I.getArgOperand(1); 5664 SDValue Chain = getRoot(); 5665 SDValue RegName = 5666 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5667 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5668 RegName, getValue(RegValue))); 5669 return; 5670 } 5671 case Intrinsic::memcpy: { 5672 const auto &MCI = cast<MemCpyInst>(I); 5673 SDValue Op1 = getValue(I.getArgOperand(0)); 5674 SDValue Op2 = getValue(I.getArgOperand(1)); 5675 SDValue Op3 = getValue(I.getArgOperand(2)); 5676 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5677 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5678 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5679 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5680 bool isVol = MCI.isVolatile(); 5681 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5682 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5683 // node. 5684 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5685 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5686 /* AlwaysInline */ false, isTC, 5687 MachinePointerInfo(I.getArgOperand(0)), 5688 MachinePointerInfo(I.getArgOperand(1))); 5689 updateDAGForMaybeTailCall(MC); 5690 return; 5691 } 5692 case Intrinsic::memcpy_inline: { 5693 const auto &MCI = cast<MemCpyInlineInst>(I); 5694 SDValue Dst = getValue(I.getArgOperand(0)); 5695 SDValue Src = getValue(I.getArgOperand(1)); 5696 SDValue Size = getValue(I.getArgOperand(2)); 5697 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5698 // @llvm.memcpy.inline 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 MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5707 /* AlwaysInline */ true, isTC, 5708 MachinePointerInfo(I.getArgOperand(0)), 5709 MachinePointerInfo(I.getArgOperand(1))); 5710 updateDAGForMaybeTailCall(MC); 5711 return; 5712 } 5713 case Intrinsic::memset: { 5714 const auto &MSI = cast<MemSetInst>(I); 5715 SDValue Op1 = getValue(I.getArgOperand(0)); 5716 SDValue Op2 = getValue(I.getArgOperand(1)); 5717 SDValue Op3 = getValue(I.getArgOperand(2)); 5718 // @llvm.memset defines 0 and 1 to both mean no alignment. 5719 Align Alignment = MSI.getDestAlign().valueOrOne(); 5720 bool isVol = MSI.isVolatile(); 5721 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5722 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5723 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5724 MachinePointerInfo(I.getArgOperand(0))); 5725 updateDAGForMaybeTailCall(MS); 5726 return; 5727 } 5728 case Intrinsic::memmove: { 5729 const auto &MMI = cast<MemMoveInst>(I); 5730 SDValue Op1 = getValue(I.getArgOperand(0)); 5731 SDValue Op2 = getValue(I.getArgOperand(1)); 5732 SDValue Op3 = getValue(I.getArgOperand(2)); 5733 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5734 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5735 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5736 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5737 bool isVol = MMI.isVolatile(); 5738 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5739 // FIXME: Support passing different dest/src alignments to the memmove DAG 5740 // node. 5741 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5742 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5743 isTC, MachinePointerInfo(I.getArgOperand(0)), 5744 MachinePointerInfo(I.getArgOperand(1))); 5745 updateDAGForMaybeTailCall(MM); 5746 return; 5747 } 5748 case Intrinsic::memcpy_element_unordered_atomic: { 5749 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5750 SDValue Dst = getValue(MI.getRawDest()); 5751 SDValue Src = getValue(MI.getRawSource()); 5752 SDValue Length = getValue(MI.getLength()); 5753 5754 unsigned DstAlign = MI.getDestAlignment(); 5755 unsigned SrcAlign = MI.getSourceAlignment(); 5756 Type *LengthTy = MI.getLength()->getType(); 5757 unsigned ElemSz = MI.getElementSizeInBytes(); 5758 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5759 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5760 SrcAlign, Length, LengthTy, ElemSz, isTC, 5761 MachinePointerInfo(MI.getRawDest()), 5762 MachinePointerInfo(MI.getRawSource())); 5763 updateDAGForMaybeTailCall(MC); 5764 return; 5765 } 5766 case Intrinsic::memmove_element_unordered_atomic: { 5767 auto &MI = cast<AtomicMemMoveInst>(I); 5768 SDValue Dst = getValue(MI.getRawDest()); 5769 SDValue Src = getValue(MI.getRawSource()); 5770 SDValue Length = getValue(MI.getLength()); 5771 5772 unsigned DstAlign = MI.getDestAlignment(); 5773 unsigned SrcAlign = MI.getSourceAlignment(); 5774 Type *LengthTy = MI.getLength()->getType(); 5775 unsigned ElemSz = MI.getElementSizeInBytes(); 5776 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5777 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5778 SrcAlign, Length, LengthTy, ElemSz, isTC, 5779 MachinePointerInfo(MI.getRawDest()), 5780 MachinePointerInfo(MI.getRawSource())); 5781 updateDAGForMaybeTailCall(MC); 5782 return; 5783 } 5784 case Intrinsic::memset_element_unordered_atomic: { 5785 auto &MI = cast<AtomicMemSetInst>(I); 5786 SDValue Dst = getValue(MI.getRawDest()); 5787 SDValue Val = getValue(MI.getValue()); 5788 SDValue Length = getValue(MI.getLength()); 5789 5790 unsigned DstAlign = MI.getDestAlignment(); 5791 Type *LengthTy = MI.getLength()->getType(); 5792 unsigned ElemSz = MI.getElementSizeInBytes(); 5793 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5794 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5795 LengthTy, ElemSz, isTC, 5796 MachinePointerInfo(MI.getRawDest())); 5797 updateDAGForMaybeTailCall(MC); 5798 return; 5799 } 5800 case Intrinsic::call_preallocated_setup: { 5801 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5802 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5803 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5804 getRoot(), SrcValue); 5805 setValue(&I, Res); 5806 DAG.setRoot(Res); 5807 return; 5808 } 5809 case Intrinsic::call_preallocated_arg: { 5810 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5811 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5812 SDValue Ops[3]; 5813 Ops[0] = getRoot(); 5814 Ops[1] = SrcValue; 5815 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5816 MVT::i32); // arg index 5817 SDValue Res = DAG.getNode( 5818 ISD::PREALLOCATED_ARG, sdl, 5819 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5820 setValue(&I, Res); 5821 DAG.setRoot(Res.getValue(1)); 5822 return; 5823 } 5824 case Intrinsic::dbg_addr: 5825 case Intrinsic::dbg_declare: { 5826 const auto &DI = cast<DbgVariableIntrinsic>(I); 5827 DILocalVariable *Variable = DI.getVariable(); 5828 DIExpression *Expression = DI.getExpression(); 5829 dropDanglingDebugInfo(Variable, Expression); 5830 assert(Variable && "Missing variable"); 5831 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5832 << "\n"); 5833 // Check if address has undef value. 5834 const Value *Address = DI.getVariableLocation(); 5835 if (!Address || isa<UndefValue>(Address) || 5836 (Address->use_empty() && !isa<Argument>(Address))) { 5837 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5838 << " (bad/undef/unused-arg address)\n"); 5839 return; 5840 } 5841 5842 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5843 5844 // Check if this variable can be described by a frame index, typically 5845 // either as a static alloca or a byval parameter. 5846 int FI = std::numeric_limits<int>::max(); 5847 if (const auto *AI = 5848 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5849 if (AI->isStaticAlloca()) { 5850 auto I = FuncInfo.StaticAllocaMap.find(AI); 5851 if (I != FuncInfo.StaticAllocaMap.end()) 5852 FI = I->second; 5853 } 5854 } else if (const auto *Arg = dyn_cast<Argument>( 5855 Address->stripInBoundsConstantOffsets())) { 5856 FI = FuncInfo.getArgumentFrameIndex(Arg); 5857 } 5858 5859 // llvm.dbg.addr is control dependent and always generates indirect 5860 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5861 // the MachineFunction variable table. 5862 if (FI != std::numeric_limits<int>::max()) { 5863 if (Intrinsic == Intrinsic::dbg_addr) { 5864 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5865 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5866 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5867 } else { 5868 LLVM_DEBUG(dbgs() << "Skipping " << DI 5869 << " (variable info stashed in MF side table)\n"); 5870 } 5871 return; 5872 } 5873 5874 SDValue &N = NodeMap[Address]; 5875 if (!N.getNode() && isa<Argument>(Address)) 5876 // Check unused arguments map. 5877 N = UnusedArgNodeMap[Address]; 5878 SDDbgValue *SDV; 5879 if (N.getNode()) { 5880 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5881 Address = BCI->getOperand(0); 5882 // Parameters are handled specially. 5883 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5884 if (isParameter && FINode) { 5885 // Byval parameter. We have a frame index at this point. 5886 SDV = 5887 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5888 /*IsIndirect*/ true, dl, SDNodeOrder); 5889 } else if (isa<Argument>(Address)) { 5890 // Address is an argument, so try to emit its dbg value using 5891 // virtual register info from the FuncInfo.ValueMap. 5892 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5893 return; 5894 } else { 5895 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5896 true, dl, SDNodeOrder); 5897 } 5898 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5899 } else { 5900 // If Address is an argument then try to emit its dbg value using 5901 // virtual register info from the FuncInfo.ValueMap. 5902 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5903 N)) { 5904 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5905 << " (could not emit func-arg dbg_value)\n"); 5906 } 5907 } 5908 return; 5909 } 5910 case Intrinsic::dbg_label: { 5911 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5912 DILabel *Label = DI.getLabel(); 5913 assert(Label && "Missing label"); 5914 5915 SDDbgLabel *SDV; 5916 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5917 DAG.AddDbgLabel(SDV); 5918 return; 5919 } 5920 case Intrinsic::dbg_value: { 5921 const DbgValueInst &DI = cast<DbgValueInst>(I); 5922 assert(DI.getVariable() && "Missing variable"); 5923 5924 DILocalVariable *Variable = DI.getVariable(); 5925 DIExpression *Expression = DI.getExpression(); 5926 dropDanglingDebugInfo(Variable, Expression); 5927 const Value *V = DI.getValue(); 5928 if (!V) 5929 return; 5930 5931 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5932 SDNodeOrder)) 5933 return; 5934 5935 // TODO: Dangling debug info will eventually either be resolved or produce 5936 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5937 // between the original dbg.value location and its resolved DBG_VALUE, which 5938 // we should ideally fill with an extra Undef DBG_VALUE. 5939 5940 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5941 return; 5942 } 5943 5944 case Intrinsic::eh_typeid_for: { 5945 // Find the type id for the given typeinfo. 5946 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5947 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5948 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5949 setValue(&I, Res); 5950 return; 5951 } 5952 5953 case Intrinsic::eh_return_i32: 5954 case Intrinsic::eh_return_i64: 5955 DAG.getMachineFunction().setCallsEHReturn(true); 5956 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5957 MVT::Other, 5958 getControlRoot(), 5959 getValue(I.getArgOperand(0)), 5960 getValue(I.getArgOperand(1)))); 5961 return; 5962 case Intrinsic::eh_unwind_init: 5963 DAG.getMachineFunction().setCallsUnwindInit(true); 5964 return; 5965 case Intrinsic::eh_dwarf_cfa: 5966 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5967 TLI.getPointerTy(DAG.getDataLayout()), 5968 getValue(I.getArgOperand(0)))); 5969 return; 5970 case Intrinsic::eh_sjlj_callsite: { 5971 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5972 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5973 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5974 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5975 5976 MMI.setCurrentCallSite(CI->getZExtValue()); 5977 return; 5978 } 5979 case Intrinsic::eh_sjlj_functioncontext: { 5980 // Get and store the index of the function context. 5981 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5982 AllocaInst *FnCtx = 5983 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5984 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5985 MFI.setFunctionContextIndex(FI); 5986 return; 5987 } 5988 case Intrinsic::eh_sjlj_setjmp: { 5989 SDValue Ops[2]; 5990 Ops[0] = getRoot(); 5991 Ops[1] = getValue(I.getArgOperand(0)); 5992 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5993 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5994 setValue(&I, Op.getValue(0)); 5995 DAG.setRoot(Op.getValue(1)); 5996 return; 5997 } 5998 case Intrinsic::eh_sjlj_longjmp: 5999 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6000 getRoot(), getValue(I.getArgOperand(0)))); 6001 return; 6002 case Intrinsic::eh_sjlj_setup_dispatch: 6003 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6004 getRoot())); 6005 return; 6006 case Intrinsic::masked_gather: 6007 visitMaskedGather(I); 6008 return; 6009 case Intrinsic::masked_load: 6010 visitMaskedLoad(I); 6011 return; 6012 case Intrinsic::masked_scatter: 6013 visitMaskedScatter(I); 6014 return; 6015 case Intrinsic::masked_store: 6016 visitMaskedStore(I); 6017 return; 6018 case Intrinsic::masked_expandload: 6019 visitMaskedLoad(I, true /* IsExpanding */); 6020 return; 6021 case Intrinsic::masked_compressstore: 6022 visitMaskedStore(I, true /* IsCompressing */); 6023 return; 6024 case Intrinsic::powi: 6025 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6026 getValue(I.getArgOperand(1)), DAG)); 6027 return; 6028 case Intrinsic::log: 6029 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6030 return; 6031 case Intrinsic::log2: 6032 setValue(&I, 6033 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6034 return; 6035 case Intrinsic::log10: 6036 setValue(&I, 6037 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6038 return; 6039 case Intrinsic::exp: 6040 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6041 return; 6042 case Intrinsic::exp2: 6043 setValue(&I, 6044 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6045 return; 6046 case Intrinsic::pow: 6047 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6048 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6049 return; 6050 case Intrinsic::sqrt: 6051 case Intrinsic::fabs: 6052 case Intrinsic::sin: 6053 case Intrinsic::cos: 6054 case Intrinsic::floor: 6055 case Intrinsic::ceil: 6056 case Intrinsic::trunc: 6057 case Intrinsic::rint: 6058 case Intrinsic::nearbyint: 6059 case Intrinsic::round: 6060 case Intrinsic::roundeven: 6061 case Intrinsic::canonicalize: { 6062 unsigned Opcode; 6063 switch (Intrinsic) { 6064 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6065 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6066 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6067 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6068 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6069 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6070 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6071 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6072 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6073 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6074 case Intrinsic::round: Opcode = ISD::FROUND; break; 6075 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6076 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6077 } 6078 6079 setValue(&I, DAG.getNode(Opcode, sdl, 6080 getValue(I.getArgOperand(0)).getValueType(), 6081 getValue(I.getArgOperand(0)), Flags)); 6082 return; 6083 } 6084 case Intrinsic::lround: 6085 case Intrinsic::llround: 6086 case Intrinsic::lrint: 6087 case Intrinsic::llrint: { 6088 unsigned Opcode; 6089 switch (Intrinsic) { 6090 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6091 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6092 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6093 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6094 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6095 } 6096 6097 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6098 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6099 getValue(I.getArgOperand(0)))); 6100 return; 6101 } 6102 case Intrinsic::minnum: 6103 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6104 getValue(I.getArgOperand(0)).getValueType(), 6105 getValue(I.getArgOperand(0)), 6106 getValue(I.getArgOperand(1)), Flags)); 6107 return; 6108 case Intrinsic::maxnum: 6109 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6110 getValue(I.getArgOperand(0)).getValueType(), 6111 getValue(I.getArgOperand(0)), 6112 getValue(I.getArgOperand(1)), Flags)); 6113 return; 6114 case Intrinsic::minimum: 6115 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6116 getValue(I.getArgOperand(0)).getValueType(), 6117 getValue(I.getArgOperand(0)), 6118 getValue(I.getArgOperand(1)), Flags)); 6119 return; 6120 case Intrinsic::maximum: 6121 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6122 getValue(I.getArgOperand(0)).getValueType(), 6123 getValue(I.getArgOperand(0)), 6124 getValue(I.getArgOperand(1)), Flags)); 6125 return; 6126 case Intrinsic::copysign: 6127 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6128 getValue(I.getArgOperand(0)).getValueType(), 6129 getValue(I.getArgOperand(0)), 6130 getValue(I.getArgOperand(1)), Flags)); 6131 return; 6132 case Intrinsic::fma: 6133 setValue(&I, DAG.getNode( 6134 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6135 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6136 getValue(I.getArgOperand(2)), Flags)); 6137 return; 6138 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6139 case Intrinsic::INTRINSIC: 6140 #include "llvm/IR/ConstrainedOps.def" 6141 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6142 return; 6143 case Intrinsic::fmuladd: { 6144 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6145 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6146 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6147 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6148 getValue(I.getArgOperand(0)).getValueType(), 6149 getValue(I.getArgOperand(0)), 6150 getValue(I.getArgOperand(1)), 6151 getValue(I.getArgOperand(2)), Flags)); 6152 } else { 6153 // TODO: Intrinsic calls should have fast-math-flags. 6154 SDValue Mul = DAG.getNode( 6155 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6156 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6157 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6158 getValue(I.getArgOperand(0)).getValueType(), 6159 Mul, getValue(I.getArgOperand(2)), Flags); 6160 setValue(&I, Add); 6161 } 6162 return; 6163 } 6164 case Intrinsic::convert_to_fp16: 6165 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6166 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6167 getValue(I.getArgOperand(0)), 6168 DAG.getTargetConstant(0, sdl, 6169 MVT::i32)))); 6170 return; 6171 case Intrinsic::convert_from_fp16: 6172 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6173 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6174 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6175 getValue(I.getArgOperand(0))))); 6176 return; 6177 case Intrinsic::pcmarker: { 6178 SDValue Tmp = getValue(I.getArgOperand(0)); 6179 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6180 return; 6181 } 6182 case Intrinsic::readcyclecounter: { 6183 SDValue Op = getRoot(); 6184 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6185 DAG.getVTList(MVT::i64, MVT::Other), Op); 6186 setValue(&I, Res); 6187 DAG.setRoot(Res.getValue(1)); 6188 return; 6189 } 6190 case Intrinsic::bitreverse: 6191 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6192 getValue(I.getArgOperand(0)).getValueType(), 6193 getValue(I.getArgOperand(0)))); 6194 return; 6195 case Intrinsic::bswap: 6196 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6197 getValue(I.getArgOperand(0)).getValueType(), 6198 getValue(I.getArgOperand(0)))); 6199 return; 6200 case Intrinsic::cttz: { 6201 SDValue Arg = getValue(I.getArgOperand(0)); 6202 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6203 EVT Ty = Arg.getValueType(); 6204 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6205 sdl, Ty, Arg)); 6206 return; 6207 } 6208 case Intrinsic::ctlz: { 6209 SDValue Arg = getValue(I.getArgOperand(0)); 6210 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6211 EVT Ty = Arg.getValueType(); 6212 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6213 sdl, Ty, Arg)); 6214 return; 6215 } 6216 case Intrinsic::ctpop: { 6217 SDValue Arg = getValue(I.getArgOperand(0)); 6218 EVT Ty = Arg.getValueType(); 6219 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6220 return; 6221 } 6222 case Intrinsic::fshl: 6223 case Intrinsic::fshr: { 6224 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6225 SDValue X = getValue(I.getArgOperand(0)); 6226 SDValue Y = getValue(I.getArgOperand(1)); 6227 SDValue Z = getValue(I.getArgOperand(2)); 6228 EVT VT = X.getValueType(); 6229 6230 if (X == Y) { 6231 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6232 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6233 } else { 6234 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6235 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6236 } 6237 return; 6238 } 6239 case Intrinsic::sadd_sat: { 6240 SDValue Op1 = getValue(I.getArgOperand(0)); 6241 SDValue Op2 = getValue(I.getArgOperand(1)); 6242 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6243 return; 6244 } 6245 case Intrinsic::uadd_sat: { 6246 SDValue Op1 = getValue(I.getArgOperand(0)); 6247 SDValue Op2 = getValue(I.getArgOperand(1)); 6248 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6249 return; 6250 } 6251 case Intrinsic::ssub_sat: { 6252 SDValue Op1 = getValue(I.getArgOperand(0)); 6253 SDValue Op2 = getValue(I.getArgOperand(1)); 6254 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6255 return; 6256 } 6257 case Intrinsic::usub_sat: { 6258 SDValue Op1 = getValue(I.getArgOperand(0)); 6259 SDValue Op2 = getValue(I.getArgOperand(1)); 6260 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6261 return; 6262 } 6263 case Intrinsic::sshl_sat: { 6264 SDValue Op1 = getValue(I.getArgOperand(0)); 6265 SDValue Op2 = getValue(I.getArgOperand(1)); 6266 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6267 return; 6268 } 6269 case Intrinsic::ushl_sat: { 6270 SDValue Op1 = getValue(I.getArgOperand(0)); 6271 SDValue Op2 = getValue(I.getArgOperand(1)); 6272 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6273 return; 6274 } 6275 case Intrinsic::smul_fix: 6276 case Intrinsic::umul_fix: 6277 case Intrinsic::smul_fix_sat: 6278 case Intrinsic::umul_fix_sat: { 6279 SDValue Op1 = getValue(I.getArgOperand(0)); 6280 SDValue Op2 = getValue(I.getArgOperand(1)); 6281 SDValue Op3 = getValue(I.getArgOperand(2)); 6282 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6283 Op1.getValueType(), Op1, Op2, Op3)); 6284 return; 6285 } 6286 case Intrinsic::sdiv_fix: 6287 case Intrinsic::udiv_fix: 6288 case Intrinsic::sdiv_fix_sat: 6289 case Intrinsic::udiv_fix_sat: { 6290 SDValue Op1 = getValue(I.getArgOperand(0)); 6291 SDValue Op2 = getValue(I.getArgOperand(1)); 6292 SDValue Op3 = getValue(I.getArgOperand(2)); 6293 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6294 Op1, Op2, Op3, DAG, TLI)); 6295 return; 6296 } 6297 case Intrinsic::smax: { 6298 SDValue Op1 = getValue(I.getArgOperand(0)); 6299 SDValue Op2 = getValue(I.getArgOperand(1)); 6300 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6301 return; 6302 } 6303 case Intrinsic::smin: { 6304 SDValue Op1 = getValue(I.getArgOperand(0)); 6305 SDValue Op2 = getValue(I.getArgOperand(1)); 6306 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6307 return; 6308 } 6309 case Intrinsic::umax: { 6310 SDValue Op1 = getValue(I.getArgOperand(0)); 6311 SDValue Op2 = getValue(I.getArgOperand(1)); 6312 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6313 return; 6314 } 6315 case Intrinsic::umin: { 6316 SDValue Op1 = getValue(I.getArgOperand(0)); 6317 SDValue Op2 = getValue(I.getArgOperand(1)); 6318 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6319 return; 6320 } 6321 case Intrinsic::abs: { 6322 // TODO: Preserve "int min is poison" arg in SDAG? 6323 SDValue Op1 = getValue(I.getArgOperand(0)); 6324 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6325 return; 6326 } 6327 case Intrinsic::stacksave: { 6328 SDValue Op = getRoot(); 6329 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6330 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6331 setValue(&I, Res); 6332 DAG.setRoot(Res.getValue(1)); 6333 return; 6334 } 6335 case Intrinsic::stackrestore: 6336 Res = getValue(I.getArgOperand(0)); 6337 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6338 return; 6339 case Intrinsic::get_dynamic_area_offset: { 6340 SDValue Op = getRoot(); 6341 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6342 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6343 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6344 // target. 6345 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6346 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6347 " intrinsic!"); 6348 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6349 Op); 6350 DAG.setRoot(Op); 6351 setValue(&I, Res); 6352 return; 6353 } 6354 case Intrinsic::stackguard: { 6355 MachineFunction &MF = DAG.getMachineFunction(); 6356 const Module &M = *MF.getFunction().getParent(); 6357 SDValue Chain = getRoot(); 6358 if (TLI.useLoadStackGuardNode()) { 6359 Res = getLoadStackGuard(DAG, sdl, Chain); 6360 } else { 6361 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6362 const Value *Global = TLI.getSDagStackGuard(M); 6363 Align Align = DL->getPrefTypeAlign(Global->getType()); 6364 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6365 MachinePointerInfo(Global, 0), Align, 6366 MachineMemOperand::MOVolatile); 6367 } 6368 if (TLI.useStackGuardXorFP()) 6369 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6370 DAG.setRoot(Chain); 6371 setValue(&I, Res); 6372 return; 6373 } 6374 case Intrinsic::stackprotector: { 6375 // Emit code into the DAG to store the stack guard onto the stack. 6376 MachineFunction &MF = DAG.getMachineFunction(); 6377 MachineFrameInfo &MFI = MF.getFrameInfo(); 6378 SDValue Src, Chain = getRoot(); 6379 6380 if (TLI.useLoadStackGuardNode()) 6381 Src = getLoadStackGuard(DAG, sdl, Chain); 6382 else 6383 Src = getValue(I.getArgOperand(0)); // The guard's value. 6384 6385 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6386 6387 int FI = FuncInfo.StaticAllocaMap[Slot]; 6388 MFI.setStackProtectorIndex(FI); 6389 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6390 6391 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6392 6393 // Store the stack protector onto the stack. 6394 Res = DAG.getStore( 6395 Chain, sdl, Src, FIN, 6396 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6397 MaybeAlign(), MachineMemOperand::MOVolatile); 6398 setValue(&I, Res); 6399 DAG.setRoot(Res); 6400 return; 6401 } 6402 case Intrinsic::objectsize: 6403 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6404 6405 case Intrinsic::is_constant: 6406 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6407 6408 case Intrinsic::annotation: 6409 case Intrinsic::ptr_annotation: 6410 case Intrinsic::launder_invariant_group: 6411 case Intrinsic::strip_invariant_group: 6412 // Drop the intrinsic, but forward the value 6413 setValue(&I, getValue(I.getOperand(0))); 6414 return; 6415 case Intrinsic::assume: 6416 case Intrinsic::var_annotation: 6417 case Intrinsic::sideeffect: 6418 // Discard annotate attributes, assumptions, and artificial side-effects. 6419 return; 6420 6421 case Intrinsic::codeview_annotation: { 6422 // Emit a label associated with this metadata. 6423 MachineFunction &MF = DAG.getMachineFunction(); 6424 MCSymbol *Label = 6425 MF.getMMI().getContext().createTempSymbol("annotation", true); 6426 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6427 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6428 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6429 DAG.setRoot(Res); 6430 return; 6431 } 6432 6433 case Intrinsic::init_trampoline: { 6434 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6435 6436 SDValue Ops[6]; 6437 Ops[0] = getRoot(); 6438 Ops[1] = getValue(I.getArgOperand(0)); 6439 Ops[2] = getValue(I.getArgOperand(1)); 6440 Ops[3] = getValue(I.getArgOperand(2)); 6441 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6442 Ops[5] = DAG.getSrcValue(F); 6443 6444 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6445 6446 DAG.setRoot(Res); 6447 return; 6448 } 6449 case Intrinsic::adjust_trampoline: 6450 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6451 TLI.getPointerTy(DAG.getDataLayout()), 6452 getValue(I.getArgOperand(0)))); 6453 return; 6454 case Intrinsic::gcroot: { 6455 assert(DAG.getMachineFunction().getFunction().hasGC() && 6456 "only valid in functions with gc specified, enforced by Verifier"); 6457 assert(GFI && "implied by previous"); 6458 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6459 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6460 6461 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6462 GFI->addStackRoot(FI->getIndex(), TypeMap); 6463 return; 6464 } 6465 case Intrinsic::gcread: 6466 case Intrinsic::gcwrite: 6467 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6468 case Intrinsic::flt_rounds: 6469 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6470 setValue(&I, Res); 6471 DAG.setRoot(Res.getValue(1)); 6472 return; 6473 6474 case Intrinsic::expect: 6475 // Just replace __builtin_expect(exp, c) with EXP. 6476 setValue(&I, getValue(I.getArgOperand(0))); 6477 return; 6478 6479 case Intrinsic::debugtrap: 6480 case Intrinsic::trap: { 6481 StringRef TrapFuncName = 6482 I.getAttributes() 6483 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6484 .getValueAsString(); 6485 if (TrapFuncName.empty()) { 6486 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6487 ISD::TRAP : ISD::DEBUGTRAP; 6488 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6489 return; 6490 } 6491 TargetLowering::ArgListTy Args; 6492 6493 TargetLowering::CallLoweringInfo CLI(DAG); 6494 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6495 CallingConv::C, I.getType(), 6496 DAG.getExternalSymbol(TrapFuncName.data(), 6497 TLI.getPointerTy(DAG.getDataLayout())), 6498 std::move(Args)); 6499 6500 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6501 DAG.setRoot(Result.second); 6502 return; 6503 } 6504 6505 case Intrinsic::uadd_with_overflow: 6506 case Intrinsic::sadd_with_overflow: 6507 case Intrinsic::usub_with_overflow: 6508 case Intrinsic::ssub_with_overflow: 6509 case Intrinsic::umul_with_overflow: 6510 case Intrinsic::smul_with_overflow: { 6511 ISD::NodeType Op; 6512 switch (Intrinsic) { 6513 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6514 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6515 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6516 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6517 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6518 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6519 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6520 } 6521 SDValue Op1 = getValue(I.getArgOperand(0)); 6522 SDValue Op2 = getValue(I.getArgOperand(1)); 6523 6524 EVT ResultVT = Op1.getValueType(); 6525 EVT OverflowVT = MVT::i1; 6526 if (ResultVT.isVector()) 6527 OverflowVT = EVT::getVectorVT( 6528 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6529 6530 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6531 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6532 return; 6533 } 6534 case Intrinsic::prefetch: { 6535 SDValue Ops[5]; 6536 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6537 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6538 Ops[0] = DAG.getRoot(); 6539 Ops[1] = getValue(I.getArgOperand(0)); 6540 Ops[2] = getValue(I.getArgOperand(1)); 6541 Ops[3] = getValue(I.getArgOperand(2)); 6542 Ops[4] = getValue(I.getArgOperand(3)); 6543 SDValue Result = DAG.getMemIntrinsicNode( 6544 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6545 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6546 /* align */ None, Flags); 6547 6548 // Chain the prefetch in parallell with any pending loads, to stay out of 6549 // the way of later optimizations. 6550 PendingLoads.push_back(Result); 6551 Result = getRoot(); 6552 DAG.setRoot(Result); 6553 return; 6554 } 6555 case Intrinsic::lifetime_start: 6556 case Intrinsic::lifetime_end: { 6557 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6558 // Stack coloring is not enabled in O0, discard region information. 6559 if (TM.getOptLevel() == CodeGenOpt::None) 6560 return; 6561 6562 const int64_t ObjectSize = 6563 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6564 Value *const ObjectPtr = I.getArgOperand(1); 6565 SmallVector<const Value *, 4> Allocas; 6566 getUnderlyingObjects(ObjectPtr, Allocas); 6567 6568 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6569 E = Allocas.end(); Object != E; ++Object) { 6570 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6571 6572 // Could not find an Alloca. 6573 if (!LifetimeObject) 6574 continue; 6575 6576 // First check that the Alloca is static, otherwise it won't have a 6577 // valid frame index. 6578 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6579 if (SI == FuncInfo.StaticAllocaMap.end()) 6580 return; 6581 6582 const int FrameIndex = SI->second; 6583 int64_t Offset; 6584 if (GetPointerBaseWithConstantOffset( 6585 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6586 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6587 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6588 Offset); 6589 DAG.setRoot(Res); 6590 } 6591 return; 6592 } 6593 case Intrinsic::pseudoprobe: { 6594 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6595 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6596 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6597 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6598 DAG.setRoot(Res); 6599 return; 6600 } 6601 case Intrinsic::invariant_start: 6602 // Discard region information. 6603 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6604 return; 6605 case Intrinsic::invariant_end: 6606 // Discard region information. 6607 return; 6608 case Intrinsic::clear_cache: 6609 /// FunctionName may be null. 6610 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6611 lowerCallToExternalSymbol(I, FunctionName); 6612 return; 6613 case Intrinsic::donothing: 6614 // ignore 6615 return; 6616 case Intrinsic::experimental_stackmap: 6617 visitStackmap(I); 6618 return; 6619 case Intrinsic::experimental_patchpoint_void: 6620 case Intrinsic::experimental_patchpoint_i64: 6621 visitPatchpoint(I); 6622 return; 6623 case Intrinsic::experimental_gc_statepoint: 6624 LowerStatepoint(cast<GCStatepointInst>(I)); 6625 return; 6626 case Intrinsic::experimental_gc_result: 6627 visitGCResult(cast<GCResultInst>(I)); 6628 return; 6629 case Intrinsic::experimental_gc_relocate: 6630 visitGCRelocate(cast<GCRelocateInst>(I)); 6631 return; 6632 case Intrinsic::instrprof_increment: 6633 llvm_unreachable("instrprof failed to lower an increment"); 6634 case Intrinsic::instrprof_value_profile: 6635 llvm_unreachable("instrprof failed to lower a value profiling call"); 6636 case Intrinsic::localescape: { 6637 MachineFunction &MF = DAG.getMachineFunction(); 6638 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6639 6640 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6641 // is the same on all targets. 6642 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6643 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6644 if (isa<ConstantPointerNull>(Arg)) 6645 continue; // Skip null pointers. They represent a hole in index space. 6646 AllocaInst *Slot = cast<AllocaInst>(Arg); 6647 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6648 "can only escape static allocas"); 6649 int FI = FuncInfo.StaticAllocaMap[Slot]; 6650 MCSymbol *FrameAllocSym = 6651 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6652 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6653 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6654 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6655 .addSym(FrameAllocSym) 6656 .addFrameIndex(FI); 6657 } 6658 6659 return; 6660 } 6661 6662 case Intrinsic::localrecover: { 6663 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6664 MachineFunction &MF = DAG.getMachineFunction(); 6665 6666 // Get the symbol that defines the frame offset. 6667 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6668 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6669 unsigned IdxVal = 6670 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6671 MCSymbol *FrameAllocSym = 6672 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6673 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6674 6675 Value *FP = I.getArgOperand(1); 6676 SDValue FPVal = getValue(FP); 6677 EVT PtrVT = FPVal.getValueType(); 6678 6679 // Create a MCSymbol for the label to avoid any target lowering 6680 // that would make this PC relative. 6681 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6682 SDValue OffsetVal = 6683 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6684 6685 // Add the offset to the FP. 6686 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6687 setValue(&I, Add); 6688 6689 return; 6690 } 6691 6692 case Intrinsic::eh_exceptionpointer: 6693 case Intrinsic::eh_exceptioncode: { 6694 // Get the exception pointer vreg, copy from it, and resize it to fit. 6695 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6696 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6697 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6698 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6699 SDValue N = 6700 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6701 if (Intrinsic == Intrinsic::eh_exceptioncode) 6702 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6703 setValue(&I, N); 6704 return; 6705 } 6706 case Intrinsic::xray_customevent: { 6707 // Here we want to make sure that the intrinsic behaves as if it has a 6708 // specific calling convention, and only for x86_64. 6709 // FIXME: Support other platforms later. 6710 const auto &Triple = DAG.getTarget().getTargetTriple(); 6711 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6712 return; 6713 6714 SDLoc DL = getCurSDLoc(); 6715 SmallVector<SDValue, 8> Ops; 6716 6717 // We want to say that we always want the arguments in registers. 6718 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6719 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6720 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6721 SDValue Chain = getRoot(); 6722 Ops.push_back(LogEntryVal); 6723 Ops.push_back(StrSizeVal); 6724 Ops.push_back(Chain); 6725 6726 // We need to enforce the calling convention for the callsite, so that 6727 // argument ordering is enforced correctly, and that register allocation can 6728 // see that some registers may be assumed clobbered and have to preserve 6729 // them across calls to the intrinsic. 6730 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6731 DL, NodeTys, Ops); 6732 SDValue patchableNode = SDValue(MN, 0); 6733 DAG.setRoot(patchableNode); 6734 setValue(&I, patchableNode); 6735 return; 6736 } 6737 case Intrinsic::xray_typedevent: { 6738 // Here we want to make sure that the intrinsic behaves as if it has a 6739 // specific calling convention, and only for x86_64. 6740 // FIXME: Support other platforms later. 6741 const auto &Triple = DAG.getTarget().getTargetTriple(); 6742 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6743 return; 6744 6745 SDLoc DL = getCurSDLoc(); 6746 SmallVector<SDValue, 8> Ops; 6747 6748 // We want to say that we always want the arguments in registers. 6749 // It's unclear to me how manipulating the selection DAG here forces callers 6750 // to provide arguments in registers instead of on the stack. 6751 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6752 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6753 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6754 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6755 SDValue Chain = getRoot(); 6756 Ops.push_back(LogTypeId); 6757 Ops.push_back(LogEntryVal); 6758 Ops.push_back(StrSizeVal); 6759 Ops.push_back(Chain); 6760 6761 // We need to enforce the calling convention for the callsite, so that 6762 // argument ordering is enforced correctly, and that register allocation can 6763 // see that some registers may be assumed clobbered and have to preserve 6764 // them across calls to the intrinsic. 6765 MachineSDNode *MN = DAG.getMachineNode( 6766 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6767 SDValue patchableNode = SDValue(MN, 0); 6768 DAG.setRoot(patchableNode); 6769 setValue(&I, patchableNode); 6770 return; 6771 } 6772 case Intrinsic::experimental_deoptimize: 6773 LowerDeoptimizeCall(&I); 6774 return; 6775 6776 case Intrinsic::vector_reduce_fadd: 6777 case Intrinsic::vector_reduce_fmul: 6778 case Intrinsic::vector_reduce_add: 6779 case Intrinsic::vector_reduce_mul: 6780 case Intrinsic::vector_reduce_and: 6781 case Intrinsic::vector_reduce_or: 6782 case Intrinsic::vector_reduce_xor: 6783 case Intrinsic::vector_reduce_smax: 6784 case Intrinsic::vector_reduce_smin: 6785 case Intrinsic::vector_reduce_umax: 6786 case Intrinsic::vector_reduce_umin: 6787 case Intrinsic::vector_reduce_fmax: 6788 case Intrinsic::vector_reduce_fmin: 6789 visitVectorReduce(I, Intrinsic); 6790 return; 6791 6792 case Intrinsic::icall_branch_funnel: { 6793 SmallVector<SDValue, 16> Ops; 6794 Ops.push_back(getValue(I.getArgOperand(0))); 6795 6796 int64_t Offset; 6797 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6798 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6799 if (!Base) 6800 report_fatal_error( 6801 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6802 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6803 6804 struct BranchFunnelTarget { 6805 int64_t Offset; 6806 SDValue Target; 6807 }; 6808 SmallVector<BranchFunnelTarget, 8> Targets; 6809 6810 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6811 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6812 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6813 if (ElemBase != Base) 6814 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6815 "to the same GlobalValue"); 6816 6817 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6818 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6819 if (!GA) 6820 report_fatal_error( 6821 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6822 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6823 GA->getGlobal(), getCurSDLoc(), 6824 Val.getValueType(), GA->getOffset())}); 6825 } 6826 llvm::sort(Targets, 6827 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6828 return T1.Offset < T2.Offset; 6829 }); 6830 6831 for (auto &T : Targets) { 6832 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6833 Ops.push_back(T.Target); 6834 } 6835 6836 Ops.push_back(DAG.getRoot()); // Chain 6837 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6838 getCurSDLoc(), MVT::Other, Ops), 6839 0); 6840 DAG.setRoot(N); 6841 setValue(&I, N); 6842 HasTailCall = true; 6843 return; 6844 } 6845 6846 case Intrinsic::wasm_landingpad_index: 6847 // Information this intrinsic contained has been transferred to 6848 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6849 // delete it now. 6850 return; 6851 6852 case Intrinsic::aarch64_settag: 6853 case Intrinsic::aarch64_settag_zero: { 6854 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6855 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6856 SDValue Val = TSI.EmitTargetCodeForSetTag( 6857 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6858 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6859 ZeroMemory); 6860 DAG.setRoot(Val); 6861 setValue(&I, Val); 6862 return; 6863 } 6864 case Intrinsic::ptrmask: { 6865 SDValue Ptr = getValue(I.getOperand(0)); 6866 SDValue Const = getValue(I.getOperand(1)); 6867 6868 EVT PtrVT = Ptr.getValueType(); 6869 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 6870 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 6871 return; 6872 } 6873 case Intrinsic::get_active_lane_mask: { 6874 auto DL = getCurSDLoc(); 6875 SDValue Index = getValue(I.getOperand(0)); 6876 SDValue TripCount = getValue(I.getOperand(1)); 6877 Type *ElementTy = I.getOperand(0)->getType(); 6878 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6879 unsigned VecWidth = VT.getVectorNumElements(); 6880 6881 SmallVector<SDValue, 16> OpsTripCount; 6882 SmallVector<SDValue, 16> OpsIndex; 6883 SmallVector<SDValue, 16> OpsStepConstants; 6884 for (unsigned i = 0; i < VecWidth; i++) { 6885 OpsTripCount.push_back(TripCount); 6886 OpsIndex.push_back(Index); 6887 OpsStepConstants.push_back( 6888 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 6889 } 6890 6891 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 6892 6893 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 6894 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 6895 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 6896 SDValue VectorInduction = DAG.getNode( 6897 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 6898 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 6899 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 6900 VectorTripCount, ISD::CondCode::SETULT); 6901 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 6902 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 6903 SetCC)); 6904 return; 6905 } 6906 } 6907 } 6908 6909 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6910 const ConstrainedFPIntrinsic &FPI) { 6911 SDLoc sdl = getCurSDLoc(); 6912 6913 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6914 SmallVector<EVT, 4> ValueVTs; 6915 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6916 ValueVTs.push_back(MVT::Other); // Out chain 6917 6918 // We do not need to serialize constrained FP intrinsics against 6919 // each other or against (nonvolatile) loads, so they can be 6920 // chained like loads. 6921 SDValue Chain = DAG.getRoot(); 6922 SmallVector<SDValue, 4> Opers; 6923 Opers.push_back(Chain); 6924 if (FPI.isUnaryOp()) { 6925 Opers.push_back(getValue(FPI.getArgOperand(0))); 6926 } else if (FPI.isTernaryOp()) { 6927 Opers.push_back(getValue(FPI.getArgOperand(0))); 6928 Opers.push_back(getValue(FPI.getArgOperand(1))); 6929 Opers.push_back(getValue(FPI.getArgOperand(2))); 6930 } else { 6931 Opers.push_back(getValue(FPI.getArgOperand(0))); 6932 Opers.push_back(getValue(FPI.getArgOperand(1))); 6933 } 6934 6935 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 6936 assert(Result.getNode()->getNumValues() == 2); 6937 6938 // Push node to the appropriate list so that future instructions can be 6939 // chained up correctly. 6940 SDValue OutChain = Result.getValue(1); 6941 switch (EB) { 6942 case fp::ExceptionBehavior::ebIgnore: 6943 // The only reason why ebIgnore nodes still need to be chained is that 6944 // they might depend on the current rounding mode, and therefore must 6945 // not be moved across instruction that may change that mode. 6946 LLVM_FALLTHROUGH; 6947 case fp::ExceptionBehavior::ebMayTrap: 6948 // These must not be moved across calls or instructions that may change 6949 // floating-point exception masks. 6950 PendingConstrainedFP.push_back(OutChain); 6951 break; 6952 case fp::ExceptionBehavior::ebStrict: 6953 // These must not be moved across calls or instructions that may change 6954 // floating-point exception masks or read floating-point exception flags. 6955 // In addition, they cannot be optimized out even if unused. 6956 PendingConstrainedFPStrict.push_back(OutChain); 6957 break; 6958 } 6959 }; 6960 6961 SDVTList VTs = DAG.getVTList(ValueVTs); 6962 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 6963 6964 SDNodeFlags Flags; 6965 if (EB == fp::ExceptionBehavior::ebIgnore) 6966 Flags.setNoFPExcept(true); 6967 6968 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 6969 Flags.copyFMF(*FPOp); 6970 6971 unsigned Opcode; 6972 switch (FPI.getIntrinsicID()) { 6973 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6974 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6975 case Intrinsic::INTRINSIC: \ 6976 Opcode = ISD::STRICT_##DAGN; \ 6977 break; 6978 #include "llvm/IR/ConstrainedOps.def" 6979 case Intrinsic::experimental_constrained_fmuladd: { 6980 Opcode = ISD::STRICT_FMA; 6981 // Break fmuladd into fmul and fadd. 6982 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 6983 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 6984 ValueVTs[0])) { 6985 Opers.pop_back(); 6986 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 6987 pushOutChain(Mul, EB); 6988 Opcode = ISD::STRICT_FADD; 6989 Opers.clear(); 6990 Opers.push_back(Mul.getValue(1)); 6991 Opers.push_back(Mul.getValue(0)); 6992 Opers.push_back(getValue(FPI.getArgOperand(2))); 6993 } 6994 break; 6995 } 6996 } 6997 6998 // A few strict DAG nodes carry additional operands that are not 6999 // set up by the default code above. 7000 switch (Opcode) { 7001 default: break; 7002 case ISD::STRICT_FP_ROUND: 7003 Opers.push_back( 7004 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7005 break; 7006 case ISD::STRICT_FSETCC: 7007 case ISD::STRICT_FSETCCS: { 7008 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7009 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 7010 break; 7011 } 7012 } 7013 7014 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7015 pushOutChain(Result, EB); 7016 7017 SDValue FPResult = Result.getValue(0); 7018 setValue(&FPI, FPResult); 7019 } 7020 7021 std::pair<SDValue, SDValue> 7022 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7023 const BasicBlock *EHPadBB) { 7024 MachineFunction &MF = DAG.getMachineFunction(); 7025 MachineModuleInfo &MMI = MF.getMMI(); 7026 MCSymbol *BeginLabel = nullptr; 7027 7028 if (EHPadBB) { 7029 // Insert a label before the invoke call to mark the try range. This can be 7030 // used to detect deletion of the invoke via the MachineModuleInfo. 7031 BeginLabel = MMI.getContext().createTempSymbol(); 7032 7033 // For SjLj, keep track of which landing pads go with which invokes 7034 // so as to maintain the ordering of pads in the LSDA. 7035 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7036 if (CallSiteIndex) { 7037 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7038 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7039 7040 // Now that the call site is handled, stop tracking it. 7041 MMI.setCurrentCallSite(0); 7042 } 7043 7044 // Both PendingLoads and PendingExports must be flushed here; 7045 // this call might not return. 7046 (void)getRoot(); 7047 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7048 7049 CLI.setChain(getRoot()); 7050 } 7051 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7052 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7053 7054 assert((CLI.IsTailCall || Result.second.getNode()) && 7055 "Non-null chain expected with non-tail call!"); 7056 assert((Result.second.getNode() || !Result.first.getNode()) && 7057 "Null value expected with tail call!"); 7058 7059 if (!Result.second.getNode()) { 7060 // As a special case, a null chain means that a tail call has been emitted 7061 // and the DAG root is already updated. 7062 HasTailCall = true; 7063 7064 // Since there's no actual continuation from this block, nothing can be 7065 // relying on us setting vregs for them. 7066 PendingExports.clear(); 7067 } else { 7068 DAG.setRoot(Result.second); 7069 } 7070 7071 if (EHPadBB) { 7072 // Insert a label at the end of the invoke call to mark the try range. This 7073 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7074 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7075 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7076 7077 // Inform MachineModuleInfo of range. 7078 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7079 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7080 // actually use outlined funclets and their LSDA info style. 7081 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7082 assert(CLI.CB); 7083 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7084 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7085 } else if (!isScopedEHPersonality(Pers)) { 7086 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7087 } 7088 } 7089 7090 return Result; 7091 } 7092 7093 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7094 bool isTailCall, 7095 const BasicBlock *EHPadBB) { 7096 auto &DL = DAG.getDataLayout(); 7097 FunctionType *FTy = CB.getFunctionType(); 7098 Type *RetTy = CB.getType(); 7099 7100 TargetLowering::ArgListTy Args; 7101 Args.reserve(CB.arg_size()); 7102 7103 const Value *SwiftErrorVal = nullptr; 7104 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7105 7106 if (isTailCall) { 7107 // Avoid emitting tail calls in functions with the disable-tail-calls 7108 // attribute. 7109 auto *Caller = CB.getParent()->getParent(); 7110 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7111 "true") 7112 isTailCall = false; 7113 7114 // We can't tail call inside a function with a swifterror argument. Lowering 7115 // does not support this yet. It would have to move into the swifterror 7116 // register before the call. 7117 if (TLI.supportSwiftError() && 7118 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7119 isTailCall = false; 7120 } 7121 7122 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7123 TargetLowering::ArgListEntry Entry; 7124 const Value *V = *I; 7125 7126 // Skip empty types 7127 if (V->getType()->isEmptyTy()) 7128 continue; 7129 7130 SDValue ArgNode = getValue(V); 7131 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7132 7133 Entry.setAttributes(&CB, I - CB.arg_begin()); 7134 7135 // Use swifterror virtual register as input to the call. 7136 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7137 SwiftErrorVal = V; 7138 // We find the virtual register for the actual swifterror argument. 7139 // Instead of using the Value, we use the virtual register instead. 7140 Entry.Node = 7141 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7142 EVT(TLI.getPointerTy(DL))); 7143 } 7144 7145 Args.push_back(Entry); 7146 7147 // If we have an explicit sret argument that is an Instruction, (i.e., it 7148 // might point to function-local memory), we can't meaningfully tail-call. 7149 if (Entry.IsSRet && isa<Instruction>(V)) 7150 isTailCall = false; 7151 } 7152 7153 // If call site has a cfguardtarget operand bundle, create and add an 7154 // additional ArgListEntry. 7155 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7156 TargetLowering::ArgListEntry Entry; 7157 Value *V = Bundle->Inputs[0]; 7158 SDValue ArgNode = getValue(V); 7159 Entry.Node = ArgNode; 7160 Entry.Ty = V->getType(); 7161 Entry.IsCFGuardTarget = true; 7162 Args.push_back(Entry); 7163 } 7164 7165 // Check if target-independent constraints permit a tail call here. 7166 // Target-dependent constraints are checked within TLI->LowerCallTo. 7167 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7168 isTailCall = false; 7169 7170 // Disable tail calls if there is an swifterror argument. Targets have not 7171 // been updated to support tail calls. 7172 if (TLI.supportSwiftError() && SwiftErrorVal) 7173 isTailCall = false; 7174 7175 TargetLowering::CallLoweringInfo CLI(DAG); 7176 CLI.setDebugLoc(getCurSDLoc()) 7177 .setChain(getRoot()) 7178 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7179 .setTailCall(isTailCall) 7180 .setConvergent(CB.isConvergent()) 7181 .setIsPreallocated( 7182 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7183 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7184 7185 if (Result.first.getNode()) { 7186 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7187 setValue(&CB, Result.first); 7188 } 7189 7190 // The last element of CLI.InVals has the SDValue for swifterror return. 7191 // Here we copy it to a virtual register and update SwiftErrorMap for 7192 // book-keeping. 7193 if (SwiftErrorVal && TLI.supportSwiftError()) { 7194 // Get the last element of InVals. 7195 SDValue Src = CLI.InVals.back(); 7196 Register VReg = 7197 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7198 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7199 DAG.setRoot(CopyNode); 7200 } 7201 } 7202 7203 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7204 SelectionDAGBuilder &Builder) { 7205 // Check to see if this load can be trivially constant folded, e.g. if the 7206 // input is from a string literal. 7207 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7208 // Cast pointer to the type we really want to load. 7209 Type *LoadTy = 7210 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7211 if (LoadVT.isVector()) 7212 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7213 7214 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7215 PointerType::getUnqual(LoadTy)); 7216 7217 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7218 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7219 return Builder.getValue(LoadCst); 7220 } 7221 7222 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7223 // still constant memory, the input chain can be the entry node. 7224 SDValue Root; 7225 bool ConstantMemory = false; 7226 7227 // Do not serialize (non-volatile) loads of constant memory with anything. 7228 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7229 Root = Builder.DAG.getEntryNode(); 7230 ConstantMemory = true; 7231 } else { 7232 // Do not serialize non-volatile loads against each other. 7233 Root = Builder.DAG.getRoot(); 7234 } 7235 7236 SDValue Ptr = Builder.getValue(PtrVal); 7237 SDValue LoadVal = 7238 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7239 MachinePointerInfo(PtrVal), Align(1)); 7240 7241 if (!ConstantMemory) 7242 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7243 return LoadVal; 7244 } 7245 7246 /// Record the value for an instruction that produces an integer result, 7247 /// converting the type where necessary. 7248 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7249 SDValue Value, 7250 bool IsSigned) { 7251 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7252 I.getType(), true); 7253 if (IsSigned) 7254 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7255 else 7256 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7257 setValue(&I, Value); 7258 } 7259 7260 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7261 /// true and lower it. Otherwise return false, and it will be lowered like a 7262 /// normal call. 7263 /// The caller already checked that \p I calls the appropriate LibFunc with a 7264 /// correct prototype. 7265 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7266 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7267 const Value *Size = I.getArgOperand(2); 7268 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7269 if (CSize && CSize->getZExtValue() == 0) { 7270 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7271 I.getType(), true); 7272 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7273 return true; 7274 } 7275 7276 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7277 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7278 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7279 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7280 if (Res.first.getNode()) { 7281 processIntegerCallValue(I, Res.first, true); 7282 PendingLoads.push_back(Res.second); 7283 return true; 7284 } 7285 7286 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7287 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7288 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7289 return false; 7290 7291 // If the target has a fast compare for the given size, it will return a 7292 // preferred load type for that size. Require that the load VT is legal and 7293 // that the target supports unaligned loads of that type. Otherwise, return 7294 // INVALID. 7295 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7296 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7297 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7298 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7299 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7300 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7301 // TODO: Check alignment of src and dest ptrs. 7302 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7303 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7304 if (!TLI.isTypeLegal(LVT) || 7305 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7306 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7307 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7308 } 7309 7310 return LVT; 7311 }; 7312 7313 // This turns into unaligned loads. We only do this if the target natively 7314 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7315 // we'll only produce a small number of byte loads. 7316 MVT LoadVT; 7317 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7318 switch (NumBitsToCompare) { 7319 default: 7320 return false; 7321 case 16: 7322 LoadVT = MVT::i16; 7323 break; 7324 case 32: 7325 LoadVT = MVT::i32; 7326 break; 7327 case 64: 7328 case 128: 7329 case 256: 7330 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7331 break; 7332 } 7333 7334 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7335 return false; 7336 7337 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7338 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7339 7340 // Bitcast to a wide integer type if the loads are vectors. 7341 if (LoadVT.isVector()) { 7342 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7343 LoadL = DAG.getBitcast(CmpVT, LoadL); 7344 LoadR = DAG.getBitcast(CmpVT, LoadR); 7345 } 7346 7347 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7348 processIntegerCallValue(I, Cmp, false); 7349 return true; 7350 } 7351 7352 /// See if we can lower a memchr call into an optimized form. If so, return 7353 /// true and lower it. Otherwise return false, and it will be lowered like a 7354 /// normal call. 7355 /// The caller already checked that \p I calls the appropriate LibFunc with a 7356 /// correct prototype. 7357 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7358 const Value *Src = I.getArgOperand(0); 7359 const Value *Char = I.getArgOperand(1); 7360 const Value *Length = I.getArgOperand(2); 7361 7362 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7363 std::pair<SDValue, SDValue> Res = 7364 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7365 getValue(Src), getValue(Char), getValue(Length), 7366 MachinePointerInfo(Src)); 7367 if (Res.first.getNode()) { 7368 setValue(&I, Res.first); 7369 PendingLoads.push_back(Res.second); 7370 return true; 7371 } 7372 7373 return false; 7374 } 7375 7376 /// See if we can lower a mempcpy call into an optimized form. If so, return 7377 /// true and lower it. Otherwise return false, and it will be lowered like a 7378 /// normal call. 7379 /// The caller already checked that \p I calls the appropriate LibFunc with a 7380 /// correct prototype. 7381 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7382 SDValue Dst = getValue(I.getArgOperand(0)); 7383 SDValue Src = getValue(I.getArgOperand(1)); 7384 SDValue Size = getValue(I.getArgOperand(2)); 7385 7386 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7387 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7388 // DAG::getMemcpy needs Alignment to be defined. 7389 Align Alignment = std::min(DstAlign, SrcAlign); 7390 7391 bool isVol = false; 7392 SDLoc sdl = getCurSDLoc(); 7393 7394 // In the mempcpy context we need to pass in a false value for isTailCall 7395 // because the return pointer needs to be adjusted by the size of 7396 // the copied memory. 7397 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7398 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7399 /*isTailCall=*/false, 7400 MachinePointerInfo(I.getArgOperand(0)), 7401 MachinePointerInfo(I.getArgOperand(1))); 7402 assert(MC.getNode() != nullptr && 7403 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7404 DAG.setRoot(MC); 7405 7406 // Check if Size needs to be truncated or extended. 7407 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7408 7409 // Adjust return pointer to point just past the last dst byte. 7410 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7411 Dst, Size); 7412 setValue(&I, DstPlusSize); 7413 return true; 7414 } 7415 7416 /// See if we can lower a strcpy call into an optimized form. If so, return 7417 /// true and lower it, otherwise return false and it will be lowered like a 7418 /// normal call. 7419 /// The caller already checked that \p I calls the appropriate LibFunc with a 7420 /// correct prototype. 7421 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7422 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7423 7424 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7425 std::pair<SDValue, SDValue> Res = 7426 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7427 getValue(Arg0), getValue(Arg1), 7428 MachinePointerInfo(Arg0), 7429 MachinePointerInfo(Arg1), isStpcpy); 7430 if (Res.first.getNode()) { 7431 setValue(&I, Res.first); 7432 DAG.setRoot(Res.second); 7433 return true; 7434 } 7435 7436 return false; 7437 } 7438 7439 /// See if we can lower a strcmp call into an optimized form. If so, return 7440 /// true and lower it, otherwise return false and it will be lowered like a 7441 /// normal call. 7442 /// The caller already checked that \p I calls the appropriate LibFunc with a 7443 /// correct prototype. 7444 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7445 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7446 7447 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7448 std::pair<SDValue, SDValue> Res = 7449 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7450 getValue(Arg0), getValue(Arg1), 7451 MachinePointerInfo(Arg0), 7452 MachinePointerInfo(Arg1)); 7453 if (Res.first.getNode()) { 7454 processIntegerCallValue(I, Res.first, true); 7455 PendingLoads.push_back(Res.second); 7456 return true; 7457 } 7458 7459 return false; 7460 } 7461 7462 /// See if we can lower a strlen call into an optimized form. If so, return 7463 /// true and lower it, otherwise return false and it will be lowered like a 7464 /// normal call. 7465 /// The caller already checked that \p I calls the appropriate LibFunc with a 7466 /// correct prototype. 7467 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7468 const Value *Arg0 = I.getArgOperand(0); 7469 7470 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7471 std::pair<SDValue, SDValue> Res = 7472 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7473 getValue(Arg0), MachinePointerInfo(Arg0)); 7474 if (Res.first.getNode()) { 7475 processIntegerCallValue(I, Res.first, false); 7476 PendingLoads.push_back(Res.second); 7477 return true; 7478 } 7479 7480 return false; 7481 } 7482 7483 /// See if we can lower a strnlen call into an optimized form. If so, return 7484 /// true and lower it, otherwise return false and it will be lowered like a 7485 /// normal call. 7486 /// The caller already checked that \p I calls the appropriate LibFunc with a 7487 /// correct prototype. 7488 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7489 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7490 7491 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7492 std::pair<SDValue, SDValue> Res = 7493 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7494 getValue(Arg0), getValue(Arg1), 7495 MachinePointerInfo(Arg0)); 7496 if (Res.first.getNode()) { 7497 processIntegerCallValue(I, Res.first, false); 7498 PendingLoads.push_back(Res.second); 7499 return true; 7500 } 7501 7502 return false; 7503 } 7504 7505 /// See if we can lower a unary floating-point operation into an SDNode with 7506 /// the specified Opcode. If so, return true and lower it, otherwise return 7507 /// false and it will be lowered like a normal call. 7508 /// The caller already checked that \p I calls the appropriate LibFunc with a 7509 /// correct prototype. 7510 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7511 unsigned Opcode) { 7512 // We already checked this call's prototype; verify it doesn't modify errno. 7513 if (!I.onlyReadsMemory()) 7514 return false; 7515 7516 SDNodeFlags Flags; 7517 Flags.copyFMF(cast<FPMathOperator>(I)); 7518 7519 SDValue Tmp = getValue(I.getArgOperand(0)); 7520 setValue(&I, 7521 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7522 return true; 7523 } 7524 7525 /// See if we can lower a binary floating-point operation into an SDNode with 7526 /// the specified Opcode. If so, return true and lower it. Otherwise return 7527 /// false, and it will be lowered like a normal call. 7528 /// The caller already checked that \p I calls the appropriate LibFunc with a 7529 /// correct prototype. 7530 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7531 unsigned Opcode) { 7532 // We already checked this call's prototype; verify it doesn't modify errno. 7533 if (!I.onlyReadsMemory()) 7534 return false; 7535 7536 SDNodeFlags Flags; 7537 Flags.copyFMF(cast<FPMathOperator>(I)); 7538 7539 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7540 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7541 EVT VT = Tmp0.getValueType(); 7542 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7543 return true; 7544 } 7545 7546 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7547 // Handle inline assembly differently. 7548 if (I.isInlineAsm()) { 7549 visitInlineAsm(I); 7550 return; 7551 } 7552 7553 if (Function *F = I.getCalledFunction()) { 7554 if (F->isDeclaration()) { 7555 // Is this an LLVM intrinsic or a target-specific intrinsic? 7556 unsigned IID = F->getIntrinsicID(); 7557 if (!IID) 7558 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7559 IID = II->getIntrinsicID(F); 7560 7561 if (IID) { 7562 visitIntrinsicCall(I, IID); 7563 return; 7564 } 7565 } 7566 7567 // Check for well-known libc/libm calls. If the function is internal, it 7568 // can't be a library call. Don't do the check if marked as nobuiltin for 7569 // some reason or the call site requires strict floating point semantics. 7570 LibFunc Func; 7571 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7572 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7573 LibInfo->hasOptimizedCodeGen(Func)) { 7574 switch (Func) { 7575 default: break; 7576 case LibFunc_bcmp: 7577 if (visitMemCmpBCmpCall(I)) 7578 return; 7579 break; 7580 case LibFunc_copysign: 7581 case LibFunc_copysignf: 7582 case LibFunc_copysignl: 7583 // We already checked this call's prototype; verify it doesn't modify 7584 // errno. 7585 if (I.onlyReadsMemory()) { 7586 SDValue LHS = getValue(I.getArgOperand(0)); 7587 SDValue RHS = getValue(I.getArgOperand(1)); 7588 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7589 LHS.getValueType(), LHS, RHS)); 7590 return; 7591 } 7592 break; 7593 case LibFunc_fabs: 7594 case LibFunc_fabsf: 7595 case LibFunc_fabsl: 7596 if (visitUnaryFloatCall(I, ISD::FABS)) 7597 return; 7598 break; 7599 case LibFunc_fmin: 7600 case LibFunc_fminf: 7601 case LibFunc_fminl: 7602 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7603 return; 7604 break; 7605 case LibFunc_fmax: 7606 case LibFunc_fmaxf: 7607 case LibFunc_fmaxl: 7608 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7609 return; 7610 break; 7611 case LibFunc_sin: 7612 case LibFunc_sinf: 7613 case LibFunc_sinl: 7614 if (visitUnaryFloatCall(I, ISD::FSIN)) 7615 return; 7616 break; 7617 case LibFunc_cos: 7618 case LibFunc_cosf: 7619 case LibFunc_cosl: 7620 if (visitUnaryFloatCall(I, ISD::FCOS)) 7621 return; 7622 break; 7623 case LibFunc_sqrt: 7624 case LibFunc_sqrtf: 7625 case LibFunc_sqrtl: 7626 case LibFunc_sqrt_finite: 7627 case LibFunc_sqrtf_finite: 7628 case LibFunc_sqrtl_finite: 7629 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7630 return; 7631 break; 7632 case LibFunc_floor: 7633 case LibFunc_floorf: 7634 case LibFunc_floorl: 7635 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7636 return; 7637 break; 7638 case LibFunc_nearbyint: 7639 case LibFunc_nearbyintf: 7640 case LibFunc_nearbyintl: 7641 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7642 return; 7643 break; 7644 case LibFunc_ceil: 7645 case LibFunc_ceilf: 7646 case LibFunc_ceill: 7647 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7648 return; 7649 break; 7650 case LibFunc_rint: 7651 case LibFunc_rintf: 7652 case LibFunc_rintl: 7653 if (visitUnaryFloatCall(I, ISD::FRINT)) 7654 return; 7655 break; 7656 case LibFunc_round: 7657 case LibFunc_roundf: 7658 case LibFunc_roundl: 7659 if (visitUnaryFloatCall(I, ISD::FROUND)) 7660 return; 7661 break; 7662 case LibFunc_trunc: 7663 case LibFunc_truncf: 7664 case LibFunc_truncl: 7665 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7666 return; 7667 break; 7668 case LibFunc_log2: 7669 case LibFunc_log2f: 7670 case LibFunc_log2l: 7671 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7672 return; 7673 break; 7674 case LibFunc_exp2: 7675 case LibFunc_exp2f: 7676 case LibFunc_exp2l: 7677 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7678 return; 7679 break; 7680 case LibFunc_memcmp: 7681 if (visitMemCmpBCmpCall(I)) 7682 return; 7683 break; 7684 case LibFunc_mempcpy: 7685 if (visitMemPCpyCall(I)) 7686 return; 7687 break; 7688 case LibFunc_memchr: 7689 if (visitMemChrCall(I)) 7690 return; 7691 break; 7692 case LibFunc_strcpy: 7693 if (visitStrCpyCall(I, false)) 7694 return; 7695 break; 7696 case LibFunc_stpcpy: 7697 if (visitStrCpyCall(I, true)) 7698 return; 7699 break; 7700 case LibFunc_strcmp: 7701 if (visitStrCmpCall(I)) 7702 return; 7703 break; 7704 case LibFunc_strlen: 7705 if (visitStrLenCall(I)) 7706 return; 7707 break; 7708 case LibFunc_strnlen: 7709 if (visitStrNLenCall(I)) 7710 return; 7711 break; 7712 } 7713 } 7714 } 7715 7716 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7717 // have to do anything here to lower funclet bundles. 7718 // CFGuardTarget bundles are lowered in LowerCallTo. 7719 assert(!I.hasOperandBundlesOtherThan( 7720 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7721 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) && 7722 "Cannot lower calls with arbitrary operand bundles!"); 7723 7724 SDValue Callee = getValue(I.getCalledOperand()); 7725 7726 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7727 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7728 else 7729 // Check if we can potentially perform a tail call. More detailed checking 7730 // is be done within LowerCallTo, after more information about the call is 7731 // known. 7732 LowerCallTo(I, Callee, I.isTailCall()); 7733 } 7734 7735 namespace { 7736 7737 /// AsmOperandInfo - This contains information for each constraint that we are 7738 /// lowering. 7739 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7740 public: 7741 /// CallOperand - If this is the result output operand or a clobber 7742 /// this is null, otherwise it is the incoming operand to the CallInst. 7743 /// This gets modified as the asm is processed. 7744 SDValue CallOperand; 7745 7746 /// AssignedRegs - If this is a register or register class operand, this 7747 /// contains the set of register corresponding to the operand. 7748 RegsForValue AssignedRegs; 7749 7750 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7751 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7752 } 7753 7754 /// Whether or not this operand accesses memory 7755 bool hasMemory(const TargetLowering &TLI) const { 7756 // Indirect operand accesses access memory. 7757 if (isIndirect) 7758 return true; 7759 7760 for (const auto &Code : Codes) 7761 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7762 return true; 7763 7764 return false; 7765 } 7766 7767 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7768 /// corresponds to. If there is no Value* for this operand, it returns 7769 /// MVT::Other. 7770 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7771 const DataLayout &DL) const { 7772 if (!CallOperandVal) return MVT::Other; 7773 7774 if (isa<BasicBlock>(CallOperandVal)) 7775 return TLI.getProgramPointerTy(DL); 7776 7777 llvm::Type *OpTy = CallOperandVal->getType(); 7778 7779 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7780 // If this is an indirect operand, the operand is a pointer to the 7781 // accessed type. 7782 if (isIndirect) { 7783 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7784 if (!PtrTy) 7785 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7786 OpTy = PtrTy->getElementType(); 7787 } 7788 7789 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7790 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7791 if (STy->getNumElements() == 1) 7792 OpTy = STy->getElementType(0); 7793 7794 // If OpTy is not a single value, it may be a struct/union that we 7795 // can tile with integers. 7796 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7797 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7798 switch (BitSize) { 7799 default: break; 7800 case 1: 7801 case 8: 7802 case 16: 7803 case 32: 7804 case 64: 7805 case 128: 7806 OpTy = IntegerType::get(Context, BitSize); 7807 break; 7808 } 7809 } 7810 7811 return TLI.getValueType(DL, OpTy, true); 7812 } 7813 }; 7814 7815 7816 } // end anonymous namespace 7817 7818 /// Make sure that the output operand \p OpInfo and its corresponding input 7819 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7820 /// out). 7821 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7822 SDISelAsmOperandInfo &MatchingOpInfo, 7823 SelectionDAG &DAG) { 7824 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7825 return; 7826 7827 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7828 const auto &TLI = DAG.getTargetLoweringInfo(); 7829 7830 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7831 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7832 OpInfo.ConstraintVT); 7833 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7834 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7835 MatchingOpInfo.ConstraintVT); 7836 if ((OpInfo.ConstraintVT.isInteger() != 7837 MatchingOpInfo.ConstraintVT.isInteger()) || 7838 (MatchRC.second != InputRC.second)) { 7839 // FIXME: error out in a more elegant fashion 7840 report_fatal_error("Unsupported asm: input constraint" 7841 " with a matching output constraint of" 7842 " incompatible type!"); 7843 } 7844 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7845 } 7846 7847 /// Get a direct memory input to behave well as an indirect operand. 7848 /// This may introduce stores, hence the need for a \p Chain. 7849 /// \return The (possibly updated) chain. 7850 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7851 SDISelAsmOperandInfo &OpInfo, 7852 SelectionDAG &DAG) { 7853 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7854 7855 // If we don't have an indirect input, put it in the constpool if we can, 7856 // otherwise spill it to a stack slot. 7857 // TODO: This isn't quite right. We need to handle these according to 7858 // the addressing mode that the constraint wants. Also, this may take 7859 // an additional register for the computation and we don't want that 7860 // either. 7861 7862 // If the operand is a float, integer, or vector constant, spill to a 7863 // constant pool entry to get its address. 7864 const Value *OpVal = OpInfo.CallOperandVal; 7865 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7866 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7867 OpInfo.CallOperand = DAG.getConstantPool( 7868 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7869 return Chain; 7870 } 7871 7872 // Otherwise, create a stack slot and emit a store to it before the asm. 7873 Type *Ty = OpVal->getType(); 7874 auto &DL = DAG.getDataLayout(); 7875 uint64_t TySize = DL.getTypeAllocSize(Ty); 7876 MachineFunction &MF = DAG.getMachineFunction(); 7877 int SSFI = MF.getFrameInfo().CreateStackObject( 7878 TySize, DL.getPrefTypeAlign(Ty), false); 7879 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7880 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7881 MachinePointerInfo::getFixedStack(MF, SSFI), 7882 TLI.getMemValueType(DL, Ty)); 7883 OpInfo.CallOperand = StackSlot; 7884 7885 return Chain; 7886 } 7887 7888 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7889 /// specified operand. We prefer to assign virtual registers, to allow the 7890 /// register allocator to handle the assignment process. However, if the asm 7891 /// uses features that we can't model on machineinstrs, we have SDISel do the 7892 /// allocation. This produces generally horrible, but correct, code. 7893 /// 7894 /// OpInfo describes the operand 7895 /// RefOpInfo describes the matching operand if any, the operand otherwise 7896 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7897 SDISelAsmOperandInfo &OpInfo, 7898 SDISelAsmOperandInfo &RefOpInfo) { 7899 LLVMContext &Context = *DAG.getContext(); 7900 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7901 7902 MachineFunction &MF = DAG.getMachineFunction(); 7903 SmallVector<unsigned, 4> Regs; 7904 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7905 7906 // No work to do for memory operations. 7907 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7908 return; 7909 7910 // If this is a constraint for a single physreg, or a constraint for a 7911 // register class, find it. 7912 unsigned AssignedReg; 7913 const TargetRegisterClass *RC; 7914 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7915 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7916 // RC is unset only on failure. Return immediately. 7917 if (!RC) 7918 return; 7919 7920 // Get the actual register value type. This is important, because the user 7921 // may have asked for (e.g.) the AX register in i32 type. We need to 7922 // remember that AX is actually i16 to get the right extension. 7923 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7924 7925 if (OpInfo.ConstraintVT != MVT::Other) { 7926 // If this is an FP operand in an integer register (or visa versa), or more 7927 // generally if the operand value disagrees with the register class we plan 7928 // to stick it in, fix the operand type. 7929 // 7930 // If this is an input value, the bitcast to the new type is done now. 7931 // Bitcast for output value is done at the end of visitInlineAsm(). 7932 if ((OpInfo.Type == InlineAsm::isOutput || 7933 OpInfo.Type == InlineAsm::isInput) && 7934 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7935 // Try to convert to the first EVT that the reg class contains. If the 7936 // types are identical size, use a bitcast to convert (e.g. two differing 7937 // vector types). Note: output bitcast is done at the end of 7938 // visitInlineAsm(). 7939 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7940 // Exclude indirect inputs while they are unsupported because the code 7941 // to perform the load is missing and thus OpInfo.CallOperand still 7942 // refers to the input address rather than the pointed-to value. 7943 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7944 OpInfo.CallOperand = 7945 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7946 OpInfo.ConstraintVT = RegVT; 7947 // If the operand is an FP value and we want it in integer registers, 7948 // use the corresponding integer type. This turns an f64 value into 7949 // i64, which can be passed with two i32 values on a 32-bit machine. 7950 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7951 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7952 if (OpInfo.Type == InlineAsm::isInput) 7953 OpInfo.CallOperand = 7954 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7955 OpInfo.ConstraintVT = VT; 7956 } 7957 } 7958 } 7959 7960 // No need to allocate a matching input constraint since the constraint it's 7961 // matching to has already been allocated. 7962 if (OpInfo.isMatchingInputConstraint()) 7963 return; 7964 7965 EVT ValueVT = OpInfo.ConstraintVT; 7966 if (OpInfo.ConstraintVT == MVT::Other) 7967 ValueVT = RegVT; 7968 7969 // Initialize NumRegs. 7970 unsigned NumRegs = 1; 7971 if (OpInfo.ConstraintVT != MVT::Other) 7972 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7973 7974 // If this is a constraint for a specific physical register, like {r17}, 7975 // assign it now. 7976 7977 // If this associated to a specific register, initialize iterator to correct 7978 // place. If virtual, make sure we have enough registers 7979 7980 // Initialize iterator if necessary 7981 TargetRegisterClass::iterator I = RC->begin(); 7982 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7983 7984 // Do not check for single registers. 7985 if (AssignedReg) { 7986 for (; *I != AssignedReg; ++I) 7987 assert(I != RC->end() && "AssignedReg should be member of RC"); 7988 } 7989 7990 for (; NumRegs; --NumRegs, ++I) { 7991 assert(I != RC->end() && "Ran out of registers to allocate!"); 7992 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7993 Regs.push_back(R); 7994 } 7995 7996 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7997 } 7998 7999 static unsigned 8000 findMatchingInlineAsmOperand(unsigned OperandNo, 8001 const std::vector<SDValue> &AsmNodeOperands) { 8002 // Scan until we find the definition we already emitted of this operand. 8003 unsigned CurOp = InlineAsm::Op_FirstOperand; 8004 for (; OperandNo; --OperandNo) { 8005 // Advance to the next operand. 8006 unsigned OpFlag = 8007 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8008 assert((InlineAsm::isRegDefKind(OpFlag) || 8009 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8010 InlineAsm::isMemKind(OpFlag)) && 8011 "Skipped past definitions?"); 8012 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8013 } 8014 return CurOp; 8015 } 8016 8017 namespace { 8018 8019 class ExtraFlags { 8020 unsigned Flags = 0; 8021 8022 public: 8023 explicit ExtraFlags(const CallBase &Call) { 8024 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8025 if (IA->hasSideEffects()) 8026 Flags |= InlineAsm::Extra_HasSideEffects; 8027 if (IA->isAlignStack()) 8028 Flags |= InlineAsm::Extra_IsAlignStack; 8029 if (Call.isConvergent()) 8030 Flags |= InlineAsm::Extra_IsConvergent; 8031 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8032 } 8033 8034 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8035 // Ideally, we would only check against memory constraints. However, the 8036 // meaning of an Other constraint can be target-specific and we can't easily 8037 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8038 // for Other constraints as well. 8039 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8040 OpInfo.ConstraintType == TargetLowering::C_Other) { 8041 if (OpInfo.Type == InlineAsm::isInput) 8042 Flags |= InlineAsm::Extra_MayLoad; 8043 else if (OpInfo.Type == InlineAsm::isOutput) 8044 Flags |= InlineAsm::Extra_MayStore; 8045 else if (OpInfo.Type == InlineAsm::isClobber) 8046 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8047 } 8048 } 8049 8050 unsigned get() const { return Flags; } 8051 }; 8052 8053 } // end anonymous namespace 8054 8055 /// visitInlineAsm - Handle a call to an InlineAsm object. 8056 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8057 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8058 8059 /// ConstraintOperands - Information about all of the constraints. 8060 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8061 8062 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8063 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8064 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8065 8066 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8067 // AsmDialect, MayLoad, MayStore). 8068 bool HasSideEffect = IA->hasSideEffects(); 8069 ExtraFlags ExtraInfo(Call); 8070 8071 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8072 unsigned ResNo = 0; // ResNo - The result number of the next output. 8073 unsigned NumMatchingOps = 0; 8074 for (auto &T : TargetConstraints) { 8075 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8076 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8077 8078 // Compute the value type for each operand. 8079 if (OpInfo.Type == InlineAsm::isInput || 8080 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8081 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8082 8083 // Process the call argument. BasicBlocks are labels, currently appearing 8084 // only in asm's. 8085 if (isa<CallBrInst>(Call) && 8086 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8087 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8088 NumMatchingOps) && 8089 (NumMatchingOps == 0 || 8090 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8091 NumMatchingOps))) { 8092 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8093 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8094 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8095 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8096 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8097 } else { 8098 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8099 } 8100 8101 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8102 DAG.getDataLayout()); 8103 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8104 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8105 // The return value of the call is this value. As such, there is no 8106 // corresponding argument. 8107 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8108 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8109 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8110 DAG.getDataLayout(), STy->getElementType(ResNo)); 8111 } else { 8112 assert(ResNo == 0 && "Asm only has one result!"); 8113 OpInfo.ConstraintVT = 8114 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8115 } 8116 ++ResNo; 8117 } else { 8118 OpInfo.ConstraintVT = MVT::Other; 8119 } 8120 8121 if (OpInfo.hasMatchingInput()) 8122 ++NumMatchingOps; 8123 8124 if (!HasSideEffect) 8125 HasSideEffect = OpInfo.hasMemory(TLI); 8126 8127 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8128 // FIXME: Could we compute this on OpInfo rather than T? 8129 8130 // Compute the constraint code and ConstraintType to use. 8131 TLI.ComputeConstraintToUse(T, SDValue()); 8132 8133 if (T.ConstraintType == TargetLowering::C_Immediate && 8134 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8135 // We've delayed emitting a diagnostic like the "n" constraint because 8136 // inlining could cause an integer showing up. 8137 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8138 "' expects an integer constant " 8139 "expression"); 8140 8141 ExtraInfo.update(T); 8142 } 8143 8144 8145 // We won't need to flush pending loads if this asm doesn't touch 8146 // memory and is nonvolatile. 8147 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8148 8149 bool IsCallBr = isa<CallBrInst>(Call); 8150 if (IsCallBr) { 8151 // If this is a callbr we need to flush pending exports since inlineasm_br 8152 // is a terminator. We need to do this before nodes are glued to 8153 // the inlineasm_br node. 8154 Chain = getControlRoot(); 8155 } 8156 8157 // Second pass over the constraints: compute which constraint option to use. 8158 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8159 // If this is an output operand with a matching input operand, look up the 8160 // matching input. If their types mismatch, e.g. one is an integer, the 8161 // other is floating point, or their sizes are different, flag it as an 8162 // error. 8163 if (OpInfo.hasMatchingInput()) { 8164 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8165 patchMatchingInput(OpInfo, Input, DAG); 8166 } 8167 8168 // Compute the constraint code and ConstraintType to use. 8169 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8170 8171 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8172 OpInfo.Type == InlineAsm::isClobber) 8173 continue; 8174 8175 // If this is a memory input, and if the operand is not indirect, do what we 8176 // need to provide an address for the memory input. 8177 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8178 !OpInfo.isIndirect) { 8179 assert((OpInfo.isMultipleAlternative || 8180 (OpInfo.Type == InlineAsm::isInput)) && 8181 "Can only indirectify direct input operands!"); 8182 8183 // Memory operands really want the address of the value. 8184 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8185 8186 // There is no longer a Value* corresponding to this operand. 8187 OpInfo.CallOperandVal = nullptr; 8188 8189 // It is now an indirect operand. 8190 OpInfo.isIndirect = true; 8191 } 8192 8193 } 8194 8195 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8196 std::vector<SDValue> AsmNodeOperands; 8197 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8198 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8199 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8200 8201 // If we have a !srcloc metadata node associated with it, we want to attach 8202 // this to the ultimately generated inline asm machineinstr. To do this, we 8203 // pass in the third operand as this (potentially null) inline asm MDNode. 8204 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8205 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8206 8207 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8208 // bits as operand 3. 8209 AsmNodeOperands.push_back(DAG.getTargetConstant( 8210 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8211 8212 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8213 // this, assign virtual and physical registers for inputs and otput. 8214 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8215 // Assign Registers. 8216 SDISelAsmOperandInfo &RefOpInfo = 8217 OpInfo.isMatchingInputConstraint() 8218 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8219 : OpInfo; 8220 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8221 8222 auto DetectWriteToReservedRegister = [&]() { 8223 const MachineFunction &MF = DAG.getMachineFunction(); 8224 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8225 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8226 if (Register::isPhysicalRegister(Reg) && 8227 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8228 const char *RegName = TRI.getName(Reg); 8229 emitInlineAsmError(Call, "write to reserved register '" + 8230 Twine(RegName) + "'"); 8231 return true; 8232 } 8233 } 8234 return false; 8235 }; 8236 8237 switch (OpInfo.Type) { 8238 case InlineAsm::isOutput: 8239 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8240 unsigned ConstraintID = 8241 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8242 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8243 "Failed to convert memory constraint code to constraint id."); 8244 8245 // Add information to the INLINEASM node to know about this output. 8246 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8247 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8248 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8249 MVT::i32)); 8250 AsmNodeOperands.push_back(OpInfo.CallOperand); 8251 } else { 8252 // Otherwise, this outputs to a register (directly for C_Register / 8253 // C_RegisterClass, and a target-defined fashion for 8254 // C_Immediate/C_Other). Find a register that we can use. 8255 if (OpInfo.AssignedRegs.Regs.empty()) { 8256 emitInlineAsmError( 8257 Call, "couldn't allocate output register for constraint '" + 8258 Twine(OpInfo.ConstraintCode) + "'"); 8259 return; 8260 } 8261 8262 if (DetectWriteToReservedRegister()) 8263 return; 8264 8265 // Add information to the INLINEASM node to know that this register is 8266 // set. 8267 OpInfo.AssignedRegs.AddInlineAsmOperands( 8268 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8269 : InlineAsm::Kind_RegDef, 8270 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8271 } 8272 break; 8273 8274 case InlineAsm::isInput: { 8275 SDValue InOperandVal = OpInfo.CallOperand; 8276 8277 if (OpInfo.isMatchingInputConstraint()) { 8278 // If this is required to match an output register we have already set, 8279 // just use its register. 8280 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8281 AsmNodeOperands); 8282 unsigned OpFlag = 8283 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8284 if (InlineAsm::isRegDefKind(OpFlag) || 8285 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8286 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8287 if (OpInfo.isIndirect) { 8288 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8289 emitInlineAsmError(Call, "inline asm not supported yet: " 8290 "don't know how to handle tied " 8291 "indirect register inputs"); 8292 return; 8293 } 8294 8295 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8296 SmallVector<unsigned, 4> Regs; 8297 8298 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8299 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8300 MachineRegisterInfo &RegInfo = 8301 DAG.getMachineFunction().getRegInfo(); 8302 for (unsigned i = 0; i != NumRegs; ++i) 8303 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8304 } else { 8305 emitInlineAsmError(Call, 8306 "inline asm error: This value type register " 8307 "class is not natively supported!"); 8308 return; 8309 } 8310 8311 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8312 8313 SDLoc dl = getCurSDLoc(); 8314 // Use the produced MatchedRegs object to 8315 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8316 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8317 true, OpInfo.getMatchedOperand(), dl, 8318 DAG, AsmNodeOperands); 8319 break; 8320 } 8321 8322 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8323 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8324 "Unexpected number of operands"); 8325 // Add information to the INLINEASM node to know about this input. 8326 // See InlineAsm.h isUseOperandTiedToDef. 8327 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8328 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8329 OpInfo.getMatchedOperand()); 8330 AsmNodeOperands.push_back(DAG.getTargetConstant( 8331 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8332 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8333 break; 8334 } 8335 8336 // Treat indirect 'X' constraint as memory. 8337 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8338 OpInfo.isIndirect) 8339 OpInfo.ConstraintType = TargetLowering::C_Memory; 8340 8341 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8342 OpInfo.ConstraintType == TargetLowering::C_Other) { 8343 std::vector<SDValue> Ops; 8344 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8345 Ops, DAG); 8346 if (Ops.empty()) { 8347 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8348 if (isa<ConstantSDNode>(InOperandVal)) { 8349 emitInlineAsmError(Call, "value out of range for constraint '" + 8350 Twine(OpInfo.ConstraintCode) + "'"); 8351 return; 8352 } 8353 8354 emitInlineAsmError(Call, 8355 "invalid operand for inline asm constraint '" + 8356 Twine(OpInfo.ConstraintCode) + "'"); 8357 return; 8358 } 8359 8360 // Add information to the INLINEASM node to know about this input. 8361 unsigned ResOpType = 8362 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8363 AsmNodeOperands.push_back(DAG.getTargetConstant( 8364 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8365 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8366 break; 8367 } 8368 8369 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8370 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8371 assert(InOperandVal.getValueType() == 8372 TLI.getPointerTy(DAG.getDataLayout()) && 8373 "Memory operands expect pointer values"); 8374 8375 unsigned ConstraintID = 8376 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8377 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8378 "Failed to convert memory constraint code to constraint id."); 8379 8380 // Add information to the INLINEASM node to know about this input. 8381 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8382 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8383 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8384 getCurSDLoc(), 8385 MVT::i32)); 8386 AsmNodeOperands.push_back(InOperandVal); 8387 break; 8388 } 8389 8390 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8391 OpInfo.ConstraintType == TargetLowering::C_Register) && 8392 "Unknown constraint type!"); 8393 8394 // TODO: Support this. 8395 if (OpInfo.isIndirect) { 8396 emitInlineAsmError( 8397 Call, "Don't know how to handle indirect register inputs yet " 8398 "for constraint '" + 8399 Twine(OpInfo.ConstraintCode) + "'"); 8400 return; 8401 } 8402 8403 // Copy the input into the appropriate registers. 8404 if (OpInfo.AssignedRegs.Regs.empty()) { 8405 emitInlineAsmError(Call, 8406 "couldn't allocate input reg for constraint '" + 8407 Twine(OpInfo.ConstraintCode) + "'"); 8408 return; 8409 } 8410 8411 if (DetectWriteToReservedRegister()) 8412 return; 8413 8414 SDLoc dl = getCurSDLoc(); 8415 8416 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8417 &Call); 8418 8419 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8420 dl, DAG, AsmNodeOperands); 8421 break; 8422 } 8423 case InlineAsm::isClobber: 8424 // Add the clobbered value to the operand list, so that the register 8425 // allocator is aware that the physreg got clobbered. 8426 if (!OpInfo.AssignedRegs.Regs.empty()) 8427 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8428 false, 0, getCurSDLoc(), DAG, 8429 AsmNodeOperands); 8430 break; 8431 } 8432 } 8433 8434 // Finish up input operands. Set the input chain and add the flag last. 8435 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8436 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8437 8438 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8439 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8440 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8441 Flag = Chain.getValue(1); 8442 8443 // Do additional work to generate outputs. 8444 8445 SmallVector<EVT, 1> ResultVTs; 8446 SmallVector<SDValue, 1> ResultValues; 8447 SmallVector<SDValue, 8> OutChains; 8448 8449 llvm::Type *CallResultType = Call.getType(); 8450 ArrayRef<Type *> ResultTypes; 8451 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8452 ResultTypes = StructResult->elements(); 8453 else if (!CallResultType->isVoidTy()) 8454 ResultTypes = makeArrayRef(CallResultType); 8455 8456 auto CurResultType = ResultTypes.begin(); 8457 auto handleRegAssign = [&](SDValue V) { 8458 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8459 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8460 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8461 ++CurResultType; 8462 // If the type of the inline asm call site return value is different but has 8463 // same size as the type of the asm output bitcast it. One example of this 8464 // is for vectors with different width / number of elements. This can 8465 // happen for register classes that can contain multiple different value 8466 // types. The preg or vreg allocated may not have the same VT as was 8467 // expected. 8468 // 8469 // This can also happen for a return value that disagrees with the register 8470 // class it is put in, eg. a double in a general-purpose register on a 8471 // 32-bit machine. 8472 if (ResultVT != V.getValueType() && 8473 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8474 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8475 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8476 V.getValueType().isInteger()) { 8477 // If a result value was tied to an input value, the computed result 8478 // may have a wider width than the expected result. Extract the 8479 // relevant portion. 8480 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8481 } 8482 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8483 ResultVTs.push_back(ResultVT); 8484 ResultValues.push_back(V); 8485 }; 8486 8487 // Deal with output operands. 8488 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8489 if (OpInfo.Type == InlineAsm::isOutput) { 8490 SDValue Val; 8491 // Skip trivial output operands. 8492 if (OpInfo.AssignedRegs.Regs.empty()) 8493 continue; 8494 8495 switch (OpInfo.ConstraintType) { 8496 case TargetLowering::C_Register: 8497 case TargetLowering::C_RegisterClass: 8498 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8499 Chain, &Flag, &Call); 8500 break; 8501 case TargetLowering::C_Immediate: 8502 case TargetLowering::C_Other: 8503 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8504 OpInfo, DAG); 8505 break; 8506 case TargetLowering::C_Memory: 8507 break; // Already handled. 8508 case TargetLowering::C_Unknown: 8509 assert(false && "Unexpected unknown constraint"); 8510 } 8511 8512 // Indirect output manifest as stores. Record output chains. 8513 if (OpInfo.isIndirect) { 8514 const Value *Ptr = OpInfo.CallOperandVal; 8515 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8516 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8517 MachinePointerInfo(Ptr)); 8518 OutChains.push_back(Store); 8519 } else { 8520 // generate CopyFromRegs to associated registers. 8521 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8522 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8523 for (const SDValue &V : Val->op_values()) 8524 handleRegAssign(V); 8525 } else 8526 handleRegAssign(Val); 8527 } 8528 } 8529 } 8530 8531 // Set results. 8532 if (!ResultValues.empty()) { 8533 assert(CurResultType == ResultTypes.end() && 8534 "Mismatch in number of ResultTypes"); 8535 assert(ResultValues.size() == ResultTypes.size() && 8536 "Mismatch in number of output operands in asm result"); 8537 8538 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8539 DAG.getVTList(ResultVTs), ResultValues); 8540 setValue(&Call, V); 8541 } 8542 8543 // Collect store chains. 8544 if (!OutChains.empty()) 8545 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8546 8547 // Only Update Root if inline assembly has a memory effect. 8548 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8549 DAG.setRoot(Chain); 8550 } 8551 8552 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8553 const Twine &Message) { 8554 LLVMContext &Ctx = *DAG.getContext(); 8555 Ctx.emitError(&Call, Message); 8556 8557 // Make sure we leave the DAG in a valid state 8558 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8559 SmallVector<EVT, 1> ValueVTs; 8560 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8561 8562 if (ValueVTs.empty()) 8563 return; 8564 8565 SmallVector<SDValue, 1> Ops; 8566 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8567 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8568 8569 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8570 } 8571 8572 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8573 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8574 MVT::Other, getRoot(), 8575 getValue(I.getArgOperand(0)), 8576 DAG.getSrcValue(I.getArgOperand(0)))); 8577 } 8578 8579 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8580 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8581 const DataLayout &DL = DAG.getDataLayout(); 8582 SDValue V = DAG.getVAArg( 8583 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8584 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8585 DL.getABITypeAlign(I.getType()).value()); 8586 DAG.setRoot(V.getValue(1)); 8587 8588 if (I.getType()->isPointerTy()) 8589 V = DAG.getPtrExtOrTrunc( 8590 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8591 setValue(&I, V); 8592 } 8593 8594 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8595 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8596 MVT::Other, getRoot(), 8597 getValue(I.getArgOperand(0)), 8598 DAG.getSrcValue(I.getArgOperand(0)))); 8599 } 8600 8601 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8602 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8603 MVT::Other, getRoot(), 8604 getValue(I.getArgOperand(0)), 8605 getValue(I.getArgOperand(1)), 8606 DAG.getSrcValue(I.getArgOperand(0)), 8607 DAG.getSrcValue(I.getArgOperand(1)))); 8608 } 8609 8610 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8611 const Instruction &I, 8612 SDValue Op) { 8613 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8614 if (!Range) 8615 return Op; 8616 8617 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8618 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8619 return Op; 8620 8621 APInt Lo = CR.getUnsignedMin(); 8622 if (!Lo.isMinValue()) 8623 return Op; 8624 8625 APInt Hi = CR.getUnsignedMax(); 8626 unsigned Bits = std::max(Hi.getActiveBits(), 8627 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8628 8629 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8630 8631 SDLoc SL = getCurSDLoc(); 8632 8633 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8634 DAG.getValueType(SmallVT)); 8635 unsigned NumVals = Op.getNode()->getNumValues(); 8636 if (NumVals == 1) 8637 return ZExt; 8638 8639 SmallVector<SDValue, 4> Ops; 8640 8641 Ops.push_back(ZExt); 8642 for (unsigned I = 1; I != NumVals; ++I) 8643 Ops.push_back(Op.getValue(I)); 8644 8645 return DAG.getMergeValues(Ops, SL); 8646 } 8647 8648 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8649 /// the call being lowered. 8650 /// 8651 /// This is a helper for lowering intrinsics that follow a target calling 8652 /// convention or require stack pointer adjustment. Only a subset of the 8653 /// intrinsic's operands need to participate in the calling convention. 8654 void SelectionDAGBuilder::populateCallLoweringInfo( 8655 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8656 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8657 bool IsPatchPoint) { 8658 TargetLowering::ArgListTy Args; 8659 Args.reserve(NumArgs); 8660 8661 // Populate the argument list. 8662 // Attributes for args start at offset 1, after the return attribute. 8663 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8664 ArgI != ArgE; ++ArgI) { 8665 const Value *V = Call->getOperand(ArgI); 8666 8667 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8668 8669 TargetLowering::ArgListEntry Entry; 8670 Entry.Node = getValue(V); 8671 Entry.Ty = V->getType(); 8672 Entry.setAttributes(Call, ArgI); 8673 Args.push_back(Entry); 8674 } 8675 8676 CLI.setDebugLoc(getCurSDLoc()) 8677 .setChain(getRoot()) 8678 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8679 .setDiscardResult(Call->use_empty()) 8680 .setIsPatchPoint(IsPatchPoint) 8681 .setIsPreallocated( 8682 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8683 } 8684 8685 /// Add a stack map intrinsic call's live variable operands to a stackmap 8686 /// or patchpoint target node's operand list. 8687 /// 8688 /// Constants are converted to TargetConstants purely as an optimization to 8689 /// avoid constant materialization and register allocation. 8690 /// 8691 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8692 /// generate addess computation nodes, and so FinalizeISel can convert the 8693 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8694 /// address materialization and register allocation, but may also be required 8695 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8696 /// alloca in the entry block, then the runtime may assume that the alloca's 8697 /// StackMap location can be read immediately after compilation and that the 8698 /// location is valid at any point during execution (this is similar to the 8699 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8700 /// only available in a register, then the runtime would need to trap when 8701 /// execution reaches the StackMap in order to read the alloca's location. 8702 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8703 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8704 SelectionDAGBuilder &Builder) { 8705 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8706 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8707 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8708 Ops.push_back( 8709 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8710 Ops.push_back( 8711 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8712 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8713 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8714 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8715 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8716 } else 8717 Ops.push_back(OpVal); 8718 } 8719 } 8720 8721 /// Lower llvm.experimental.stackmap directly to its target opcode. 8722 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8723 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8724 // [live variables...]) 8725 8726 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8727 8728 SDValue Chain, InFlag, Callee, NullPtr; 8729 SmallVector<SDValue, 32> Ops; 8730 8731 SDLoc DL = getCurSDLoc(); 8732 Callee = getValue(CI.getCalledOperand()); 8733 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8734 8735 // The stackmap intrinsic only records the live variables (the arguments 8736 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8737 // intrinsic, this won't be lowered to a function call. This means we don't 8738 // have to worry about calling conventions and target specific lowering code. 8739 // Instead we perform the call lowering right here. 8740 // 8741 // chain, flag = CALLSEQ_START(chain, 0, 0) 8742 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8743 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8744 // 8745 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8746 InFlag = Chain.getValue(1); 8747 8748 // Add the <id> and <numBytes> constants. 8749 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8750 Ops.push_back(DAG.getTargetConstant( 8751 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8752 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8753 Ops.push_back(DAG.getTargetConstant( 8754 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8755 MVT::i32)); 8756 8757 // Push live variables for the stack map. 8758 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8759 8760 // We are not pushing any register mask info here on the operands list, 8761 // because the stackmap doesn't clobber anything. 8762 8763 // Push the chain and the glue flag. 8764 Ops.push_back(Chain); 8765 Ops.push_back(InFlag); 8766 8767 // Create the STACKMAP node. 8768 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8769 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8770 Chain = SDValue(SM, 0); 8771 InFlag = Chain.getValue(1); 8772 8773 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8774 8775 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8776 8777 // Set the root to the target-lowered call chain. 8778 DAG.setRoot(Chain); 8779 8780 // Inform the Frame Information that we have a stackmap in this function. 8781 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8782 } 8783 8784 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8785 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8786 const BasicBlock *EHPadBB) { 8787 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8788 // i32 <numBytes>, 8789 // i8* <target>, 8790 // i32 <numArgs>, 8791 // [Args...], 8792 // [live variables...]) 8793 8794 CallingConv::ID CC = CB.getCallingConv(); 8795 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8796 bool HasDef = !CB.getType()->isVoidTy(); 8797 SDLoc dl = getCurSDLoc(); 8798 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8799 8800 // Handle immediate and symbolic callees. 8801 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8802 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8803 /*isTarget=*/true); 8804 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8805 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8806 SDLoc(SymbolicCallee), 8807 SymbolicCallee->getValueType(0)); 8808 8809 // Get the real number of arguments participating in the call <numArgs> 8810 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8811 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8812 8813 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8814 // Intrinsics include all meta-operands up to but not including CC. 8815 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8816 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8817 "Not enough arguments provided to the patchpoint intrinsic"); 8818 8819 // For AnyRegCC the arguments are lowered later on manually. 8820 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8821 Type *ReturnTy = 8822 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8823 8824 TargetLowering::CallLoweringInfo CLI(DAG); 8825 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8826 ReturnTy, true); 8827 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8828 8829 SDNode *CallEnd = Result.second.getNode(); 8830 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8831 CallEnd = CallEnd->getOperand(0).getNode(); 8832 8833 /// Get a call instruction from the call sequence chain. 8834 /// Tail calls are not allowed. 8835 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8836 "Expected a callseq node."); 8837 SDNode *Call = CallEnd->getOperand(0).getNode(); 8838 bool HasGlue = Call->getGluedNode(); 8839 8840 // Replace the target specific call node with the patchable intrinsic. 8841 SmallVector<SDValue, 8> Ops; 8842 8843 // Add the <id> and <numBytes> constants. 8844 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 8845 Ops.push_back(DAG.getTargetConstant( 8846 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8847 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 8848 Ops.push_back(DAG.getTargetConstant( 8849 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8850 MVT::i32)); 8851 8852 // Add the callee. 8853 Ops.push_back(Callee); 8854 8855 // Adjust <numArgs> to account for any arguments that have been passed on the 8856 // stack instead. 8857 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8858 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8859 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8860 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8861 8862 // Add the calling convention 8863 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8864 8865 // Add the arguments we omitted previously. The register allocator should 8866 // place these in any free register. 8867 if (IsAnyRegCC) 8868 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8869 Ops.push_back(getValue(CB.getArgOperand(i))); 8870 8871 // Push the arguments from the call instruction up to the register mask. 8872 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8873 Ops.append(Call->op_begin() + 2, e); 8874 8875 // Push live variables for the stack map. 8876 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 8877 8878 // Push the register mask info. 8879 if (HasGlue) 8880 Ops.push_back(*(Call->op_end()-2)); 8881 else 8882 Ops.push_back(*(Call->op_end()-1)); 8883 8884 // Push the chain (this is originally the first operand of the call, but 8885 // becomes now the last or second to last operand). 8886 Ops.push_back(*(Call->op_begin())); 8887 8888 // Push the glue flag (last operand). 8889 if (HasGlue) 8890 Ops.push_back(*(Call->op_end()-1)); 8891 8892 SDVTList NodeTys; 8893 if (IsAnyRegCC && HasDef) { 8894 // Create the return types based on the intrinsic definition 8895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8896 SmallVector<EVT, 3> ValueVTs; 8897 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 8898 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8899 8900 // There is always a chain and a glue type at the end 8901 ValueVTs.push_back(MVT::Other); 8902 ValueVTs.push_back(MVT::Glue); 8903 NodeTys = DAG.getVTList(ValueVTs); 8904 } else 8905 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8906 8907 // Replace the target specific call node with a PATCHPOINT node. 8908 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8909 dl, NodeTys, Ops); 8910 8911 // Update the NodeMap. 8912 if (HasDef) { 8913 if (IsAnyRegCC) 8914 setValue(&CB, SDValue(MN, 0)); 8915 else 8916 setValue(&CB, Result.first); 8917 } 8918 8919 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8920 // call sequence. Furthermore the location of the chain and glue can change 8921 // when the AnyReg calling convention is used and the intrinsic returns a 8922 // value. 8923 if (IsAnyRegCC && HasDef) { 8924 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8925 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8926 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8927 } else 8928 DAG.ReplaceAllUsesWith(Call, MN); 8929 DAG.DeleteNode(Call); 8930 8931 // Inform the Frame Information that we have a patchpoint in this function. 8932 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8933 } 8934 8935 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8936 unsigned Intrinsic) { 8937 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8938 SDValue Op1 = getValue(I.getArgOperand(0)); 8939 SDValue Op2; 8940 if (I.getNumArgOperands() > 1) 8941 Op2 = getValue(I.getArgOperand(1)); 8942 SDLoc dl = getCurSDLoc(); 8943 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8944 SDValue Res; 8945 SDNodeFlags SDFlags; 8946 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 8947 SDFlags.copyFMF(*FPMO); 8948 8949 switch (Intrinsic) { 8950 case Intrinsic::vector_reduce_fadd: 8951 if (SDFlags.hasAllowReassociation()) 8952 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8953 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 8954 SDFlags); 8955 else 8956 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 8957 break; 8958 case Intrinsic::vector_reduce_fmul: 8959 if (SDFlags.hasAllowReassociation()) 8960 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8961 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 8962 SDFlags); 8963 else 8964 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 8965 break; 8966 case Intrinsic::vector_reduce_add: 8967 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8968 break; 8969 case Intrinsic::vector_reduce_mul: 8970 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8971 break; 8972 case Intrinsic::vector_reduce_and: 8973 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8974 break; 8975 case Intrinsic::vector_reduce_or: 8976 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8977 break; 8978 case Intrinsic::vector_reduce_xor: 8979 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8980 break; 8981 case Intrinsic::vector_reduce_smax: 8982 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8983 break; 8984 case Intrinsic::vector_reduce_smin: 8985 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8986 break; 8987 case Intrinsic::vector_reduce_umax: 8988 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8989 break; 8990 case Intrinsic::vector_reduce_umin: 8991 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8992 break; 8993 case Intrinsic::vector_reduce_fmax: 8994 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 8995 break; 8996 case Intrinsic::vector_reduce_fmin: 8997 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 8998 break; 8999 default: 9000 llvm_unreachable("Unhandled vector reduce intrinsic"); 9001 } 9002 setValue(&I, Res); 9003 } 9004 9005 /// Returns an AttributeList representing the attributes applied to the return 9006 /// value of the given call. 9007 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9008 SmallVector<Attribute::AttrKind, 2> Attrs; 9009 if (CLI.RetSExt) 9010 Attrs.push_back(Attribute::SExt); 9011 if (CLI.RetZExt) 9012 Attrs.push_back(Attribute::ZExt); 9013 if (CLI.IsInReg) 9014 Attrs.push_back(Attribute::InReg); 9015 9016 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9017 Attrs); 9018 } 9019 9020 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9021 /// implementation, which just calls LowerCall. 9022 /// FIXME: When all targets are 9023 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9024 std::pair<SDValue, SDValue> 9025 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9026 // Handle the incoming return values from the call. 9027 CLI.Ins.clear(); 9028 Type *OrigRetTy = CLI.RetTy; 9029 SmallVector<EVT, 4> RetTys; 9030 SmallVector<uint64_t, 4> Offsets; 9031 auto &DL = CLI.DAG.getDataLayout(); 9032 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9033 9034 if (CLI.IsPostTypeLegalization) { 9035 // If we are lowering a libcall after legalization, split the return type. 9036 SmallVector<EVT, 4> OldRetTys; 9037 SmallVector<uint64_t, 4> OldOffsets; 9038 RetTys.swap(OldRetTys); 9039 Offsets.swap(OldOffsets); 9040 9041 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9042 EVT RetVT = OldRetTys[i]; 9043 uint64_t Offset = OldOffsets[i]; 9044 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9045 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9046 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9047 RetTys.append(NumRegs, RegisterVT); 9048 for (unsigned j = 0; j != NumRegs; ++j) 9049 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9050 } 9051 } 9052 9053 SmallVector<ISD::OutputArg, 4> Outs; 9054 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9055 9056 bool CanLowerReturn = 9057 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9058 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9059 9060 SDValue DemoteStackSlot; 9061 int DemoteStackIdx = -100; 9062 if (!CanLowerReturn) { 9063 // FIXME: equivalent assert? 9064 // assert(!CS.hasInAllocaArgument() && 9065 // "sret demotion is incompatible with inalloca"); 9066 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9067 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9068 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9069 DemoteStackIdx = 9070 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9071 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9072 DL.getAllocaAddrSpace()); 9073 9074 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9075 ArgListEntry Entry; 9076 Entry.Node = DemoteStackSlot; 9077 Entry.Ty = StackSlotPtrType; 9078 Entry.IsSExt = false; 9079 Entry.IsZExt = false; 9080 Entry.IsInReg = false; 9081 Entry.IsSRet = true; 9082 Entry.IsNest = false; 9083 Entry.IsByVal = false; 9084 Entry.IsByRef = false; 9085 Entry.IsReturned = false; 9086 Entry.IsSwiftSelf = false; 9087 Entry.IsSwiftError = false; 9088 Entry.IsCFGuardTarget = false; 9089 Entry.Alignment = Alignment; 9090 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9091 CLI.NumFixedArgs += 1; 9092 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9093 9094 // sret demotion isn't compatible with tail-calls, since the sret argument 9095 // points into the callers stack frame. 9096 CLI.IsTailCall = false; 9097 } else { 9098 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9099 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9100 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9101 ISD::ArgFlagsTy Flags; 9102 if (NeedsRegBlock) { 9103 Flags.setInConsecutiveRegs(); 9104 if (I == RetTys.size() - 1) 9105 Flags.setInConsecutiveRegsLast(); 9106 } 9107 EVT VT = RetTys[I]; 9108 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9109 CLI.CallConv, VT); 9110 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9111 CLI.CallConv, VT); 9112 for (unsigned i = 0; i != NumRegs; ++i) { 9113 ISD::InputArg MyFlags; 9114 MyFlags.Flags = Flags; 9115 MyFlags.VT = RegisterVT; 9116 MyFlags.ArgVT = VT; 9117 MyFlags.Used = CLI.IsReturnValueUsed; 9118 if (CLI.RetTy->isPointerTy()) { 9119 MyFlags.Flags.setPointer(); 9120 MyFlags.Flags.setPointerAddrSpace( 9121 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9122 } 9123 if (CLI.RetSExt) 9124 MyFlags.Flags.setSExt(); 9125 if (CLI.RetZExt) 9126 MyFlags.Flags.setZExt(); 9127 if (CLI.IsInReg) 9128 MyFlags.Flags.setInReg(); 9129 CLI.Ins.push_back(MyFlags); 9130 } 9131 } 9132 } 9133 9134 // We push in swifterror return as the last element of CLI.Ins. 9135 ArgListTy &Args = CLI.getArgs(); 9136 if (supportSwiftError()) { 9137 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9138 if (Args[i].IsSwiftError) { 9139 ISD::InputArg MyFlags; 9140 MyFlags.VT = getPointerTy(DL); 9141 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9142 MyFlags.Flags.setSwiftError(); 9143 CLI.Ins.push_back(MyFlags); 9144 } 9145 } 9146 } 9147 9148 // Handle all of the outgoing arguments. 9149 CLI.Outs.clear(); 9150 CLI.OutVals.clear(); 9151 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9152 SmallVector<EVT, 4> ValueVTs; 9153 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9154 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9155 Type *FinalType = Args[i].Ty; 9156 if (Args[i].IsByVal) 9157 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9158 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9159 FinalType, CLI.CallConv, CLI.IsVarArg); 9160 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9161 ++Value) { 9162 EVT VT = ValueVTs[Value]; 9163 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9164 SDValue Op = SDValue(Args[i].Node.getNode(), 9165 Args[i].Node.getResNo() + Value); 9166 ISD::ArgFlagsTy Flags; 9167 9168 // Certain targets (such as MIPS), may have a different ABI alignment 9169 // for a type depending on the context. Give the target a chance to 9170 // specify the alignment it wants. 9171 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9172 9173 if (Args[i].Ty->isPointerTy()) { 9174 Flags.setPointer(); 9175 Flags.setPointerAddrSpace( 9176 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9177 } 9178 if (Args[i].IsZExt) 9179 Flags.setZExt(); 9180 if (Args[i].IsSExt) 9181 Flags.setSExt(); 9182 if (Args[i].IsInReg) { 9183 // If we are using vectorcall calling convention, a structure that is 9184 // passed InReg - is surely an HVA 9185 if (CLI.CallConv == CallingConv::X86_VectorCall && 9186 isa<StructType>(FinalType)) { 9187 // The first value of a structure is marked 9188 if (0 == Value) 9189 Flags.setHvaStart(); 9190 Flags.setHva(); 9191 } 9192 // Set InReg Flag 9193 Flags.setInReg(); 9194 } 9195 if (Args[i].IsSRet) 9196 Flags.setSRet(); 9197 if (Args[i].IsSwiftSelf) 9198 Flags.setSwiftSelf(); 9199 if (Args[i].IsSwiftError) 9200 Flags.setSwiftError(); 9201 if (Args[i].IsCFGuardTarget) 9202 Flags.setCFGuardTarget(); 9203 if (Args[i].IsByVal) 9204 Flags.setByVal(); 9205 if (Args[i].IsByRef) 9206 Flags.setByRef(); 9207 if (Args[i].IsPreallocated) { 9208 Flags.setPreallocated(); 9209 // Set the byval flag for CCAssignFn callbacks that don't know about 9210 // preallocated. This way we can know how many bytes we should've 9211 // allocated and how many bytes a callee cleanup function will pop. If 9212 // we port preallocated to more targets, we'll have to add custom 9213 // preallocated handling in the various CC lowering callbacks. 9214 Flags.setByVal(); 9215 } 9216 if (Args[i].IsInAlloca) { 9217 Flags.setInAlloca(); 9218 // Set the byval flag for CCAssignFn callbacks that don't know about 9219 // inalloca. This way we can know how many bytes we should've allocated 9220 // and how many bytes a callee cleanup function will pop. If we port 9221 // inalloca to more targets, we'll have to add custom inalloca handling 9222 // in the various CC lowering callbacks. 9223 Flags.setByVal(); 9224 } 9225 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9226 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9227 Type *ElementTy = Ty->getElementType(); 9228 9229 unsigned FrameSize = DL.getTypeAllocSize( 9230 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9231 Flags.setByValSize(FrameSize); 9232 9233 // info is not there but there are cases it cannot get right. 9234 Align FrameAlign; 9235 if (auto MA = Args[i].Alignment) 9236 FrameAlign = *MA; 9237 else 9238 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9239 Flags.setByValAlign(FrameAlign); 9240 } 9241 if (Args[i].IsNest) 9242 Flags.setNest(); 9243 if (NeedsRegBlock) 9244 Flags.setInConsecutiveRegs(); 9245 Flags.setOrigAlign(OriginalAlignment); 9246 9247 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9248 CLI.CallConv, VT); 9249 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9250 CLI.CallConv, VT); 9251 SmallVector<SDValue, 4> Parts(NumParts); 9252 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9253 9254 if (Args[i].IsSExt) 9255 ExtendKind = ISD::SIGN_EXTEND; 9256 else if (Args[i].IsZExt) 9257 ExtendKind = ISD::ZERO_EXTEND; 9258 9259 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9260 // for now. 9261 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9262 CanLowerReturn) { 9263 assert((CLI.RetTy == Args[i].Ty || 9264 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9265 CLI.RetTy->getPointerAddressSpace() == 9266 Args[i].Ty->getPointerAddressSpace())) && 9267 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9268 // Before passing 'returned' to the target lowering code, ensure that 9269 // either the register MVT and the actual EVT are the same size or that 9270 // the return value and argument are extended in the same way; in these 9271 // cases it's safe to pass the argument register value unchanged as the 9272 // return register value (although it's at the target's option whether 9273 // to do so) 9274 // TODO: allow code generation to take advantage of partially preserved 9275 // registers rather than clobbering the entire register when the 9276 // parameter extension method is not compatible with the return 9277 // extension method 9278 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9279 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9280 CLI.RetZExt == Args[i].IsZExt)) 9281 Flags.setReturned(); 9282 } 9283 9284 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9285 CLI.CallConv, ExtendKind); 9286 9287 for (unsigned j = 0; j != NumParts; ++j) { 9288 // if it isn't first piece, alignment must be 1 9289 // For scalable vectors the scalable part is currently handled 9290 // by individual targets, so we just use the known minimum size here. 9291 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9292 i < CLI.NumFixedArgs, i, 9293 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9294 if (NumParts > 1 && j == 0) 9295 MyFlags.Flags.setSplit(); 9296 else if (j != 0) { 9297 MyFlags.Flags.setOrigAlign(Align(1)); 9298 if (j == NumParts - 1) 9299 MyFlags.Flags.setSplitEnd(); 9300 } 9301 9302 CLI.Outs.push_back(MyFlags); 9303 CLI.OutVals.push_back(Parts[j]); 9304 } 9305 9306 if (NeedsRegBlock && Value == NumValues - 1) 9307 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9308 } 9309 } 9310 9311 SmallVector<SDValue, 4> InVals; 9312 CLI.Chain = LowerCall(CLI, InVals); 9313 9314 // Update CLI.InVals to use outside of this function. 9315 CLI.InVals = InVals; 9316 9317 // Verify that the target's LowerCall behaved as expected. 9318 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9319 "LowerCall didn't return a valid chain!"); 9320 assert((!CLI.IsTailCall || InVals.empty()) && 9321 "LowerCall emitted a return value for a tail call!"); 9322 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9323 "LowerCall didn't emit the correct number of values!"); 9324 9325 // For a tail call, the return value is merely live-out and there aren't 9326 // any nodes in the DAG representing it. Return a special value to 9327 // indicate that a tail call has been emitted and no more Instructions 9328 // should be processed in the current block. 9329 if (CLI.IsTailCall) { 9330 CLI.DAG.setRoot(CLI.Chain); 9331 return std::make_pair(SDValue(), SDValue()); 9332 } 9333 9334 #ifndef NDEBUG 9335 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9336 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9337 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9338 "LowerCall emitted a value with the wrong type!"); 9339 } 9340 #endif 9341 9342 SmallVector<SDValue, 4> ReturnValues; 9343 if (!CanLowerReturn) { 9344 // The instruction result is the result of loading from the 9345 // hidden sret parameter. 9346 SmallVector<EVT, 1> PVTs; 9347 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9348 9349 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9350 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9351 EVT PtrVT = PVTs[0]; 9352 9353 unsigned NumValues = RetTys.size(); 9354 ReturnValues.resize(NumValues); 9355 SmallVector<SDValue, 4> Chains(NumValues); 9356 9357 // An aggregate return value cannot wrap around the address space, so 9358 // offsets to its parts don't wrap either. 9359 SDNodeFlags Flags; 9360 Flags.setNoUnsignedWrap(true); 9361 9362 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9363 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9364 for (unsigned i = 0; i < NumValues; ++i) { 9365 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9366 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9367 PtrVT), Flags); 9368 SDValue L = CLI.DAG.getLoad( 9369 RetTys[i], CLI.DL, CLI.Chain, Add, 9370 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9371 DemoteStackIdx, Offsets[i]), 9372 HiddenSRetAlign); 9373 ReturnValues[i] = L; 9374 Chains[i] = L.getValue(1); 9375 } 9376 9377 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9378 } else { 9379 // Collect the legal value parts into potentially illegal values 9380 // that correspond to the original function's return values. 9381 Optional<ISD::NodeType> AssertOp; 9382 if (CLI.RetSExt) 9383 AssertOp = ISD::AssertSext; 9384 else if (CLI.RetZExt) 9385 AssertOp = ISD::AssertZext; 9386 unsigned CurReg = 0; 9387 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9388 EVT VT = RetTys[I]; 9389 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9390 CLI.CallConv, VT); 9391 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9392 CLI.CallConv, VT); 9393 9394 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9395 NumRegs, RegisterVT, VT, nullptr, 9396 CLI.CallConv, AssertOp)); 9397 CurReg += NumRegs; 9398 } 9399 9400 // For a function returning void, there is no return value. We can't create 9401 // such a node, so we just return a null return value in that case. In 9402 // that case, nothing will actually look at the value. 9403 if (ReturnValues.empty()) 9404 return std::make_pair(SDValue(), CLI.Chain); 9405 } 9406 9407 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9408 CLI.DAG.getVTList(RetTys), ReturnValues); 9409 return std::make_pair(Res, CLI.Chain); 9410 } 9411 9412 /// Places new result values for the node in Results (their number 9413 /// and types must exactly match those of the original return values of 9414 /// the node), or leaves Results empty, which indicates that the node is not 9415 /// to be custom lowered after all. 9416 void TargetLowering::LowerOperationWrapper(SDNode *N, 9417 SmallVectorImpl<SDValue> &Results, 9418 SelectionDAG &DAG) const { 9419 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9420 9421 if (!Res.getNode()) 9422 return; 9423 9424 // If the original node has one result, take the return value from 9425 // LowerOperation as is. It might not be result number 0. 9426 if (N->getNumValues() == 1) { 9427 Results.push_back(Res); 9428 return; 9429 } 9430 9431 // If the original node has multiple results, then the return node should 9432 // have the same number of results. 9433 assert((N->getNumValues() == Res->getNumValues()) && 9434 "Lowering returned the wrong number of results!"); 9435 9436 // Places new result values base on N result number. 9437 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9438 Results.push_back(Res.getValue(I)); 9439 } 9440 9441 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9442 llvm_unreachable("LowerOperation not implemented for this target!"); 9443 } 9444 9445 void 9446 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9447 SDValue Op = getNonRegisterValue(V); 9448 assert((Op.getOpcode() != ISD::CopyFromReg || 9449 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9450 "Copy from a reg to the same reg!"); 9451 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9452 9453 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9454 // If this is an InlineAsm we have to match the registers required, not the 9455 // notional registers required by the type. 9456 9457 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9458 None); // This is not an ABI copy. 9459 SDValue Chain = DAG.getEntryNode(); 9460 9461 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9462 FuncInfo.PreferredExtendType.end()) 9463 ? ISD::ANY_EXTEND 9464 : FuncInfo.PreferredExtendType[V]; 9465 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9466 PendingExports.push_back(Chain); 9467 } 9468 9469 #include "llvm/CodeGen/SelectionDAGISel.h" 9470 9471 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9472 /// entry block, return true. This includes arguments used by switches, since 9473 /// the switch may expand into multiple basic blocks. 9474 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9475 // With FastISel active, we may be splitting blocks, so force creation 9476 // of virtual registers for all non-dead arguments. 9477 if (FastISel) 9478 return A->use_empty(); 9479 9480 const BasicBlock &Entry = A->getParent()->front(); 9481 for (const User *U : A->users()) 9482 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9483 return false; // Use not in entry block. 9484 9485 return true; 9486 } 9487 9488 using ArgCopyElisionMapTy = 9489 DenseMap<const Argument *, 9490 std::pair<const AllocaInst *, const StoreInst *>>; 9491 9492 /// Scan the entry block of the function in FuncInfo for arguments that look 9493 /// like copies into a local alloca. Record any copied arguments in 9494 /// ArgCopyElisionCandidates. 9495 static void 9496 findArgumentCopyElisionCandidates(const DataLayout &DL, 9497 FunctionLoweringInfo *FuncInfo, 9498 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9499 // Record the state of every static alloca used in the entry block. Argument 9500 // allocas are all used in the entry block, so we need approximately as many 9501 // entries as we have arguments. 9502 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9503 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9504 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9505 StaticAllocas.reserve(NumArgs * 2); 9506 9507 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9508 if (!V) 9509 return nullptr; 9510 V = V->stripPointerCasts(); 9511 const auto *AI = dyn_cast<AllocaInst>(V); 9512 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9513 return nullptr; 9514 auto Iter = StaticAllocas.insert({AI, Unknown}); 9515 return &Iter.first->second; 9516 }; 9517 9518 // Look for stores of arguments to static allocas. Look through bitcasts and 9519 // GEPs to handle type coercions, as long as the alloca is fully initialized 9520 // by the store. Any non-store use of an alloca escapes it and any subsequent 9521 // unanalyzed store might write it. 9522 // FIXME: Handle structs initialized with multiple stores. 9523 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9524 // Look for stores, and handle non-store uses conservatively. 9525 const auto *SI = dyn_cast<StoreInst>(&I); 9526 if (!SI) { 9527 // We will look through cast uses, so ignore them completely. 9528 if (I.isCast()) 9529 continue; 9530 // Ignore debug info intrinsics, they don't escape or store to allocas. 9531 if (isa<DbgInfoIntrinsic>(I)) 9532 continue; 9533 // This is an unknown instruction. Assume it escapes or writes to all 9534 // static alloca operands. 9535 for (const Use &U : I.operands()) { 9536 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9537 *Info = StaticAllocaInfo::Clobbered; 9538 } 9539 continue; 9540 } 9541 9542 // If the stored value is a static alloca, mark it as escaped. 9543 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9544 *Info = StaticAllocaInfo::Clobbered; 9545 9546 // Check if the destination is a static alloca. 9547 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9548 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9549 if (!Info) 9550 continue; 9551 const AllocaInst *AI = cast<AllocaInst>(Dst); 9552 9553 // Skip allocas that have been initialized or clobbered. 9554 if (*Info != StaticAllocaInfo::Unknown) 9555 continue; 9556 9557 // Check if the stored value is an argument, and that this store fully 9558 // initializes the alloca. Don't elide copies from the same argument twice. 9559 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9560 const auto *Arg = dyn_cast<Argument>(Val); 9561 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9562 Arg->getType()->isEmptyTy() || 9563 DL.getTypeStoreSize(Arg->getType()) != 9564 DL.getTypeAllocSize(AI->getAllocatedType()) || 9565 ArgCopyElisionCandidates.count(Arg)) { 9566 *Info = StaticAllocaInfo::Clobbered; 9567 continue; 9568 } 9569 9570 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9571 << '\n'); 9572 9573 // Mark this alloca and store for argument copy elision. 9574 *Info = StaticAllocaInfo::Elidable; 9575 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9576 9577 // Stop scanning if we've seen all arguments. This will happen early in -O0 9578 // builds, which is useful, because -O0 builds have large entry blocks and 9579 // many allocas. 9580 if (ArgCopyElisionCandidates.size() == NumArgs) 9581 break; 9582 } 9583 } 9584 9585 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9586 /// ArgVal is a load from a suitable fixed stack object. 9587 static void tryToElideArgumentCopy( 9588 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9589 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9590 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9591 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9592 SDValue ArgVal, bool &ArgHasUses) { 9593 // Check if this is a load from a fixed stack object. 9594 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9595 if (!LNode) 9596 return; 9597 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9598 if (!FINode) 9599 return; 9600 9601 // Check that the fixed stack object is the right size and alignment. 9602 // Look at the alignment that the user wrote on the alloca instead of looking 9603 // at the stack object. 9604 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9605 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9606 const AllocaInst *AI = ArgCopyIter->second.first; 9607 int FixedIndex = FINode->getIndex(); 9608 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9609 int OldIndex = AllocaIndex; 9610 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9611 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9612 LLVM_DEBUG( 9613 dbgs() << " argument copy elision failed due to bad fixed stack " 9614 "object size\n"); 9615 return; 9616 } 9617 Align RequiredAlignment = AI->getAlign(); 9618 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9619 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9620 "greater than stack argument alignment (" 9621 << DebugStr(RequiredAlignment) << " vs " 9622 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9623 return; 9624 } 9625 9626 // Perform the elision. Delete the old stack object and replace its only use 9627 // in the variable info map. Mark the stack object as mutable. 9628 LLVM_DEBUG({ 9629 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9630 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9631 << '\n'; 9632 }); 9633 MFI.RemoveStackObject(OldIndex); 9634 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9635 AllocaIndex = FixedIndex; 9636 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9637 Chains.push_back(ArgVal.getValue(1)); 9638 9639 // Avoid emitting code for the store implementing the copy. 9640 const StoreInst *SI = ArgCopyIter->second.second; 9641 ElidedArgCopyInstrs.insert(SI); 9642 9643 // Check for uses of the argument again so that we can avoid exporting ArgVal 9644 // if it is't used by anything other than the store. 9645 for (const Value *U : Arg.users()) { 9646 if (U != SI) { 9647 ArgHasUses = true; 9648 break; 9649 } 9650 } 9651 } 9652 9653 void SelectionDAGISel::LowerArguments(const Function &F) { 9654 SelectionDAG &DAG = SDB->DAG; 9655 SDLoc dl = SDB->getCurSDLoc(); 9656 const DataLayout &DL = DAG.getDataLayout(); 9657 SmallVector<ISD::InputArg, 16> Ins; 9658 9659 // In Naked functions we aren't going to save any registers. 9660 if (F.hasFnAttribute(Attribute::Naked)) 9661 return; 9662 9663 if (!FuncInfo->CanLowerReturn) { 9664 // Put in an sret pointer parameter before all the other parameters. 9665 SmallVector<EVT, 1> ValueVTs; 9666 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9667 F.getReturnType()->getPointerTo( 9668 DAG.getDataLayout().getAllocaAddrSpace()), 9669 ValueVTs); 9670 9671 // NOTE: Assuming that a pointer will never break down to more than one VT 9672 // or one register. 9673 ISD::ArgFlagsTy Flags; 9674 Flags.setSRet(); 9675 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9676 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9677 ISD::InputArg::NoArgIndex, 0); 9678 Ins.push_back(RetArg); 9679 } 9680 9681 // Look for stores of arguments to static allocas. Mark such arguments with a 9682 // flag to ask the target to give us the memory location of that argument if 9683 // available. 9684 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9685 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9686 ArgCopyElisionCandidates); 9687 9688 // Set up the incoming argument description vector. 9689 for (const Argument &Arg : F.args()) { 9690 unsigned ArgNo = Arg.getArgNo(); 9691 SmallVector<EVT, 4> ValueVTs; 9692 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9693 bool isArgValueUsed = !Arg.use_empty(); 9694 unsigned PartBase = 0; 9695 Type *FinalType = Arg.getType(); 9696 if (Arg.hasAttribute(Attribute::ByVal)) 9697 FinalType = Arg.getParamByValType(); 9698 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9699 FinalType, F.getCallingConv(), F.isVarArg()); 9700 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9701 Value != NumValues; ++Value) { 9702 EVT VT = ValueVTs[Value]; 9703 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9704 ISD::ArgFlagsTy Flags; 9705 9706 // Certain targets (such as MIPS), may have a different ABI alignment 9707 // for a type depending on the context. Give the target a chance to 9708 // specify the alignment it wants. 9709 const Align OriginalAlignment( 9710 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9711 9712 if (Arg.getType()->isPointerTy()) { 9713 Flags.setPointer(); 9714 Flags.setPointerAddrSpace( 9715 cast<PointerType>(Arg.getType())->getAddressSpace()); 9716 } 9717 if (Arg.hasAttribute(Attribute::ZExt)) 9718 Flags.setZExt(); 9719 if (Arg.hasAttribute(Attribute::SExt)) 9720 Flags.setSExt(); 9721 if (Arg.hasAttribute(Attribute::InReg)) { 9722 // If we are using vectorcall calling convention, a structure that is 9723 // passed InReg - is surely an HVA 9724 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9725 isa<StructType>(Arg.getType())) { 9726 // The first value of a structure is marked 9727 if (0 == Value) 9728 Flags.setHvaStart(); 9729 Flags.setHva(); 9730 } 9731 // Set InReg Flag 9732 Flags.setInReg(); 9733 } 9734 if (Arg.hasAttribute(Attribute::StructRet)) 9735 Flags.setSRet(); 9736 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9737 Flags.setSwiftSelf(); 9738 if (Arg.hasAttribute(Attribute::SwiftError)) 9739 Flags.setSwiftError(); 9740 if (Arg.hasAttribute(Attribute::ByVal)) 9741 Flags.setByVal(); 9742 if (Arg.hasAttribute(Attribute::ByRef)) 9743 Flags.setByRef(); 9744 if (Arg.hasAttribute(Attribute::InAlloca)) { 9745 Flags.setInAlloca(); 9746 // Set the byval flag for CCAssignFn callbacks that don't know about 9747 // inalloca. This way we can know how many bytes we should've allocated 9748 // and how many bytes a callee cleanup function will pop. If we port 9749 // inalloca to more targets, we'll have to add custom inalloca handling 9750 // in the various CC lowering callbacks. 9751 Flags.setByVal(); 9752 } 9753 if (Arg.hasAttribute(Attribute::Preallocated)) { 9754 Flags.setPreallocated(); 9755 // Set the byval flag for CCAssignFn callbacks that don't know about 9756 // preallocated. This way we can know how many bytes we should've 9757 // allocated and how many bytes a callee cleanup function will pop. If 9758 // we port preallocated to more targets, we'll have to add custom 9759 // preallocated handling in the various CC lowering callbacks. 9760 Flags.setByVal(); 9761 } 9762 9763 Type *ArgMemTy = nullptr; 9764 if (F.getCallingConv() == CallingConv::X86_INTR) { 9765 // IA Interrupt passes frame (1st parameter) by value in the stack. 9766 if (ArgNo == 0) { 9767 Flags.setByVal(); 9768 // FIXME: Dependence on pointee element type. See bug 46672. 9769 ArgMemTy = Arg.getType()->getPointerElementType(); 9770 } 9771 } 9772 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 9773 Flags.isByRef()) { 9774 if (!ArgMemTy) 9775 ArgMemTy = Arg.getPointeeInMemoryValueType(); 9776 9777 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 9778 9779 // For in-memory arguments, size and alignment should be passed from FE. 9780 // BE will guess if this info is not there but there are cases it cannot 9781 // get right. 9782 MaybeAlign MemAlign = Arg.getParamAlign(); 9783 if (!MemAlign) 9784 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 9785 9786 if (Flags.isByRef()) { 9787 Flags.setByRefSize(MemSize); 9788 Flags.setByRefAlign(*MemAlign); 9789 } else { 9790 Flags.setByValSize(MemSize); 9791 Flags.setByValAlign(*MemAlign); 9792 } 9793 } 9794 9795 if (Arg.hasAttribute(Attribute::Nest)) 9796 Flags.setNest(); 9797 if (NeedsRegBlock) 9798 Flags.setInConsecutiveRegs(); 9799 Flags.setOrigAlign(OriginalAlignment); 9800 if (ArgCopyElisionCandidates.count(&Arg)) 9801 Flags.setCopyElisionCandidate(); 9802 if (Arg.hasAttribute(Attribute::Returned)) 9803 Flags.setReturned(); 9804 9805 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9806 *CurDAG->getContext(), F.getCallingConv(), VT); 9807 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9808 *CurDAG->getContext(), F.getCallingConv(), VT); 9809 for (unsigned i = 0; i != NumRegs; ++i) { 9810 // For scalable vectors, use the minimum size; individual targets 9811 // are responsible for handling scalable vector arguments and 9812 // return values. 9813 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9814 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9815 if (NumRegs > 1 && i == 0) 9816 MyFlags.Flags.setSplit(); 9817 // if it isn't first piece, alignment must be 1 9818 else if (i > 0) { 9819 MyFlags.Flags.setOrigAlign(Align(1)); 9820 if (i == NumRegs - 1) 9821 MyFlags.Flags.setSplitEnd(); 9822 } 9823 Ins.push_back(MyFlags); 9824 } 9825 if (NeedsRegBlock && Value == NumValues - 1) 9826 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9827 PartBase += VT.getStoreSize().getKnownMinSize(); 9828 } 9829 } 9830 9831 // Call the target to set up the argument values. 9832 SmallVector<SDValue, 8> InVals; 9833 SDValue NewRoot = TLI->LowerFormalArguments( 9834 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9835 9836 // Verify that the target's LowerFormalArguments behaved as expected. 9837 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9838 "LowerFormalArguments didn't return a valid chain!"); 9839 assert(InVals.size() == Ins.size() && 9840 "LowerFormalArguments didn't emit the correct number of values!"); 9841 LLVM_DEBUG({ 9842 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9843 assert(InVals[i].getNode() && 9844 "LowerFormalArguments emitted a null value!"); 9845 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9846 "LowerFormalArguments emitted a value with the wrong type!"); 9847 } 9848 }); 9849 9850 // Update the DAG with the new chain value resulting from argument lowering. 9851 DAG.setRoot(NewRoot); 9852 9853 // Set up the argument values. 9854 unsigned i = 0; 9855 if (!FuncInfo->CanLowerReturn) { 9856 // Create a virtual register for the sret pointer, and put in a copy 9857 // from the sret argument into it. 9858 SmallVector<EVT, 1> ValueVTs; 9859 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9860 F.getReturnType()->getPointerTo( 9861 DAG.getDataLayout().getAllocaAddrSpace()), 9862 ValueVTs); 9863 MVT VT = ValueVTs[0].getSimpleVT(); 9864 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9865 Optional<ISD::NodeType> AssertOp = None; 9866 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9867 nullptr, F.getCallingConv(), AssertOp); 9868 9869 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9870 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9871 Register SRetReg = 9872 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9873 FuncInfo->DemoteRegister = SRetReg; 9874 NewRoot = 9875 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9876 DAG.setRoot(NewRoot); 9877 9878 // i indexes lowered arguments. Bump it past the hidden sret argument. 9879 ++i; 9880 } 9881 9882 SmallVector<SDValue, 4> Chains; 9883 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9884 for (const Argument &Arg : F.args()) { 9885 SmallVector<SDValue, 4> ArgValues; 9886 SmallVector<EVT, 4> ValueVTs; 9887 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9888 unsigned NumValues = ValueVTs.size(); 9889 if (NumValues == 0) 9890 continue; 9891 9892 bool ArgHasUses = !Arg.use_empty(); 9893 9894 // Elide the copying store if the target loaded this argument from a 9895 // suitable fixed stack object. 9896 if (Ins[i].Flags.isCopyElisionCandidate()) { 9897 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9898 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9899 InVals[i], ArgHasUses); 9900 } 9901 9902 // If this argument is unused then remember its value. It is used to generate 9903 // debugging information. 9904 bool isSwiftErrorArg = 9905 TLI->supportSwiftError() && 9906 Arg.hasAttribute(Attribute::SwiftError); 9907 if (!ArgHasUses && !isSwiftErrorArg) { 9908 SDB->setUnusedArgValue(&Arg, InVals[i]); 9909 9910 // Also remember any frame index for use in FastISel. 9911 if (FrameIndexSDNode *FI = 9912 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9913 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9914 } 9915 9916 for (unsigned Val = 0; Val != NumValues; ++Val) { 9917 EVT VT = ValueVTs[Val]; 9918 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9919 F.getCallingConv(), VT); 9920 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9921 *CurDAG->getContext(), F.getCallingConv(), VT); 9922 9923 // Even an apparent 'unused' swifterror argument needs to be returned. So 9924 // we do generate a copy for it that can be used on return from the 9925 // function. 9926 if (ArgHasUses || isSwiftErrorArg) { 9927 Optional<ISD::NodeType> AssertOp; 9928 if (Arg.hasAttribute(Attribute::SExt)) 9929 AssertOp = ISD::AssertSext; 9930 else if (Arg.hasAttribute(Attribute::ZExt)) 9931 AssertOp = ISD::AssertZext; 9932 9933 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9934 PartVT, VT, nullptr, 9935 F.getCallingConv(), AssertOp)); 9936 } 9937 9938 i += NumParts; 9939 } 9940 9941 // We don't need to do anything else for unused arguments. 9942 if (ArgValues.empty()) 9943 continue; 9944 9945 // Note down frame index. 9946 if (FrameIndexSDNode *FI = 9947 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9948 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9949 9950 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9951 SDB->getCurSDLoc()); 9952 9953 SDB->setValue(&Arg, Res); 9954 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9955 // We want to associate the argument with the frame index, among 9956 // involved operands, that correspond to the lowest address. The 9957 // getCopyFromParts function, called earlier, is swapping the order of 9958 // the operands to BUILD_PAIR depending on endianness. The result of 9959 // that swapping is that the least significant bits of the argument will 9960 // be in the first operand of the BUILD_PAIR node, and the most 9961 // significant bits will be in the second operand. 9962 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9963 if (LoadSDNode *LNode = 9964 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9965 if (FrameIndexSDNode *FI = 9966 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9967 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9968 } 9969 9970 // Analyses past this point are naive and don't expect an assertion. 9971 if (Res.getOpcode() == ISD::AssertZext) 9972 Res = Res.getOperand(0); 9973 9974 // Update the SwiftErrorVRegDefMap. 9975 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9976 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9977 if (Register::isVirtualRegister(Reg)) 9978 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9979 Reg); 9980 } 9981 9982 // If this argument is live outside of the entry block, insert a copy from 9983 // wherever we got it to the vreg that other BB's will reference it as. 9984 if (Res.getOpcode() == ISD::CopyFromReg) { 9985 // If we can, though, try to skip creating an unnecessary vreg. 9986 // FIXME: This isn't very clean... it would be nice to make this more 9987 // general. 9988 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9989 if (Register::isVirtualRegister(Reg)) { 9990 FuncInfo->ValueMap[&Arg] = Reg; 9991 continue; 9992 } 9993 } 9994 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9995 FuncInfo->InitializeRegForValue(&Arg); 9996 SDB->CopyToExportRegsIfNeeded(&Arg); 9997 } 9998 } 9999 10000 if (!Chains.empty()) { 10001 Chains.push_back(NewRoot); 10002 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10003 } 10004 10005 DAG.setRoot(NewRoot); 10006 10007 assert(i == InVals.size() && "Argument register count mismatch!"); 10008 10009 // If any argument copy elisions occurred and we have debug info, update the 10010 // stale frame indices used in the dbg.declare variable info table. 10011 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10012 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10013 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10014 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10015 if (I != ArgCopyElisionFrameIndexMap.end()) 10016 VI.Slot = I->second; 10017 } 10018 } 10019 10020 // Finally, if the target has anything special to do, allow it to do so. 10021 emitFunctionEntryCode(); 10022 } 10023 10024 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10025 /// ensure constants are generated when needed. Remember the virtual registers 10026 /// that need to be added to the Machine PHI nodes as input. We cannot just 10027 /// directly add them, because expansion might result in multiple MBB's for one 10028 /// BB. As such, the start of the BB might correspond to a different MBB than 10029 /// the end. 10030 void 10031 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10032 const Instruction *TI = LLVMBB->getTerminator(); 10033 10034 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10035 10036 // Check PHI nodes in successors that expect a value to be available from this 10037 // block. 10038 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10039 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10040 if (!isa<PHINode>(SuccBB->begin())) continue; 10041 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10042 10043 // If this terminator has multiple identical successors (common for 10044 // switches), only handle each succ once. 10045 if (!SuccsHandled.insert(SuccMBB).second) 10046 continue; 10047 10048 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10049 10050 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10051 // nodes and Machine PHI nodes, but the incoming operands have not been 10052 // emitted yet. 10053 for (const PHINode &PN : SuccBB->phis()) { 10054 // Ignore dead phi's. 10055 if (PN.use_empty()) 10056 continue; 10057 10058 // Skip empty types 10059 if (PN.getType()->isEmptyTy()) 10060 continue; 10061 10062 unsigned Reg; 10063 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10064 10065 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10066 unsigned &RegOut = ConstantsOut[C]; 10067 if (RegOut == 0) { 10068 RegOut = FuncInfo.CreateRegs(C); 10069 CopyValueToVirtualRegister(C, RegOut); 10070 } 10071 Reg = RegOut; 10072 } else { 10073 DenseMap<const Value *, Register>::iterator I = 10074 FuncInfo.ValueMap.find(PHIOp); 10075 if (I != FuncInfo.ValueMap.end()) 10076 Reg = I->second; 10077 else { 10078 assert(isa<AllocaInst>(PHIOp) && 10079 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10080 "Didn't codegen value into a register!??"); 10081 Reg = FuncInfo.CreateRegs(PHIOp); 10082 CopyValueToVirtualRegister(PHIOp, Reg); 10083 } 10084 } 10085 10086 // Remember that this register needs to added to the machine PHI node as 10087 // the input for this MBB. 10088 SmallVector<EVT, 4> ValueVTs; 10089 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10090 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10091 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10092 EVT VT = ValueVTs[vti]; 10093 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10094 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10095 FuncInfo.PHINodesToUpdate.push_back( 10096 std::make_pair(&*MBBI++, Reg + i)); 10097 Reg += NumRegisters; 10098 } 10099 } 10100 } 10101 10102 ConstantsOut.clear(); 10103 } 10104 10105 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10106 /// is 0. 10107 MachineBasicBlock * 10108 SelectionDAGBuilder::StackProtectorDescriptor:: 10109 AddSuccessorMBB(const BasicBlock *BB, 10110 MachineBasicBlock *ParentMBB, 10111 bool IsLikely, 10112 MachineBasicBlock *SuccMBB) { 10113 // If SuccBB has not been created yet, create it. 10114 if (!SuccMBB) { 10115 MachineFunction *MF = ParentMBB->getParent(); 10116 MachineFunction::iterator BBI(ParentMBB); 10117 SuccMBB = MF->CreateMachineBasicBlock(BB); 10118 MF->insert(++BBI, SuccMBB); 10119 } 10120 // Add it as a successor of ParentMBB. 10121 ParentMBB->addSuccessor( 10122 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10123 return SuccMBB; 10124 } 10125 10126 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10127 MachineFunction::iterator I(MBB); 10128 if (++I == FuncInfo.MF->end()) 10129 return nullptr; 10130 return &*I; 10131 } 10132 10133 /// During lowering new call nodes can be created (such as memset, etc.). 10134 /// Those will become new roots of the current DAG, but complications arise 10135 /// when they are tail calls. In such cases, the call lowering will update 10136 /// the root, but the builder still needs to know that a tail call has been 10137 /// lowered in order to avoid generating an additional return. 10138 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10139 // If the node is null, we do have a tail call. 10140 if (MaybeTC.getNode() != nullptr) 10141 DAG.setRoot(MaybeTC); 10142 else 10143 HasTailCall = true; 10144 } 10145 10146 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10147 MachineBasicBlock *SwitchMBB, 10148 MachineBasicBlock *DefaultMBB) { 10149 MachineFunction *CurMF = FuncInfo.MF; 10150 MachineBasicBlock *NextMBB = nullptr; 10151 MachineFunction::iterator BBI(W.MBB); 10152 if (++BBI != FuncInfo.MF->end()) 10153 NextMBB = &*BBI; 10154 10155 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10156 10157 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10158 10159 if (Size == 2 && W.MBB == SwitchMBB) { 10160 // If any two of the cases has the same destination, and if one value 10161 // is the same as the other, but has one bit unset that the other has set, 10162 // use bit manipulation to do two compares at once. For example: 10163 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10164 // TODO: This could be extended to merge any 2 cases in switches with 3 10165 // cases. 10166 // TODO: Handle cases where W.CaseBB != SwitchBB. 10167 CaseCluster &Small = *W.FirstCluster; 10168 CaseCluster &Big = *W.LastCluster; 10169 10170 if (Small.Low == Small.High && Big.Low == Big.High && 10171 Small.MBB == Big.MBB) { 10172 const APInt &SmallValue = Small.Low->getValue(); 10173 const APInt &BigValue = Big.Low->getValue(); 10174 10175 // Check that there is only one bit different. 10176 APInt CommonBit = BigValue ^ SmallValue; 10177 if (CommonBit.isPowerOf2()) { 10178 SDValue CondLHS = getValue(Cond); 10179 EVT VT = CondLHS.getValueType(); 10180 SDLoc DL = getCurSDLoc(); 10181 10182 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10183 DAG.getConstant(CommonBit, DL, VT)); 10184 SDValue Cond = DAG.getSetCC( 10185 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10186 ISD::SETEQ); 10187 10188 // Update successor info. 10189 // Both Small and Big will jump to Small.BB, so we sum up the 10190 // probabilities. 10191 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10192 if (BPI) 10193 addSuccessorWithProb( 10194 SwitchMBB, DefaultMBB, 10195 // The default destination is the first successor in IR. 10196 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10197 else 10198 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10199 10200 // Insert the true branch. 10201 SDValue BrCond = 10202 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10203 DAG.getBasicBlock(Small.MBB)); 10204 // Insert the false branch. 10205 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10206 DAG.getBasicBlock(DefaultMBB)); 10207 10208 DAG.setRoot(BrCond); 10209 return; 10210 } 10211 } 10212 } 10213 10214 if (TM.getOptLevel() != CodeGenOpt::None) { 10215 // Here, we order cases by probability so the most likely case will be 10216 // checked first. However, two clusters can have the same probability in 10217 // which case their relative ordering is non-deterministic. So we use Low 10218 // as a tie-breaker as clusters are guaranteed to never overlap. 10219 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10220 [](const CaseCluster &a, const CaseCluster &b) { 10221 return a.Prob != b.Prob ? 10222 a.Prob > b.Prob : 10223 a.Low->getValue().slt(b.Low->getValue()); 10224 }); 10225 10226 // Rearrange the case blocks so that the last one falls through if possible 10227 // without changing the order of probabilities. 10228 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10229 --I; 10230 if (I->Prob > W.LastCluster->Prob) 10231 break; 10232 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10233 std::swap(*I, *W.LastCluster); 10234 break; 10235 } 10236 } 10237 } 10238 10239 // Compute total probability. 10240 BranchProbability DefaultProb = W.DefaultProb; 10241 BranchProbability UnhandledProbs = DefaultProb; 10242 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10243 UnhandledProbs += I->Prob; 10244 10245 MachineBasicBlock *CurMBB = W.MBB; 10246 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10247 bool FallthroughUnreachable = false; 10248 MachineBasicBlock *Fallthrough; 10249 if (I == W.LastCluster) { 10250 // For the last cluster, fall through to the default destination. 10251 Fallthrough = DefaultMBB; 10252 FallthroughUnreachable = isa<UnreachableInst>( 10253 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10254 } else { 10255 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10256 CurMF->insert(BBI, Fallthrough); 10257 // Put Cond in a virtual register to make it available from the new blocks. 10258 ExportFromCurrentBlock(Cond); 10259 } 10260 UnhandledProbs -= I->Prob; 10261 10262 switch (I->Kind) { 10263 case CC_JumpTable: { 10264 // FIXME: Optimize away range check based on pivot comparisons. 10265 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10266 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10267 10268 // The jump block hasn't been inserted yet; insert it here. 10269 MachineBasicBlock *JumpMBB = JT->MBB; 10270 CurMF->insert(BBI, JumpMBB); 10271 10272 auto JumpProb = I->Prob; 10273 auto FallthroughProb = UnhandledProbs; 10274 10275 // If the default statement is a target of the jump table, we evenly 10276 // distribute the default probability to successors of CurMBB. Also 10277 // update the probability on the edge from JumpMBB to Fallthrough. 10278 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10279 SE = JumpMBB->succ_end(); 10280 SI != SE; ++SI) { 10281 if (*SI == DefaultMBB) { 10282 JumpProb += DefaultProb / 2; 10283 FallthroughProb -= DefaultProb / 2; 10284 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10285 JumpMBB->normalizeSuccProbs(); 10286 break; 10287 } 10288 } 10289 10290 if (FallthroughUnreachable) { 10291 // Skip the range check if the fallthrough block is unreachable. 10292 JTH->OmitRangeCheck = true; 10293 } 10294 10295 if (!JTH->OmitRangeCheck) 10296 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10297 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10298 CurMBB->normalizeSuccProbs(); 10299 10300 // The jump table header will be inserted in our current block, do the 10301 // range check, and fall through to our fallthrough block. 10302 JTH->HeaderBB = CurMBB; 10303 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10304 10305 // If we're in the right place, emit the jump table header right now. 10306 if (CurMBB == SwitchMBB) { 10307 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10308 JTH->Emitted = true; 10309 } 10310 break; 10311 } 10312 case CC_BitTests: { 10313 // FIXME: Optimize away range check based on pivot comparisons. 10314 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10315 10316 // The bit test blocks haven't been inserted yet; insert them here. 10317 for (BitTestCase &BTC : BTB->Cases) 10318 CurMF->insert(BBI, BTC.ThisBB); 10319 10320 // Fill in fields of the BitTestBlock. 10321 BTB->Parent = CurMBB; 10322 BTB->Default = Fallthrough; 10323 10324 BTB->DefaultProb = UnhandledProbs; 10325 // If the cases in bit test don't form a contiguous range, we evenly 10326 // distribute the probability on the edge to Fallthrough to two 10327 // successors of CurMBB. 10328 if (!BTB->ContiguousRange) { 10329 BTB->Prob += DefaultProb / 2; 10330 BTB->DefaultProb -= DefaultProb / 2; 10331 } 10332 10333 if (FallthroughUnreachable) { 10334 // Skip the range check if the fallthrough block is unreachable. 10335 BTB->OmitRangeCheck = true; 10336 } 10337 10338 // If we're in the right place, emit the bit test header right now. 10339 if (CurMBB == SwitchMBB) { 10340 visitBitTestHeader(*BTB, SwitchMBB); 10341 BTB->Emitted = true; 10342 } 10343 break; 10344 } 10345 case CC_Range: { 10346 const Value *RHS, *LHS, *MHS; 10347 ISD::CondCode CC; 10348 if (I->Low == I->High) { 10349 // Check Cond == I->Low. 10350 CC = ISD::SETEQ; 10351 LHS = Cond; 10352 RHS=I->Low; 10353 MHS = nullptr; 10354 } else { 10355 // Check I->Low <= Cond <= I->High. 10356 CC = ISD::SETLE; 10357 LHS = I->Low; 10358 MHS = Cond; 10359 RHS = I->High; 10360 } 10361 10362 // If Fallthrough is unreachable, fold away the comparison. 10363 if (FallthroughUnreachable) 10364 CC = ISD::SETTRUE; 10365 10366 // The false probability is the sum of all unhandled cases. 10367 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10368 getCurSDLoc(), I->Prob, UnhandledProbs); 10369 10370 if (CurMBB == SwitchMBB) 10371 visitSwitchCase(CB, SwitchMBB); 10372 else 10373 SL->SwitchCases.push_back(CB); 10374 10375 break; 10376 } 10377 } 10378 CurMBB = Fallthrough; 10379 } 10380 } 10381 10382 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10383 CaseClusterIt First, 10384 CaseClusterIt Last) { 10385 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10386 if (X.Prob != CC.Prob) 10387 return X.Prob > CC.Prob; 10388 10389 // Ties are broken by comparing the case value. 10390 return X.Low->getValue().slt(CC.Low->getValue()); 10391 }); 10392 } 10393 10394 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10395 const SwitchWorkListItem &W, 10396 Value *Cond, 10397 MachineBasicBlock *SwitchMBB) { 10398 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10399 "Clusters not sorted?"); 10400 10401 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10402 10403 // Balance the tree based on branch probabilities to create a near-optimal (in 10404 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10405 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10406 CaseClusterIt LastLeft = W.FirstCluster; 10407 CaseClusterIt FirstRight = W.LastCluster; 10408 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10409 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10410 10411 // Move LastLeft and FirstRight towards each other from opposite directions to 10412 // find a partitioning of the clusters which balances the probability on both 10413 // sides. If LeftProb and RightProb are equal, alternate which side is 10414 // taken to ensure 0-probability nodes are distributed evenly. 10415 unsigned I = 0; 10416 while (LastLeft + 1 < FirstRight) { 10417 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10418 LeftProb += (++LastLeft)->Prob; 10419 else 10420 RightProb += (--FirstRight)->Prob; 10421 I++; 10422 } 10423 10424 while (true) { 10425 // Our binary search tree differs from a typical BST in that ours can have up 10426 // to three values in each leaf. The pivot selection above doesn't take that 10427 // into account, which means the tree might require more nodes and be less 10428 // efficient. We compensate for this here. 10429 10430 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10431 unsigned NumRight = W.LastCluster - FirstRight + 1; 10432 10433 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10434 // If one side has less than 3 clusters, and the other has more than 3, 10435 // consider taking a cluster from the other side. 10436 10437 if (NumLeft < NumRight) { 10438 // Consider moving the first cluster on the right to the left side. 10439 CaseCluster &CC = *FirstRight; 10440 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10441 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10442 if (LeftSideRank <= RightSideRank) { 10443 // Moving the cluster to the left does not demote it. 10444 ++LastLeft; 10445 ++FirstRight; 10446 continue; 10447 } 10448 } else { 10449 assert(NumRight < NumLeft); 10450 // Consider moving the last element on the left to the right side. 10451 CaseCluster &CC = *LastLeft; 10452 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10453 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10454 if (RightSideRank <= LeftSideRank) { 10455 // Moving the cluster to the right does not demot it. 10456 --LastLeft; 10457 --FirstRight; 10458 continue; 10459 } 10460 } 10461 } 10462 break; 10463 } 10464 10465 assert(LastLeft + 1 == FirstRight); 10466 assert(LastLeft >= W.FirstCluster); 10467 assert(FirstRight <= W.LastCluster); 10468 10469 // Use the first element on the right as pivot since we will make less-than 10470 // comparisons against it. 10471 CaseClusterIt PivotCluster = FirstRight; 10472 assert(PivotCluster > W.FirstCluster); 10473 assert(PivotCluster <= W.LastCluster); 10474 10475 CaseClusterIt FirstLeft = W.FirstCluster; 10476 CaseClusterIt LastRight = W.LastCluster; 10477 10478 const ConstantInt *Pivot = PivotCluster->Low; 10479 10480 // New blocks will be inserted immediately after the current one. 10481 MachineFunction::iterator BBI(W.MBB); 10482 ++BBI; 10483 10484 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10485 // we can branch to its destination directly if it's squeezed exactly in 10486 // between the known lower bound and Pivot - 1. 10487 MachineBasicBlock *LeftMBB; 10488 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10489 FirstLeft->Low == W.GE && 10490 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10491 LeftMBB = FirstLeft->MBB; 10492 } else { 10493 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10494 FuncInfo.MF->insert(BBI, LeftMBB); 10495 WorkList.push_back( 10496 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10497 // Put Cond in a virtual register to make it available from the new blocks. 10498 ExportFromCurrentBlock(Cond); 10499 } 10500 10501 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10502 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10503 // directly if RHS.High equals the current upper bound. 10504 MachineBasicBlock *RightMBB; 10505 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10506 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10507 RightMBB = FirstRight->MBB; 10508 } else { 10509 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10510 FuncInfo.MF->insert(BBI, RightMBB); 10511 WorkList.push_back( 10512 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10513 // Put Cond in a virtual register to make it available from the new blocks. 10514 ExportFromCurrentBlock(Cond); 10515 } 10516 10517 // Create the CaseBlock record that will be used to lower the branch. 10518 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10519 getCurSDLoc(), LeftProb, RightProb); 10520 10521 if (W.MBB == SwitchMBB) 10522 visitSwitchCase(CB, SwitchMBB); 10523 else 10524 SL->SwitchCases.push_back(CB); 10525 } 10526 10527 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10528 // from the swith statement. 10529 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10530 BranchProbability PeeledCaseProb) { 10531 if (PeeledCaseProb == BranchProbability::getOne()) 10532 return BranchProbability::getZero(); 10533 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10534 10535 uint32_t Numerator = CaseProb.getNumerator(); 10536 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10537 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10538 } 10539 10540 // Try to peel the top probability case if it exceeds the threshold. 10541 // Return current MachineBasicBlock for the switch statement if the peeling 10542 // does not occur. 10543 // If the peeling is performed, return the newly created MachineBasicBlock 10544 // for the peeled switch statement. Also update Clusters to remove the peeled 10545 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10546 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10547 const SwitchInst &SI, CaseClusterVector &Clusters, 10548 BranchProbability &PeeledCaseProb) { 10549 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10550 // Don't perform if there is only one cluster or optimizing for size. 10551 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10552 TM.getOptLevel() == CodeGenOpt::None || 10553 SwitchMBB->getParent()->getFunction().hasMinSize()) 10554 return SwitchMBB; 10555 10556 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10557 unsigned PeeledCaseIndex = 0; 10558 bool SwitchPeeled = false; 10559 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10560 CaseCluster &CC = Clusters[Index]; 10561 if (CC.Prob < TopCaseProb) 10562 continue; 10563 TopCaseProb = CC.Prob; 10564 PeeledCaseIndex = Index; 10565 SwitchPeeled = true; 10566 } 10567 if (!SwitchPeeled) 10568 return SwitchMBB; 10569 10570 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10571 << TopCaseProb << "\n"); 10572 10573 // Record the MBB for the peeled switch statement. 10574 MachineFunction::iterator BBI(SwitchMBB); 10575 ++BBI; 10576 MachineBasicBlock *PeeledSwitchMBB = 10577 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10578 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10579 10580 ExportFromCurrentBlock(SI.getCondition()); 10581 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10582 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10583 nullptr, nullptr, TopCaseProb.getCompl()}; 10584 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10585 10586 Clusters.erase(PeeledCaseIt); 10587 for (CaseCluster &CC : Clusters) { 10588 LLVM_DEBUG( 10589 dbgs() << "Scale the probablity for one cluster, before scaling: " 10590 << CC.Prob << "\n"); 10591 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10592 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10593 } 10594 PeeledCaseProb = TopCaseProb; 10595 return PeeledSwitchMBB; 10596 } 10597 10598 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10599 // Extract cases from the switch. 10600 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10601 CaseClusterVector Clusters; 10602 Clusters.reserve(SI.getNumCases()); 10603 for (auto I : SI.cases()) { 10604 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10605 const ConstantInt *CaseVal = I.getCaseValue(); 10606 BranchProbability Prob = 10607 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10608 : BranchProbability(1, SI.getNumCases() + 1); 10609 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10610 } 10611 10612 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10613 10614 // Cluster adjacent cases with the same destination. We do this at all 10615 // optimization levels because it's cheap to do and will make codegen faster 10616 // if there are many clusters. 10617 sortAndRangeify(Clusters); 10618 10619 // The branch probablity of the peeled case. 10620 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10621 MachineBasicBlock *PeeledSwitchMBB = 10622 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10623 10624 // If there is only the default destination, jump there directly. 10625 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10626 if (Clusters.empty()) { 10627 assert(PeeledSwitchMBB == SwitchMBB); 10628 SwitchMBB->addSuccessor(DefaultMBB); 10629 if (DefaultMBB != NextBlock(SwitchMBB)) { 10630 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10631 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10632 } 10633 return; 10634 } 10635 10636 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10637 SL->findBitTestClusters(Clusters, &SI); 10638 10639 LLVM_DEBUG({ 10640 dbgs() << "Case clusters: "; 10641 for (const CaseCluster &C : Clusters) { 10642 if (C.Kind == CC_JumpTable) 10643 dbgs() << "JT:"; 10644 if (C.Kind == CC_BitTests) 10645 dbgs() << "BT:"; 10646 10647 C.Low->getValue().print(dbgs(), true); 10648 if (C.Low != C.High) { 10649 dbgs() << '-'; 10650 C.High->getValue().print(dbgs(), true); 10651 } 10652 dbgs() << ' '; 10653 } 10654 dbgs() << '\n'; 10655 }); 10656 10657 assert(!Clusters.empty()); 10658 SwitchWorkList WorkList; 10659 CaseClusterIt First = Clusters.begin(); 10660 CaseClusterIt Last = Clusters.end() - 1; 10661 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10662 // Scale the branchprobability for DefaultMBB if the peel occurs and 10663 // DefaultMBB is not replaced. 10664 if (PeeledCaseProb != BranchProbability::getZero() && 10665 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10666 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10667 WorkList.push_back( 10668 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10669 10670 while (!WorkList.empty()) { 10671 SwitchWorkListItem W = WorkList.back(); 10672 WorkList.pop_back(); 10673 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10674 10675 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10676 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10677 // For optimized builds, lower large range as a balanced binary tree. 10678 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10679 continue; 10680 } 10681 10682 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10683 } 10684 } 10685 10686 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10687 SmallVector<EVT, 4> ValueVTs; 10688 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10689 ValueVTs); 10690 unsigned NumValues = ValueVTs.size(); 10691 if (NumValues == 0) return; 10692 10693 SmallVector<SDValue, 4> Values(NumValues); 10694 SDValue Op = getValue(I.getOperand(0)); 10695 10696 for (unsigned i = 0; i != NumValues; ++i) 10697 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10698 SDValue(Op.getNode(), Op.getResNo() + i)); 10699 10700 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10701 DAG.getVTList(ValueVTs), Values)); 10702 } 10703