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, TypeSize>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, TypeSize>, 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 TypeSize 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 erase_if(DDIV, isMatchingDbgValue); 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 // Bail out if all bits are described already. 1325 if (Offset >= BitsToDescribe) 1326 break; 1327 // TODO: handle scalable vectors. 1328 unsigned RegisterSize = RegAndSize.second; 1329 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1330 ? BitsToDescribe - Offset 1331 : RegisterSize; 1332 auto FragmentExpr = DIExpression::createFragmentExpression( 1333 Expr, Offset, FragmentSize); 1334 if (!FragmentExpr) 1335 continue; 1336 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1337 false, dl, SDNodeOrder); 1338 DAG.AddDbgValue(SDV, nullptr, false); 1339 Offset += RegisterSize; 1340 } 1341 } else { 1342 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1343 DAG.AddDbgValue(SDV, nullptr, false); 1344 } 1345 return true; 1346 } 1347 } 1348 1349 return false; 1350 } 1351 1352 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1353 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1354 for (auto &Pair : DanglingDebugInfoMap) 1355 for (auto &DDI : Pair.second) 1356 salvageUnresolvedDbgValue(DDI); 1357 clearDanglingDebugInfo(); 1358 } 1359 1360 /// getCopyFromRegs - If there was virtual register allocated for the value V 1361 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1362 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1363 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V); 1364 SDValue Result; 1365 1366 if (It != FuncInfo.ValueMap.end()) { 1367 Register InReg = It->second; 1368 1369 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1370 DAG.getDataLayout(), InReg, Ty, 1371 None); // This is not an ABI copy. 1372 SDValue Chain = DAG.getEntryNode(); 1373 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1374 V); 1375 resolveDanglingDebugInfo(V, Result); 1376 } 1377 1378 return Result; 1379 } 1380 1381 /// getValue - Return an SDValue for the given Value. 1382 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1383 // If we already have an SDValue for this value, use it. It's important 1384 // to do this first, so that we don't create a CopyFromReg if we already 1385 // have a regular SDValue. 1386 SDValue &N = NodeMap[V]; 1387 if (N.getNode()) return N; 1388 1389 // If there's a virtual register allocated and initialized for this 1390 // value, use it. 1391 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1392 return copyFromReg; 1393 1394 // Otherwise create a new SDValue and remember it. 1395 SDValue Val = getValueImpl(V); 1396 NodeMap[V] = Val; 1397 resolveDanglingDebugInfo(V, Val); 1398 return Val; 1399 } 1400 1401 /// getNonRegisterValue - Return an SDValue for the given Value, but 1402 /// don't look in FuncInfo.ValueMap for a virtual register. 1403 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1404 // If we already have an SDValue for this value, use it. 1405 SDValue &N = NodeMap[V]; 1406 if (N.getNode()) { 1407 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1408 // Remove the debug location from the node as the node is about to be used 1409 // in a location which may differ from the original debug location. This 1410 // is relevant to Constant and ConstantFP nodes because they can appear 1411 // as constant expressions inside PHI nodes. 1412 N->setDebugLoc(DebugLoc()); 1413 } 1414 return N; 1415 } 1416 1417 // Otherwise create a new SDValue and remember it. 1418 SDValue Val = getValueImpl(V); 1419 NodeMap[V] = Val; 1420 resolveDanglingDebugInfo(V, Val); 1421 return Val; 1422 } 1423 1424 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1425 /// Create an SDValue for the given value. 1426 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1427 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1428 1429 if (const Constant *C = dyn_cast<Constant>(V)) { 1430 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1431 1432 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1433 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1434 1435 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1436 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1437 1438 if (isa<ConstantPointerNull>(C)) { 1439 unsigned AS = V->getType()->getPointerAddressSpace(); 1440 return DAG.getConstant(0, getCurSDLoc(), 1441 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1442 } 1443 1444 if (match(C, m_VScale(DAG.getDataLayout()))) 1445 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)); 1446 1447 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1448 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1449 1450 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1451 return DAG.getUNDEF(VT); 1452 1453 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1454 visit(CE->getOpcode(), *CE); 1455 SDValue N1 = NodeMap[V]; 1456 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1457 return N1; 1458 } 1459 1460 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1461 SmallVector<SDValue, 4> Constants; 1462 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1463 OI != OE; ++OI) { 1464 SDNode *Val = getValue(*OI).getNode(); 1465 // If the operand is an empty aggregate, there are no values. 1466 if (!Val) continue; 1467 // Add each leaf value from the operand to the Constants list 1468 // to form a flattened list of all the values. 1469 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1470 Constants.push_back(SDValue(Val, i)); 1471 } 1472 1473 return DAG.getMergeValues(Constants, getCurSDLoc()); 1474 } 1475 1476 if (const ConstantDataSequential *CDS = 1477 dyn_cast<ConstantDataSequential>(C)) { 1478 SmallVector<SDValue, 4> Ops; 1479 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1480 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1481 // Add each leaf value from the operand to the Constants list 1482 // to form a flattened list of all the values. 1483 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1484 Ops.push_back(SDValue(Val, i)); 1485 } 1486 1487 if (isa<ArrayType>(CDS->getType())) 1488 return DAG.getMergeValues(Ops, getCurSDLoc()); 1489 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1490 } 1491 1492 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1493 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1494 "Unknown struct or array constant!"); 1495 1496 SmallVector<EVT, 4> ValueVTs; 1497 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1498 unsigned NumElts = ValueVTs.size(); 1499 if (NumElts == 0) 1500 return SDValue(); // empty struct 1501 SmallVector<SDValue, 4> Constants(NumElts); 1502 for (unsigned i = 0; i != NumElts; ++i) { 1503 EVT EltVT = ValueVTs[i]; 1504 if (isa<UndefValue>(C)) 1505 Constants[i] = DAG.getUNDEF(EltVT); 1506 else if (EltVT.isFloatingPoint()) 1507 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1508 else 1509 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1510 } 1511 1512 return DAG.getMergeValues(Constants, getCurSDLoc()); 1513 } 1514 1515 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1516 return DAG.getBlockAddress(BA, VT); 1517 1518 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) 1519 return getValue(Equiv->getGlobalValue()); 1520 1521 VectorType *VecTy = cast<VectorType>(V->getType()); 1522 1523 // Now that we know the number and type of the elements, get that number of 1524 // elements into the Ops array based on what kind of constant it is. 1525 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1526 SmallVector<SDValue, 16> Ops; 1527 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements(); 1528 for (unsigned i = 0; i != NumElements; ++i) 1529 Ops.push_back(getValue(CV->getOperand(i))); 1530 1531 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1532 } else if (isa<ConstantAggregateZero>(C)) { 1533 EVT EltVT = 1534 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1535 1536 SDValue Op; 1537 if (EltVT.isFloatingPoint()) 1538 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1539 else 1540 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1541 1542 if (isa<ScalableVectorType>(VecTy)) 1543 return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op); 1544 else { 1545 SmallVector<SDValue, 16> Ops; 1546 Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op); 1547 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1548 } 1549 } 1550 llvm_unreachable("Unknown vector constant"); 1551 } 1552 1553 // If this is a static alloca, generate it as the frameindex instead of 1554 // computation. 1555 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1556 DenseMap<const AllocaInst*, int>::iterator SI = 1557 FuncInfo.StaticAllocaMap.find(AI); 1558 if (SI != FuncInfo.StaticAllocaMap.end()) 1559 return DAG.getFrameIndex(SI->second, 1560 TLI.getFrameIndexTy(DAG.getDataLayout())); 1561 } 1562 1563 // If this is an instruction which fast-isel has deferred, select it now. 1564 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1565 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1566 1567 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1568 Inst->getType(), None); 1569 SDValue Chain = DAG.getEntryNode(); 1570 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1571 } 1572 1573 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) { 1574 return DAG.getMDNode(cast<MDNode>(MD->getMetadata())); 1575 } 1576 llvm_unreachable("Can't get register for value!"); 1577 } 1578 1579 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1580 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1581 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1582 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1583 bool IsSEH = isAsynchronousEHPersonality(Pers); 1584 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1585 if (!IsSEH) 1586 CatchPadMBB->setIsEHScopeEntry(); 1587 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1588 if (IsMSVCCXX || IsCoreCLR) 1589 CatchPadMBB->setIsEHFuncletEntry(); 1590 } 1591 1592 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1593 // Update machine-CFG edge. 1594 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1595 FuncInfo.MBB->addSuccessor(TargetMBB); 1596 1597 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1598 bool IsSEH = isAsynchronousEHPersonality(Pers); 1599 if (IsSEH) { 1600 // If this is not a fall-through branch or optimizations are switched off, 1601 // emit the branch. 1602 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1603 TM.getOptLevel() == CodeGenOpt::None) 1604 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1605 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1606 return; 1607 } 1608 1609 // Figure out the funclet membership for the catchret's successor. 1610 // This will be used by the FuncletLayout pass to determine how to order the 1611 // BB's. 1612 // A 'catchret' returns to the outer scope's color. 1613 Value *ParentPad = I.getCatchSwitchParentPad(); 1614 const BasicBlock *SuccessorColor; 1615 if (isa<ConstantTokenNone>(ParentPad)) 1616 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1617 else 1618 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1619 assert(SuccessorColor && "No parent funclet for catchret!"); 1620 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1621 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1622 1623 // Create the terminator node. 1624 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1625 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1626 DAG.getBasicBlock(SuccessorColorMBB)); 1627 DAG.setRoot(Ret); 1628 } 1629 1630 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1631 // Don't emit any special code for the cleanuppad instruction. It just marks 1632 // the start of an EH scope/funclet. 1633 FuncInfo.MBB->setIsEHScopeEntry(); 1634 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1635 if (Pers != EHPersonality::Wasm_CXX) { 1636 FuncInfo.MBB->setIsEHFuncletEntry(); 1637 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1638 } 1639 } 1640 1641 // In wasm EH, even though a catchpad may not catch an exception if a tag does 1642 // not match, it is OK to add only the first unwind destination catchpad to the 1643 // successors, because there will be at least one invoke instruction within the 1644 // catch scope that points to the next unwind destination, if one exists, so 1645 // CFGSort cannot mess up with BB sorting order. 1646 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic 1647 // call within them, and catchpads only consisting of 'catch (...)' have a 1648 // '__cxa_end_catch' call within them, both of which generate invokes in case 1649 // the next unwind destination exists, i.e., the next unwind destination is not 1650 // the caller.) 1651 // 1652 // Having at most one EH pad successor is also simpler and helps later 1653 // transformations. 1654 // 1655 // For example, 1656 // current: 1657 // invoke void @foo to ... unwind label %catch.dispatch 1658 // catch.dispatch: 1659 // %0 = catchswitch within ... [label %catch.start] unwind label %next 1660 // catch.start: 1661 // ... 1662 // ... in this BB or some other child BB dominated by this BB there will be an 1663 // invoke that points to 'next' BB as an unwind destination 1664 // 1665 // next: ; We don't need to add this to 'current' BB's successor 1666 // ... 1667 static void findWasmUnwindDestinations( 1668 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1669 BranchProbability Prob, 1670 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1671 &UnwindDests) { 1672 while (EHPadBB) { 1673 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1674 if (isa<CleanupPadInst>(Pad)) { 1675 // Stop on cleanup pads. 1676 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1677 UnwindDests.back().first->setIsEHScopeEntry(); 1678 break; 1679 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1680 // Add the catchpad handlers to the possible destinations. We don't 1681 // continue to the unwind destination of the catchswitch for wasm. 1682 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1683 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1684 UnwindDests.back().first->setIsEHScopeEntry(); 1685 } 1686 break; 1687 } else { 1688 continue; 1689 } 1690 } 1691 } 1692 1693 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1694 /// many places it could ultimately go. In the IR, we have a single unwind 1695 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1696 /// This function skips over imaginary basic blocks that hold catchswitch 1697 /// instructions, and finds all the "real" machine 1698 /// basic block destinations. As those destinations may not be successors of 1699 /// EHPadBB, here we also calculate the edge probability to those destinations. 1700 /// The passed-in Prob is the edge probability to EHPadBB. 1701 static void findUnwindDestinations( 1702 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1703 BranchProbability Prob, 1704 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1705 &UnwindDests) { 1706 EHPersonality Personality = 1707 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1708 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1709 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1710 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1711 bool IsSEH = isAsynchronousEHPersonality(Personality); 1712 1713 if (IsWasmCXX) { 1714 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1715 assert(UnwindDests.size() <= 1 && 1716 "There should be at most one unwind destination for wasm"); 1717 return; 1718 } 1719 1720 while (EHPadBB) { 1721 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1722 BasicBlock *NewEHPadBB = nullptr; 1723 if (isa<LandingPadInst>(Pad)) { 1724 // Stop on landingpads. They are not funclets. 1725 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1726 break; 1727 } else if (isa<CleanupPadInst>(Pad)) { 1728 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1729 // personalities. 1730 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1731 UnwindDests.back().first->setIsEHScopeEntry(); 1732 UnwindDests.back().first->setIsEHFuncletEntry(); 1733 break; 1734 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1735 // Add the catchpad handlers to the possible destinations. 1736 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1737 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1738 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1739 if (IsMSVCCXX || IsCoreCLR) 1740 UnwindDests.back().first->setIsEHFuncletEntry(); 1741 if (!IsSEH) 1742 UnwindDests.back().first->setIsEHScopeEntry(); 1743 } 1744 NewEHPadBB = CatchSwitch->getUnwindDest(); 1745 } else { 1746 continue; 1747 } 1748 1749 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1750 if (BPI && NewEHPadBB) 1751 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1752 EHPadBB = NewEHPadBB; 1753 } 1754 } 1755 1756 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1757 // Update successor info. 1758 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1759 auto UnwindDest = I.getUnwindDest(); 1760 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1761 BranchProbability UnwindDestProb = 1762 (BPI && UnwindDest) 1763 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1764 : BranchProbability::getZero(); 1765 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1766 for (auto &UnwindDest : UnwindDests) { 1767 UnwindDest.first->setIsEHPad(); 1768 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1769 } 1770 FuncInfo.MBB->normalizeSuccProbs(); 1771 1772 // Create the terminator node. 1773 SDValue Ret = 1774 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1775 DAG.setRoot(Ret); 1776 } 1777 1778 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1779 report_fatal_error("visitCatchSwitch not yet implemented!"); 1780 } 1781 1782 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1783 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1784 auto &DL = DAG.getDataLayout(); 1785 SDValue Chain = getControlRoot(); 1786 SmallVector<ISD::OutputArg, 8> Outs; 1787 SmallVector<SDValue, 8> OutVals; 1788 1789 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1790 // lower 1791 // 1792 // %val = call <ty> @llvm.experimental.deoptimize() 1793 // ret <ty> %val 1794 // 1795 // differently. 1796 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1797 LowerDeoptimizingReturn(); 1798 return; 1799 } 1800 1801 if (!FuncInfo.CanLowerReturn) { 1802 unsigned DemoteReg = FuncInfo.DemoteRegister; 1803 const Function *F = I.getParent()->getParent(); 1804 1805 // Emit a store of the return value through the virtual register. 1806 // Leave Outs empty so that LowerReturn won't try to load return 1807 // registers the usual way. 1808 SmallVector<EVT, 1> PtrValueVTs; 1809 ComputeValueVTs(TLI, DL, 1810 F->getReturnType()->getPointerTo( 1811 DAG.getDataLayout().getAllocaAddrSpace()), 1812 PtrValueVTs); 1813 1814 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1815 DemoteReg, PtrValueVTs[0]); 1816 SDValue RetOp = getValue(I.getOperand(0)); 1817 1818 SmallVector<EVT, 4> ValueVTs, MemVTs; 1819 SmallVector<uint64_t, 4> Offsets; 1820 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1821 &Offsets); 1822 unsigned NumValues = ValueVTs.size(); 1823 1824 SmallVector<SDValue, 4> Chains(NumValues); 1825 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType()); 1826 for (unsigned i = 0; i != NumValues; ++i) { 1827 // An aggregate return value cannot wrap around the address space, so 1828 // offsets to its parts don't wrap either. 1829 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, 1830 TypeSize::Fixed(Offsets[i])); 1831 1832 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1833 if (MemVTs[i] != ValueVTs[i]) 1834 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1835 Chains[i] = DAG.getStore( 1836 Chain, getCurSDLoc(), Val, 1837 // FIXME: better loc info would be nice. 1838 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), 1839 commonAlignment(BaseAlign, Offsets[i])); 1840 } 1841 1842 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1843 MVT::Other, Chains); 1844 } else if (I.getNumOperands() != 0) { 1845 SmallVector<EVT, 4> ValueVTs; 1846 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1847 unsigned NumValues = ValueVTs.size(); 1848 if (NumValues) { 1849 SDValue RetOp = getValue(I.getOperand(0)); 1850 1851 const Function *F = I.getParent()->getParent(); 1852 1853 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1854 I.getOperand(0)->getType(), F->getCallingConv(), 1855 /*IsVarArg*/ false); 1856 1857 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1858 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1859 Attribute::SExt)) 1860 ExtendKind = ISD::SIGN_EXTEND; 1861 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1862 Attribute::ZExt)) 1863 ExtendKind = ISD::ZERO_EXTEND; 1864 1865 LLVMContext &Context = F->getContext(); 1866 bool RetInReg = F->getAttributes().hasAttribute( 1867 AttributeList::ReturnIndex, Attribute::InReg); 1868 1869 for (unsigned j = 0; j != NumValues; ++j) { 1870 EVT VT = ValueVTs[j]; 1871 1872 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1873 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1874 1875 CallingConv::ID CC = F->getCallingConv(); 1876 1877 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1878 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1879 SmallVector<SDValue, 4> Parts(NumParts); 1880 getCopyToParts(DAG, getCurSDLoc(), 1881 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1882 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1883 1884 // 'inreg' on function refers to return value 1885 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1886 if (RetInReg) 1887 Flags.setInReg(); 1888 1889 if (I.getOperand(0)->getType()->isPointerTy()) { 1890 Flags.setPointer(); 1891 Flags.setPointerAddrSpace( 1892 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1893 } 1894 1895 if (NeedsRegBlock) { 1896 Flags.setInConsecutiveRegs(); 1897 if (j == NumValues - 1) 1898 Flags.setInConsecutiveRegsLast(); 1899 } 1900 1901 // Propagate extension type if any 1902 if (ExtendKind == ISD::SIGN_EXTEND) 1903 Flags.setSExt(); 1904 else if (ExtendKind == ISD::ZERO_EXTEND) 1905 Flags.setZExt(); 1906 1907 for (unsigned i = 0; i < NumParts; ++i) { 1908 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1909 VT, /*isfixed=*/true, 0, 0)); 1910 OutVals.push_back(Parts[i]); 1911 } 1912 } 1913 } 1914 } 1915 1916 // Push in swifterror virtual register as the last element of Outs. This makes 1917 // sure swifterror virtual register will be returned in the swifterror 1918 // physical register. 1919 const Function *F = I.getParent()->getParent(); 1920 if (TLI.supportSwiftError() && 1921 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1922 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1923 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1924 Flags.setSwiftError(); 1925 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1926 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1927 true /*isfixed*/, 1 /*origidx*/, 1928 0 /*partOffs*/)); 1929 // Create SDNode for the swifterror virtual register. 1930 OutVals.push_back( 1931 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1932 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1933 EVT(TLI.getPointerTy(DL)))); 1934 } 1935 1936 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1937 CallingConv::ID CallConv = 1938 DAG.getMachineFunction().getFunction().getCallingConv(); 1939 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1940 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1941 1942 // Verify that the target's LowerReturn behaved as expected. 1943 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1944 "LowerReturn didn't return a valid chain!"); 1945 1946 // Update the DAG with the new chain value resulting from return lowering. 1947 DAG.setRoot(Chain); 1948 } 1949 1950 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1951 /// created for it, emit nodes to copy the value into the virtual 1952 /// registers. 1953 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1954 // Skip empty types 1955 if (V->getType()->isEmptyTy()) 1956 return; 1957 1958 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V); 1959 if (VMI != FuncInfo.ValueMap.end()) { 1960 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1961 CopyValueToVirtualRegister(V, VMI->second); 1962 } 1963 } 1964 1965 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1966 /// the current basic block, add it to ValueMap now so that we'll get a 1967 /// CopyTo/FromReg. 1968 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1969 // No need to export constants. 1970 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1971 1972 // Already exported? 1973 if (FuncInfo.isExportedInst(V)) return; 1974 1975 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1976 CopyValueToVirtualRegister(V, Reg); 1977 } 1978 1979 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1980 const BasicBlock *FromBB) { 1981 // The operands of the setcc have to be in this block. We don't know 1982 // how to export them from some other block. 1983 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1984 // Can export from current BB. 1985 if (VI->getParent() == FromBB) 1986 return true; 1987 1988 // Is already exported, noop. 1989 return FuncInfo.isExportedInst(V); 1990 } 1991 1992 // If this is an argument, we can export it if the BB is the entry block or 1993 // if it is already exported. 1994 if (isa<Argument>(V)) { 1995 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1996 return true; 1997 1998 // Otherwise, can only export this if it is already exported. 1999 return FuncInfo.isExportedInst(V); 2000 } 2001 2002 // Otherwise, constants can always be exported. 2003 return true; 2004 } 2005 2006 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 2007 BranchProbability 2008 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2009 const MachineBasicBlock *Dst) const { 2010 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2011 const BasicBlock *SrcBB = Src->getBasicBlock(); 2012 const BasicBlock *DstBB = Dst->getBasicBlock(); 2013 if (!BPI) { 2014 // If BPI is not available, set the default probability as 1 / N, where N is 2015 // the number of successors. 2016 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2017 return BranchProbability(1, SuccSize); 2018 } 2019 return BPI->getEdgeProbability(SrcBB, DstBB); 2020 } 2021 2022 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2023 MachineBasicBlock *Dst, 2024 BranchProbability Prob) { 2025 if (!FuncInfo.BPI) 2026 Src->addSuccessorWithoutProb(Dst); 2027 else { 2028 if (Prob.isUnknown()) 2029 Prob = getEdgeProbability(Src, Dst); 2030 Src->addSuccessor(Dst, Prob); 2031 } 2032 } 2033 2034 static bool InBlock(const Value *V, const BasicBlock *BB) { 2035 if (const Instruction *I = dyn_cast<Instruction>(V)) 2036 return I->getParent() == BB; 2037 return true; 2038 } 2039 2040 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2041 /// This function emits a branch and is used at the leaves of an OR or an 2042 /// AND operator tree. 2043 void 2044 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2045 MachineBasicBlock *TBB, 2046 MachineBasicBlock *FBB, 2047 MachineBasicBlock *CurBB, 2048 MachineBasicBlock *SwitchBB, 2049 BranchProbability TProb, 2050 BranchProbability FProb, 2051 bool InvertCond) { 2052 const BasicBlock *BB = CurBB->getBasicBlock(); 2053 2054 // If the leaf of the tree is a comparison, merge the condition into 2055 // the caseblock. 2056 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2057 // The operands of the cmp have to be in this block. We don't know 2058 // how to export them from some other block. If this is the first block 2059 // of the sequence, no exporting is needed. 2060 if (CurBB == SwitchBB || 2061 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2062 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2063 ISD::CondCode Condition; 2064 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2065 ICmpInst::Predicate Pred = 2066 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2067 Condition = getICmpCondCode(Pred); 2068 } else { 2069 const FCmpInst *FC = cast<FCmpInst>(Cond); 2070 FCmpInst::Predicate Pred = 2071 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2072 Condition = getFCmpCondCode(Pred); 2073 if (TM.Options.NoNaNsFPMath) 2074 Condition = getFCmpCodeWithoutNaN(Condition); 2075 } 2076 2077 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2078 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2079 SL->SwitchCases.push_back(CB); 2080 return; 2081 } 2082 } 2083 2084 // Create a CaseBlock record representing this branch. 2085 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2086 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2087 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2088 SL->SwitchCases.push_back(CB); 2089 } 2090 2091 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2092 MachineBasicBlock *TBB, 2093 MachineBasicBlock *FBB, 2094 MachineBasicBlock *CurBB, 2095 MachineBasicBlock *SwitchBB, 2096 Instruction::BinaryOps Opc, 2097 BranchProbability TProb, 2098 BranchProbability FProb, 2099 bool InvertCond) { 2100 // Skip over not part of the tree and remember to invert op and operands at 2101 // next level. 2102 Value *NotCond; 2103 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2104 InBlock(NotCond, CurBB->getBasicBlock())) { 2105 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2106 !InvertCond); 2107 return; 2108 } 2109 2110 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2111 const Value *BOpOp0, *BOpOp1; 2112 // Compute the effective opcode for Cond, taking into account whether it needs 2113 // to be inverted, e.g. 2114 // and (not (or A, B)), C 2115 // gets lowered as 2116 // and (and (not A, not B), C) 2117 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0; 2118 if (BOp) { 2119 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1))) 2120 ? Instruction::And 2121 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1))) 2122 ? Instruction::Or 2123 : (Instruction::BinaryOps)0); 2124 if (InvertCond) { 2125 if (BOpc == Instruction::And) 2126 BOpc = Instruction::Or; 2127 else if (BOpc == Instruction::Or) 2128 BOpc = Instruction::And; 2129 } 2130 } 2131 2132 // If this node is not part of the or/and tree, emit it as a branch. 2133 // Note that all nodes in the tree should have same opcode. 2134 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse(); 2135 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() || 2136 !InBlock(BOpOp0, CurBB->getBasicBlock()) || 2137 !InBlock(BOpOp1, CurBB->getBasicBlock())) { 2138 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2139 TProb, FProb, InvertCond); 2140 return; 2141 } 2142 2143 // Create TmpBB after CurBB. 2144 MachineFunction::iterator BBI(CurBB); 2145 MachineFunction &MF = DAG.getMachineFunction(); 2146 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2147 CurBB->getParent()->insert(++BBI, TmpBB); 2148 2149 if (Opc == Instruction::Or) { 2150 // Codegen X | Y as: 2151 // BB1: 2152 // jmp_if_X TBB 2153 // jmp TmpBB 2154 // TmpBB: 2155 // jmp_if_Y TBB 2156 // jmp FBB 2157 // 2158 2159 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2160 // The requirement is that 2161 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2162 // = TrueProb for original BB. 2163 // Assuming the original probabilities are A and B, one choice is to set 2164 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2165 // A/(1+B) and 2B/(1+B). This choice assumes that 2166 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2167 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2168 // TmpBB, but the math is more complicated. 2169 2170 auto NewTrueProb = TProb / 2; 2171 auto NewFalseProb = TProb / 2 + FProb; 2172 // Emit the LHS condition. 2173 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb, 2174 NewFalseProb, InvertCond); 2175 2176 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2177 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2178 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2179 // Emit the RHS condition into TmpBB. 2180 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2181 Probs[1], InvertCond); 2182 } else { 2183 assert(Opc == Instruction::And && "Unknown merge op!"); 2184 // Codegen X & Y as: 2185 // BB1: 2186 // jmp_if_X TmpBB 2187 // jmp FBB 2188 // TmpBB: 2189 // jmp_if_Y TBB 2190 // jmp FBB 2191 // 2192 // This requires creation of TmpBB after CurBB. 2193 2194 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2195 // The requirement is that 2196 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2197 // = FalseProb for original BB. 2198 // Assuming the original probabilities are A and B, one choice is to set 2199 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2200 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2201 // TrueProb for BB1 * FalseProb for TmpBB. 2202 2203 auto NewTrueProb = TProb + FProb / 2; 2204 auto NewFalseProb = FProb / 2; 2205 // Emit the LHS condition. 2206 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb, 2207 NewFalseProb, InvertCond); 2208 2209 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2210 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2211 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2212 // Emit the RHS condition into TmpBB. 2213 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0], 2214 Probs[1], InvertCond); 2215 } 2216 } 2217 2218 /// If the set of cases should be emitted as a series of branches, return true. 2219 /// If we should emit this as a bunch of and/or'd together conditions, return 2220 /// false. 2221 bool 2222 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2223 if (Cases.size() != 2) return true; 2224 2225 // If this is two comparisons of the same values or'd or and'd together, they 2226 // will get folded into a single comparison, so don't emit two blocks. 2227 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2228 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2229 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2230 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2231 return false; 2232 } 2233 2234 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2235 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2236 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2237 Cases[0].CC == Cases[1].CC && 2238 isa<Constant>(Cases[0].CmpRHS) && 2239 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2240 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2241 return false; 2242 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2243 return false; 2244 } 2245 2246 return true; 2247 } 2248 2249 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2250 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2251 2252 // Update machine-CFG edges. 2253 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2254 2255 if (I.isUnconditional()) { 2256 // Update machine-CFG edges. 2257 BrMBB->addSuccessor(Succ0MBB); 2258 2259 // If this is not a fall-through branch or optimizations are switched off, 2260 // emit the branch. 2261 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2262 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2263 MVT::Other, getControlRoot(), 2264 DAG.getBasicBlock(Succ0MBB))); 2265 2266 return; 2267 } 2268 2269 // If this condition is one of the special cases we handle, do special stuff 2270 // now. 2271 const Value *CondVal = I.getCondition(); 2272 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2273 2274 // If this is a series of conditions that are or'd or and'd together, emit 2275 // this as a sequence of branches instead of setcc's with and/or operations. 2276 // As long as jumps are not expensive (exceptions for multi-use logic ops, 2277 // unpredictable branches, and vector extracts because those jumps are likely 2278 // expensive for any target), this should improve performance. 2279 // For example, instead of something like: 2280 // cmp A, B 2281 // C = seteq 2282 // cmp D, E 2283 // F = setle 2284 // or C, F 2285 // jnz foo 2286 // Emit: 2287 // cmp A, B 2288 // je foo 2289 // cmp D, E 2290 // jle foo 2291 const Instruction *BOp = dyn_cast<Instruction>(CondVal); 2292 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp && 2293 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) { 2294 Value *Vec; 2295 const Value *BOp0, *BOp1; 2296 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0; 2297 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1)))) 2298 Opcode = Instruction::And; 2299 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1)))) 2300 Opcode = Instruction::Or; 2301 2302 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 2303 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 2304 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode, 2305 getEdgeProbability(BrMBB, Succ0MBB), 2306 getEdgeProbability(BrMBB, Succ1MBB), 2307 /*InvertCond=*/false); 2308 // If the compares in later blocks need to use values not currently 2309 // exported from this block, export them now. This block should always 2310 // be the first entry. 2311 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2312 2313 // Allow some cases to be rejected. 2314 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2315 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2316 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2317 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2318 } 2319 2320 // Emit the branch for this block. 2321 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2322 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2323 return; 2324 } 2325 2326 // Okay, we decided not to do this, remove any inserted MBB's and clear 2327 // SwitchCases. 2328 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2329 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2330 2331 SL->SwitchCases.clear(); 2332 } 2333 } 2334 2335 // Create a CaseBlock record representing this branch. 2336 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2337 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2338 2339 // Use visitSwitchCase to actually insert the fast branch sequence for this 2340 // cond branch. 2341 visitSwitchCase(CB, BrMBB); 2342 } 2343 2344 /// visitSwitchCase - Emits the necessary code to represent a single node in 2345 /// the binary search tree resulting from lowering a switch instruction. 2346 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2347 MachineBasicBlock *SwitchBB) { 2348 SDValue Cond; 2349 SDValue CondLHS = getValue(CB.CmpLHS); 2350 SDLoc dl = CB.DL; 2351 2352 if (CB.CC == ISD::SETTRUE) { 2353 // Branch or fall through to TrueBB. 2354 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2355 SwitchBB->normalizeSuccProbs(); 2356 if (CB.TrueBB != NextBlock(SwitchBB)) { 2357 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2358 DAG.getBasicBlock(CB.TrueBB))); 2359 } 2360 return; 2361 } 2362 2363 auto &TLI = DAG.getTargetLoweringInfo(); 2364 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2365 2366 // Build the setcc now. 2367 if (!CB.CmpMHS) { 2368 // Fold "(X == true)" to X and "(X == false)" to !X to 2369 // handle common cases produced by branch lowering. 2370 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2371 CB.CC == ISD::SETEQ) 2372 Cond = CondLHS; 2373 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2374 CB.CC == ISD::SETEQ) { 2375 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2376 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2377 } else { 2378 SDValue CondRHS = getValue(CB.CmpRHS); 2379 2380 // If a pointer's DAG type is larger than its memory type then the DAG 2381 // values are zero-extended. This breaks signed comparisons so truncate 2382 // back to the underlying type before doing the compare. 2383 if (CondLHS.getValueType() != MemVT) { 2384 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2385 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2386 } 2387 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2388 } 2389 } else { 2390 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2391 2392 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2393 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2394 2395 SDValue CmpOp = getValue(CB.CmpMHS); 2396 EVT VT = CmpOp.getValueType(); 2397 2398 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2399 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2400 ISD::SETLE); 2401 } else { 2402 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2403 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2404 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2405 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2406 } 2407 } 2408 2409 // Update successor info 2410 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2411 // TrueBB and FalseBB are always different unless the incoming IR is 2412 // degenerate. This only happens when running llc on weird IR. 2413 if (CB.TrueBB != CB.FalseBB) 2414 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2415 SwitchBB->normalizeSuccProbs(); 2416 2417 // If the lhs block is the next block, invert the condition so that we can 2418 // fall through to the lhs instead of the rhs block. 2419 if (CB.TrueBB == NextBlock(SwitchBB)) { 2420 std::swap(CB.TrueBB, CB.FalseBB); 2421 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2422 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2423 } 2424 2425 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2426 MVT::Other, getControlRoot(), Cond, 2427 DAG.getBasicBlock(CB.TrueBB)); 2428 2429 // Insert the false branch. Do this even if it's a fall through branch, 2430 // this makes it easier to do DAG optimizations which require inverting 2431 // the branch condition. 2432 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2433 DAG.getBasicBlock(CB.FalseBB)); 2434 2435 DAG.setRoot(BrCond); 2436 } 2437 2438 /// visitJumpTable - Emit JumpTable node in the current MBB 2439 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2440 // Emit the code for the jump table 2441 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2442 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2443 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2444 JT.Reg, PTy); 2445 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2446 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2447 MVT::Other, Index.getValue(1), 2448 Table, Index); 2449 DAG.setRoot(BrJumpTable); 2450 } 2451 2452 /// visitJumpTableHeader - This function emits necessary code to produce index 2453 /// in the JumpTable from switch case. 2454 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2455 JumpTableHeader &JTH, 2456 MachineBasicBlock *SwitchBB) { 2457 SDLoc dl = getCurSDLoc(); 2458 2459 // Subtract the lowest switch case value from the value being switched on. 2460 SDValue SwitchOp = getValue(JTH.SValue); 2461 EVT VT = SwitchOp.getValueType(); 2462 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2463 DAG.getConstant(JTH.First, dl, VT)); 2464 2465 // The SDNode we just created, which holds the value being switched on minus 2466 // the smallest case value, needs to be copied to a virtual register so it 2467 // can be used as an index into the jump table in a subsequent basic block. 2468 // This value may be smaller or larger than the target's pointer type, and 2469 // therefore require extension or truncating. 2470 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2471 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2472 2473 unsigned JumpTableReg = 2474 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2475 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2476 JumpTableReg, SwitchOp); 2477 JT.Reg = JumpTableReg; 2478 2479 if (!JTH.OmitRangeCheck) { 2480 // Emit the range check for the jump table, and branch to the default block 2481 // for the switch statement if the value being switched on exceeds the 2482 // largest case in the switch. 2483 SDValue CMP = DAG.getSetCC( 2484 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2485 Sub.getValueType()), 2486 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2487 2488 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2489 MVT::Other, CopyTo, CMP, 2490 DAG.getBasicBlock(JT.Default)); 2491 2492 // Avoid emitting unnecessary branches to the next block. 2493 if (JT.MBB != NextBlock(SwitchBB)) 2494 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2495 DAG.getBasicBlock(JT.MBB)); 2496 2497 DAG.setRoot(BrCond); 2498 } else { 2499 // Avoid emitting unnecessary branches to the next block. 2500 if (JT.MBB != NextBlock(SwitchBB)) 2501 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2502 DAG.getBasicBlock(JT.MBB))); 2503 else 2504 DAG.setRoot(CopyTo); 2505 } 2506 } 2507 2508 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2509 /// variable if there exists one. 2510 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2511 SDValue &Chain) { 2512 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2513 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2514 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2515 MachineFunction &MF = DAG.getMachineFunction(); 2516 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2517 MachineSDNode *Node = 2518 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2519 if (Global) { 2520 MachinePointerInfo MPInfo(Global); 2521 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2522 MachineMemOperand::MODereferenceable; 2523 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2524 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy)); 2525 DAG.setNodeMemRefs(Node, {MemRef}); 2526 } 2527 if (PtrTy != PtrMemTy) 2528 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2529 return SDValue(Node, 0); 2530 } 2531 2532 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2533 /// tail spliced into a stack protector check success bb. 2534 /// 2535 /// For a high level explanation of how this fits into the stack protector 2536 /// generation see the comment on the declaration of class 2537 /// StackProtectorDescriptor. 2538 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2539 MachineBasicBlock *ParentBB) { 2540 2541 // First create the loads to the guard/stack slot for the comparison. 2542 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2543 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2544 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2545 2546 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2547 int FI = MFI.getStackProtectorIndex(); 2548 2549 SDValue Guard; 2550 SDLoc dl = getCurSDLoc(); 2551 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2552 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2553 Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext())); 2554 2555 // Generate code to load the content of the guard slot. 2556 SDValue GuardVal = DAG.getLoad( 2557 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2558 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2559 MachineMemOperand::MOVolatile); 2560 2561 if (TLI.useStackGuardXorFP()) 2562 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2563 2564 // Retrieve guard check function, nullptr if instrumentation is inlined. 2565 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2566 // The target provides a guard check function to validate the guard value. 2567 // Generate a call to that function with the content of the guard slot as 2568 // argument. 2569 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2570 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2571 2572 TargetLowering::ArgListTy Args; 2573 TargetLowering::ArgListEntry Entry; 2574 Entry.Node = GuardVal; 2575 Entry.Ty = FnTy->getParamType(0); 2576 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2577 Entry.IsInReg = true; 2578 Args.push_back(Entry); 2579 2580 TargetLowering::CallLoweringInfo CLI(DAG); 2581 CLI.setDebugLoc(getCurSDLoc()) 2582 .setChain(DAG.getEntryNode()) 2583 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2584 getValue(GuardCheckFn), std::move(Args)); 2585 2586 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2587 DAG.setRoot(Result.second); 2588 return; 2589 } 2590 2591 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2592 // Otherwise, emit a volatile load to retrieve the stack guard value. 2593 SDValue Chain = DAG.getEntryNode(); 2594 if (TLI.useLoadStackGuardNode()) { 2595 Guard = getLoadStackGuard(DAG, dl, Chain); 2596 } else { 2597 const Value *IRGuard = TLI.getSDagStackGuard(M); 2598 SDValue GuardPtr = getValue(IRGuard); 2599 2600 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2601 MachinePointerInfo(IRGuard, 0), Align, 2602 MachineMemOperand::MOVolatile); 2603 } 2604 2605 // Perform the comparison via a getsetcc. 2606 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2607 *DAG.getContext(), 2608 Guard.getValueType()), 2609 Guard, GuardVal, ISD::SETNE); 2610 2611 // If the guard/stackslot do not equal, branch to failure MBB. 2612 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2613 MVT::Other, GuardVal.getOperand(0), 2614 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2615 // Otherwise branch to success MBB. 2616 SDValue Br = DAG.getNode(ISD::BR, dl, 2617 MVT::Other, BrCond, 2618 DAG.getBasicBlock(SPD.getSuccessMBB())); 2619 2620 DAG.setRoot(Br); 2621 } 2622 2623 /// Codegen the failure basic block for a stack protector check. 2624 /// 2625 /// A failure stack protector machine basic block consists simply of a call to 2626 /// __stack_chk_fail(). 2627 /// 2628 /// For a high level explanation of how this fits into the stack protector 2629 /// generation see the comment on the declaration of class 2630 /// StackProtectorDescriptor. 2631 void 2632 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2633 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2634 TargetLowering::MakeLibCallOptions CallOptions; 2635 CallOptions.setDiscardResult(true); 2636 SDValue Chain = 2637 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2638 None, CallOptions, getCurSDLoc()).second; 2639 // On PS4, the "return address" must still be within the calling function, 2640 // even if it's at the very end, so emit an explicit TRAP here. 2641 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2642 if (TM.getTargetTriple().isPS4CPU()) 2643 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2644 // WebAssembly needs an unreachable instruction after a non-returning call, 2645 // because the function return type can be different from __stack_chk_fail's 2646 // return type (void). 2647 if (TM.getTargetTriple().isWasm()) 2648 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2649 2650 DAG.setRoot(Chain); 2651 } 2652 2653 /// visitBitTestHeader - This function emits necessary code to produce value 2654 /// suitable for "bit tests" 2655 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2656 MachineBasicBlock *SwitchBB) { 2657 SDLoc dl = getCurSDLoc(); 2658 2659 // Subtract the minimum value. 2660 SDValue SwitchOp = getValue(B.SValue); 2661 EVT VT = SwitchOp.getValueType(); 2662 SDValue RangeSub = 2663 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2664 2665 // Determine the type of the test operands. 2666 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2667 bool UsePtrType = false; 2668 if (!TLI.isTypeLegal(VT)) { 2669 UsePtrType = true; 2670 } else { 2671 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2672 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2673 // Switch table case range are encoded into series of masks. 2674 // Just use pointer type, it's guaranteed to fit. 2675 UsePtrType = true; 2676 break; 2677 } 2678 } 2679 SDValue Sub = RangeSub; 2680 if (UsePtrType) { 2681 VT = TLI.getPointerTy(DAG.getDataLayout()); 2682 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2683 } 2684 2685 B.RegVT = VT.getSimpleVT(); 2686 B.Reg = FuncInfo.CreateReg(B.RegVT); 2687 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2688 2689 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2690 2691 if (!B.OmitRangeCheck) 2692 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2693 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2694 SwitchBB->normalizeSuccProbs(); 2695 2696 SDValue Root = CopyTo; 2697 if (!B.OmitRangeCheck) { 2698 // Conditional branch to the default block. 2699 SDValue RangeCmp = DAG.getSetCC(dl, 2700 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2701 RangeSub.getValueType()), 2702 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2703 ISD::SETUGT); 2704 2705 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2706 DAG.getBasicBlock(B.Default)); 2707 } 2708 2709 // Avoid emitting unnecessary branches to the next block. 2710 if (MBB != NextBlock(SwitchBB)) 2711 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2712 2713 DAG.setRoot(Root); 2714 } 2715 2716 /// visitBitTestCase - this function produces one "bit test" 2717 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2718 MachineBasicBlock* NextMBB, 2719 BranchProbability BranchProbToNext, 2720 unsigned Reg, 2721 BitTestCase &B, 2722 MachineBasicBlock *SwitchBB) { 2723 SDLoc dl = getCurSDLoc(); 2724 MVT VT = BB.RegVT; 2725 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2726 SDValue Cmp; 2727 unsigned PopCount = countPopulation(B.Mask); 2728 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2729 if (PopCount == 1) { 2730 // Testing for a single bit; just compare the shift count with what it 2731 // would need to be to shift a 1 bit in that position. 2732 Cmp = DAG.getSetCC( 2733 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2734 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2735 ISD::SETEQ); 2736 } else if (PopCount == BB.Range) { 2737 // There is only one zero bit in the range, test for it directly. 2738 Cmp = DAG.getSetCC( 2739 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2740 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2741 ISD::SETNE); 2742 } else { 2743 // Make desired shift 2744 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2745 DAG.getConstant(1, dl, VT), ShiftOp); 2746 2747 // Emit bit tests and jumps 2748 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2749 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2750 Cmp = DAG.getSetCC( 2751 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2752 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2753 } 2754 2755 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2756 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2757 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2758 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2759 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2760 // one as they are relative probabilities (and thus work more like weights), 2761 // and hence we need to normalize them to let the sum of them become one. 2762 SwitchBB->normalizeSuccProbs(); 2763 2764 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2765 MVT::Other, getControlRoot(), 2766 Cmp, DAG.getBasicBlock(B.TargetBB)); 2767 2768 // Avoid emitting unnecessary branches to the next block. 2769 if (NextMBB != NextBlock(SwitchBB)) 2770 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2771 DAG.getBasicBlock(NextMBB)); 2772 2773 DAG.setRoot(BrAnd); 2774 } 2775 2776 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2777 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2778 2779 // Retrieve successors. Look through artificial IR level blocks like 2780 // catchswitch for successors. 2781 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2782 const BasicBlock *EHPadBB = I.getSuccessor(1); 2783 2784 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2785 // have to do anything here to lower funclet bundles. 2786 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2787 LLVMContext::OB_gc_transition, 2788 LLVMContext::OB_gc_live, 2789 LLVMContext::OB_funclet, 2790 LLVMContext::OB_cfguardtarget}) && 2791 "Cannot lower invokes with arbitrary operand bundles yet!"); 2792 2793 const Value *Callee(I.getCalledOperand()); 2794 const Function *Fn = dyn_cast<Function>(Callee); 2795 if (isa<InlineAsm>(Callee)) 2796 visitInlineAsm(I); 2797 else if (Fn && Fn->isIntrinsic()) { 2798 switch (Fn->getIntrinsicID()) { 2799 default: 2800 llvm_unreachable("Cannot invoke this intrinsic"); 2801 case Intrinsic::donothing: 2802 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2803 break; 2804 case Intrinsic::experimental_patchpoint_void: 2805 case Intrinsic::experimental_patchpoint_i64: 2806 visitPatchpoint(I, EHPadBB); 2807 break; 2808 case Intrinsic::experimental_gc_statepoint: 2809 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB); 2810 break; 2811 case Intrinsic::wasm_rethrow: { 2812 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2813 // special because it can be invoked, so we manually lower it to a DAG 2814 // node here. 2815 SmallVector<SDValue, 8> Ops; 2816 Ops.push_back(getRoot()); // inchain 2817 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2818 Ops.push_back( 2819 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(), 2820 TLI.getPointerTy(DAG.getDataLayout()))); 2821 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2822 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2823 break; 2824 } 2825 } 2826 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2827 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2828 // Eventually we will support lowering the @llvm.experimental.deoptimize 2829 // intrinsic, and right now there are no plans to support other intrinsics 2830 // with deopt state. 2831 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2832 } else { 2833 LowerCallTo(I, getValue(Callee), false, EHPadBB); 2834 } 2835 2836 // If the value of the invoke is used outside of its defining block, make it 2837 // available as a virtual register. 2838 // We already took care of the exported value for the statepoint instruction 2839 // during call to the LowerStatepoint. 2840 if (!isa<GCStatepointInst>(I)) { 2841 CopyToExportRegsIfNeeded(&I); 2842 } 2843 2844 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2845 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2846 BranchProbability EHPadBBProb = 2847 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2848 : BranchProbability::getZero(); 2849 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2850 2851 // Update successor info. 2852 addSuccessorWithProb(InvokeMBB, Return); 2853 for (auto &UnwindDest : UnwindDests) { 2854 UnwindDest.first->setIsEHPad(); 2855 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2856 } 2857 InvokeMBB->normalizeSuccProbs(); 2858 2859 // Drop into normal successor. 2860 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2861 DAG.getBasicBlock(Return))); 2862 } 2863 2864 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2865 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2866 2867 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2868 // have to do anything here to lower funclet bundles. 2869 assert(!I.hasOperandBundlesOtherThan( 2870 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2871 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2872 2873 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr"); 2874 visitInlineAsm(I); 2875 CopyToExportRegsIfNeeded(&I); 2876 2877 // Retrieve successors. 2878 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2879 2880 // Update successor info. 2881 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne()); 2882 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2883 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2884 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero()); 2885 Target->setIsInlineAsmBrIndirectTarget(); 2886 } 2887 CallBrMBB->normalizeSuccProbs(); 2888 2889 // Drop into default successor. 2890 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2891 MVT::Other, getControlRoot(), 2892 DAG.getBasicBlock(Return))); 2893 } 2894 2895 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2896 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2897 } 2898 2899 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2900 assert(FuncInfo.MBB->isEHPad() && 2901 "Call to landingpad not in landing pad!"); 2902 2903 // If there aren't registers to copy the values into (e.g., during SjLj 2904 // exceptions), then don't bother to create these DAG nodes. 2905 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2906 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2907 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2908 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2909 return; 2910 2911 // If landingpad's return type is token type, we don't create DAG nodes 2912 // for its exception pointer and selector value. The extraction of exception 2913 // pointer or selector value from token type landingpads is not currently 2914 // supported. 2915 if (LP.getType()->isTokenTy()) 2916 return; 2917 2918 SmallVector<EVT, 2> ValueVTs; 2919 SDLoc dl = getCurSDLoc(); 2920 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2921 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2922 2923 // Get the two live-in registers as SDValues. The physregs have already been 2924 // copied into virtual registers. 2925 SDValue Ops[2]; 2926 if (FuncInfo.ExceptionPointerVirtReg) { 2927 Ops[0] = DAG.getZExtOrTrunc( 2928 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2929 FuncInfo.ExceptionPointerVirtReg, 2930 TLI.getPointerTy(DAG.getDataLayout())), 2931 dl, ValueVTs[0]); 2932 } else { 2933 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2934 } 2935 Ops[1] = DAG.getZExtOrTrunc( 2936 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2937 FuncInfo.ExceptionSelectorVirtReg, 2938 TLI.getPointerTy(DAG.getDataLayout())), 2939 dl, ValueVTs[1]); 2940 2941 // Merge into one. 2942 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2943 DAG.getVTList(ValueVTs), Ops); 2944 setValue(&LP, Res); 2945 } 2946 2947 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2948 MachineBasicBlock *Last) { 2949 // Update JTCases. 2950 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2951 if (SL->JTCases[i].first.HeaderBB == First) 2952 SL->JTCases[i].first.HeaderBB = Last; 2953 2954 // Update BitTestCases. 2955 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2956 if (SL->BitTestCases[i].Parent == First) 2957 SL->BitTestCases[i].Parent = Last; 2958 } 2959 2960 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2961 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2962 2963 // Update machine-CFG edges with unique successors. 2964 SmallSet<BasicBlock*, 32> Done; 2965 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2966 BasicBlock *BB = I.getSuccessor(i); 2967 bool Inserted = Done.insert(BB).second; 2968 if (!Inserted) 2969 continue; 2970 2971 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2972 addSuccessorWithProb(IndirectBrMBB, Succ); 2973 } 2974 IndirectBrMBB->normalizeSuccProbs(); 2975 2976 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2977 MVT::Other, getControlRoot(), 2978 getValue(I.getAddress()))); 2979 } 2980 2981 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2982 if (!DAG.getTarget().Options.TrapUnreachable) 2983 return; 2984 2985 // We may be able to ignore unreachable behind a noreturn call. 2986 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2987 const BasicBlock &BB = *I.getParent(); 2988 if (&I != &BB.front()) { 2989 BasicBlock::const_iterator PredI = 2990 std::prev(BasicBlock::const_iterator(&I)); 2991 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2992 if (Call->doesNotReturn()) 2993 return; 2994 } 2995 } 2996 } 2997 2998 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2999 } 3000 3001 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3002 SDNodeFlags Flags; 3003 3004 SDValue Op = getValue(I.getOperand(0)); 3005 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3006 Op, Flags); 3007 setValue(&I, UnNodeValue); 3008 } 3009 3010 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3011 SDNodeFlags Flags; 3012 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3013 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3014 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3015 } 3016 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) 3017 Flags.setExact(ExactOp->isExact()); 3018 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3019 Flags.copyFMF(*FPOp); 3020 3021 SDValue Op1 = getValue(I.getOperand(0)); 3022 SDValue Op2 = getValue(I.getOperand(1)); 3023 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3024 Op1, Op2, Flags); 3025 setValue(&I, BinNodeValue); 3026 } 3027 3028 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3029 SDValue Op1 = getValue(I.getOperand(0)); 3030 SDValue Op2 = getValue(I.getOperand(1)); 3031 3032 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3033 Op1.getValueType(), DAG.getDataLayout()); 3034 3035 // Coerce the shift amount to the right type if we can. 3036 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3037 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3038 unsigned Op2Size = Op2.getValueSizeInBits(); 3039 SDLoc DL = getCurSDLoc(); 3040 3041 // If the operand is smaller than the shift count type, promote it. 3042 if (ShiftSize > Op2Size) 3043 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3044 3045 // If the operand is larger than the shift count type but the shift 3046 // count type has enough bits to represent any shift value, truncate 3047 // it now. This is a common case and it exposes the truncate to 3048 // optimization early. 3049 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3050 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3051 // Otherwise we'll need to temporarily settle for some other convenient 3052 // type. Type legalization will make adjustments once the shiftee is split. 3053 else 3054 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3055 } 3056 3057 bool nuw = false; 3058 bool nsw = false; 3059 bool exact = false; 3060 3061 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3062 3063 if (const OverflowingBinaryOperator *OFBinOp = 3064 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3065 nuw = OFBinOp->hasNoUnsignedWrap(); 3066 nsw = OFBinOp->hasNoSignedWrap(); 3067 } 3068 if (const PossiblyExactOperator *ExactOp = 3069 dyn_cast<const PossiblyExactOperator>(&I)) 3070 exact = ExactOp->isExact(); 3071 } 3072 SDNodeFlags Flags; 3073 Flags.setExact(exact); 3074 Flags.setNoSignedWrap(nsw); 3075 Flags.setNoUnsignedWrap(nuw); 3076 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3077 Flags); 3078 setValue(&I, Res); 3079 } 3080 3081 void SelectionDAGBuilder::visitSDiv(const User &I) { 3082 SDValue Op1 = getValue(I.getOperand(0)); 3083 SDValue Op2 = getValue(I.getOperand(1)); 3084 3085 SDNodeFlags Flags; 3086 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3087 cast<PossiblyExactOperator>(&I)->isExact()); 3088 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3089 Op2, Flags)); 3090 } 3091 3092 void SelectionDAGBuilder::visitICmp(const User &I) { 3093 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3094 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3095 predicate = IC->getPredicate(); 3096 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3097 predicate = ICmpInst::Predicate(IC->getPredicate()); 3098 SDValue Op1 = getValue(I.getOperand(0)); 3099 SDValue Op2 = getValue(I.getOperand(1)); 3100 ISD::CondCode Opcode = getICmpCondCode(predicate); 3101 3102 auto &TLI = DAG.getTargetLoweringInfo(); 3103 EVT MemVT = 3104 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3105 3106 // If a pointer's DAG type is larger than its memory type then the DAG values 3107 // are zero-extended. This breaks signed comparisons so truncate back to the 3108 // underlying type before doing the compare. 3109 if (Op1.getValueType() != MemVT) { 3110 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3111 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3112 } 3113 3114 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3115 I.getType()); 3116 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3117 } 3118 3119 void SelectionDAGBuilder::visitFCmp(const User &I) { 3120 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3121 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3122 predicate = FC->getPredicate(); 3123 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3124 predicate = FCmpInst::Predicate(FC->getPredicate()); 3125 SDValue Op1 = getValue(I.getOperand(0)); 3126 SDValue Op2 = getValue(I.getOperand(1)); 3127 3128 ISD::CondCode Condition = getFCmpCondCode(predicate); 3129 auto *FPMO = cast<FPMathOperator>(&I); 3130 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath) 3131 Condition = getFCmpCodeWithoutNaN(Condition); 3132 3133 SDNodeFlags Flags; 3134 Flags.copyFMF(*FPMO); 3135 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags); 3136 3137 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3138 I.getType()); 3139 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3140 } 3141 3142 // Check if the condition of the select has one use or two users that are both 3143 // selects with the same condition. 3144 static bool hasOnlySelectUsers(const Value *Cond) { 3145 return llvm::all_of(Cond->users(), [](const Value *V) { 3146 return isa<SelectInst>(V); 3147 }); 3148 } 3149 3150 void SelectionDAGBuilder::visitSelect(const User &I) { 3151 SmallVector<EVT, 4> ValueVTs; 3152 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3153 ValueVTs); 3154 unsigned NumValues = ValueVTs.size(); 3155 if (NumValues == 0) return; 3156 3157 SmallVector<SDValue, 4> Values(NumValues); 3158 SDValue Cond = getValue(I.getOperand(0)); 3159 SDValue LHSVal = getValue(I.getOperand(1)); 3160 SDValue RHSVal = getValue(I.getOperand(2)); 3161 SmallVector<SDValue, 1> BaseOps(1, Cond); 3162 ISD::NodeType OpCode = 3163 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT; 3164 3165 bool IsUnaryAbs = false; 3166 bool Negate = false; 3167 3168 SDNodeFlags Flags; 3169 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 3170 Flags.copyFMF(*FPOp); 3171 3172 // Min/max matching is only viable if all output VTs are the same. 3173 if (is_splat(ValueVTs)) { 3174 EVT VT = ValueVTs[0]; 3175 LLVMContext &Ctx = *DAG.getContext(); 3176 auto &TLI = DAG.getTargetLoweringInfo(); 3177 3178 // We care about the legality of the operation after it has been type 3179 // legalized. 3180 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3181 VT = TLI.getTypeToTransformTo(Ctx, VT); 3182 3183 // If the vselect is legal, assume we want to leave this as a vector setcc + 3184 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3185 // min/max is legal on the scalar type. 3186 bool UseScalarMinMax = VT.isVector() && 3187 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3188 3189 Value *LHS, *RHS; 3190 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3191 ISD::NodeType Opc = ISD::DELETED_NODE; 3192 switch (SPR.Flavor) { 3193 case SPF_UMAX: Opc = ISD::UMAX; break; 3194 case SPF_UMIN: Opc = ISD::UMIN; break; 3195 case SPF_SMAX: Opc = ISD::SMAX; break; 3196 case SPF_SMIN: Opc = ISD::SMIN; break; 3197 case SPF_FMINNUM: 3198 switch (SPR.NaNBehavior) { 3199 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3200 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3201 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3202 case SPNB_RETURNS_ANY: { 3203 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3204 Opc = ISD::FMINNUM; 3205 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3206 Opc = ISD::FMINIMUM; 3207 else if (UseScalarMinMax) 3208 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3209 ISD::FMINNUM : ISD::FMINIMUM; 3210 break; 3211 } 3212 } 3213 break; 3214 case SPF_FMAXNUM: 3215 switch (SPR.NaNBehavior) { 3216 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3217 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3218 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3219 case SPNB_RETURNS_ANY: 3220 3221 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3222 Opc = ISD::FMAXNUM; 3223 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3224 Opc = ISD::FMAXIMUM; 3225 else if (UseScalarMinMax) 3226 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3227 ISD::FMAXNUM : ISD::FMAXIMUM; 3228 break; 3229 } 3230 break; 3231 case SPF_NABS: 3232 Negate = true; 3233 LLVM_FALLTHROUGH; 3234 case SPF_ABS: 3235 IsUnaryAbs = true; 3236 Opc = ISD::ABS; 3237 break; 3238 default: break; 3239 } 3240 3241 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3242 (TLI.isOperationLegalOrCustom(Opc, VT) || 3243 (UseScalarMinMax && 3244 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3245 // If the underlying comparison instruction is used by any other 3246 // instruction, the consumed instructions won't be destroyed, so it is 3247 // not profitable to convert to a min/max. 3248 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3249 OpCode = Opc; 3250 LHSVal = getValue(LHS); 3251 RHSVal = getValue(RHS); 3252 BaseOps.clear(); 3253 } 3254 3255 if (IsUnaryAbs) { 3256 OpCode = Opc; 3257 LHSVal = getValue(LHS); 3258 BaseOps.clear(); 3259 } 3260 } 3261 3262 if (IsUnaryAbs) { 3263 for (unsigned i = 0; i != NumValues; ++i) { 3264 SDLoc dl = getCurSDLoc(); 3265 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i); 3266 Values[i] = 3267 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i)); 3268 if (Negate) 3269 Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), 3270 Values[i]); 3271 } 3272 } else { 3273 for (unsigned i = 0; i != NumValues; ++i) { 3274 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3275 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3276 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3277 Values[i] = DAG.getNode( 3278 OpCode, getCurSDLoc(), 3279 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags); 3280 } 3281 } 3282 3283 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3284 DAG.getVTList(ValueVTs), Values)); 3285 } 3286 3287 void SelectionDAGBuilder::visitTrunc(const User &I) { 3288 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3289 SDValue N = getValue(I.getOperand(0)); 3290 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3291 I.getType()); 3292 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3293 } 3294 3295 void SelectionDAGBuilder::visitZExt(const User &I) { 3296 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3297 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3298 SDValue N = getValue(I.getOperand(0)); 3299 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3300 I.getType()); 3301 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3302 } 3303 3304 void SelectionDAGBuilder::visitSExt(const User &I) { 3305 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3306 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3307 SDValue N = getValue(I.getOperand(0)); 3308 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3309 I.getType()); 3310 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3311 } 3312 3313 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3314 // FPTrunc is never a no-op cast, no need to check 3315 SDValue N = getValue(I.getOperand(0)); 3316 SDLoc dl = getCurSDLoc(); 3317 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3318 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3319 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3320 DAG.getTargetConstant( 3321 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3322 } 3323 3324 void SelectionDAGBuilder::visitFPExt(const User &I) { 3325 // FPExt is never a no-op cast, no need to check 3326 SDValue N = getValue(I.getOperand(0)); 3327 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3328 I.getType()); 3329 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3330 } 3331 3332 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3333 // FPToUI is never a no-op cast, no need to check 3334 SDValue N = getValue(I.getOperand(0)); 3335 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3336 I.getType()); 3337 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3338 } 3339 3340 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3341 // FPToSI is never a no-op cast, no need to check 3342 SDValue N = getValue(I.getOperand(0)); 3343 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3344 I.getType()); 3345 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3346 } 3347 3348 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3349 // UIToFP is never a no-op cast, no need to check 3350 SDValue N = getValue(I.getOperand(0)); 3351 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3352 I.getType()); 3353 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3354 } 3355 3356 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3357 // SIToFP is never a no-op cast, no need to check 3358 SDValue N = getValue(I.getOperand(0)); 3359 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3360 I.getType()); 3361 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3362 } 3363 3364 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3365 // What to do depends on the size of the integer and the size of the pointer. 3366 // We can either truncate, zero extend, or no-op, accordingly. 3367 SDValue N = getValue(I.getOperand(0)); 3368 auto &TLI = DAG.getTargetLoweringInfo(); 3369 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3370 I.getType()); 3371 EVT PtrMemVT = 3372 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3373 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3374 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3375 setValue(&I, N); 3376 } 3377 3378 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3379 // What to do depends on the size of the integer and the size of the pointer. 3380 // We can either truncate, zero extend, or no-op, accordingly. 3381 SDValue N = getValue(I.getOperand(0)); 3382 auto &TLI = DAG.getTargetLoweringInfo(); 3383 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3384 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3385 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3386 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3387 setValue(&I, N); 3388 } 3389 3390 void SelectionDAGBuilder::visitBitCast(const User &I) { 3391 SDValue N = getValue(I.getOperand(0)); 3392 SDLoc dl = getCurSDLoc(); 3393 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3394 I.getType()); 3395 3396 // BitCast assures us that source and destination are the same size so this is 3397 // either a BITCAST or a no-op. 3398 if (DestVT != N.getValueType()) 3399 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3400 DestVT, N)); // convert types. 3401 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3402 // might fold any kind of constant expression to an integer constant and that 3403 // is not what we are looking for. Only recognize a bitcast of a genuine 3404 // constant integer as an opaque constant. 3405 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3406 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3407 /*isOpaque*/true)); 3408 else 3409 setValue(&I, N); // noop cast. 3410 } 3411 3412 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3413 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3414 const Value *SV = I.getOperand(0); 3415 SDValue N = getValue(SV); 3416 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3417 3418 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3419 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3420 3421 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS)) 3422 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3423 3424 setValue(&I, N); 3425 } 3426 3427 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3428 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3429 SDValue InVec = getValue(I.getOperand(0)); 3430 SDValue InVal = getValue(I.getOperand(1)); 3431 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3432 TLI.getVectorIdxTy(DAG.getDataLayout())); 3433 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3434 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3435 InVec, InVal, InIdx)); 3436 } 3437 3438 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3439 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3440 SDValue InVec = getValue(I.getOperand(0)); 3441 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3442 TLI.getVectorIdxTy(DAG.getDataLayout())); 3443 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3444 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3445 InVec, InIdx)); 3446 } 3447 3448 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3449 SDValue Src1 = getValue(I.getOperand(0)); 3450 SDValue Src2 = getValue(I.getOperand(1)); 3451 ArrayRef<int> Mask; 3452 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 3453 Mask = SVI->getShuffleMask(); 3454 else 3455 Mask = cast<ConstantExpr>(I).getShuffleMask(); 3456 SDLoc DL = getCurSDLoc(); 3457 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3458 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3459 EVT SrcVT = Src1.getValueType(); 3460 3461 if (all_of(Mask, [](int Elem) { return Elem == 0; }) && 3462 VT.isScalableVector()) { 3463 // Canonical splat form of first element of first input vector. 3464 SDValue FirstElt = 3465 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1, 3466 DAG.getVectorIdxConstant(0, DL)); 3467 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3468 return; 3469 } 3470 3471 // For now, we only handle splats for scalable vectors. 3472 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3473 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3474 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3475 3476 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3477 unsigned MaskNumElts = Mask.size(); 3478 3479 if (SrcNumElts == MaskNumElts) { 3480 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3481 return; 3482 } 3483 3484 // Normalize the shuffle vector since mask and vector length don't match. 3485 if (SrcNumElts < MaskNumElts) { 3486 // Mask is longer than the source vectors. We can use concatenate vector to 3487 // make the mask and vectors lengths match. 3488 3489 if (MaskNumElts % SrcNumElts == 0) { 3490 // Mask length is a multiple of the source vector length. 3491 // Check if the shuffle is some kind of concatenation of the input 3492 // vectors. 3493 unsigned NumConcat = MaskNumElts / SrcNumElts; 3494 bool IsConcat = true; 3495 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3496 for (unsigned i = 0; i != MaskNumElts; ++i) { 3497 int Idx = Mask[i]; 3498 if (Idx < 0) 3499 continue; 3500 // Ensure the indices in each SrcVT sized piece are sequential and that 3501 // the same source is used for the whole piece. 3502 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3503 (ConcatSrcs[i / SrcNumElts] >= 0 && 3504 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3505 IsConcat = false; 3506 break; 3507 } 3508 // Remember which source this index came from. 3509 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3510 } 3511 3512 // The shuffle is concatenating multiple vectors together. Just emit 3513 // a CONCAT_VECTORS operation. 3514 if (IsConcat) { 3515 SmallVector<SDValue, 8> ConcatOps; 3516 for (auto Src : ConcatSrcs) { 3517 if (Src < 0) 3518 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3519 else if (Src == 0) 3520 ConcatOps.push_back(Src1); 3521 else 3522 ConcatOps.push_back(Src2); 3523 } 3524 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3525 return; 3526 } 3527 } 3528 3529 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3530 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3531 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3532 PaddedMaskNumElts); 3533 3534 // Pad both vectors with undefs to make them the same length as the mask. 3535 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3536 3537 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3538 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3539 MOps1[0] = Src1; 3540 MOps2[0] = Src2; 3541 3542 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3543 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3544 3545 // Readjust mask for new input vector length. 3546 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3547 for (unsigned i = 0; i != MaskNumElts; ++i) { 3548 int Idx = Mask[i]; 3549 if (Idx >= (int)SrcNumElts) 3550 Idx -= SrcNumElts - PaddedMaskNumElts; 3551 MappedOps[i] = Idx; 3552 } 3553 3554 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3555 3556 // If the concatenated vector was padded, extract a subvector with the 3557 // correct number of elements. 3558 if (MaskNumElts != PaddedMaskNumElts) 3559 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3560 DAG.getVectorIdxConstant(0, DL)); 3561 3562 setValue(&I, Result); 3563 return; 3564 } 3565 3566 if (SrcNumElts > MaskNumElts) { 3567 // Analyze the access pattern of the vector to see if we can extract 3568 // two subvectors and do the shuffle. 3569 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3570 bool CanExtract = true; 3571 for (int Idx : Mask) { 3572 unsigned Input = 0; 3573 if (Idx < 0) 3574 continue; 3575 3576 if (Idx >= (int)SrcNumElts) { 3577 Input = 1; 3578 Idx -= SrcNumElts; 3579 } 3580 3581 // If all the indices come from the same MaskNumElts sized portion of 3582 // the sources we can use extract. Also make sure the extract wouldn't 3583 // extract past the end of the source. 3584 int NewStartIdx = alignDown(Idx, MaskNumElts); 3585 if (NewStartIdx + MaskNumElts > SrcNumElts || 3586 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3587 CanExtract = false; 3588 // Make sure we always update StartIdx as we use it to track if all 3589 // elements are undef. 3590 StartIdx[Input] = NewStartIdx; 3591 } 3592 3593 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3594 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3595 return; 3596 } 3597 if (CanExtract) { 3598 // Extract appropriate subvector and generate a vector shuffle 3599 for (unsigned Input = 0; Input < 2; ++Input) { 3600 SDValue &Src = Input == 0 ? Src1 : Src2; 3601 if (StartIdx[Input] < 0) 3602 Src = DAG.getUNDEF(VT); 3603 else { 3604 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3605 DAG.getVectorIdxConstant(StartIdx[Input], DL)); 3606 } 3607 } 3608 3609 // Calculate new mask. 3610 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3611 for (int &Idx : MappedOps) { 3612 if (Idx >= (int)SrcNumElts) 3613 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3614 else if (Idx >= 0) 3615 Idx -= StartIdx[0]; 3616 } 3617 3618 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3619 return; 3620 } 3621 } 3622 3623 // We can't use either concat vectors or extract subvectors so fall back to 3624 // replacing the shuffle with extract and build vector. 3625 // to insert and build vector. 3626 EVT EltVT = VT.getVectorElementType(); 3627 SmallVector<SDValue,8> Ops; 3628 for (int Idx : Mask) { 3629 SDValue Res; 3630 3631 if (Idx < 0) { 3632 Res = DAG.getUNDEF(EltVT); 3633 } else { 3634 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3635 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3636 3637 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src, 3638 DAG.getVectorIdxConstant(Idx, DL)); 3639 } 3640 3641 Ops.push_back(Res); 3642 } 3643 3644 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3645 } 3646 3647 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3648 ArrayRef<unsigned> Indices; 3649 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3650 Indices = IV->getIndices(); 3651 else 3652 Indices = cast<ConstantExpr>(&I)->getIndices(); 3653 3654 const Value *Op0 = I.getOperand(0); 3655 const Value *Op1 = I.getOperand(1); 3656 Type *AggTy = I.getType(); 3657 Type *ValTy = Op1->getType(); 3658 bool IntoUndef = isa<UndefValue>(Op0); 3659 bool FromUndef = isa<UndefValue>(Op1); 3660 3661 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3662 3663 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3664 SmallVector<EVT, 4> AggValueVTs; 3665 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3666 SmallVector<EVT, 4> ValValueVTs; 3667 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3668 3669 unsigned NumAggValues = AggValueVTs.size(); 3670 unsigned NumValValues = ValValueVTs.size(); 3671 SmallVector<SDValue, 4> Values(NumAggValues); 3672 3673 // Ignore an insertvalue that produces an empty object 3674 if (!NumAggValues) { 3675 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3676 return; 3677 } 3678 3679 SDValue Agg = getValue(Op0); 3680 unsigned i = 0; 3681 // Copy the beginning value(s) from the original aggregate. 3682 for (; i != LinearIndex; ++i) 3683 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3684 SDValue(Agg.getNode(), Agg.getResNo() + i); 3685 // Copy values from the inserted value(s). 3686 if (NumValValues) { 3687 SDValue Val = getValue(Op1); 3688 for (; i != LinearIndex + NumValValues; ++i) 3689 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3690 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3691 } 3692 // Copy remaining value(s) from the original aggregate. 3693 for (; i != NumAggValues; ++i) 3694 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3695 SDValue(Agg.getNode(), Agg.getResNo() + i); 3696 3697 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3698 DAG.getVTList(AggValueVTs), Values)); 3699 } 3700 3701 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3702 ArrayRef<unsigned> Indices; 3703 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3704 Indices = EV->getIndices(); 3705 else 3706 Indices = cast<ConstantExpr>(&I)->getIndices(); 3707 3708 const Value *Op0 = I.getOperand(0); 3709 Type *AggTy = Op0->getType(); 3710 Type *ValTy = I.getType(); 3711 bool OutOfUndef = isa<UndefValue>(Op0); 3712 3713 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3714 3715 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3716 SmallVector<EVT, 4> ValValueVTs; 3717 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3718 3719 unsigned NumValValues = ValValueVTs.size(); 3720 3721 // Ignore a extractvalue that produces an empty object 3722 if (!NumValValues) { 3723 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3724 return; 3725 } 3726 3727 SmallVector<SDValue, 4> Values(NumValValues); 3728 3729 SDValue Agg = getValue(Op0); 3730 // Copy out the selected value(s). 3731 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3732 Values[i - LinearIndex] = 3733 OutOfUndef ? 3734 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3735 SDValue(Agg.getNode(), Agg.getResNo() + i); 3736 3737 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3738 DAG.getVTList(ValValueVTs), Values)); 3739 } 3740 3741 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3742 Value *Op0 = I.getOperand(0); 3743 // Note that the pointer operand may be a vector of pointers. Take the scalar 3744 // element which holds a pointer. 3745 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3746 SDValue N = getValue(Op0); 3747 SDLoc dl = getCurSDLoc(); 3748 auto &TLI = DAG.getTargetLoweringInfo(); 3749 3750 // Normalize Vector GEP - all scalar operands should be converted to the 3751 // splat vector. 3752 bool IsVectorGEP = I.getType()->isVectorTy(); 3753 ElementCount VectorElementCount = 3754 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount() 3755 : ElementCount::getFixed(0); 3756 3757 if (IsVectorGEP && !N.getValueType().isVector()) { 3758 LLVMContext &Context = *DAG.getContext(); 3759 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount); 3760 if (VectorElementCount.isScalable()) 3761 N = DAG.getSplatVector(VT, dl, N); 3762 else 3763 N = DAG.getSplatBuildVector(VT, dl, N); 3764 } 3765 3766 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3767 GTI != E; ++GTI) { 3768 const Value *Idx = GTI.getOperand(); 3769 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3770 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3771 if (Field) { 3772 // N = N + Offset 3773 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3774 3775 // In an inbounds GEP with an offset that is nonnegative even when 3776 // interpreted as signed, assume there is no unsigned overflow. 3777 SDNodeFlags Flags; 3778 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3779 Flags.setNoUnsignedWrap(true); 3780 3781 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3782 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3783 } 3784 } else { 3785 // IdxSize is the width of the arithmetic according to IR semantics. 3786 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth 3787 // (and fix up the result later). 3788 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3789 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3790 TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 3791 // We intentionally mask away the high bits here; ElementSize may not 3792 // fit in IdxTy. 3793 APInt ElementMul(IdxSize, ElementSize.getKnownMinSize()); 3794 bool ElementScalable = ElementSize.isScalable(); 3795 3796 // If this is a scalar constant or a splat vector of constants, 3797 // handle it quickly. 3798 const auto *C = dyn_cast<Constant>(Idx); 3799 if (C && isa<VectorType>(C->getType())) 3800 C = C->getSplatValue(); 3801 3802 const auto *CI = dyn_cast_or_null<ConstantInt>(C); 3803 if (CI && CI->isZero()) 3804 continue; 3805 if (CI && !ElementScalable) { 3806 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize); 3807 LLVMContext &Context = *DAG.getContext(); 3808 SDValue OffsVal; 3809 if (IsVectorGEP) 3810 OffsVal = DAG.getConstant( 3811 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount)); 3812 else 3813 OffsVal = DAG.getConstant(Offs, dl, IdxTy); 3814 3815 // In an inbounds GEP with an offset that is nonnegative even when 3816 // interpreted as signed, assume there is no unsigned overflow. 3817 SDNodeFlags Flags; 3818 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3819 Flags.setNoUnsignedWrap(true); 3820 3821 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3822 3823 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3824 continue; 3825 } 3826 3827 // N = N + Idx * ElementMul; 3828 SDValue IdxN = getValue(Idx); 3829 3830 if (!IdxN.getValueType().isVector() && IsVectorGEP) { 3831 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), 3832 VectorElementCount); 3833 if (VectorElementCount.isScalable()) 3834 IdxN = DAG.getSplatVector(VT, dl, IdxN); 3835 else 3836 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3837 } 3838 3839 // If the index is smaller or larger than intptr_t, truncate or extend 3840 // it. 3841 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3842 3843 if (ElementScalable) { 3844 EVT VScaleTy = N.getValueType().getScalarType(); 3845 SDValue VScale = DAG.getNode( 3846 ISD::VSCALE, dl, VScaleTy, 3847 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy)); 3848 if (IsVectorGEP) 3849 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale); 3850 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale); 3851 } else { 3852 // If this is a multiply by a power of two, turn it into a shl 3853 // immediately. This is a very common case. 3854 if (ElementMul != 1) { 3855 if (ElementMul.isPowerOf2()) { 3856 unsigned Amt = ElementMul.logBase2(); 3857 IdxN = DAG.getNode(ISD::SHL, dl, 3858 N.getValueType(), IdxN, 3859 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3860 } else { 3861 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl, 3862 IdxN.getValueType()); 3863 IdxN = DAG.getNode(ISD::MUL, dl, 3864 N.getValueType(), IdxN, Scale); 3865 } 3866 } 3867 } 3868 3869 N = DAG.getNode(ISD::ADD, dl, 3870 N.getValueType(), N, IdxN); 3871 } 3872 } 3873 3874 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3875 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3876 if (IsVectorGEP) { 3877 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount); 3878 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount); 3879 } 3880 3881 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3882 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3883 3884 setValue(&I, N); 3885 } 3886 3887 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3888 // If this is a fixed sized alloca in the entry block of the function, 3889 // allocate it statically on the stack. 3890 if (FuncInfo.StaticAllocaMap.count(&I)) 3891 return; // getValue will auto-populate this. 3892 3893 SDLoc dl = getCurSDLoc(); 3894 Type *Ty = I.getAllocatedType(); 3895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3896 auto &DL = DAG.getDataLayout(); 3897 uint64_t TySize = DL.getTypeAllocSize(Ty); 3898 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign()); 3899 3900 SDValue AllocSize = getValue(I.getArraySize()); 3901 3902 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3903 if (AllocSize.getValueType() != IntPtr) 3904 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3905 3906 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3907 AllocSize, 3908 DAG.getConstant(TySize, dl, IntPtr)); 3909 3910 // Handle alignment. If the requested alignment is less than or equal to 3911 // the stack alignment, ignore it. If the size is greater than or equal to 3912 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3913 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign(); 3914 if (*Alignment <= StackAlign) 3915 Alignment = None; 3916 3917 const uint64_t StackAlignMask = StackAlign.value() - 1U; 3918 // Round the size of the allocation up to the stack alignment size 3919 // by add SA-1 to the size. This doesn't overflow because we're computing 3920 // an address inside an alloca. 3921 SDNodeFlags Flags; 3922 Flags.setNoUnsignedWrap(true); 3923 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3924 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags); 3925 3926 // Mask out the low bits for alignment purposes. 3927 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3928 DAG.getConstant(~StackAlignMask, dl, IntPtr)); 3929 3930 SDValue Ops[] = { 3931 getRoot(), AllocSize, 3932 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)}; 3933 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3934 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3935 setValue(&I, DSA); 3936 DAG.setRoot(DSA.getValue(1)); 3937 3938 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3939 } 3940 3941 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3942 if (I.isAtomic()) 3943 return visitAtomicLoad(I); 3944 3945 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3946 const Value *SV = I.getOperand(0); 3947 if (TLI.supportSwiftError()) { 3948 // Swifterror values can come from either a function parameter with 3949 // swifterror attribute or an alloca with swifterror attribute. 3950 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3951 if (Arg->hasSwiftErrorAttr()) 3952 return visitLoadFromSwiftError(I); 3953 } 3954 3955 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3956 if (Alloca->isSwiftError()) 3957 return visitLoadFromSwiftError(I); 3958 } 3959 } 3960 3961 SDValue Ptr = getValue(SV); 3962 3963 Type *Ty = I.getType(); 3964 Align Alignment = I.getAlign(); 3965 3966 AAMDNodes AAInfo; 3967 I.getAAMetadata(AAInfo); 3968 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3969 3970 SmallVector<EVT, 4> ValueVTs, MemVTs; 3971 SmallVector<uint64_t, 4> Offsets; 3972 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 3973 unsigned NumValues = ValueVTs.size(); 3974 if (NumValues == 0) 3975 return; 3976 3977 bool isVolatile = I.isVolatile(); 3978 3979 SDValue Root; 3980 bool ConstantMemory = false; 3981 if (isVolatile) 3982 // Serialize volatile loads with other side effects. 3983 Root = getRoot(); 3984 else if (NumValues > MaxParallelChains) 3985 Root = getMemoryRoot(); 3986 else if (AA && 3987 AA->pointsToConstantMemory(MemoryLocation( 3988 SV, 3989 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3990 AAInfo))) { 3991 // Do not serialize (non-volatile) loads of constant memory with anything. 3992 Root = DAG.getEntryNode(); 3993 ConstantMemory = true; 3994 } else { 3995 // Do not serialize non-volatile loads against each other. 3996 Root = DAG.getRoot(); 3997 } 3998 3999 SDLoc dl = getCurSDLoc(); 4000 4001 if (isVolatile) 4002 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4003 4004 // An aggregate load cannot wrap around the address space, so offsets to its 4005 // parts don't wrap either. 4006 SDNodeFlags Flags; 4007 Flags.setNoUnsignedWrap(true); 4008 4009 SmallVector<SDValue, 4> Values(NumValues); 4010 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4011 EVT PtrVT = Ptr.getValueType(); 4012 4013 MachineMemOperand::Flags MMOFlags 4014 = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4015 4016 unsigned ChainI = 0; 4017 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4018 // Serializing loads here may result in excessive register pressure, and 4019 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4020 // could recover a bit by hoisting nodes upward in the chain by recognizing 4021 // they are side-effect free or do not alias. The optimizer should really 4022 // avoid this case by converting large object/array copies to llvm.memcpy 4023 // (MaxParallelChains should always remain as failsafe). 4024 if (ChainI == MaxParallelChains) { 4025 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4026 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4027 makeArrayRef(Chains.data(), ChainI)); 4028 Root = Chain; 4029 ChainI = 0; 4030 } 4031 SDValue A = DAG.getNode(ISD::ADD, dl, 4032 PtrVT, Ptr, 4033 DAG.getConstant(Offsets[i], dl, PtrVT), 4034 Flags); 4035 4036 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4037 MachinePointerInfo(SV, Offsets[i]), Alignment, 4038 MMOFlags, AAInfo, Ranges); 4039 Chains[ChainI] = L.getValue(1); 4040 4041 if (MemVTs[i] != ValueVTs[i]) 4042 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4043 4044 Values[i] = L; 4045 } 4046 4047 if (!ConstantMemory) { 4048 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4049 makeArrayRef(Chains.data(), ChainI)); 4050 if (isVolatile) 4051 DAG.setRoot(Chain); 4052 else 4053 PendingLoads.push_back(Chain); 4054 } 4055 4056 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4057 DAG.getVTList(ValueVTs), Values)); 4058 } 4059 4060 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4061 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4062 "call visitStoreToSwiftError when backend supports swifterror"); 4063 4064 SmallVector<EVT, 4> ValueVTs; 4065 SmallVector<uint64_t, 4> Offsets; 4066 const Value *SrcV = I.getOperand(0); 4067 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4068 SrcV->getType(), ValueVTs, &Offsets); 4069 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4070 "expect a single EVT for swifterror"); 4071 4072 SDValue Src = getValue(SrcV); 4073 // Create a virtual register, then update the virtual register. 4074 Register VReg = 4075 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4076 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4077 // Chain can be getRoot or getControlRoot. 4078 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4079 SDValue(Src.getNode(), Src.getResNo())); 4080 DAG.setRoot(CopyNode); 4081 } 4082 4083 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4084 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4085 "call visitLoadFromSwiftError when backend supports swifterror"); 4086 4087 assert(!I.isVolatile() && 4088 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4089 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4090 "Support volatile, non temporal, invariant for load_from_swift_error"); 4091 4092 const Value *SV = I.getOperand(0); 4093 Type *Ty = I.getType(); 4094 AAMDNodes AAInfo; 4095 I.getAAMetadata(AAInfo); 4096 assert( 4097 (!AA || 4098 !AA->pointsToConstantMemory(MemoryLocation( 4099 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4100 AAInfo))) && 4101 "load_from_swift_error should not be constant memory"); 4102 4103 SmallVector<EVT, 4> ValueVTs; 4104 SmallVector<uint64_t, 4> Offsets; 4105 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4106 ValueVTs, &Offsets); 4107 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4108 "expect a single EVT for swifterror"); 4109 4110 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4111 SDValue L = DAG.getCopyFromReg( 4112 getRoot(), getCurSDLoc(), 4113 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4114 4115 setValue(&I, L); 4116 } 4117 4118 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4119 if (I.isAtomic()) 4120 return visitAtomicStore(I); 4121 4122 const Value *SrcV = I.getOperand(0); 4123 const Value *PtrV = I.getOperand(1); 4124 4125 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4126 if (TLI.supportSwiftError()) { 4127 // Swifterror values can come from either a function parameter with 4128 // swifterror attribute or an alloca with swifterror attribute. 4129 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4130 if (Arg->hasSwiftErrorAttr()) 4131 return visitStoreToSwiftError(I); 4132 } 4133 4134 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4135 if (Alloca->isSwiftError()) 4136 return visitStoreToSwiftError(I); 4137 } 4138 } 4139 4140 SmallVector<EVT, 4> ValueVTs, MemVTs; 4141 SmallVector<uint64_t, 4> Offsets; 4142 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4143 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4144 unsigned NumValues = ValueVTs.size(); 4145 if (NumValues == 0) 4146 return; 4147 4148 // Get the lowered operands. Note that we do this after 4149 // checking if NumResults is zero, because with zero results 4150 // the operands won't have values in the map. 4151 SDValue Src = getValue(SrcV); 4152 SDValue Ptr = getValue(PtrV); 4153 4154 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot(); 4155 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4156 SDLoc dl = getCurSDLoc(); 4157 Align Alignment = I.getAlign(); 4158 AAMDNodes AAInfo; 4159 I.getAAMetadata(AAInfo); 4160 4161 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4162 4163 // An aggregate load cannot wrap around the address space, so offsets to its 4164 // parts don't wrap either. 4165 SDNodeFlags Flags; 4166 Flags.setNoUnsignedWrap(true); 4167 4168 unsigned ChainI = 0; 4169 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4170 // See visitLoad comments. 4171 if (ChainI == MaxParallelChains) { 4172 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4173 makeArrayRef(Chains.data(), ChainI)); 4174 Root = Chain; 4175 ChainI = 0; 4176 } 4177 SDValue Add = 4178 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags); 4179 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4180 if (MemVTs[i] != ValueVTs[i]) 4181 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4182 SDValue St = 4183 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4184 Alignment, MMOFlags, AAInfo); 4185 Chains[ChainI] = St; 4186 } 4187 4188 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4189 makeArrayRef(Chains.data(), ChainI)); 4190 DAG.setRoot(StoreNode); 4191 } 4192 4193 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4194 bool IsCompressing) { 4195 SDLoc sdl = getCurSDLoc(); 4196 4197 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4198 MaybeAlign &Alignment) { 4199 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4200 Src0 = I.getArgOperand(0); 4201 Ptr = I.getArgOperand(1); 4202 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue(); 4203 Mask = I.getArgOperand(3); 4204 }; 4205 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4206 MaybeAlign &Alignment) { 4207 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4208 Src0 = I.getArgOperand(0); 4209 Ptr = I.getArgOperand(1); 4210 Mask = I.getArgOperand(2); 4211 Alignment = None; 4212 }; 4213 4214 Value *PtrOperand, *MaskOperand, *Src0Operand; 4215 MaybeAlign Alignment; 4216 if (IsCompressing) 4217 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4218 else 4219 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4220 4221 SDValue Ptr = getValue(PtrOperand); 4222 SDValue Src0 = getValue(Src0Operand); 4223 SDValue Mask = getValue(MaskOperand); 4224 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4225 4226 EVT VT = Src0.getValueType(); 4227 if (!Alignment) 4228 Alignment = DAG.getEVTAlign(VT); 4229 4230 AAMDNodes AAInfo; 4231 I.getAAMetadata(AAInfo); 4232 4233 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4234 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore, 4235 // TODO: Make MachineMemOperands aware of scalable 4236 // vectors. 4237 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo); 4238 SDValue StoreNode = 4239 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4240 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4241 DAG.setRoot(StoreNode); 4242 setValue(&I, StoreNode); 4243 } 4244 4245 // Get a uniform base for the Gather/Scatter intrinsic. 4246 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4247 // We try to represent it as a base pointer + vector of indices. 4248 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4249 // The first operand of the GEP may be a single pointer or a vector of pointers 4250 // Example: 4251 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4252 // or 4253 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4254 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4255 // 4256 // When the first GEP operand is a single pointer - it is the uniform base we 4257 // are looking for. If first operand of the GEP is a splat vector - we 4258 // extract the splat value and use it as a uniform base. 4259 // In all other cases the function returns 'false'. 4260 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index, 4261 ISD::MemIndexType &IndexType, SDValue &Scale, 4262 SelectionDAGBuilder *SDB, const BasicBlock *CurBB) { 4263 SelectionDAG& DAG = SDB->DAG; 4264 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4265 const DataLayout &DL = DAG.getDataLayout(); 4266 4267 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4268 4269 // Handle splat constant pointer. 4270 if (auto *C = dyn_cast<Constant>(Ptr)) { 4271 C = C->getSplatValue(); 4272 if (!C) 4273 return false; 4274 4275 Base = SDB->getValue(C); 4276 4277 unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements(); 4278 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts); 4279 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT); 4280 IndexType = ISD::SIGNED_SCALED; 4281 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4282 return true; 4283 } 4284 4285 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4286 if (!GEP || GEP->getParent() != CurBB) 4287 return false; 4288 4289 if (GEP->getNumOperands() != 2) 4290 return false; 4291 4292 const Value *BasePtr = GEP->getPointerOperand(); 4293 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1); 4294 4295 // Make sure the base is scalar and the index is a vector. 4296 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy()) 4297 return false; 4298 4299 Base = SDB->getValue(BasePtr); 4300 Index = SDB->getValue(IndexVal); 4301 IndexType = ISD::SIGNED_SCALED; 4302 Scale = DAG.getTargetConstant( 4303 DL.getTypeAllocSize(GEP->getResultElementType()), 4304 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4305 return true; 4306 } 4307 4308 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4309 SDLoc sdl = getCurSDLoc(); 4310 4311 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4312 const Value *Ptr = I.getArgOperand(1); 4313 SDValue Src0 = getValue(I.getArgOperand(0)); 4314 SDValue Mask = getValue(I.getArgOperand(3)); 4315 EVT VT = Src0.getValueType(); 4316 Align Alignment = cast<ConstantInt>(I.getArgOperand(2)) 4317 ->getMaybeAlignValue() 4318 .getValueOr(DAG.getEVTAlign(VT)); 4319 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4320 4321 AAMDNodes AAInfo; 4322 I.getAAMetadata(AAInfo); 4323 4324 SDValue Base; 4325 SDValue Index; 4326 ISD::MemIndexType IndexType; 4327 SDValue Scale; 4328 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4329 I.getParent()); 4330 4331 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4332 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4333 MachinePointerInfo(AS), MachineMemOperand::MOStore, 4334 // TODO: Make MachineMemOperands aware of scalable 4335 // vectors. 4336 MemoryLocation::UnknownSize, Alignment, AAInfo); 4337 if (!UniformBase) { 4338 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4339 Index = getValue(Ptr); 4340 IndexType = ISD::SIGNED_UNSCALED; 4341 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4342 } 4343 4344 EVT IdxVT = Index.getValueType(); 4345 EVT EltTy = IdxVT.getVectorElementType(); 4346 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4347 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4348 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4349 } 4350 4351 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale }; 4352 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4353 Ops, MMO, IndexType, false); 4354 DAG.setRoot(Scatter); 4355 setValue(&I, Scatter); 4356 } 4357 4358 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4359 SDLoc sdl = getCurSDLoc(); 4360 4361 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4362 MaybeAlign &Alignment) { 4363 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4364 Ptr = I.getArgOperand(0); 4365 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue(); 4366 Mask = I.getArgOperand(2); 4367 Src0 = I.getArgOperand(3); 4368 }; 4369 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0, 4370 MaybeAlign &Alignment) { 4371 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4372 Ptr = I.getArgOperand(0); 4373 Alignment = None; 4374 Mask = I.getArgOperand(1); 4375 Src0 = I.getArgOperand(2); 4376 }; 4377 4378 Value *PtrOperand, *MaskOperand, *Src0Operand; 4379 MaybeAlign Alignment; 4380 if (IsExpanding) 4381 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4382 else 4383 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4384 4385 SDValue Ptr = getValue(PtrOperand); 4386 SDValue Src0 = getValue(Src0Operand); 4387 SDValue Mask = getValue(MaskOperand); 4388 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4389 4390 EVT VT = Src0.getValueType(); 4391 if (!Alignment) 4392 Alignment = DAG.getEVTAlign(VT); 4393 4394 AAMDNodes AAInfo; 4395 I.getAAMetadata(AAInfo); 4396 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4397 4398 // Do not serialize masked loads of constant memory with anything. 4399 MemoryLocation ML; 4400 if (VT.isScalableVector()) 4401 ML = MemoryLocation::getAfter(PtrOperand); 4402 else 4403 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4404 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4405 AAInfo); 4406 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4407 4408 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4409 4410 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4411 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad, 4412 // TODO: Make MachineMemOperands aware of scalable 4413 // vectors. 4414 VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges); 4415 4416 SDValue Load = 4417 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4418 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4419 if (AddToChain) 4420 PendingLoads.push_back(Load.getValue(1)); 4421 setValue(&I, Load); 4422 } 4423 4424 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4425 SDLoc sdl = getCurSDLoc(); 4426 4427 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4428 const Value *Ptr = I.getArgOperand(0); 4429 SDValue Src0 = getValue(I.getArgOperand(3)); 4430 SDValue Mask = getValue(I.getArgOperand(2)); 4431 4432 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4433 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4434 Align Alignment = cast<ConstantInt>(I.getArgOperand(1)) 4435 ->getMaybeAlignValue() 4436 .getValueOr(DAG.getEVTAlign(VT)); 4437 4438 AAMDNodes AAInfo; 4439 I.getAAMetadata(AAInfo); 4440 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4441 4442 SDValue Root = DAG.getRoot(); 4443 SDValue Base; 4444 SDValue Index; 4445 ISD::MemIndexType IndexType; 4446 SDValue Scale; 4447 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this, 4448 I.getParent()); 4449 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace(); 4450 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4451 MachinePointerInfo(AS), MachineMemOperand::MOLoad, 4452 // TODO: Make MachineMemOperands aware of scalable 4453 // vectors. 4454 MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges); 4455 4456 if (!UniformBase) { 4457 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4458 Index = getValue(Ptr); 4459 IndexType = ISD::SIGNED_UNSCALED; 4460 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4461 } 4462 4463 EVT IdxVT = Index.getValueType(); 4464 EVT EltTy = IdxVT.getVectorElementType(); 4465 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) { 4466 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy); 4467 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index); 4468 } 4469 4470 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4471 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4472 Ops, MMO, IndexType, ISD::NON_EXTLOAD); 4473 4474 PendingLoads.push_back(Gather.getValue(1)); 4475 setValue(&I, Gather); 4476 } 4477 4478 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4479 SDLoc dl = getCurSDLoc(); 4480 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4481 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4482 SyncScope::ID SSID = I.getSyncScopeID(); 4483 4484 SDValue InChain = getRoot(); 4485 4486 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4487 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4488 4489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4490 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4491 4492 MachineFunction &MF = DAG.getMachineFunction(); 4493 MachineMemOperand *MMO = MF.getMachineMemOperand( 4494 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4495 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering, 4496 FailureOrdering); 4497 4498 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4499 dl, MemVT, VTs, InChain, 4500 getValue(I.getPointerOperand()), 4501 getValue(I.getCompareOperand()), 4502 getValue(I.getNewValOperand()), MMO); 4503 4504 SDValue OutChain = L.getValue(2); 4505 4506 setValue(&I, L); 4507 DAG.setRoot(OutChain); 4508 } 4509 4510 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4511 SDLoc dl = getCurSDLoc(); 4512 ISD::NodeType NT; 4513 switch (I.getOperation()) { 4514 default: llvm_unreachable("Unknown atomicrmw operation"); 4515 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4516 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4517 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4518 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4519 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4520 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4521 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4522 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4523 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4524 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4525 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4526 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4527 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4528 } 4529 AtomicOrdering Ordering = I.getOrdering(); 4530 SyncScope::ID SSID = I.getSyncScopeID(); 4531 4532 SDValue InChain = getRoot(); 4533 4534 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4535 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4536 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout()); 4537 4538 MachineFunction &MF = DAG.getMachineFunction(); 4539 MachineMemOperand *MMO = MF.getMachineMemOperand( 4540 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4541 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering); 4542 4543 SDValue L = 4544 DAG.getAtomic(NT, dl, MemVT, InChain, 4545 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4546 MMO); 4547 4548 SDValue OutChain = L.getValue(1); 4549 4550 setValue(&I, L); 4551 DAG.setRoot(OutChain); 4552 } 4553 4554 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4555 SDLoc dl = getCurSDLoc(); 4556 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4557 SDValue Ops[3]; 4558 Ops[0] = getRoot(); 4559 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4560 TLI.getFenceOperandTy(DAG.getDataLayout())); 4561 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4562 TLI.getFenceOperandTy(DAG.getDataLayout())); 4563 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4564 } 4565 4566 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4567 SDLoc dl = getCurSDLoc(); 4568 AtomicOrdering Order = I.getOrdering(); 4569 SyncScope::ID SSID = I.getSyncScopeID(); 4570 4571 SDValue InChain = getRoot(); 4572 4573 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4574 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4575 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4576 4577 if (!TLI.supportsUnalignedAtomics() && 4578 I.getAlignment() < MemVT.getSizeInBits() / 8) 4579 report_fatal_error("Cannot generate unaligned atomic load"); 4580 4581 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout()); 4582 4583 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand( 4584 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4585 I.getAlign(), AAMDNodes(), nullptr, SSID, Order); 4586 4587 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4588 4589 SDValue Ptr = getValue(I.getPointerOperand()); 4590 4591 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4592 // TODO: Once this is better exercised by tests, it should be merged with 4593 // the normal path for loads to prevent future divergence. 4594 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4595 if (MemVT != VT) 4596 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4597 4598 setValue(&I, L); 4599 SDValue OutChain = L.getValue(1); 4600 if (!I.isUnordered()) 4601 DAG.setRoot(OutChain); 4602 else 4603 PendingLoads.push_back(OutChain); 4604 return; 4605 } 4606 4607 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4608 Ptr, MMO); 4609 4610 SDValue OutChain = L.getValue(1); 4611 if (MemVT != VT) 4612 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4613 4614 setValue(&I, L); 4615 DAG.setRoot(OutChain); 4616 } 4617 4618 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4619 SDLoc dl = getCurSDLoc(); 4620 4621 AtomicOrdering Ordering = I.getOrdering(); 4622 SyncScope::ID SSID = I.getSyncScopeID(); 4623 4624 SDValue InChain = getRoot(); 4625 4626 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4627 EVT MemVT = 4628 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4629 4630 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4631 report_fatal_error("Cannot generate unaligned atomic store"); 4632 4633 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout()); 4634 4635 MachineFunction &MF = DAG.getMachineFunction(); 4636 MachineMemOperand *MMO = MF.getMachineMemOperand( 4637 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(), 4638 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering); 4639 4640 SDValue Val = getValue(I.getValueOperand()); 4641 if (Val.getValueType() != MemVT) 4642 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4643 SDValue Ptr = getValue(I.getPointerOperand()); 4644 4645 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4646 // TODO: Once this is better exercised by tests, it should be merged with 4647 // the normal path for stores to prevent future divergence. 4648 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4649 DAG.setRoot(S); 4650 return; 4651 } 4652 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4653 Ptr, Val, MMO); 4654 4655 4656 DAG.setRoot(OutChain); 4657 } 4658 4659 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4660 /// node. 4661 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4662 unsigned Intrinsic) { 4663 // Ignore the callsite's attributes. A specific call site may be marked with 4664 // readnone, but the lowering code will expect the chain based on the 4665 // definition. 4666 const Function *F = I.getCalledFunction(); 4667 bool HasChain = !F->doesNotAccessMemory(); 4668 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4669 4670 // Build the operand list. 4671 SmallVector<SDValue, 8> Ops; 4672 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4673 if (OnlyLoad) { 4674 // We don't need to serialize loads against other loads. 4675 Ops.push_back(DAG.getRoot()); 4676 } else { 4677 Ops.push_back(getRoot()); 4678 } 4679 } 4680 4681 // Info is set by getTgtMemInstrinsic 4682 TargetLowering::IntrinsicInfo Info; 4683 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4684 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4685 DAG.getMachineFunction(), 4686 Intrinsic); 4687 4688 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4689 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4690 Info.opc == ISD::INTRINSIC_W_CHAIN) 4691 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4692 TLI.getPointerTy(DAG.getDataLayout()))); 4693 4694 // Add all operands of the call to the operand list. 4695 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4696 const Value *Arg = I.getArgOperand(i); 4697 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4698 Ops.push_back(getValue(Arg)); 4699 continue; 4700 } 4701 4702 // Use TargetConstant instead of a regular constant for immarg. 4703 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4704 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4705 assert(CI->getBitWidth() <= 64 && 4706 "large intrinsic immediates not handled"); 4707 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4708 } else { 4709 Ops.push_back( 4710 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4711 } 4712 } 4713 4714 SmallVector<EVT, 4> ValueVTs; 4715 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4716 4717 if (HasChain) 4718 ValueVTs.push_back(MVT::Other); 4719 4720 SDVTList VTs = DAG.getVTList(ValueVTs); 4721 4722 // Create the node. 4723 SDValue Result; 4724 if (IsTgtIntrinsic) { 4725 // This is target intrinsic that touches memory 4726 AAMDNodes AAInfo; 4727 I.getAAMetadata(AAInfo); 4728 Result = 4729 DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4730 MachinePointerInfo(Info.ptrVal, Info.offset), 4731 Info.align, Info.flags, Info.size, AAInfo); 4732 } else if (!HasChain) { 4733 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4734 } else if (!I.getType()->isVoidTy()) { 4735 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4736 } else { 4737 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4738 } 4739 4740 if (HasChain) { 4741 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4742 if (OnlyLoad) 4743 PendingLoads.push_back(Chain); 4744 else 4745 DAG.setRoot(Chain); 4746 } 4747 4748 if (!I.getType()->isVoidTy()) { 4749 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4750 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4751 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4752 } else 4753 Result = lowerRangeToAssertZExt(DAG, I, Result); 4754 4755 MaybeAlign Alignment = I.getRetAlign(); 4756 if (!Alignment) 4757 Alignment = F->getAttributes().getRetAlignment(); 4758 // Insert `assertalign` node if there's an alignment. 4759 if (InsertAssertAlign && Alignment) { 4760 Result = 4761 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne()); 4762 } 4763 4764 setValue(&I, Result); 4765 } 4766 } 4767 4768 /// GetSignificand - Get the significand and build it into a floating-point 4769 /// number with exponent of 1: 4770 /// 4771 /// Op = (Op & 0x007fffff) | 0x3f800000; 4772 /// 4773 /// where Op is the hexadecimal representation of floating point value. 4774 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4775 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4776 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4777 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4778 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4779 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4780 } 4781 4782 /// GetExponent - Get the exponent: 4783 /// 4784 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4785 /// 4786 /// where Op is the hexadecimal representation of floating point value. 4787 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4788 const TargetLowering &TLI, const SDLoc &dl) { 4789 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4790 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4791 SDValue t1 = DAG.getNode( 4792 ISD::SRL, dl, MVT::i32, t0, 4793 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4794 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4795 DAG.getConstant(127, dl, MVT::i32)); 4796 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4797 } 4798 4799 /// getF32Constant - Get 32-bit floating point constant. 4800 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4801 const SDLoc &dl) { 4802 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4803 MVT::f32); 4804 } 4805 4806 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4807 SelectionDAG &DAG) { 4808 // TODO: What fast-math-flags should be set on the floating-point nodes? 4809 4810 // IntegerPartOfX = ((int32_t)(t0); 4811 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4812 4813 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4814 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4815 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4816 4817 // IntegerPartOfX <<= 23; 4818 IntegerPartOfX = DAG.getNode( 4819 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4820 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4821 DAG.getDataLayout()))); 4822 4823 SDValue TwoToFractionalPartOfX; 4824 if (LimitFloatPrecision <= 6) { 4825 // For floating-point precision of 6: 4826 // 4827 // TwoToFractionalPartOfX = 4828 // 0.997535578f + 4829 // (0.735607626f + 0.252464424f * x) * x; 4830 // 4831 // error 0.0144103317, which is 6 bits 4832 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4833 getF32Constant(DAG, 0x3e814304, dl)); 4834 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4835 getF32Constant(DAG, 0x3f3c50c8, dl)); 4836 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4837 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4838 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4839 } else if (LimitFloatPrecision <= 12) { 4840 // For floating-point precision of 12: 4841 // 4842 // TwoToFractionalPartOfX = 4843 // 0.999892986f + 4844 // (0.696457318f + 4845 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4846 // 4847 // error 0.000107046256, which is 13 to 14 bits 4848 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4849 getF32Constant(DAG, 0x3da235e3, dl)); 4850 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4851 getF32Constant(DAG, 0x3e65b8f3, dl)); 4852 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4853 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4854 getF32Constant(DAG, 0x3f324b07, dl)); 4855 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4856 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4857 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4858 } else { // LimitFloatPrecision <= 18 4859 // For floating-point precision of 18: 4860 // 4861 // TwoToFractionalPartOfX = 4862 // 0.999999982f + 4863 // (0.693148872f + 4864 // (0.240227044f + 4865 // (0.554906021e-1f + 4866 // (0.961591928e-2f + 4867 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4868 // error 2.47208000*10^(-7), which is better than 18 bits 4869 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4870 getF32Constant(DAG, 0x3924b03e, dl)); 4871 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4872 getF32Constant(DAG, 0x3ab24b87, dl)); 4873 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4874 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4875 getF32Constant(DAG, 0x3c1d8c17, dl)); 4876 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4877 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4878 getF32Constant(DAG, 0x3d634a1d, dl)); 4879 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4880 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4881 getF32Constant(DAG, 0x3e75fe14, dl)); 4882 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4883 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4884 getF32Constant(DAG, 0x3f317234, dl)); 4885 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4886 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4887 getF32Constant(DAG, 0x3f800000, dl)); 4888 } 4889 4890 // Add the exponent into the result in integer domain. 4891 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4892 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4893 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4894 } 4895 4896 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4897 /// limited-precision mode. 4898 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4899 const TargetLowering &TLI, SDNodeFlags Flags) { 4900 if (Op.getValueType() == MVT::f32 && 4901 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4902 4903 // Put the exponent in the right bit position for later addition to the 4904 // final result: 4905 // 4906 // t0 = Op * log2(e) 4907 4908 // TODO: What fast-math-flags should be set here? 4909 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4910 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 4911 return getLimitedPrecisionExp2(t0, dl, DAG); 4912 } 4913 4914 // No special expansion. 4915 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags); 4916 } 4917 4918 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4919 /// limited-precision mode. 4920 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4921 const TargetLowering &TLI, SDNodeFlags Flags) { 4922 // TODO: What fast-math-flags should be set on the floating-point nodes? 4923 4924 if (Op.getValueType() == MVT::f32 && 4925 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4926 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4927 4928 // Scale the exponent by log(2). 4929 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4930 SDValue LogOfExponent = 4931 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4932 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 4933 4934 // Get the significand and build it into a floating-point number with 4935 // exponent of 1. 4936 SDValue X = GetSignificand(DAG, Op1, dl); 4937 4938 SDValue LogOfMantissa; 4939 if (LimitFloatPrecision <= 6) { 4940 // For floating-point precision of 6: 4941 // 4942 // LogofMantissa = 4943 // -1.1609546f + 4944 // (1.4034025f - 0.23903021f * x) * x; 4945 // 4946 // error 0.0034276066, which is better than 8 bits 4947 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4948 getF32Constant(DAG, 0xbe74c456, dl)); 4949 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4950 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4951 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4952 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4953 getF32Constant(DAG, 0x3f949a29, dl)); 4954 } else if (LimitFloatPrecision <= 12) { 4955 // For floating-point precision of 12: 4956 // 4957 // LogOfMantissa = 4958 // -1.7417939f + 4959 // (2.8212026f + 4960 // (-1.4699568f + 4961 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4962 // 4963 // error 0.000061011436, which is 14 bits 4964 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4965 getF32Constant(DAG, 0xbd67b6d6, dl)); 4966 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4967 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4968 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4969 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4970 getF32Constant(DAG, 0x3fbc278b, dl)); 4971 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4972 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4973 getF32Constant(DAG, 0x40348e95, dl)); 4974 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4975 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4976 getF32Constant(DAG, 0x3fdef31a, dl)); 4977 } else { // LimitFloatPrecision <= 18 4978 // For floating-point precision of 18: 4979 // 4980 // LogOfMantissa = 4981 // -2.1072184f + 4982 // (4.2372794f + 4983 // (-3.7029485f + 4984 // (2.2781945f + 4985 // (-0.87823314f + 4986 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4987 // 4988 // error 0.0000023660568, which is better than 18 bits 4989 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4990 getF32Constant(DAG, 0xbc91e5ac, dl)); 4991 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4992 getF32Constant(DAG, 0x3e4350aa, dl)); 4993 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4994 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4995 getF32Constant(DAG, 0x3f60d3e3, dl)); 4996 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4997 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4998 getF32Constant(DAG, 0x4011cdf0, dl)); 4999 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5000 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5001 getF32Constant(DAG, 0x406cfd1c, dl)); 5002 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5003 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5004 getF32Constant(DAG, 0x408797cb, dl)); 5005 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5006 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5007 getF32Constant(DAG, 0x4006dcab, dl)); 5008 } 5009 5010 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5011 } 5012 5013 // No special expansion. 5014 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags); 5015 } 5016 5017 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5018 /// limited-precision mode. 5019 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5020 const TargetLowering &TLI, SDNodeFlags Flags) { 5021 // TODO: What fast-math-flags should be set on the floating-point nodes? 5022 5023 if (Op.getValueType() == MVT::f32 && 5024 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5025 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5026 5027 // Get the exponent. 5028 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5029 5030 // Get the significand and build it into a floating-point number with 5031 // exponent of 1. 5032 SDValue X = GetSignificand(DAG, Op1, dl); 5033 5034 // Different possible minimax approximations of significand in 5035 // floating-point for various degrees of accuracy over [1,2]. 5036 SDValue Log2ofMantissa; 5037 if (LimitFloatPrecision <= 6) { 5038 // For floating-point precision of 6: 5039 // 5040 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5041 // 5042 // error 0.0049451742, which is more than 7 bits 5043 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5044 getF32Constant(DAG, 0xbeb08fe0, dl)); 5045 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5046 getF32Constant(DAG, 0x40019463, dl)); 5047 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5048 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5049 getF32Constant(DAG, 0x3fd6633d, dl)); 5050 } else if (LimitFloatPrecision <= 12) { 5051 // For floating-point precision of 12: 5052 // 5053 // Log2ofMantissa = 5054 // -2.51285454f + 5055 // (4.07009056f + 5056 // (-2.12067489f + 5057 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5058 // 5059 // error 0.0000876136000, which is better than 13 bits 5060 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5061 getF32Constant(DAG, 0xbda7262e, dl)); 5062 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5063 getF32Constant(DAG, 0x3f25280b, dl)); 5064 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5065 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5066 getF32Constant(DAG, 0x4007b923, dl)); 5067 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5068 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5069 getF32Constant(DAG, 0x40823e2f, dl)); 5070 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5071 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5072 getF32Constant(DAG, 0x4020d29c, dl)); 5073 } else { // LimitFloatPrecision <= 18 5074 // For floating-point precision of 18: 5075 // 5076 // Log2ofMantissa = 5077 // -3.0400495f + 5078 // (6.1129976f + 5079 // (-5.3420409f + 5080 // (3.2865683f + 5081 // (-1.2669343f + 5082 // (0.27515199f - 5083 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5084 // 5085 // error 0.0000018516, which is better than 18 bits 5086 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5087 getF32Constant(DAG, 0xbcd2769e, dl)); 5088 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5089 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5090 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5091 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5092 getF32Constant(DAG, 0x3fa22ae7, dl)); 5093 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5094 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5095 getF32Constant(DAG, 0x40525723, dl)); 5096 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5097 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5098 getF32Constant(DAG, 0x40aaf200, dl)); 5099 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5100 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5101 getF32Constant(DAG, 0x40c39dad, dl)); 5102 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5103 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5104 getF32Constant(DAG, 0x4042902c, dl)); 5105 } 5106 5107 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5108 } 5109 5110 // No special expansion. 5111 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags); 5112 } 5113 5114 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5115 /// limited-precision mode. 5116 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5117 const TargetLowering &TLI, SDNodeFlags Flags) { 5118 // TODO: What fast-math-flags should be set on the floating-point nodes? 5119 5120 if (Op.getValueType() == MVT::f32 && 5121 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5122 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5123 5124 // Scale the exponent by log10(2) [0.30102999f]. 5125 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5126 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5127 getF32Constant(DAG, 0x3e9a209a, dl)); 5128 5129 // Get the significand and build it into a floating-point number with 5130 // exponent of 1. 5131 SDValue X = GetSignificand(DAG, Op1, dl); 5132 5133 SDValue Log10ofMantissa; 5134 if (LimitFloatPrecision <= 6) { 5135 // For floating-point precision of 6: 5136 // 5137 // Log10ofMantissa = 5138 // -0.50419619f + 5139 // (0.60948995f - 0.10380950f * x) * x; 5140 // 5141 // error 0.0014886165, which is 6 bits 5142 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5143 getF32Constant(DAG, 0xbdd49a13, dl)); 5144 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5145 getF32Constant(DAG, 0x3f1c0789, dl)); 5146 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5147 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5148 getF32Constant(DAG, 0x3f011300, dl)); 5149 } else if (LimitFloatPrecision <= 12) { 5150 // For floating-point precision of 12: 5151 // 5152 // Log10ofMantissa = 5153 // -0.64831180f + 5154 // (0.91751397f + 5155 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5156 // 5157 // error 0.00019228036, which is better than 12 bits 5158 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5159 getF32Constant(DAG, 0x3d431f31, dl)); 5160 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5161 getF32Constant(DAG, 0x3ea21fb2, dl)); 5162 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5163 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5164 getF32Constant(DAG, 0x3f6ae232, dl)); 5165 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5166 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5167 getF32Constant(DAG, 0x3f25f7c3, dl)); 5168 } else { // LimitFloatPrecision <= 18 5169 // For floating-point precision of 18: 5170 // 5171 // Log10ofMantissa = 5172 // -0.84299375f + 5173 // (1.5327582f + 5174 // (-1.0688956f + 5175 // (0.49102474f + 5176 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5177 // 5178 // error 0.0000037995730, which is better than 18 bits 5179 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5180 getF32Constant(DAG, 0x3c5d51ce, dl)); 5181 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5182 getF32Constant(DAG, 0x3e00685a, dl)); 5183 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5184 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5185 getF32Constant(DAG, 0x3efb6798, dl)); 5186 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5187 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5188 getF32Constant(DAG, 0x3f88d192, dl)); 5189 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5190 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5191 getF32Constant(DAG, 0x3fc4316c, dl)); 5192 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5193 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5194 getF32Constant(DAG, 0x3f57ce70, dl)); 5195 } 5196 5197 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5198 } 5199 5200 // No special expansion. 5201 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags); 5202 } 5203 5204 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5205 /// limited-precision mode. 5206 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5207 const TargetLowering &TLI, SDNodeFlags Flags) { 5208 if (Op.getValueType() == MVT::f32 && 5209 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5210 return getLimitedPrecisionExp2(Op, dl, DAG); 5211 5212 // No special expansion. 5213 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags); 5214 } 5215 5216 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5217 /// limited-precision mode with x == 10.0f. 5218 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5219 SelectionDAG &DAG, const TargetLowering &TLI, 5220 SDNodeFlags Flags) { 5221 bool IsExp10 = false; 5222 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5223 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5224 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5225 APFloat Ten(10.0f); 5226 IsExp10 = LHSC->isExactlyValue(Ten); 5227 } 5228 } 5229 5230 // TODO: What fast-math-flags should be set on the FMUL node? 5231 if (IsExp10) { 5232 // Put the exponent in the right bit position for later addition to the 5233 // final result: 5234 // 5235 // #define LOG2OF10 3.3219281f 5236 // t0 = Op * LOG2OF10; 5237 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5238 getF32Constant(DAG, 0x40549a78, dl)); 5239 return getLimitedPrecisionExp2(t0, dl, DAG); 5240 } 5241 5242 // No special expansion. 5243 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags); 5244 } 5245 5246 /// ExpandPowI - Expand a llvm.powi intrinsic. 5247 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5248 SelectionDAG &DAG) { 5249 // If RHS is a constant, we can expand this out to a multiplication tree, 5250 // otherwise we end up lowering to a call to __powidf2 (for example). When 5251 // optimizing for size, we only want to do this if the expansion would produce 5252 // a small number of multiplies, otherwise we do the full expansion. 5253 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5254 // Get the exponent as a positive value. 5255 unsigned Val = RHSC->getSExtValue(); 5256 if ((int)Val < 0) Val = -Val; 5257 5258 // powi(x, 0) -> 1.0 5259 if (Val == 0) 5260 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5261 5262 bool OptForSize = DAG.shouldOptForSize(); 5263 if (!OptForSize || 5264 // If optimizing for size, don't insert too many multiplies. 5265 // This inserts up to 5 multiplies. 5266 countPopulation(Val) + Log2_32(Val) < 7) { 5267 // We use the simple binary decomposition method to generate the multiply 5268 // sequence. There are more optimal ways to do this (for example, 5269 // powi(x,15) generates one more multiply than it should), but this has 5270 // the benefit of being both really simple and much better than a libcall. 5271 SDValue Res; // Logically starts equal to 1.0 5272 SDValue CurSquare = LHS; 5273 // TODO: Intrinsics should have fast-math-flags that propagate to these 5274 // nodes. 5275 while (Val) { 5276 if (Val & 1) { 5277 if (Res.getNode()) 5278 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5279 else 5280 Res = CurSquare; // 1.0*CurSquare. 5281 } 5282 5283 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5284 CurSquare, CurSquare); 5285 Val >>= 1; 5286 } 5287 5288 // If the original was negative, invert the result, producing 1/(x*x*x). 5289 if (RHSC->getSExtValue() < 0) 5290 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5291 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5292 return Res; 5293 } 5294 } 5295 5296 // Otherwise, expand to a libcall. 5297 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5298 } 5299 5300 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL, 5301 SDValue LHS, SDValue RHS, SDValue Scale, 5302 SelectionDAG &DAG, const TargetLowering &TLI) { 5303 EVT VT = LHS.getValueType(); 5304 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT; 5305 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT; 5306 LLVMContext &Ctx = *DAG.getContext(); 5307 5308 // If the type is legal but the operation isn't, this node might survive all 5309 // the way to operation legalization. If we end up there and we do not have 5310 // the ability to widen the type (if VT*2 is not legal), we cannot expand the 5311 // node. 5312 5313 // Coax the legalizer into expanding the node during type legalization instead 5314 // by bumping the size by one bit. This will force it to Promote, enabling the 5315 // early expansion and avoiding the need to expand later. 5316 5317 // We don't have to do this if Scale is 0; that can always be expanded, unless 5318 // it's a saturating signed operation. Those can experience true integer 5319 // division overflow, a case which we must avoid. 5320 5321 // FIXME: We wouldn't have to do this (or any of the early 5322 // expansion/promotion) if it was possible to expand a libcall of an 5323 // illegal type during operation legalization. But it's not, so things 5324 // get a bit hacky. 5325 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue(); 5326 if ((ScaleInt > 0 || (Saturating && Signed)) && 5327 (TLI.isTypeLegal(VT) || 5328 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) { 5329 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction( 5330 Opcode, VT, ScaleInt); 5331 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) { 5332 EVT PromVT; 5333 if (VT.isScalarInteger()) 5334 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1); 5335 else if (VT.isVector()) { 5336 PromVT = VT.getVectorElementType(); 5337 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1); 5338 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount()); 5339 } else 5340 llvm_unreachable("Wrong VT for DIVFIX?"); 5341 if (Signed) { 5342 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT); 5343 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT); 5344 } else { 5345 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT); 5346 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT); 5347 } 5348 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout()); 5349 // For saturating operations, we need to shift up the LHS to get the 5350 // proper saturation width, and then shift down again afterwards. 5351 if (Saturating) 5352 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS, 5353 DAG.getConstant(1, DL, ShiftTy)); 5354 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale); 5355 if (Saturating) 5356 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res, 5357 DAG.getConstant(1, DL, ShiftTy)); 5358 return DAG.getZExtOrTrunc(Res, DL, VT); 5359 } 5360 } 5361 5362 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale); 5363 } 5364 5365 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5366 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5367 static void 5368 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs, 5369 const SDValue &N) { 5370 switch (N.getOpcode()) { 5371 case ISD::CopyFromReg: { 5372 SDValue Op = N.getOperand(1); 5373 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5374 Op.getValueType().getSizeInBits()); 5375 return; 5376 } 5377 case ISD::BITCAST: 5378 case ISD::AssertZext: 5379 case ISD::AssertSext: 5380 case ISD::TRUNCATE: 5381 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5382 return; 5383 case ISD::BUILD_PAIR: 5384 case ISD::BUILD_VECTOR: 5385 case ISD::CONCAT_VECTORS: 5386 for (SDValue Op : N->op_values()) 5387 getUnderlyingArgRegs(Regs, Op); 5388 return; 5389 default: 5390 return; 5391 } 5392 } 5393 5394 /// If the DbgValueInst is a dbg_value of a function argument, create the 5395 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5396 /// instruction selection, they will be inserted to the entry BB. 5397 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5398 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5399 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5400 const Argument *Arg = dyn_cast<Argument>(V); 5401 if (!Arg) 5402 return false; 5403 5404 if (!IsDbgDeclare) { 5405 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5406 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5407 // the entry block. 5408 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5409 if (!IsInEntryBlock) 5410 return false; 5411 5412 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5413 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5414 // variable that also is a param. 5415 // 5416 // Although, if we are at the top of the entry block already, we can still 5417 // emit using ArgDbgValue. This might catch some situations when the 5418 // dbg.value refers to an argument that isn't used in the entry block, so 5419 // any CopyToReg node would be optimized out and the only way to express 5420 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5421 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5422 // we should only emit as ArgDbgValue if the Variable is an argument to the 5423 // current function, and the dbg.value intrinsic is found in the entry 5424 // block. 5425 bool VariableIsFunctionInputArg = Variable->isParameter() && 5426 !DL->getInlinedAt(); 5427 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5428 if (!IsInPrologue && !VariableIsFunctionInputArg) 5429 return false; 5430 5431 // Here we assume that a function argument on IR level only can be used to 5432 // describe one input parameter on source level. If we for example have 5433 // source code like this 5434 // 5435 // struct A { long x, y; }; 5436 // void foo(struct A a, long b) { 5437 // ... 5438 // b = a.x; 5439 // ... 5440 // } 5441 // 5442 // and IR like this 5443 // 5444 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5445 // entry: 5446 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5447 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5448 // call void @llvm.dbg.value(metadata i32 %b, "b", 5449 // ... 5450 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5451 // ... 5452 // 5453 // then the last dbg.value is describing a parameter "b" using a value that 5454 // is an argument. But since we already has used %a1 to describe a parameter 5455 // we should not handle that last dbg.value here (that would result in an 5456 // incorrect hoisting of the DBG_VALUE to the function entry). 5457 // Notice that we allow one dbg.value per IR level argument, to accommodate 5458 // for the situation with fragments above. 5459 if (VariableIsFunctionInputArg) { 5460 unsigned ArgNo = Arg->getArgNo(); 5461 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5462 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5463 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5464 return false; 5465 FuncInfo.DescribedArgs.set(ArgNo); 5466 } 5467 } 5468 5469 MachineFunction &MF = DAG.getMachineFunction(); 5470 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5471 5472 bool IsIndirect = false; 5473 Optional<MachineOperand> Op; 5474 // Some arguments' frame index is recorded during argument lowering. 5475 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5476 if (FI != std::numeric_limits<int>::max()) 5477 Op = MachineOperand::CreateFI(FI); 5478 5479 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes; 5480 if (!Op && N.getNode()) { 5481 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5482 Register Reg; 5483 if (ArgRegsAndSizes.size() == 1) 5484 Reg = ArgRegsAndSizes.front().first; 5485 5486 if (Reg && Reg.isVirtual()) { 5487 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5488 Register PR = RegInfo.getLiveInPhysReg(Reg); 5489 if (PR) 5490 Reg = PR; 5491 } 5492 if (Reg) { 5493 Op = MachineOperand::CreateReg(Reg, false); 5494 IsIndirect = IsDbgDeclare; 5495 } 5496 } 5497 5498 if (!Op && N.getNode()) { 5499 // Check if frame index is available. 5500 SDValue LCandidate = peekThroughBitcasts(N); 5501 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5502 if (FrameIndexSDNode *FINode = 5503 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5504 Op = MachineOperand::CreateFI(FINode->getIndex()); 5505 } 5506 5507 if (!Op) { 5508 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5509 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>> 5510 SplitRegs) { 5511 unsigned Offset = 0; 5512 for (auto RegAndSize : SplitRegs) { 5513 // If the expression is already a fragment, the current register 5514 // offset+size might extend beyond the fragment. In this case, only 5515 // the register bits that are inside the fragment are relevant. 5516 int RegFragmentSizeInBits = RegAndSize.second; 5517 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5518 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5519 // The register is entirely outside the expression fragment, 5520 // so is irrelevant for debug info. 5521 if (Offset >= ExprFragmentSizeInBits) 5522 break; 5523 // The register is partially outside the expression fragment, only 5524 // the low bits within the fragment are relevant for debug info. 5525 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5526 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5527 } 5528 } 5529 5530 auto FragmentExpr = DIExpression::createFragmentExpression( 5531 Expr, Offset, RegFragmentSizeInBits); 5532 Offset += RegAndSize.second; 5533 // If a valid fragment expression cannot be created, the variable's 5534 // correct value cannot be determined and so it is set as Undef. 5535 if (!FragmentExpr) { 5536 SDDbgValue *SDV = DAG.getConstantDbgValue( 5537 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5538 DAG.AddDbgValue(SDV, nullptr, false); 5539 continue; 5540 } 5541 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5542 FuncInfo.ArgDbgValues.push_back( 5543 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5544 RegAndSize.first, Variable, *FragmentExpr)); 5545 } 5546 }; 5547 5548 // Check if ValueMap has reg number. 5549 DenseMap<const Value *, Register>::const_iterator 5550 VMI = FuncInfo.ValueMap.find(V); 5551 if (VMI != FuncInfo.ValueMap.end()) { 5552 const auto &TLI = DAG.getTargetLoweringInfo(); 5553 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5554 V->getType(), None); 5555 if (RFV.occupiesMultipleRegs()) { 5556 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5557 return true; 5558 } 5559 5560 Op = MachineOperand::CreateReg(VMI->second, false); 5561 IsIndirect = IsDbgDeclare; 5562 } else if (ArgRegsAndSizes.size() > 1) { 5563 // This was split due to the calling convention, and no virtual register 5564 // mapping exists for the value. 5565 splitMultiRegDbgValue(ArgRegsAndSizes); 5566 return true; 5567 } 5568 } 5569 5570 if (!Op) 5571 return false; 5572 5573 assert(Variable->isValidLocationForIntrinsic(DL) && 5574 "Expected inlined-at fields to agree"); 5575 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5576 FuncInfo.ArgDbgValues.push_back( 5577 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5578 *Op, Variable, Expr)); 5579 5580 return true; 5581 } 5582 5583 /// Return the appropriate SDDbgValue based on N. 5584 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5585 DILocalVariable *Variable, 5586 DIExpression *Expr, 5587 const DebugLoc &dl, 5588 unsigned DbgSDNodeOrder) { 5589 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5590 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5591 // stack slot locations. 5592 // 5593 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5594 // debug values here after optimization: 5595 // 5596 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5597 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5598 // 5599 // Both describe the direct values of their associated variables. 5600 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5601 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5602 } 5603 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5604 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5605 } 5606 5607 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5608 switch (Intrinsic) { 5609 case Intrinsic::smul_fix: 5610 return ISD::SMULFIX; 5611 case Intrinsic::umul_fix: 5612 return ISD::UMULFIX; 5613 case Intrinsic::smul_fix_sat: 5614 return ISD::SMULFIXSAT; 5615 case Intrinsic::umul_fix_sat: 5616 return ISD::UMULFIXSAT; 5617 case Intrinsic::sdiv_fix: 5618 return ISD::SDIVFIX; 5619 case Intrinsic::udiv_fix: 5620 return ISD::UDIVFIX; 5621 case Intrinsic::sdiv_fix_sat: 5622 return ISD::SDIVFIXSAT; 5623 case Intrinsic::udiv_fix_sat: 5624 return ISD::UDIVFIXSAT; 5625 default: 5626 llvm_unreachable("Unhandled fixed point intrinsic"); 5627 } 5628 } 5629 5630 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5631 const char *FunctionName) { 5632 assert(FunctionName && "FunctionName must not be nullptr"); 5633 SDValue Callee = DAG.getExternalSymbol( 5634 FunctionName, 5635 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5636 LowerCallTo(I, Callee, I.isTailCall()); 5637 } 5638 5639 /// Given a @llvm.call.preallocated.setup, return the corresponding 5640 /// preallocated call. 5641 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) { 5642 assert(cast<CallBase>(PreallocatedSetup) 5643 ->getCalledFunction() 5644 ->getIntrinsicID() == Intrinsic::call_preallocated_setup && 5645 "expected call_preallocated_setup Value"); 5646 for (auto *U : PreallocatedSetup->users()) { 5647 auto *UseCall = cast<CallBase>(U); 5648 const Function *Fn = UseCall->getCalledFunction(); 5649 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) { 5650 return UseCall; 5651 } 5652 } 5653 llvm_unreachable("expected corresponding call to preallocated setup/arg"); 5654 } 5655 5656 /// Lower the call to the specified intrinsic function. 5657 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5658 unsigned Intrinsic) { 5659 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5660 SDLoc sdl = getCurSDLoc(); 5661 DebugLoc dl = getCurDebugLoc(); 5662 SDValue Res; 5663 5664 SDNodeFlags Flags; 5665 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) 5666 Flags.copyFMF(*FPOp); 5667 5668 switch (Intrinsic) { 5669 default: 5670 // By default, turn this into a target intrinsic node. 5671 visitTargetIntrinsic(I, Intrinsic); 5672 return; 5673 case Intrinsic::vscale: { 5674 match(&I, m_VScale(DAG.getDataLayout())); 5675 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5676 setValue(&I, 5677 DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1))); 5678 return; 5679 } 5680 case Intrinsic::vastart: visitVAStart(I); return; 5681 case Intrinsic::vaend: visitVAEnd(I); return; 5682 case Intrinsic::vacopy: visitVACopy(I); return; 5683 case Intrinsic::returnaddress: 5684 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5685 TLI.getPointerTy(DAG.getDataLayout()), 5686 getValue(I.getArgOperand(0)))); 5687 return; 5688 case Intrinsic::addressofreturnaddress: 5689 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5690 TLI.getPointerTy(DAG.getDataLayout()))); 5691 return; 5692 case Intrinsic::sponentry: 5693 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5694 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5695 return; 5696 case Intrinsic::frameaddress: 5697 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5698 TLI.getFrameIndexTy(DAG.getDataLayout()), 5699 getValue(I.getArgOperand(0)))); 5700 return; 5701 case Intrinsic::read_volatile_register: 5702 case Intrinsic::read_register: { 5703 Value *Reg = I.getArgOperand(0); 5704 SDValue Chain = getRoot(); 5705 SDValue RegName = 5706 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5707 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5708 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5709 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5710 setValue(&I, Res); 5711 DAG.setRoot(Res.getValue(1)); 5712 return; 5713 } 5714 case Intrinsic::write_register: { 5715 Value *Reg = I.getArgOperand(0); 5716 Value *RegValue = I.getArgOperand(1); 5717 SDValue Chain = getRoot(); 5718 SDValue RegName = 5719 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5720 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5721 RegName, getValue(RegValue))); 5722 return; 5723 } 5724 case Intrinsic::memcpy: { 5725 const auto &MCI = cast<MemCpyInst>(I); 5726 SDValue Op1 = getValue(I.getArgOperand(0)); 5727 SDValue Op2 = getValue(I.getArgOperand(1)); 5728 SDValue Op3 = getValue(I.getArgOperand(2)); 5729 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5730 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5731 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5732 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5733 bool isVol = MCI.isVolatile(); 5734 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5735 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5736 // node. 5737 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5738 SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5739 /* AlwaysInline */ false, isTC, 5740 MachinePointerInfo(I.getArgOperand(0)), 5741 MachinePointerInfo(I.getArgOperand(1))); 5742 updateDAGForMaybeTailCall(MC); 5743 return; 5744 } 5745 case Intrinsic::memcpy_inline: { 5746 const auto &MCI = cast<MemCpyInlineInst>(I); 5747 SDValue Dst = getValue(I.getArgOperand(0)); 5748 SDValue Src = getValue(I.getArgOperand(1)); 5749 SDValue Size = getValue(I.getArgOperand(2)); 5750 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size"); 5751 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment. 5752 Align DstAlign = MCI.getDestAlign().valueOrOne(); 5753 Align SrcAlign = MCI.getSourceAlign().valueOrOne(); 5754 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5755 bool isVol = MCI.isVolatile(); 5756 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5757 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5758 // node. 5759 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol, 5760 /* AlwaysInline */ true, isTC, 5761 MachinePointerInfo(I.getArgOperand(0)), 5762 MachinePointerInfo(I.getArgOperand(1))); 5763 updateDAGForMaybeTailCall(MC); 5764 return; 5765 } 5766 case Intrinsic::memset: { 5767 const auto &MSI = cast<MemSetInst>(I); 5768 SDValue Op1 = getValue(I.getArgOperand(0)); 5769 SDValue Op2 = getValue(I.getArgOperand(1)); 5770 SDValue Op3 = getValue(I.getArgOperand(2)); 5771 // @llvm.memset defines 0 and 1 to both mean no alignment. 5772 Align Alignment = MSI.getDestAlign().valueOrOne(); 5773 bool isVol = MSI.isVolatile(); 5774 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5775 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5776 SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC, 5777 MachinePointerInfo(I.getArgOperand(0))); 5778 updateDAGForMaybeTailCall(MS); 5779 return; 5780 } 5781 case Intrinsic::memmove: { 5782 const auto &MMI = cast<MemMoveInst>(I); 5783 SDValue Op1 = getValue(I.getArgOperand(0)); 5784 SDValue Op2 = getValue(I.getArgOperand(1)); 5785 SDValue Op3 = getValue(I.getArgOperand(2)); 5786 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5787 Align DstAlign = MMI.getDestAlign().valueOrOne(); 5788 Align SrcAlign = MMI.getSourceAlign().valueOrOne(); 5789 Align Alignment = commonAlignment(DstAlign, SrcAlign); 5790 bool isVol = MMI.isVolatile(); 5791 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5792 // FIXME: Support passing different dest/src alignments to the memmove DAG 5793 // node. 5794 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 5795 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, 5796 isTC, MachinePointerInfo(I.getArgOperand(0)), 5797 MachinePointerInfo(I.getArgOperand(1))); 5798 updateDAGForMaybeTailCall(MM); 5799 return; 5800 } 5801 case Intrinsic::memcpy_element_unordered_atomic: { 5802 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5803 SDValue Dst = getValue(MI.getRawDest()); 5804 SDValue Src = getValue(MI.getRawSource()); 5805 SDValue Length = getValue(MI.getLength()); 5806 5807 unsigned DstAlign = MI.getDestAlignment(); 5808 unsigned SrcAlign = MI.getSourceAlignment(); 5809 Type *LengthTy = MI.getLength()->getType(); 5810 unsigned ElemSz = MI.getElementSizeInBytes(); 5811 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5812 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5813 SrcAlign, Length, LengthTy, ElemSz, isTC, 5814 MachinePointerInfo(MI.getRawDest()), 5815 MachinePointerInfo(MI.getRawSource())); 5816 updateDAGForMaybeTailCall(MC); 5817 return; 5818 } 5819 case Intrinsic::memmove_element_unordered_atomic: { 5820 auto &MI = cast<AtomicMemMoveInst>(I); 5821 SDValue Dst = getValue(MI.getRawDest()); 5822 SDValue Src = getValue(MI.getRawSource()); 5823 SDValue Length = getValue(MI.getLength()); 5824 5825 unsigned DstAlign = MI.getDestAlignment(); 5826 unsigned SrcAlign = MI.getSourceAlignment(); 5827 Type *LengthTy = MI.getLength()->getType(); 5828 unsigned ElemSz = MI.getElementSizeInBytes(); 5829 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5830 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5831 SrcAlign, Length, LengthTy, ElemSz, isTC, 5832 MachinePointerInfo(MI.getRawDest()), 5833 MachinePointerInfo(MI.getRawSource())); 5834 updateDAGForMaybeTailCall(MC); 5835 return; 5836 } 5837 case Intrinsic::memset_element_unordered_atomic: { 5838 auto &MI = cast<AtomicMemSetInst>(I); 5839 SDValue Dst = getValue(MI.getRawDest()); 5840 SDValue Val = getValue(MI.getValue()); 5841 SDValue Length = getValue(MI.getLength()); 5842 5843 unsigned DstAlign = MI.getDestAlignment(); 5844 Type *LengthTy = MI.getLength()->getType(); 5845 unsigned ElemSz = MI.getElementSizeInBytes(); 5846 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget()); 5847 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5848 LengthTy, ElemSz, isTC, 5849 MachinePointerInfo(MI.getRawDest())); 5850 updateDAGForMaybeTailCall(MC); 5851 return; 5852 } 5853 case Intrinsic::call_preallocated_setup: { 5854 const CallBase *PreallocatedCall = FindPreallocatedCall(&I); 5855 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5856 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other, 5857 getRoot(), SrcValue); 5858 setValue(&I, Res); 5859 DAG.setRoot(Res); 5860 return; 5861 } 5862 case Intrinsic::call_preallocated_arg: { 5863 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0)); 5864 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall); 5865 SDValue Ops[3]; 5866 Ops[0] = getRoot(); 5867 Ops[1] = SrcValue; 5868 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl, 5869 MVT::i32); // arg index 5870 SDValue Res = DAG.getNode( 5871 ISD::PREALLOCATED_ARG, sdl, 5872 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops); 5873 setValue(&I, Res); 5874 DAG.setRoot(Res.getValue(1)); 5875 return; 5876 } 5877 case Intrinsic::dbg_addr: 5878 case Intrinsic::dbg_declare: { 5879 const auto &DI = cast<DbgVariableIntrinsic>(I); 5880 DILocalVariable *Variable = DI.getVariable(); 5881 DIExpression *Expression = DI.getExpression(); 5882 dropDanglingDebugInfo(Variable, Expression); 5883 assert(Variable && "Missing variable"); 5884 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI 5885 << "\n"); 5886 // Check if address has undef value. 5887 const Value *Address = DI.getVariableLocation(); 5888 if (!Address || isa<UndefValue>(Address) || 5889 (Address->use_empty() && !isa<Argument>(Address))) { 5890 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5891 << " (bad/undef/unused-arg address)\n"); 5892 return; 5893 } 5894 5895 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5896 5897 // Check if this variable can be described by a frame index, typically 5898 // either as a static alloca or a byval parameter. 5899 int FI = std::numeric_limits<int>::max(); 5900 if (const auto *AI = 5901 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5902 if (AI->isStaticAlloca()) { 5903 auto I = FuncInfo.StaticAllocaMap.find(AI); 5904 if (I != FuncInfo.StaticAllocaMap.end()) 5905 FI = I->second; 5906 } 5907 } else if (const auto *Arg = dyn_cast<Argument>( 5908 Address->stripInBoundsConstantOffsets())) { 5909 FI = FuncInfo.getArgumentFrameIndex(Arg); 5910 } 5911 5912 // llvm.dbg.addr is control dependent and always generates indirect 5913 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5914 // the MachineFunction variable table. 5915 if (FI != std::numeric_limits<int>::max()) { 5916 if (Intrinsic == Intrinsic::dbg_addr) { 5917 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5918 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5919 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5920 } else { 5921 LLVM_DEBUG(dbgs() << "Skipping " << DI 5922 << " (variable info stashed in MF side table)\n"); 5923 } 5924 return; 5925 } 5926 5927 SDValue &N = NodeMap[Address]; 5928 if (!N.getNode() && isa<Argument>(Address)) 5929 // Check unused arguments map. 5930 N = UnusedArgNodeMap[Address]; 5931 SDDbgValue *SDV; 5932 if (N.getNode()) { 5933 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5934 Address = BCI->getOperand(0); 5935 // Parameters are handled specially. 5936 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5937 if (isParameter && FINode) { 5938 // Byval parameter. We have a frame index at this point. 5939 SDV = 5940 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5941 /*IsIndirect*/ true, dl, SDNodeOrder); 5942 } else if (isa<Argument>(Address)) { 5943 // Address is an argument, so try to emit its dbg value using 5944 // virtual register info from the FuncInfo.ValueMap. 5945 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5946 return; 5947 } else { 5948 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5949 true, dl, SDNodeOrder); 5950 } 5951 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5952 } else { 5953 // If Address is an argument then try to emit its dbg value using 5954 // virtual register info from the FuncInfo.ValueMap. 5955 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5956 N)) { 5957 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI 5958 << " (could not emit func-arg dbg_value)\n"); 5959 } 5960 } 5961 return; 5962 } 5963 case Intrinsic::dbg_label: { 5964 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5965 DILabel *Label = DI.getLabel(); 5966 assert(Label && "Missing label"); 5967 5968 SDDbgLabel *SDV; 5969 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5970 DAG.AddDbgLabel(SDV); 5971 return; 5972 } 5973 case Intrinsic::dbg_value: { 5974 const DbgValueInst &DI = cast<DbgValueInst>(I); 5975 assert(DI.getVariable() && "Missing variable"); 5976 5977 DILocalVariable *Variable = DI.getVariable(); 5978 DIExpression *Expression = DI.getExpression(); 5979 dropDanglingDebugInfo(Variable, Expression); 5980 const Value *V = DI.getValue(); 5981 if (!V) 5982 return; 5983 5984 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5985 SDNodeOrder)) 5986 return; 5987 5988 // TODO: Dangling debug info will eventually either be resolved or produce 5989 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5990 // between the original dbg.value location and its resolved DBG_VALUE, which 5991 // we should ideally fill with an extra Undef DBG_VALUE. 5992 5993 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5994 return; 5995 } 5996 5997 case Intrinsic::eh_typeid_for: { 5998 // Find the type id for the given typeinfo. 5999 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 6000 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 6001 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 6002 setValue(&I, Res); 6003 return; 6004 } 6005 6006 case Intrinsic::eh_return_i32: 6007 case Intrinsic::eh_return_i64: 6008 DAG.getMachineFunction().setCallsEHReturn(true); 6009 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 6010 MVT::Other, 6011 getControlRoot(), 6012 getValue(I.getArgOperand(0)), 6013 getValue(I.getArgOperand(1)))); 6014 return; 6015 case Intrinsic::eh_unwind_init: 6016 DAG.getMachineFunction().setCallsUnwindInit(true); 6017 return; 6018 case Intrinsic::eh_dwarf_cfa: 6019 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 6020 TLI.getPointerTy(DAG.getDataLayout()), 6021 getValue(I.getArgOperand(0)))); 6022 return; 6023 case Intrinsic::eh_sjlj_callsite: { 6024 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6025 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 6026 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 6027 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 6028 6029 MMI.setCurrentCallSite(CI->getZExtValue()); 6030 return; 6031 } 6032 case Intrinsic::eh_sjlj_functioncontext: { 6033 // Get and store the index of the function context. 6034 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 6035 AllocaInst *FnCtx = 6036 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 6037 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 6038 MFI.setFunctionContextIndex(FI); 6039 return; 6040 } 6041 case Intrinsic::eh_sjlj_setjmp: { 6042 SDValue Ops[2]; 6043 Ops[0] = getRoot(); 6044 Ops[1] = getValue(I.getArgOperand(0)); 6045 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 6046 DAG.getVTList(MVT::i32, MVT::Other), Ops); 6047 setValue(&I, Op.getValue(0)); 6048 DAG.setRoot(Op.getValue(1)); 6049 return; 6050 } 6051 case Intrinsic::eh_sjlj_longjmp: 6052 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 6053 getRoot(), getValue(I.getArgOperand(0)))); 6054 return; 6055 case Intrinsic::eh_sjlj_setup_dispatch: 6056 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 6057 getRoot())); 6058 return; 6059 case Intrinsic::masked_gather: 6060 visitMaskedGather(I); 6061 return; 6062 case Intrinsic::masked_load: 6063 visitMaskedLoad(I); 6064 return; 6065 case Intrinsic::masked_scatter: 6066 visitMaskedScatter(I); 6067 return; 6068 case Intrinsic::masked_store: 6069 visitMaskedStore(I); 6070 return; 6071 case Intrinsic::masked_expandload: 6072 visitMaskedLoad(I, true /* IsExpanding */); 6073 return; 6074 case Intrinsic::masked_compressstore: 6075 visitMaskedStore(I, true /* IsCompressing */); 6076 return; 6077 case Intrinsic::powi: 6078 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6079 getValue(I.getArgOperand(1)), DAG)); 6080 return; 6081 case Intrinsic::log: 6082 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6083 return; 6084 case Intrinsic::log2: 6085 setValue(&I, 6086 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6087 return; 6088 case Intrinsic::log10: 6089 setValue(&I, 6090 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6091 return; 6092 case Intrinsic::exp: 6093 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6094 return; 6095 case Intrinsic::exp2: 6096 setValue(&I, 6097 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags)); 6098 return; 6099 case Intrinsic::pow: 6100 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6101 getValue(I.getArgOperand(1)), DAG, TLI, Flags)); 6102 return; 6103 case Intrinsic::sqrt: 6104 case Intrinsic::fabs: 6105 case Intrinsic::sin: 6106 case Intrinsic::cos: 6107 case Intrinsic::floor: 6108 case Intrinsic::ceil: 6109 case Intrinsic::trunc: 6110 case Intrinsic::rint: 6111 case Intrinsic::nearbyint: 6112 case Intrinsic::round: 6113 case Intrinsic::roundeven: 6114 case Intrinsic::canonicalize: { 6115 unsigned Opcode; 6116 switch (Intrinsic) { 6117 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6118 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6119 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6120 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6121 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6122 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6123 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6124 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6125 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6126 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6127 case Intrinsic::round: Opcode = ISD::FROUND; break; 6128 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break; 6129 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6130 } 6131 6132 setValue(&I, DAG.getNode(Opcode, sdl, 6133 getValue(I.getArgOperand(0)).getValueType(), 6134 getValue(I.getArgOperand(0)), Flags)); 6135 return; 6136 } 6137 case Intrinsic::lround: 6138 case Intrinsic::llround: 6139 case Intrinsic::lrint: 6140 case Intrinsic::llrint: { 6141 unsigned Opcode; 6142 switch (Intrinsic) { 6143 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6144 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6145 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6146 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6147 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6148 } 6149 6150 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6151 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6152 getValue(I.getArgOperand(0)))); 6153 return; 6154 } 6155 case Intrinsic::minnum: 6156 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6157 getValue(I.getArgOperand(0)).getValueType(), 6158 getValue(I.getArgOperand(0)), 6159 getValue(I.getArgOperand(1)), Flags)); 6160 return; 6161 case Intrinsic::maxnum: 6162 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6163 getValue(I.getArgOperand(0)).getValueType(), 6164 getValue(I.getArgOperand(0)), 6165 getValue(I.getArgOperand(1)), Flags)); 6166 return; 6167 case Intrinsic::minimum: 6168 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6169 getValue(I.getArgOperand(0)).getValueType(), 6170 getValue(I.getArgOperand(0)), 6171 getValue(I.getArgOperand(1)), Flags)); 6172 return; 6173 case Intrinsic::maximum: 6174 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6175 getValue(I.getArgOperand(0)).getValueType(), 6176 getValue(I.getArgOperand(0)), 6177 getValue(I.getArgOperand(1)), Flags)); 6178 return; 6179 case Intrinsic::copysign: 6180 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6181 getValue(I.getArgOperand(0)).getValueType(), 6182 getValue(I.getArgOperand(0)), 6183 getValue(I.getArgOperand(1)), Flags)); 6184 return; 6185 case Intrinsic::fma: 6186 setValue(&I, DAG.getNode( 6187 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(), 6188 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), 6189 getValue(I.getArgOperand(2)), Flags)); 6190 return; 6191 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 6192 case Intrinsic::INTRINSIC: 6193 #include "llvm/IR/ConstrainedOps.def" 6194 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6195 return; 6196 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID: 6197 #include "llvm/IR/VPIntrinsics.def" 6198 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I)); 6199 return; 6200 case Intrinsic::fmuladd: { 6201 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6202 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6203 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6204 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6205 getValue(I.getArgOperand(0)).getValueType(), 6206 getValue(I.getArgOperand(0)), 6207 getValue(I.getArgOperand(1)), 6208 getValue(I.getArgOperand(2)), Flags)); 6209 } else { 6210 // TODO: Intrinsic calls should have fast-math-flags. 6211 SDValue Mul = DAG.getNode( 6212 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(), 6213 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags); 6214 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6215 getValue(I.getArgOperand(0)).getValueType(), 6216 Mul, getValue(I.getArgOperand(2)), Flags); 6217 setValue(&I, Add); 6218 } 6219 return; 6220 } 6221 case Intrinsic::convert_to_fp16: 6222 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6223 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6224 getValue(I.getArgOperand(0)), 6225 DAG.getTargetConstant(0, sdl, 6226 MVT::i32)))); 6227 return; 6228 case Intrinsic::convert_from_fp16: 6229 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6230 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6231 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6232 getValue(I.getArgOperand(0))))); 6233 return; 6234 case Intrinsic::fptosi_sat: { 6235 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6236 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6237 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type, 6238 getValue(I.getArgOperand(0)), SatW)); 6239 return; 6240 } 6241 case Intrinsic::fptoui_sat: { 6242 EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6243 SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32); 6244 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type, 6245 getValue(I.getArgOperand(0)), SatW)); 6246 return; 6247 } 6248 case Intrinsic::set_rounding: 6249 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other, 6250 {getRoot(), getValue(I.getArgOperand(0))}); 6251 setValue(&I, Res); 6252 DAG.setRoot(Res.getValue(0)); 6253 return; 6254 case Intrinsic::pcmarker: { 6255 SDValue Tmp = getValue(I.getArgOperand(0)); 6256 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6257 return; 6258 } 6259 case Intrinsic::readcyclecounter: { 6260 SDValue Op = getRoot(); 6261 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6262 DAG.getVTList(MVT::i64, MVT::Other), Op); 6263 setValue(&I, Res); 6264 DAG.setRoot(Res.getValue(1)); 6265 return; 6266 } 6267 case Intrinsic::bitreverse: 6268 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6269 getValue(I.getArgOperand(0)).getValueType(), 6270 getValue(I.getArgOperand(0)))); 6271 return; 6272 case Intrinsic::bswap: 6273 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6274 getValue(I.getArgOperand(0)).getValueType(), 6275 getValue(I.getArgOperand(0)))); 6276 return; 6277 case Intrinsic::cttz: { 6278 SDValue Arg = getValue(I.getArgOperand(0)); 6279 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6280 EVT Ty = Arg.getValueType(); 6281 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6282 sdl, Ty, Arg)); 6283 return; 6284 } 6285 case Intrinsic::ctlz: { 6286 SDValue Arg = getValue(I.getArgOperand(0)); 6287 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6288 EVT Ty = Arg.getValueType(); 6289 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6290 sdl, Ty, Arg)); 6291 return; 6292 } 6293 case Intrinsic::ctpop: { 6294 SDValue Arg = getValue(I.getArgOperand(0)); 6295 EVT Ty = Arg.getValueType(); 6296 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6297 return; 6298 } 6299 case Intrinsic::fshl: 6300 case Intrinsic::fshr: { 6301 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6302 SDValue X = getValue(I.getArgOperand(0)); 6303 SDValue Y = getValue(I.getArgOperand(1)); 6304 SDValue Z = getValue(I.getArgOperand(2)); 6305 EVT VT = X.getValueType(); 6306 6307 if (X == Y) { 6308 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6309 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6310 } else { 6311 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6312 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6313 } 6314 return; 6315 } 6316 case Intrinsic::sadd_sat: { 6317 SDValue Op1 = getValue(I.getArgOperand(0)); 6318 SDValue Op2 = getValue(I.getArgOperand(1)); 6319 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6320 return; 6321 } 6322 case Intrinsic::uadd_sat: { 6323 SDValue Op1 = getValue(I.getArgOperand(0)); 6324 SDValue Op2 = getValue(I.getArgOperand(1)); 6325 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6326 return; 6327 } 6328 case Intrinsic::ssub_sat: { 6329 SDValue Op1 = getValue(I.getArgOperand(0)); 6330 SDValue Op2 = getValue(I.getArgOperand(1)); 6331 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6332 return; 6333 } 6334 case Intrinsic::usub_sat: { 6335 SDValue Op1 = getValue(I.getArgOperand(0)); 6336 SDValue Op2 = getValue(I.getArgOperand(1)); 6337 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6338 return; 6339 } 6340 case Intrinsic::sshl_sat: { 6341 SDValue Op1 = getValue(I.getArgOperand(0)); 6342 SDValue Op2 = getValue(I.getArgOperand(1)); 6343 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6344 return; 6345 } 6346 case Intrinsic::ushl_sat: { 6347 SDValue Op1 = getValue(I.getArgOperand(0)); 6348 SDValue Op2 = getValue(I.getArgOperand(1)); 6349 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2)); 6350 return; 6351 } 6352 case Intrinsic::smul_fix: 6353 case Intrinsic::umul_fix: 6354 case Intrinsic::smul_fix_sat: 6355 case Intrinsic::umul_fix_sat: { 6356 SDValue Op1 = getValue(I.getArgOperand(0)); 6357 SDValue Op2 = getValue(I.getArgOperand(1)); 6358 SDValue Op3 = getValue(I.getArgOperand(2)); 6359 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6360 Op1.getValueType(), Op1, Op2, Op3)); 6361 return; 6362 } 6363 case Intrinsic::sdiv_fix: 6364 case Intrinsic::udiv_fix: 6365 case Intrinsic::sdiv_fix_sat: 6366 case Intrinsic::udiv_fix_sat: { 6367 SDValue Op1 = getValue(I.getArgOperand(0)); 6368 SDValue Op2 = getValue(I.getArgOperand(1)); 6369 SDValue Op3 = getValue(I.getArgOperand(2)); 6370 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6371 Op1, Op2, Op3, DAG, TLI)); 6372 return; 6373 } 6374 case Intrinsic::smax: { 6375 SDValue Op1 = getValue(I.getArgOperand(0)); 6376 SDValue Op2 = getValue(I.getArgOperand(1)); 6377 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2)); 6378 return; 6379 } 6380 case Intrinsic::smin: { 6381 SDValue Op1 = getValue(I.getArgOperand(0)); 6382 SDValue Op2 = getValue(I.getArgOperand(1)); 6383 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2)); 6384 return; 6385 } 6386 case Intrinsic::umax: { 6387 SDValue Op1 = getValue(I.getArgOperand(0)); 6388 SDValue Op2 = getValue(I.getArgOperand(1)); 6389 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2)); 6390 return; 6391 } 6392 case Intrinsic::umin: { 6393 SDValue Op1 = getValue(I.getArgOperand(0)); 6394 SDValue Op2 = getValue(I.getArgOperand(1)); 6395 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2)); 6396 return; 6397 } 6398 case Intrinsic::abs: { 6399 // TODO: Preserve "int min is poison" arg in SDAG? 6400 SDValue Op1 = getValue(I.getArgOperand(0)); 6401 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1)); 6402 return; 6403 } 6404 case Intrinsic::stacksave: { 6405 SDValue Op = getRoot(); 6406 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6407 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op); 6408 setValue(&I, Res); 6409 DAG.setRoot(Res.getValue(1)); 6410 return; 6411 } 6412 case Intrinsic::stackrestore: 6413 Res = getValue(I.getArgOperand(0)); 6414 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6415 return; 6416 case Intrinsic::get_dynamic_area_offset: { 6417 SDValue Op = getRoot(); 6418 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6419 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6420 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6421 // target. 6422 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits()) 6423 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6424 " intrinsic!"); 6425 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6426 Op); 6427 DAG.setRoot(Op); 6428 setValue(&I, Res); 6429 return; 6430 } 6431 case Intrinsic::stackguard: { 6432 MachineFunction &MF = DAG.getMachineFunction(); 6433 const Module &M = *MF.getFunction().getParent(); 6434 SDValue Chain = getRoot(); 6435 if (TLI.useLoadStackGuardNode()) { 6436 Res = getLoadStackGuard(DAG, sdl, Chain); 6437 } else { 6438 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6439 const Value *Global = TLI.getSDagStackGuard(M); 6440 Align Align = DL->getPrefTypeAlign(Global->getType()); 6441 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6442 MachinePointerInfo(Global, 0), Align, 6443 MachineMemOperand::MOVolatile); 6444 } 6445 if (TLI.useStackGuardXorFP()) 6446 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6447 DAG.setRoot(Chain); 6448 setValue(&I, Res); 6449 return; 6450 } 6451 case Intrinsic::stackprotector: { 6452 // Emit code into the DAG to store the stack guard onto the stack. 6453 MachineFunction &MF = DAG.getMachineFunction(); 6454 MachineFrameInfo &MFI = MF.getFrameInfo(); 6455 SDValue Src, Chain = getRoot(); 6456 6457 if (TLI.useLoadStackGuardNode()) 6458 Src = getLoadStackGuard(DAG, sdl, Chain); 6459 else 6460 Src = getValue(I.getArgOperand(0)); // The guard's value. 6461 6462 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6463 6464 int FI = FuncInfo.StaticAllocaMap[Slot]; 6465 MFI.setStackProtectorIndex(FI); 6466 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout()); 6467 6468 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6469 6470 // Store the stack protector onto the stack. 6471 Res = DAG.getStore( 6472 Chain, sdl, Src, FIN, 6473 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 6474 MaybeAlign(), MachineMemOperand::MOVolatile); 6475 setValue(&I, Res); 6476 DAG.setRoot(Res); 6477 return; 6478 } 6479 case Intrinsic::objectsize: 6480 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6481 6482 case Intrinsic::is_constant: 6483 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6484 6485 case Intrinsic::annotation: 6486 case Intrinsic::ptr_annotation: 6487 case Intrinsic::launder_invariant_group: 6488 case Intrinsic::strip_invariant_group: 6489 // Drop the intrinsic, but forward the value 6490 setValue(&I, getValue(I.getOperand(0))); 6491 return; 6492 6493 case Intrinsic::assume: 6494 case Intrinsic::experimental_noalias_scope_decl: 6495 case Intrinsic::var_annotation: 6496 case Intrinsic::sideeffect: 6497 // Discard annotate attributes, noalias scope declarations, assumptions, and 6498 // artificial side-effects. 6499 return; 6500 6501 case Intrinsic::codeview_annotation: { 6502 // Emit a label associated with this metadata. 6503 MachineFunction &MF = DAG.getMachineFunction(); 6504 MCSymbol *Label = 6505 MF.getMMI().getContext().createTempSymbol("annotation", true); 6506 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6507 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6508 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6509 DAG.setRoot(Res); 6510 return; 6511 } 6512 6513 case Intrinsic::init_trampoline: { 6514 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6515 6516 SDValue Ops[6]; 6517 Ops[0] = getRoot(); 6518 Ops[1] = getValue(I.getArgOperand(0)); 6519 Ops[2] = getValue(I.getArgOperand(1)); 6520 Ops[3] = getValue(I.getArgOperand(2)); 6521 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6522 Ops[5] = DAG.getSrcValue(F); 6523 6524 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6525 6526 DAG.setRoot(Res); 6527 return; 6528 } 6529 case Intrinsic::adjust_trampoline: 6530 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6531 TLI.getPointerTy(DAG.getDataLayout()), 6532 getValue(I.getArgOperand(0)))); 6533 return; 6534 case Intrinsic::gcroot: { 6535 assert(DAG.getMachineFunction().getFunction().hasGC() && 6536 "only valid in functions with gc specified, enforced by Verifier"); 6537 assert(GFI && "implied by previous"); 6538 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6539 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6540 6541 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6542 GFI->addStackRoot(FI->getIndex(), TypeMap); 6543 return; 6544 } 6545 case Intrinsic::gcread: 6546 case Intrinsic::gcwrite: 6547 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6548 case Intrinsic::flt_rounds: 6549 Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot()); 6550 setValue(&I, Res); 6551 DAG.setRoot(Res.getValue(1)); 6552 return; 6553 6554 case Intrinsic::expect: 6555 // Just replace __builtin_expect(exp, c) with EXP. 6556 setValue(&I, getValue(I.getArgOperand(0))); 6557 return; 6558 6559 case Intrinsic::ubsantrap: 6560 case Intrinsic::debugtrap: 6561 case Intrinsic::trap: { 6562 StringRef TrapFuncName = 6563 I.getAttributes() 6564 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6565 .getValueAsString(); 6566 if (TrapFuncName.empty()) { 6567 switch (Intrinsic) { 6568 case Intrinsic::trap: 6569 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot())); 6570 break; 6571 case Intrinsic::debugtrap: 6572 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot())); 6573 break; 6574 case Intrinsic::ubsantrap: 6575 DAG.setRoot(DAG.getNode( 6576 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(), 6577 DAG.getTargetConstant( 6578 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl, 6579 MVT::i32))); 6580 break; 6581 default: llvm_unreachable("unknown trap intrinsic"); 6582 } 6583 return; 6584 } 6585 TargetLowering::ArgListTy Args; 6586 if (Intrinsic == Intrinsic::ubsantrap) { 6587 Args.push_back(TargetLoweringBase::ArgListEntry()); 6588 Args[0].Val = I.getArgOperand(0); 6589 Args[0].Node = getValue(Args[0].Val); 6590 Args[0].Ty = Args[0].Val->getType(); 6591 } 6592 6593 TargetLowering::CallLoweringInfo CLI(DAG); 6594 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6595 CallingConv::C, I.getType(), 6596 DAG.getExternalSymbol(TrapFuncName.data(), 6597 TLI.getPointerTy(DAG.getDataLayout())), 6598 std::move(Args)); 6599 6600 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6601 DAG.setRoot(Result.second); 6602 return; 6603 } 6604 6605 case Intrinsic::uadd_with_overflow: 6606 case Intrinsic::sadd_with_overflow: 6607 case Intrinsic::usub_with_overflow: 6608 case Intrinsic::ssub_with_overflow: 6609 case Intrinsic::umul_with_overflow: 6610 case Intrinsic::smul_with_overflow: { 6611 ISD::NodeType Op; 6612 switch (Intrinsic) { 6613 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6614 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6615 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6616 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6617 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6618 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6619 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6620 } 6621 SDValue Op1 = getValue(I.getArgOperand(0)); 6622 SDValue Op2 = getValue(I.getArgOperand(1)); 6623 6624 EVT ResultVT = Op1.getValueType(); 6625 EVT OverflowVT = MVT::i1; 6626 if (ResultVT.isVector()) 6627 OverflowVT = EVT::getVectorVT( 6628 *Context, OverflowVT, ResultVT.getVectorElementCount()); 6629 6630 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6631 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6632 return; 6633 } 6634 case Intrinsic::prefetch: { 6635 SDValue Ops[5]; 6636 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6637 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6638 Ops[0] = DAG.getRoot(); 6639 Ops[1] = getValue(I.getArgOperand(0)); 6640 Ops[2] = getValue(I.getArgOperand(1)); 6641 Ops[3] = getValue(I.getArgOperand(2)); 6642 Ops[4] = getValue(I.getArgOperand(3)); 6643 SDValue Result = DAG.getMemIntrinsicNode( 6644 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops, 6645 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)), 6646 /* align */ None, Flags); 6647 6648 // Chain the prefetch in parallell with any pending loads, to stay out of 6649 // the way of later optimizations. 6650 PendingLoads.push_back(Result); 6651 Result = getRoot(); 6652 DAG.setRoot(Result); 6653 return; 6654 } 6655 case Intrinsic::lifetime_start: 6656 case Intrinsic::lifetime_end: { 6657 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6658 // Stack coloring is not enabled in O0, discard region information. 6659 if (TM.getOptLevel() == CodeGenOpt::None) 6660 return; 6661 6662 const int64_t ObjectSize = 6663 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6664 Value *const ObjectPtr = I.getArgOperand(1); 6665 SmallVector<const Value *, 4> Allocas; 6666 getUnderlyingObjects(ObjectPtr, Allocas); 6667 6668 for (const Value *Alloca : Allocas) { 6669 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca); 6670 6671 // Could not find an Alloca. 6672 if (!LifetimeObject) 6673 continue; 6674 6675 // First check that the Alloca is static, otherwise it won't have a 6676 // valid frame index. 6677 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6678 if (SI == FuncInfo.StaticAllocaMap.end()) 6679 return; 6680 6681 const int FrameIndex = SI->second; 6682 int64_t Offset; 6683 if (GetPointerBaseWithConstantOffset( 6684 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6685 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6686 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6687 Offset); 6688 DAG.setRoot(Res); 6689 } 6690 return; 6691 } 6692 case Intrinsic::pseudoprobe: { 6693 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(); 6694 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6695 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 6696 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr); 6697 DAG.setRoot(Res); 6698 return; 6699 } 6700 case Intrinsic::invariant_start: 6701 // Discard region information. 6702 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6703 return; 6704 case Intrinsic::invariant_end: 6705 // Discard region information. 6706 return; 6707 case Intrinsic::clear_cache: 6708 /// FunctionName may be null. 6709 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6710 lowerCallToExternalSymbol(I, FunctionName); 6711 return; 6712 case Intrinsic::donothing: 6713 // ignore 6714 return; 6715 case Intrinsic::experimental_stackmap: 6716 visitStackmap(I); 6717 return; 6718 case Intrinsic::experimental_patchpoint_void: 6719 case Intrinsic::experimental_patchpoint_i64: 6720 visitPatchpoint(I); 6721 return; 6722 case Intrinsic::experimental_gc_statepoint: 6723 LowerStatepoint(cast<GCStatepointInst>(I)); 6724 return; 6725 case Intrinsic::experimental_gc_result: 6726 visitGCResult(cast<GCResultInst>(I)); 6727 return; 6728 case Intrinsic::experimental_gc_relocate: 6729 visitGCRelocate(cast<GCRelocateInst>(I)); 6730 return; 6731 case Intrinsic::instrprof_increment: 6732 llvm_unreachable("instrprof failed to lower an increment"); 6733 case Intrinsic::instrprof_value_profile: 6734 llvm_unreachable("instrprof failed to lower a value profiling call"); 6735 case Intrinsic::localescape: { 6736 MachineFunction &MF = DAG.getMachineFunction(); 6737 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6738 6739 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6740 // is the same on all targets. 6741 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6742 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6743 if (isa<ConstantPointerNull>(Arg)) 6744 continue; // Skip null pointers. They represent a hole in index space. 6745 AllocaInst *Slot = cast<AllocaInst>(Arg); 6746 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6747 "can only escape static allocas"); 6748 int FI = FuncInfo.StaticAllocaMap[Slot]; 6749 MCSymbol *FrameAllocSym = 6750 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6751 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6752 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6753 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6754 .addSym(FrameAllocSym) 6755 .addFrameIndex(FI); 6756 } 6757 6758 return; 6759 } 6760 6761 case Intrinsic::localrecover: { 6762 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6763 MachineFunction &MF = DAG.getMachineFunction(); 6764 6765 // Get the symbol that defines the frame offset. 6766 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6767 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6768 unsigned IdxVal = 6769 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6770 MCSymbol *FrameAllocSym = 6771 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6772 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6773 6774 Value *FP = I.getArgOperand(1); 6775 SDValue FPVal = getValue(FP); 6776 EVT PtrVT = FPVal.getValueType(); 6777 6778 // Create a MCSymbol for the label to avoid any target lowering 6779 // that would make this PC relative. 6780 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6781 SDValue OffsetVal = 6782 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6783 6784 // Add the offset to the FP. 6785 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6786 setValue(&I, Add); 6787 6788 return; 6789 } 6790 6791 case Intrinsic::eh_exceptionpointer: 6792 case Intrinsic::eh_exceptioncode: { 6793 // Get the exception pointer vreg, copy from it, and resize it to fit. 6794 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6795 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6796 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6797 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6798 SDValue N = 6799 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6800 if (Intrinsic == Intrinsic::eh_exceptioncode) 6801 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6802 setValue(&I, N); 6803 return; 6804 } 6805 case Intrinsic::xray_customevent: { 6806 // Here we want to make sure that the intrinsic behaves as if it has a 6807 // specific calling convention, and only for x86_64. 6808 // FIXME: Support other platforms later. 6809 const auto &Triple = DAG.getTarget().getTargetTriple(); 6810 if (Triple.getArch() != Triple::x86_64) 6811 return; 6812 6813 SDLoc DL = getCurSDLoc(); 6814 SmallVector<SDValue, 8> Ops; 6815 6816 // We want to say that we always want the arguments in registers. 6817 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6818 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6819 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6820 SDValue Chain = getRoot(); 6821 Ops.push_back(LogEntryVal); 6822 Ops.push_back(StrSizeVal); 6823 Ops.push_back(Chain); 6824 6825 // We need to enforce the calling convention for the callsite, so that 6826 // argument ordering is enforced correctly, and that register allocation can 6827 // see that some registers may be assumed clobbered and have to preserve 6828 // them across calls to the intrinsic. 6829 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6830 DL, NodeTys, Ops); 6831 SDValue patchableNode = SDValue(MN, 0); 6832 DAG.setRoot(patchableNode); 6833 setValue(&I, patchableNode); 6834 return; 6835 } 6836 case Intrinsic::xray_typedevent: { 6837 // Here we want to make sure that the intrinsic behaves as if it has a 6838 // specific calling convention, and only for x86_64. 6839 // FIXME: Support other platforms later. 6840 const auto &Triple = DAG.getTarget().getTargetTriple(); 6841 if (Triple.getArch() != Triple::x86_64) 6842 return; 6843 6844 SDLoc DL = getCurSDLoc(); 6845 SmallVector<SDValue, 8> Ops; 6846 6847 // We want to say that we always want the arguments in registers. 6848 // It's unclear to me how manipulating the selection DAG here forces callers 6849 // to provide arguments in registers instead of on the stack. 6850 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6851 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6852 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6853 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6854 SDValue Chain = getRoot(); 6855 Ops.push_back(LogTypeId); 6856 Ops.push_back(LogEntryVal); 6857 Ops.push_back(StrSizeVal); 6858 Ops.push_back(Chain); 6859 6860 // We need to enforce the calling convention for the callsite, so that 6861 // argument ordering is enforced correctly, and that register allocation can 6862 // see that some registers may be assumed clobbered and have to preserve 6863 // them across calls to the intrinsic. 6864 MachineSDNode *MN = DAG.getMachineNode( 6865 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6866 SDValue patchableNode = SDValue(MN, 0); 6867 DAG.setRoot(patchableNode); 6868 setValue(&I, patchableNode); 6869 return; 6870 } 6871 case Intrinsic::experimental_deoptimize: 6872 LowerDeoptimizeCall(&I); 6873 return; 6874 6875 case Intrinsic::vector_reduce_fadd: 6876 case Intrinsic::vector_reduce_fmul: 6877 case Intrinsic::vector_reduce_add: 6878 case Intrinsic::vector_reduce_mul: 6879 case Intrinsic::vector_reduce_and: 6880 case Intrinsic::vector_reduce_or: 6881 case Intrinsic::vector_reduce_xor: 6882 case Intrinsic::vector_reduce_smax: 6883 case Intrinsic::vector_reduce_smin: 6884 case Intrinsic::vector_reduce_umax: 6885 case Intrinsic::vector_reduce_umin: 6886 case Intrinsic::vector_reduce_fmax: 6887 case Intrinsic::vector_reduce_fmin: 6888 visitVectorReduce(I, Intrinsic); 6889 return; 6890 6891 case Intrinsic::icall_branch_funnel: { 6892 SmallVector<SDValue, 16> Ops; 6893 Ops.push_back(getValue(I.getArgOperand(0))); 6894 6895 int64_t Offset; 6896 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6897 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6898 if (!Base) 6899 report_fatal_error( 6900 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6901 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6902 6903 struct BranchFunnelTarget { 6904 int64_t Offset; 6905 SDValue Target; 6906 }; 6907 SmallVector<BranchFunnelTarget, 8> Targets; 6908 6909 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6910 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6911 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6912 if (ElemBase != Base) 6913 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6914 "to the same GlobalValue"); 6915 6916 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6917 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6918 if (!GA) 6919 report_fatal_error( 6920 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6921 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6922 GA->getGlobal(), getCurSDLoc(), 6923 Val.getValueType(), GA->getOffset())}); 6924 } 6925 llvm::sort(Targets, 6926 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6927 return T1.Offset < T2.Offset; 6928 }); 6929 6930 for (auto &T : Targets) { 6931 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6932 Ops.push_back(T.Target); 6933 } 6934 6935 Ops.push_back(DAG.getRoot()); // Chain 6936 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6937 getCurSDLoc(), MVT::Other, Ops), 6938 0); 6939 DAG.setRoot(N); 6940 setValue(&I, N); 6941 HasTailCall = true; 6942 return; 6943 } 6944 6945 case Intrinsic::wasm_landingpad_index: 6946 // Information this intrinsic contained has been transferred to 6947 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6948 // delete it now. 6949 return; 6950 6951 case Intrinsic::aarch64_settag: 6952 case Intrinsic::aarch64_settag_zero: { 6953 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6954 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6955 SDValue Val = TSI.EmitTargetCodeForSetTag( 6956 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6957 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6958 ZeroMemory); 6959 DAG.setRoot(Val); 6960 setValue(&I, Val); 6961 return; 6962 } 6963 case Intrinsic::ptrmask: { 6964 SDValue Ptr = getValue(I.getOperand(0)); 6965 SDValue Const = getValue(I.getOperand(1)); 6966 6967 EVT PtrVT = Ptr.getValueType(); 6968 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr, 6969 DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT))); 6970 return; 6971 } 6972 case Intrinsic::get_active_lane_mask: { 6973 auto DL = getCurSDLoc(); 6974 SDValue Index = getValue(I.getOperand(0)); 6975 SDValue TripCount = getValue(I.getOperand(1)); 6976 Type *ElementTy = I.getOperand(0)->getType(); 6977 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6978 unsigned VecWidth = VT.getVectorNumElements(); 6979 6980 SmallVector<SDValue, 16> OpsTripCount; 6981 SmallVector<SDValue, 16> OpsIndex; 6982 SmallVector<SDValue, 16> OpsStepConstants; 6983 for (unsigned i = 0; i < VecWidth; i++) { 6984 OpsTripCount.push_back(TripCount); 6985 OpsIndex.push_back(Index); 6986 OpsStepConstants.push_back( 6987 DAG.getConstant(i, DL, EVT::getEVT(ElementTy))); 6988 } 6989 6990 EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth); 6991 6992 auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth)); 6993 SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex); 6994 SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants); 6995 SDValue VectorInduction = DAG.getNode( 6996 ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep); 6997 SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount); 6998 SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0), 6999 VectorTripCount, ISD::CondCode::SETULT); 7000 setValue(&I, DAG.getNode(ISD::AND, DL, CCVT, 7001 DAG.getNOT(DL, VectorInduction.getValue(1), CCVT), 7002 SetCC)); 7003 return; 7004 } 7005 case Intrinsic::experimental_vector_insert: { 7006 auto DL = getCurSDLoc(); 7007 7008 SDValue Vec = getValue(I.getOperand(0)); 7009 SDValue SubVec = getValue(I.getOperand(1)); 7010 SDValue Index = getValue(I.getOperand(2)); 7011 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7012 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec, 7013 Index)); 7014 return; 7015 } 7016 case Intrinsic::experimental_vector_extract: { 7017 auto DL = getCurSDLoc(); 7018 7019 SDValue Vec = getValue(I.getOperand(0)); 7020 SDValue Index = getValue(I.getOperand(1)); 7021 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7022 7023 setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index)); 7024 return; 7025 } 7026 } 7027 } 7028 7029 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 7030 const ConstrainedFPIntrinsic &FPI) { 7031 SDLoc sdl = getCurSDLoc(); 7032 7033 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7034 SmallVector<EVT, 4> ValueVTs; 7035 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 7036 ValueVTs.push_back(MVT::Other); // Out chain 7037 7038 // We do not need to serialize constrained FP intrinsics against 7039 // each other or against (nonvolatile) loads, so they can be 7040 // chained like loads. 7041 SDValue Chain = DAG.getRoot(); 7042 SmallVector<SDValue, 4> Opers; 7043 Opers.push_back(Chain); 7044 if (FPI.isUnaryOp()) { 7045 Opers.push_back(getValue(FPI.getArgOperand(0))); 7046 } else if (FPI.isTernaryOp()) { 7047 Opers.push_back(getValue(FPI.getArgOperand(0))); 7048 Opers.push_back(getValue(FPI.getArgOperand(1))); 7049 Opers.push_back(getValue(FPI.getArgOperand(2))); 7050 } else { 7051 Opers.push_back(getValue(FPI.getArgOperand(0))); 7052 Opers.push_back(getValue(FPI.getArgOperand(1))); 7053 } 7054 7055 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) { 7056 assert(Result.getNode()->getNumValues() == 2); 7057 7058 // Push node to the appropriate list so that future instructions can be 7059 // chained up correctly. 7060 SDValue OutChain = Result.getValue(1); 7061 switch (EB) { 7062 case fp::ExceptionBehavior::ebIgnore: 7063 // The only reason why ebIgnore nodes still need to be chained is that 7064 // they might depend on the current rounding mode, and therefore must 7065 // not be moved across instruction that may change that mode. 7066 LLVM_FALLTHROUGH; 7067 case fp::ExceptionBehavior::ebMayTrap: 7068 // These must not be moved across calls or instructions that may change 7069 // floating-point exception masks. 7070 PendingConstrainedFP.push_back(OutChain); 7071 break; 7072 case fp::ExceptionBehavior::ebStrict: 7073 // These must not be moved across calls or instructions that may change 7074 // floating-point exception masks or read floating-point exception flags. 7075 // In addition, they cannot be optimized out even if unused. 7076 PendingConstrainedFPStrict.push_back(OutChain); 7077 break; 7078 } 7079 }; 7080 7081 SDVTList VTs = DAG.getVTList(ValueVTs); 7082 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 7083 7084 SDNodeFlags Flags; 7085 if (EB == fp::ExceptionBehavior::ebIgnore) 7086 Flags.setNoFPExcept(true); 7087 7088 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI)) 7089 Flags.copyFMF(*FPOp); 7090 7091 unsigned Opcode; 7092 switch (FPI.getIntrinsicID()) { 7093 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 7094 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 7095 case Intrinsic::INTRINSIC: \ 7096 Opcode = ISD::STRICT_##DAGN; \ 7097 break; 7098 #include "llvm/IR/ConstrainedOps.def" 7099 case Intrinsic::experimental_constrained_fmuladd: { 7100 Opcode = ISD::STRICT_FMA; 7101 // Break fmuladd into fmul and fadd. 7102 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict || 7103 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), 7104 ValueVTs[0])) { 7105 Opers.pop_back(); 7106 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags); 7107 pushOutChain(Mul, EB); 7108 Opcode = ISD::STRICT_FADD; 7109 Opers.clear(); 7110 Opers.push_back(Mul.getValue(1)); 7111 Opers.push_back(Mul.getValue(0)); 7112 Opers.push_back(getValue(FPI.getArgOperand(2))); 7113 } 7114 break; 7115 } 7116 } 7117 7118 // A few strict DAG nodes carry additional operands that are not 7119 // set up by the default code above. 7120 switch (Opcode) { 7121 default: break; 7122 case ISD::STRICT_FP_ROUND: 7123 Opers.push_back( 7124 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 7125 break; 7126 case ISD::STRICT_FSETCC: 7127 case ISD::STRICT_FSETCCS: { 7128 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 7129 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate()); 7130 if (TM.Options.NoNaNsFPMath) 7131 Condition = getFCmpCodeWithoutNaN(Condition); 7132 Opers.push_back(DAG.getCondCode(Condition)); 7133 break; 7134 } 7135 } 7136 7137 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags); 7138 pushOutChain(Result, EB); 7139 7140 SDValue FPResult = Result.getValue(0); 7141 setValue(&FPI, FPResult); 7142 } 7143 7144 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) { 7145 Optional<unsigned> ResOPC; 7146 switch (VPIntrin.getIntrinsicID()) { 7147 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN: 7148 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID; 7149 #define END_REGISTER_VP_INTRINSIC(...) break; 7150 #include "llvm/IR/VPIntrinsics.def" 7151 } 7152 7153 if (!ResOPC.hasValue()) 7154 llvm_unreachable( 7155 "Inconsistency: no SDNode available for this VPIntrinsic!"); 7156 7157 return ResOPC.getValue(); 7158 } 7159 7160 void SelectionDAGBuilder::visitVectorPredicationIntrinsic( 7161 const VPIntrinsic &VPIntrin) { 7162 unsigned Opcode = getISDForVPIntrinsic(VPIntrin); 7163 7164 SmallVector<EVT, 4> ValueVTs; 7165 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7166 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs); 7167 SDVTList VTs = DAG.getVTList(ValueVTs); 7168 7169 // Request operands. 7170 SmallVector<SDValue, 7> OpValues; 7171 for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i) 7172 OpValues.push_back(getValue(VPIntrin.getArgOperand(i))); 7173 7174 SDLoc DL = getCurSDLoc(); 7175 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues); 7176 setValue(&VPIntrin, Result); 7177 } 7178 7179 std::pair<SDValue, SDValue> 7180 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7181 const BasicBlock *EHPadBB) { 7182 MachineFunction &MF = DAG.getMachineFunction(); 7183 MachineModuleInfo &MMI = MF.getMMI(); 7184 MCSymbol *BeginLabel = nullptr; 7185 7186 if (EHPadBB) { 7187 // Insert a label before the invoke call to mark the try range. This can be 7188 // used to detect deletion of the invoke via the MachineModuleInfo. 7189 BeginLabel = MMI.getContext().createTempSymbol(); 7190 7191 // For SjLj, keep track of which landing pads go with which invokes 7192 // so as to maintain the ordering of pads in the LSDA. 7193 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7194 if (CallSiteIndex) { 7195 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7196 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7197 7198 // Now that the call site is handled, stop tracking it. 7199 MMI.setCurrentCallSite(0); 7200 } 7201 7202 // Both PendingLoads and PendingExports must be flushed here; 7203 // this call might not return. 7204 (void)getRoot(); 7205 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7206 7207 CLI.setChain(getRoot()); 7208 } 7209 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7210 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7211 7212 assert((CLI.IsTailCall || Result.second.getNode()) && 7213 "Non-null chain expected with non-tail call!"); 7214 assert((Result.second.getNode() || !Result.first.getNode()) && 7215 "Null value expected with tail call!"); 7216 7217 if (!Result.second.getNode()) { 7218 // As a special case, a null chain means that a tail call has been emitted 7219 // and the DAG root is already updated. 7220 HasTailCall = true; 7221 7222 // Since there's no actual continuation from this block, nothing can be 7223 // relying on us setting vregs for them. 7224 PendingExports.clear(); 7225 } else { 7226 DAG.setRoot(Result.second); 7227 } 7228 7229 if (EHPadBB) { 7230 // Insert a label at the end of the invoke call to mark the try range. This 7231 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7232 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7233 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7234 7235 // Inform MachineModuleInfo of range. 7236 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7237 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7238 // actually use outlined funclets and their LSDA info style. 7239 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7240 assert(CLI.CB); 7241 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7242 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel); 7243 } else if (!isScopedEHPersonality(Pers)) { 7244 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7245 } 7246 } 7247 7248 return Result; 7249 } 7250 7251 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee, 7252 bool isTailCall, 7253 const BasicBlock *EHPadBB) { 7254 auto &DL = DAG.getDataLayout(); 7255 FunctionType *FTy = CB.getFunctionType(); 7256 Type *RetTy = CB.getType(); 7257 7258 TargetLowering::ArgListTy Args; 7259 Args.reserve(CB.arg_size()); 7260 7261 const Value *SwiftErrorVal = nullptr; 7262 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7263 7264 if (isTailCall) { 7265 // Avoid emitting tail calls in functions with the disable-tail-calls 7266 // attribute. 7267 auto *Caller = CB.getParent()->getParent(); 7268 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7269 "true") 7270 isTailCall = false; 7271 7272 // We can't tail call inside a function with a swifterror argument. Lowering 7273 // does not support this yet. It would have to move into the swifterror 7274 // register before the call. 7275 if (TLI.supportSwiftError() && 7276 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7277 isTailCall = false; 7278 } 7279 7280 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) { 7281 TargetLowering::ArgListEntry Entry; 7282 const Value *V = *I; 7283 7284 // Skip empty types 7285 if (V->getType()->isEmptyTy()) 7286 continue; 7287 7288 SDValue ArgNode = getValue(V); 7289 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7290 7291 Entry.setAttributes(&CB, I - CB.arg_begin()); 7292 7293 // Use swifterror virtual register as input to the call. 7294 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7295 SwiftErrorVal = V; 7296 // We find the virtual register for the actual swifterror argument. 7297 // Instead of using the Value, we use the virtual register instead. 7298 Entry.Node = 7299 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V), 7300 EVT(TLI.getPointerTy(DL))); 7301 } 7302 7303 Args.push_back(Entry); 7304 7305 // If we have an explicit sret argument that is an Instruction, (i.e., it 7306 // might point to function-local memory), we can't meaningfully tail-call. 7307 if (Entry.IsSRet && isa<Instruction>(V)) 7308 isTailCall = false; 7309 } 7310 7311 // If call site has a cfguardtarget operand bundle, create and add an 7312 // additional ArgListEntry. 7313 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7314 TargetLowering::ArgListEntry Entry; 7315 Value *V = Bundle->Inputs[0]; 7316 SDValue ArgNode = getValue(V); 7317 Entry.Node = ArgNode; 7318 Entry.Ty = V->getType(); 7319 Entry.IsCFGuardTarget = true; 7320 Args.push_back(Entry); 7321 } 7322 7323 // Check if target-independent constraints permit a tail call here. 7324 // Target-dependent constraints are checked within TLI->LowerCallTo. 7325 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget())) 7326 isTailCall = false; 7327 7328 // Disable tail calls if there is an swifterror argument. Targets have not 7329 // been updated to support tail calls. 7330 if (TLI.supportSwiftError() && SwiftErrorVal) 7331 isTailCall = false; 7332 7333 TargetLowering::CallLoweringInfo CLI(DAG); 7334 CLI.setDebugLoc(getCurSDLoc()) 7335 .setChain(getRoot()) 7336 .setCallee(RetTy, FTy, Callee, std::move(Args), CB) 7337 .setTailCall(isTailCall) 7338 .setConvergent(CB.isConvergent()) 7339 .setIsPreallocated( 7340 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 7341 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7342 7343 if (Result.first.getNode()) { 7344 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first); 7345 setValue(&CB, Result.first); 7346 } 7347 7348 // The last element of CLI.InVals has the SDValue for swifterror return. 7349 // Here we copy it to a virtual register and update SwiftErrorMap for 7350 // book-keeping. 7351 if (SwiftErrorVal && TLI.supportSwiftError()) { 7352 // Get the last element of InVals. 7353 SDValue Src = CLI.InVals.back(); 7354 Register VReg = 7355 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal); 7356 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7357 DAG.setRoot(CopyNode); 7358 } 7359 } 7360 7361 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7362 SelectionDAGBuilder &Builder) { 7363 // Check to see if this load can be trivially constant folded, e.g. if the 7364 // input is from a string literal. 7365 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7366 // Cast pointer to the type we really want to load. 7367 Type *LoadTy = 7368 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7369 if (LoadVT.isVector()) 7370 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7371 7372 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7373 PointerType::getUnqual(LoadTy)); 7374 7375 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7376 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7377 return Builder.getValue(LoadCst); 7378 } 7379 7380 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7381 // still constant memory, the input chain can be the entry node. 7382 SDValue Root; 7383 bool ConstantMemory = false; 7384 7385 // Do not serialize (non-volatile) loads of constant memory with anything. 7386 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7387 Root = Builder.DAG.getEntryNode(); 7388 ConstantMemory = true; 7389 } else { 7390 // Do not serialize non-volatile loads against each other. 7391 Root = Builder.DAG.getRoot(); 7392 } 7393 7394 SDValue Ptr = Builder.getValue(PtrVal); 7395 SDValue LoadVal = 7396 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr, 7397 MachinePointerInfo(PtrVal), Align(1)); 7398 7399 if (!ConstantMemory) 7400 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7401 return LoadVal; 7402 } 7403 7404 /// Record the value for an instruction that produces an integer result, 7405 /// converting the type where necessary. 7406 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7407 SDValue Value, 7408 bool IsSigned) { 7409 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7410 I.getType(), true); 7411 if (IsSigned) 7412 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7413 else 7414 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7415 setValue(&I, Value); 7416 } 7417 7418 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return 7419 /// true and lower it. Otherwise return false, and it will be lowered like a 7420 /// normal call. 7421 /// The caller already checked that \p I calls the appropriate LibFunc with a 7422 /// correct prototype. 7423 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) { 7424 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7425 const Value *Size = I.getArgOperand(2); 7426 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7427 if (CSize && CSize->getZExtValue() == 0) { 7428 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7429 I.getType(), true); 7430 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7431 return true; 7432 } 7433 7434 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7435 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7436 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7437 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7438 if (Res.first.getNode()) { 7439 processIntegerCallValue(I, Res.first, true); 7440 PendingLoads.push_back(Res.second); 7441 return true; 7442 } 7443 7444 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7445 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7446 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7447 return false; 7448 7449 // If the target has a fast compare for the given size, it will return a 7450 // preferred load type for that size. Require that the load VT is legal and 7451 // that the target supports unaligned loads of that type. Otherwise, return 7452 // INVALID. 7453 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7455 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7456 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7457 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7458 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7459 // TODO: Check alignment of src and dest ptrs. 7460 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7461 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7462 if (!TLI.isTypeLegal(LVT) || 7463 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7464 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7465 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7466 } 7467 7468 return LVT; 7469 }; 7470 7471 // This turns into unaligned loads. We only do this if the target natively 7472 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7473 // we'll only produce a small number of byte loads. 7474 MVT LoadVT; 7475 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7476 switch (NumBitsToCompare) { 7477 default: 7478 return false; 7479 case 16: 7480 LoadVT = MVT::i16; 7481 break; 7482 case 32: 7483 LoadVT = MVT::i32; 7484 break; 7485 case 64: 7486 case 128: 7487 case 256: 7488 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7489 break; 7490 } 7491 7492 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7493 return false; 7494 7495 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7496 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7497 7498 // Bitcast to a wide integer type if the loads are vectors. 7499 if (LoadVT.isVector()) { 7500 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7501 LoadL = DAG.getBitcast(CmpVT, LoadL); 7502 LoadR = DAG.getBitcast(CmpVT, LoadR); 7503 } 7504 7505 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7506 processIntegerCallValue(I, Cmp, false); 7507 return true; 7508 } 7509 7510 /// See if we can lower a memchr call into an optimized form. If so, return 7511 /// true and lower it. Otherwise return false, and it will be lowered like a 7512 /// normal call. 7513 /// The caller already checked that \p I calls the appropriate LibFunc with a 7514 /// correct prototype. 7515 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7516 const Value *Src = I.getArgOperand(0); 7517 const Value *Char = I.getArgOperand(1); 7518 const Value *Length = I.getArgOperand(2); 7519 7520 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7521 std::pair<SDValue, SDValue> Res = 7522 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7523 getValue(Src), getValue(Char), getValue(Length), 7524 MachinePointerInfo(Src)); 7525 if (Res.first.getNode()) { 7526 setValue(&I, Res.first); 7527 PendingLoads.push_back(Res.second); 7528 return true; 7529 } 7530 7531 return false; 7532 } 7533 7534 /// See if we can lower a mempcpy call into an optimized form. If so, return 7535 /// true and lower it. Otherwise return false, and it will be lowered like a 7536 /// normal call. 7537 /// The caller already checked that \p I calls the appropriate LibFunc with a 7538 /// correct prototype. 7539 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7540 SDValue Dst = getValue(I.getArgOperand(0)); 7541 SDValue Src = getValue(I.getArgOperand(1)); 7542 SDValue Size = getValue(I.getArgOperand(2)); 7543 7544 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne(); 7545 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne(); 7546 // DAG::getMemcpy needs Alignment to be defined. 7547 Align Alignment = std::min(DstAlign, SrcAlign); 7548 7549 bool isVol = false; 7550 SDLoc sdl = getCurSDLoc(); 7551 7552 // In the mempcpy context we need to pass in a false value for isTailCall 7553 // because the return pointer needs to be adjusted by the size of 7554 // the copied memory. 7555 SDValue Root = isVol ? getRoot() : getMemoryRoot(); 7556 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false, 7557 /*isTailCall=*/false, 7558 MachinePointerInfo(I.getArgOperand(0)), 7559 MachinePointerInfo(I.getArgOperand(1))); 7560 assert(MC.getNode() != nullptr && 7561 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7562 DAG.setRoot(MC); 7563 7564 // Check if Size needs to be truncated or extended. 7565 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7566 7567 // Adjust return pointer to point just past the last dst byte. 7568 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7569 Dst, Size); 7570 setValue(&I, DstPlusSize); 7571 return true; 7572 } 7573 7574 /// See if we can lower a strcpy call into an optimized form. If so, return 7575 /// true and lower it, otherwise return false and it will be lowered like a 7576 /// normal call. 7577 /// The caller already checked that \p I calls the appropriate LibFunc with a 7578 /// correct prototype. 7579 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7580 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7581 7582 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7583 std::pair<SDValue, SDValue> Res = 7584 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7585 getValue(Arg0), getValue(Arg1), 7586 MachinePointerInfo(Arg0), 7587 MachinePointerInfo(Arg1), isStpcpy); 7588 if (Res.first.getNode()) { 7589 setValue(&I, Res.first); 7590 DAG.setRoot(Res.second); 7591 return true; 7592 } 7593 7594 return false; 7595 } 7596 7597 /// See if we can lower a strcmp call into an optimized form. If so, return 7598 /// true and lower it, otherwise return false and it will be lowered like a 7599 /// normal call. 7600 /// The caller already checked that \p I calls the appropriate LibFunc with a 7601 /// correct prototype. 7602 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7603 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7604 7605 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7606 std::pair<SDValue, SDValue> Res = 7607 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7608 getValue(Arg0), getValue(Arg1), 7609 MachinePointerInfo(Arg0), 7610 MachinePointerInfo(Arg1)); 7611 if (Res.first.getNode()) { 7612 processIntegerCallValue(I, Res.first, true); 7613 PendingLoads.push_back(Res.second); 7614 return true; 7615 } 7616 7617 return false; 7618 } 7619 7620 /// See if we can lower a strlen call into an optimized form. If so, return 7621 /// true and lower it, otherwise return false and it will be lowered like a 7622 /// normal call. 7623 /// The caller already checked that \p I calls the appropriate LibFunc with a 7624 /// correct prototype. 7625 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7626 const Value *Arg0 = I.getArgOperand(0); 7627 7628 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7629 std::pair<SDValue, SDValue> Res = 7630 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7631 getValue(Arg0), MachinePointerInfo(Arg0)); 7632 if (Res.first.getNode()) { 7633 processIntegerCallValue(I, Res.first, false); 7634 PendingLoads.push_back(Res.second); 7635 return true; 7636 } 7637 7638 return false; 7639 } 7640 7641 /// See if we can lower a strnlen call into an optimized form. If so, return 7642 /// true and lower it, otherwise return false and it will be lowered like a 7643 /// normal call. 7644 /// The caller already checked that \p I calls the appropriate LibFunc with a 7645 /// correct prototype. 7646 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7647 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7648 7649 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7650 std::pair<SDValue, SDValue> Res = 7651 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7652 getValue(Arg0), getValue(Arg1), 7653 MachinePointerInfo(Arg0)); 7654 if (Res.first.getNode()) { 7655 processIntegerCallValue(I, Res.first, false); 7656 PendingLoads.push_back(Res.second); 7657 return true; 7658 } 7659 7660 return false; 7661 } 7662 7663 /// See if we can lower a unary floating-point operation into an SDNode with 7664 /// the specified Opcode. If so, return true and lower it, otherwise return 7665 /// false and it will be lowered like a normal call. 7666 /// The caller already checked that \p I calls the appropriate LibFunc with a 7667 /// correct prototype. 7668 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7669 unsigned Opcode) { 7670 // We already checked this call's prototype; verify it doesn't modify errno. 7671 if (!I.onlyReadsMemory()) 7672 return false; 7673 7674 SDNodeFlags Flags; 7675 Flags.copyFMF(cast<FPMathOperator>(I)); 7676 7677 SDValue Tmp = getValue(I.getArgOperand(0)); 7678 setValue(&I, 7679 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags)); 7680 return true; 7681 } 7682 7683 /// See if we can lower a binary floating-point operation into an SDNode with 7684 /// the specified Opcode. If so, return true and lower it. Otherwise return 7685 /// false, and it will be lowered like a normal call. 7686 /// The caller already checked that \p I calls the appropriate LibFunc with a 7687 /// correct prototype. 7688 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7689 unsigned Opcode) { 7690 // We already checked this call's prototype; verify it doesn't modify errno. 7691 if (!I.onlyReadsMemory()) 7692 return false; 7693 7694 SDNodeFlags Flags; 7695 Flags.copyFMF(cast<FPMathOperator>(I)); 7696 7697 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7698 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7699 EVT VT = Tmp0.getValueType(); 7700 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags)); 7701 return true; 7702 } 7703 7704 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7705 // Handle inline assembly differently. 7706 if (I.isInlineAsm()) { 7707 visitInlineAsm(I); 7708 return; 7709 } 7710 7711 if (Function *F = I.getCalledFunction()) { 7712 if (F->isDeclaration()) { 7713 // Is this an LLVM intrinsic or a target-specific intrinsic? 7714 unsigned IID = F->getIntrinsicID(); 7715 if (!IID) 7716 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7717 IID = II->getIntrinsicID(F); 7718 7719 if (IID) { 7720 visitIntrinsicCall(I, IID); 7721 return; 7722 } 7723 } 7724 7725 // Check for well-known libc/libm calls. If the function is internal, it 7726 // can't be a library call. Don't do the check if marked as nobuiltin for 7727 // some reason or the call site requires strict floating point semantics. 7728 LibFunc Func; 7729 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7730 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7731 LibInfo->hasOptimizedCodeGen(Func)) { 7732 switch (Func) { 7733 default: break; 7734 case LibFunc_bcmp: 7735 if (visitMemCmpBCmpCall(I)) 7736 return; 7737 break; 7738 case LibFunc_copysign: 7739 case LibFunc_copysignf: 7740 case LibFunc_copysignl: 7741 // We already checked this call's prototype; verify it doesn't modify 7742 // errno. 7743 if (I.onlyReadsMemory()) { 7744 SDValue LHS = getValue(I.getArgOperand(0)); 7745 SDValue RHS = getValue(I.getArgOperand(1)); 7746 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7747 LHS.getValueType(), LHS, RHS)); 7748 return; 7749 } 7750 break; 7751 case LibFunc_fabs: 7752 case LibFunc_fabsf: 7753 case LibFunc_fabsl: 7754 if (visitUnaryFloatCall(I, ISD::FABS)) 7755 return; 7756 break; 7757 case LibFunc_fmin: 7758 case LibFunc_fminf: 7759 case LibFunc_fminl: 7760 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7761 return; 7762 break; 7763 case LibFunc_fmax: 7764 case LibFunc_fmaxf: 7765 case LibFunc_fmaxl: 7766 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7767 return; 7768 break; 7769 case LibFunc_sin: 7770 case LibFunc_sinf: 7771 case LibFunc_sinl: 7772 if (visitUnaryFloatCall(I, ISD::FSIN)) 7773 return; 7774 break; 7775 case LibFunc_cos: 7776 case LibFunc_cosf: 7777 case LibFunc_cosl: 7778 if (visitUnaryFloatCall(I, ISD::FCOS)) 7779 return; 7780 break; 7781 case LibFunc_sqrt: 7782 case LibFunc_sqrtf: 7783 case LibFunc_sqrtl: 7784 case LibFunc_sqrt_finite: 7785 case LibFunc_sqrtf_finite: 7786 case LibFunc_sqrtl_finite: 7787 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7788 return; 7789 break; 7790 case LibFunc_floor: 7791 case LibFunc_floorf: 7792 case LibFunc_floorl: 7793 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7794 return; 7795 break; 7796 case LibFunc_nearbyint: 7797 case LibFunc_nearbyintf: 7798 case LibFunc_nearbyintl: 7799 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7800 return; 7801 break; 7802 case LibFunc_ceil: 7803 case LibFunc_ceilf: 7804 case LibFunc_ceill: 7805 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7806 return; 7807 break; 7808 case LibFunc_rint: 7809 case LibFunc_rintf: 7810 case LibFunc_rintl: 7811 if (visitUnaryFloatCall(I, ISD::FRINT)) 7812 return; 7813 break; 7814 case LibFunc_round: 7815 case LibFunc_roundf: 7816 case LibFunc_roundl: 7817 if (visitUnaryFloatCall(I, ISD::FROUND)) 7818 return; 7819 break; 7820 case LibFunc_trunc: 7821 case LibFunc_truncf: 7822 case LibFunc_truncl: 7823 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7824 return; 7825 break; 7826 case LibFunc_log2: 7827 case LibFunc_log2f: 7828 case LibFunc_log2l: 7829 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7830 return; 7831 break; 7832 case LibFunc_exp2: 7833 case LibFunc_exp2f: 7834 case LibFunc_exp2l: 7835 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7836 return; 7837 break; 7838 case LibFunc_memcmp: 7839 if (visitMemCmpBCmpCall(I)) 7840 return; 7841 break; 7842 case LibFunc_mempcpy: 7843 if (visitMemPCpyCall(I)) 7844 return; 7845 break; 7846 case LibFunc_memchr: 7847 if (visitMemChrCall(I)) 7848 return; 7849 break; 7850 case LibFunc_strcpy: 7851 if (visitStrCpyCall(I, false)) 7852 return; 7853 break; 7854 case LibFunc_stpcpy: 7855 if (visitStrCpyCall(I, true)) 7856 return; 7857 break; 7858 case LibFunc_strcmp: 7859 if (visitStrCmpCall(I)) 7860 return; 7861 break; 7862 case LibFunc_strlen: 7863 if (visitStrLenCall(I)) 7864 return; 7865 break; 7866 case LibFunc_strnlen: 7867 if (visitStrNLenCall(I)) 7868 return; 7869 break; 7870 } 7871 } 7872 } 7873 7874 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7875 // have to do anything here to lower funclet bundles. 7876 // CFGuardTarget bundles are lowered in LowerCallTo. 7877 assert(!I.hasOperandBundlesOtherThan( 7878 {LLVMContext::OB_deopt, LLVMContext::OB_funclet, 7879 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) && 7880 "Cannot lower calls with arbitrary operand bundles!"); 7881 7882 SDValue Callee = getValue(I.getCalledOperand()); 7883 7884 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7885 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7886 else 7887 // Check if we can potentially perform a tail call. More detailed checking 7888 // is be done within LowerCallTo, after more information about the call is 7889 // known. 7890 LowerCallTo(I, Callee, I.isTailCall()); 7891 } 7892 7893 namespace { 7894 7895 /// AsmOperandInfo - This contains information for each constraint that we are 7896 /// lowering. 7897 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7898 public: 7899 /// CallOperand - If this is the result output operand or a clobber 7900 /// this is null, otherwise it is the incoming operand to the CallInst. 7901 /// This gets modified as the asm is processed. 7902 SDValue CallOperand; 7903 7904 /// AssignedRegs - If this is a register or register class operand, this 7905 /// contains the set of register corresponding to the operand. 7906 RegsForValue AssignedRegs; 7907 7908 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7909 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7910 } 7911 7912 /// Whether or not this operand accesses memory 7913 bool hasMemory(const TargetLowering &TLI) const { 7914 // Indirect operand accesses access memory. 7915 if (isIndirect) 7916 return true; 7917 7918 for (const auto &Code : Codes) 7919 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7920 return true; 7921 7922 return false; 7923 } 7924 7925 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7926 /// corresponds to. If there is no Value* for this operand, it returns 7927 /// MVT::Other. 7928 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7929 const DataLayout &DL) const { 7930 if (!CallOperandVal) return MVT::Other; 7931 7932 if (isa<BasicBlock>(CallOperandVal)) 7933 return TLI.getProgramPointerTy(DL); 7934 7935 llvm::Type *OpTy = CallOperandVal->getType(); 7936 7937 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7938 // If this is an indirect operand, the operand is a pointer to the 7939 // accessed type. 7940 if (isIndirect) { 7941 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7942 if (!PtrTy) 7943 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7944 OpTy = PtrTy->getElementType(); 7945 } 7946 7947 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7948 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7949 if (STy->getNumElements() == 1) 7950 OpTy = STy->getElementType(0); 7951 7952 // If OpTy is not a single value, it may be a struct/union that we 7953 // can tile with integers. 7954 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7955 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7956 switch (BitSize) { 7957 default: break; 7958 case 1: 7959 case 8: 7960 case 16: 7961 case 32: 7962 case 64: 7963 case 128: 7964 OpTy = IntegerType::get(Context, BitSize); 7965 break; 7966 } 7967 } 7968 7969 return TLI.getValueType(DL, OpTy, true); 7970 } 7971 }; 7972 7973 7974 } // end anonymous namespace 7975 7976 /// Make sure that the output operand \p OpInfo and its corresponding input 7977 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7978 /// out). 7979 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7980 SDISelAsmOperandInfo &MatchingOpInfo, 7981 SelectionDAG &DAG) { 7982 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7983 return; 7984 7985 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7986 const auto &TLI = DAG.getTargetLoweringInfo(); 7987 7988 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7989 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7990 OpInfo.ConstraintVT); 7991 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7992 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7993 MatchingOpInfo.ConstraintVT); 7994 if ((OpInfo.ConstraintVT.isInteger() != 7995 MatchingOpInfo.ConstraintVT.isInteger()) || 7996 (MatchRC.second != InputRC.second)) { 7997 // FIXME: error out in a more elegant fashion 7998 report_fatal_error("Unsupported asm: input constraint" 7999 " with a matching output constraint of" 8000 " incompatible type!"); 8001 } 8002 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 8003 } 8004 8005 /// Get a direct memory input to behave well as an indirect operand. 8006 /// This may introduce stores, hence the need for a \p Chain. 8007 /// \return The (possibly updated) chain. 8008 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 8009 SDISelAsmOperandInfo &OpInfo, 8010 SelectionDAG &DAG) { 8011 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8012 8013 // If we don't have an indirect input, put it in the constpool if we can, 8014 // otherwise spill it to a stack slot. 8015 // TODO: This isn't quite right. We need to handle these according to 8016 // the addressing mode that the constraint wants. Also, this may take 8017 // an additional register for the computation and we don't want that 8018 // either. 8019 8020 // If the operand is a float, integer, or vector constant, spill to a 8021 // constant pool entry to get its address. 8022 const Value *OpVal = OpInfo.CallOperandVal; 8023 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 8024 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 8025 OpInfo.CallOperand = DAG.getConstantPool( 8026 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 8027 return Chain; 8028 } 8029 8030 // Otherwise, create a stack slot and emit a store to it before the asm. 8031 Type *Ty = OpVal->getType(); 8032 auto &DL = DAG.getDataLayout(); 8033 uint64_t TySize = DL.getTypeAllocSize(Ty); 8034 MachineFunction &MF = DAG.getMachineFunction(); 8035 int SSFI = MF.getFrameInfo().CreateStackObject( 8036 TySize, DL.getPrefTypeAlign(Ty), false); 8037 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 8038 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 8039 MachinePointerInfo::getFixedStack(MF, SSFI), 8040 TLI.getMemValueType(DL, Ty)); 8041 OpInfo.CallOperand = StackSlot; 8042 8043 return Chain; 8044 } 8045 8046 /// GetRegistersForValue - Assign registers (virtual or physical) for the 8047 /// specified operand. We prefer to assign virtual registers, to allow the 8048 /// register allocator to handle the assignment process. However, if the asm 8049 /// uses features that we can't model on machineinstrs, we have SDISel do the 8050 /// allocation. This produces generally horrible, but correct, code. 8051 /// 8052 /// OpInfo describes the operand 8053 /// RefOpInfo describes the matching operand if any, the operand otherwise 8054 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 8055 SDISelAsmOperandInfo &OpInfo, 8056 SDISelAsmOperandInfo &RefOpInfo) { 8057 LLVMContext &Context = *DAG.getContext(); 8058 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8059 8060 MachineFunction &MF = DAG.getMachineFunction(); 8061 SmallVector<unsigned, 4> Regs; 8062 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8063 8064 // No work to do for memory operations. 8065 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 8066 return; 8067 8068 // If this is a constraint for a single physreg, or a constraint for a 8069 // register class, find it. 8070 unsigned AssignedReg; 8071 const TargetRegisterClass *RC; 8072 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 8073 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 8074 // RC is unset only on failure. Return immediately. 8075 if (!RC) 8076 return; 8077 8078 // Get the actual register value type. This is important, because the user 8079 // may have asked for (e.g.) the AX register in i32 type. We need to 8080 // remember that AX is actually i16 to get the right extension. 8081 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 8082 8083 if (OpInfo.ConstraintVT != MVT::Other) { 8084 // If this is an FP operand in an integer register (or visa versa), or more 8085 // generally if the operand value disagrees with the register class we plan 8086 // to stick it in, fix the operand type. 8087 // 8088 // If this is an input value, the bitcast to the new type is done now. 8089 // Bitcast for output value is done at the end of visitInlineAsm(). 8090 if ((OpInfo.Type == InlineAsm::isOutput || 8091 OpInfo.Type == InlineAsm::isInput) && 8092 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 8093 // Try to convert to the first EVT that the reg class contains. If the 8094 // types are identical size, use a bitcast to convert (e.g. two differing 8095 // vector types). Note: output bitcast is done at the end of 8096 // visitInlineAsm(). 8097 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 8098 // Exclude indirect inputs while they are unsupported because the code 8099 // to perform the load is missing and thus OpInfo.CallOperand still 8100 // refers to the input address rather than the pointed-to value. 8101 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 8102 OpInfo.CallOperand = 8103 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 8104 OpInfo.ConstraintVT = RegVT; 8105 // If the operand is an FP value and we want it in integer registers, 8106 // use the corresponding integer type. This turns an f64 value into 8107 // i64, which can be passed with two i32 values on a 32-bit machine. 8108 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 8109 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 8110 if (OpInfo.Type == InlineAsm::isInput) 8111 OpInfo.CallOperand = 8112 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 8113 OpInfo.ConstraintVT = VT; 8114 } 8115 } 8116 } 8117 8118 // No need to allocate a matching input constraint since the constraint it's 8119 // matching to has already been allocated. 8120 if (OpInfo.isMatchingInputConstraint()) 8121 return; 8122 8123 EVT ValueVT = OpInfo.ConstraintVT; 8124 if (OpInfo.ConstraintVT == MVT::Other) 8125 ValueVT = RegVT; 8126 8127 // Initialize NumRegs. 8128 unsigned NumRegs = 1; 8129 if (OpInfo.ConstraintVT != MVT::Other) 8130 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 8131 8132 // If this is a constraint for a specific physical register, like {r17}, 8133 // assign it now. 8134 8135 // If this associated to a specific register, initialize iterator to correct 8136 // place. If virtual, make sure we have enough registers 8137 8138 // Initialize iterator if necessary 8139 TargetRegisterClass::iterator I = RC->begin(); 8140 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 8141 8142 // Do not check for single registers. 8143 if (AssignedReg) { 8144 for (; *I != AssignedReg; ++I) 8145 assert(I != RC->end() && "AssignedReg should be member of RC"); 8146 } 8147 8148 for (; NumRegs; --NumRegs, ++I) { 8149 assert(I != RC->end() && "Ran out of registers to allocate!"); 8150 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 8151 Regs.push_back(R); 8152 } 8153 8154 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 8155 } 8156 8157 static unsigned 8158 findMatchingInlineAsmOperand(unsigned OperandNo, 8159 const std::vector<SDValue> &AsmNodeOperands) { 8160 // Scan until we find the definition we already emitted of this operand. 8161 unsigned CurOp = InlineAsm::Op_FirstOperand; 8162 for (; OperandNo; --OperandNo) { 8163 // Advance to the next operand. 8164 unsigned OpFlag = 8165 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8166 assert((InlineAsm::isRegDefKind(OpFlag) || 8167 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 8168 InlineAsm::isMemKind(OpFlag)) && 8169 "Skipped past definitions?"); 8170 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 8171 } 8172 return CurOp; 8173 } 8174 8175 namespace { 8176 8177 class ExtraFlags { 8178 unsigned Flags = 0; 8179 8180 public: 8181 explicit ExtraFlags(const CallBase &Call) { 8182 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8183 if (IA->hasSideEffects()) 8184 Flags |= InlineAsm::Extra_HasSideEffects; 8185 if (IA->isAlignStack()) 8186 Flags |= InlineAsm::Extra_IsAlignStack; 8187 if (Call.isConvergent()) 8188 Flags |= InlineAsm::Extra_IsConvergent; 8189 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8190 } 8191 8192 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8193 // Ideally, we would only check against memory constraints. However, the 8194 // meaning of an Other constraint can be target-specific and we can't easily 8195 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8196 // for Other constraints as well. 8197 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8198 OpInfo.ConstraintType == TargetLowering::C_Other) { 8199 if (OpInfo.Type == InlineAsm::isInput) 8200 Flags |= InlineAsm::Extra_MayLoad; 8201 else if (OpInfo.Type == InlineAsm::isOutput) 8202 Flags |= InlineAsm::Extra_MayStore; 8203 else if (OpInfo.Type == InlineAsm::isClobber) 8204 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8205 } 8206 } 8207 8208 unsigned get() const { return Flags; } 8209 }; 8210 8211 } // end anonymous namespace 8212 8213 /// visitInlineAsm - Handle a call to an InlineAsm object. 8214 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) { 8215 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand()); 8216 8217 /// ConstraintOperands - Information about all of the constraints. 8218 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands; 8219 8220 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8221 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8222 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call); 8223 8224 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8225 // AsmDialect, MayLoad, MayStore). 8226 bool HasSideEffect = IA->hasSideEffects(); 8227 ExtraFlags ExtraInfo(Call); 8228 8229 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8230 unsigned ResNo = 0; // ResNo - The result number of the next output. 8231 unsigned NumMatchingOps = 0; 8232 for (auto &T : TargetConstraints) { 8233 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8234 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8235 8236 // Compute the value type for each operand. 8237 if (OpInfo.Type == InlineAsm::isInput || 8238 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8239 OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++); 8240 8241 // Process the call argument. BasicBlocks are labels, currently appearing 8242 // only in asm's. 8243 if (isa<CallBrInst>(Call) && 8244 ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() - 8245 cast<CallBrInst>(&Call)->getNumIndirectDests() - 8246 NumMatchingOps) && 8247 (NumMatchingOps == 0 || 8248 ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() - 8249 NumMatchingOps))) { 8250 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8251 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8252 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8253 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8254 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8255 } else { 8256 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8257 } 8258 8259 EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, 8260 DAG.getDataLayout()); 8261 OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other; 8262 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8263 // The return value of the call is this value. As such, there is no 8264 // corresponding argument. 8265 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8266 if (StructType *STy = dyn_cast<StructType>(Call.getType())) { 8267 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8268 DAG.getDataLayout(), STy->getElementType(ResNo)); 8269 } else { 8270 assert(ResNo == 0 && "Asm only has one result!"); 8271 OpInfo.ConstraintVT = 8272 TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType()); 8273 } 8274 ++ResNo; 8275 } else { 8276 OpInfo.ConstraintVT = MVT::Other; 8277 } 8278 8279 if (OpInfo.hasMatchingInput()) 8280 ++NumMatchingOps; 8281 8282 if (!HasSideEffect) 8283 HasSideEffect = OpInfo.hasMemory(TLI); 8284 8285 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8286 // FIXME: Could we compute this on OpInfo rather than T? 8287 8288 // Compute the constraint code and ConstraintType to use. 8289 TLI.ComputeConstraintToUse(T, SDValue()); 8290 8291 if (T.ConstraintType == TargetLowering::C_Immediate && 8292 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8293 // We've delayed emitting a diagnostic like the "n" constraint because 8294 // inlining could cause an integer showing up. 8295 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) + 8296 "' expects an integer constant " 8297 "expression"); 8298 8299 ExtraInfo.update(T); 8300 } 8301 8302 8303 // We won't need to flush pending loads if this asm doesn't touch 8304 // memory and is nonvolatile. 8305 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8306 8307 bool IsCallBr = isa<CallBrInst>(Call); 8308 if (IsCallBr) { 8309 // If this is a callbr we need to flush pending exports since inlineasm_br 8310 // is a terminator. We need to do this before nodes are glued to 8311 // the inlineasm_br node. 8312 Chain = getControlRoot(); 8313 } 8314 8315 // Second pass over the constraints: compute which constraint option to use. 8316 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8317 // If this is an output operand with a matching input operand, look up the 8318 // matching input. If their types mismatch, e.g. one is an integer, the 8319 // other is floating point, or their sizes are different, flag it as an 8320 // error. 8321 if (OpInfo.hasMatchingInput()) { 8322 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8323 patchMatchingInput(OpInfo, Input, DAG); 8324 } 8325 8326 // Compute the constraint code and ConstraintType to use. 8327 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8328 8329 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8330 OpInfo.Type == InlineAsm::isClobber) 8331 continue; 8332 8333 // If this is a memory input, and if the operand is not indirect, do what we 8334 // need to provide an address for the memory input. 8335 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8336 !OpInfo.isIndirect) { 8337 assert((OpInfo.isMultipleAlternative || 8338 (OpInfo.Type == InlineAsm::isInput)) && 8339 "Can only indirectify direct input operands!"); 8340 8341 // Memory operands really want the address of the value. 8342 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8343 8344 // There is no longer a Value* corresponding to this operand. 8345 OpInfo.CallOperandVal = nullptr; 8346 8347 // It is now an indirect operand. 8348 OpInfo.isIndirect = true; 8349 } 8350 8351 } 8352 8353 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8354 std::vector<SDValue> AsmNodeOperands; 8355 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8356 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8357 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout()))); 8358 8359 // If we have a !srcloc metadata node associated with it, we want to attach 8360 // this to the ultimately generated inline asm machineinstr. To do this, we 8361 // pass in the third operand as this (potentially null) inline asm MDNode. 8362 const MDNode *SrcLoc = Call.getMetadata("srcloc"); 8363 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8364 8365 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8366 // bits as operand 3. 8367 AsmNodeOperands.push_back(DAG.getTargetConstant( 8368 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8369 8370 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8371 // this, assign virtual and physical registers for inputs and otput. 8372 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8373 // Assign Registers. 8374 SDISelAsmOperandInfo &RefOpInfo = 8375 OpInfo.isMatchingInputConstraint() 8376 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8377 : OpInfo; 8378 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8379 8380 auto DetectWriteToReservedRegister = [&]() { 8381 const MachineFunction &MF = DAG.getMachineFunction(); 8382 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 8383 for (unsigned Reg : OpInfo.AssignedRegs.Regs) { 8384 if (Register::isPhysicalRegister(Reg) && 8385 TRI.isInlineAsmReadOnlyReg(MF, Reg)) { 8386 const char *RegName = TRI.getName(Reg); 8387 emitInlineAsmError(Call, "write to reserved register '" + 8388 Twine(RegName) + "'"); 8389 return true; 8390 } 8391 } 8392 return false; 8393 }; 8394 8395 switch (OpInfo.Type) { 8396 case InlineAsm::isOutput: 8397 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8398 unsigned ConstraintID = 8399 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8400 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8401 "Failed to convert memory constraint code to constraint id."); 8402 8403 // Add information to the INLINEASM node to know about this output. 8404 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8405 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8406 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8407 MVT::i32)); 8408 AsmNodeOperands.push_back(OpInfo.CallOperand); 8409 } else { 8410 // Otherwise, this outputs to a register (directly for C_Register / 8411 // C_RegisterClass, and a target-defined fashion for 8412 // C_Immediate/C_Other). Find a register that we can use. 8413 if (OpInfo.AssignedRegs.Regs.empty()) { 8414 emitInlineAsmError( 8415 Call, "couldn't allocate output register for constraint '" + 8416 Twine(OpInfo.ConstraintCode) + "'"); 8417 return; 8418 } 8419 8420 if (DetectWriteToReservedRegister()) 8421 return; 8422 8423 // Add information to the INLINEASM node to know that this register is 8424 // set. 8425 OpInfo.AssignedRegs.AddInlineAsmOperands( 8426 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8427 : InlineAsm::Kind_RegDef, 8428 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8429 } 8430 break; 8431 8432 case InlineAsm::isInput: { 8433 SDValue InOperandVal = OpInfo.CallOperand; 8434 8435 if (OpInfo.isMatchingInputConstraint()) { 8436 // If this is required to match an output register we have already set, 8437 // just use its register. 8438 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8439 AsmNodeOperands); 8440 unsigned OpFlag = 8441 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8442 if (InlineAsm::isRegDefKind(OpFlag) || 8443 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8444 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8445 if (OpInfo.isIndirect) { 8446 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8447 emitInlineAsmError(Call, "inline asm not supported yet: " 8448 "don't know how to handle tied " 8449 "indirect register inputs"); 8450 return; 8451 } 8452 8453 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8454 SmallVector<unsigned, 4> Regs; 8455 8456 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8457 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8458 MachineRegisterInfo &RegInfo = 8459 DAG.getMachineFunction().getRegInfo(); 8460 for (unsigned i = 0; i != NumRegs; ++i) 8461 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8462 } else { 8463 emitInlineAsmError(Call, 8464 "inline asm error: This value type register " 8465 "class is not natively supported!"); 8466 return; 8467 } 8468 8469 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8470 8471 SDLoc dl = getCurSDLoc(); 8472 // Use the produced MatchedRegs object to 8473 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call); 8474 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8475 true, OpInfo.getMatchedOperand(), dl, 8476 DAG, AsmNodeOperands); 8477 break; 8478 } 8479 8480 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8481 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8482 "Unexpected number of operands"); 8483 // Add information to the INLINEASM node to know about this input. 8484 // See InlineAsm.h isUseOperandTiedToDef. 8485 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8486 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8487 OpInfo.getMatchedOperand()); 8488 AsmNodeOperands.push_back(DAG.getTargetConstant( 8489 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8490 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8491 break; 8492 } 8493 8494 // Treat indirect 'X' constraint as memory. 8495 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8496 OpInfo.isIndirect) 8497 OpInfo.ConstraintType = TargetLowering::C_Memory; 8498 8499 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8500 OpInfo.ConstraintType == TargetLowering::C_Other) { 8501 std::vector<SDValue> Ops; 8502 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8503 Ops, DAG); 8504 if (Ops.empty()) { 8505 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8506 if (isa<ConstantSDNode>(InOperandVal)) { 8507 emitInlineAsmError(Call, "value out of range for constraint '" + 8508 Twine(OpInfo.ConstraintCode) + "'"); 8509 return; 8510 } 8511 8512 emitInlineAsmError(Call, 8513 "invalid operand for inline asm constraint '" + 8514 Twine(OpInfo.ConstraintCode) + "'"); 8515 return; 8516 } 8517 8518 // Add information to the INLINEASM node to know about this input. 8519 unsigned ResOpType = 8520 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8521 AsmNodeOperands.push_back(DAG.getTargetConstant( 8522 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8523 llvm::append_range(AsmNodeOperands, Ops); 8524 break; 8525 } 8526 8527 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8528 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8529 assert(InOperandVal.getValueType() == 8530 TLI.getPointerTy(DAG.getDataLayout()) && 8531 "Memory operands expect pointer values"); 8532 8533 unsigned ConstraintID = 8534 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8535 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8536 "Failed to convert memory constraint code to constraint id."); 8537 8538 // Add information to the INLINEASM node to know about this input. 8539 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8540 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8541 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8542 getCurSDLoc(), 8543 MVT::i32)); 8544 AsmNodeOperands.push_back(InOperandVal); 8545 break; 8546 } 8547 8548 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8549 OpInfo.ConstraintType == TargetLowering::C_Register) && 8550 "Unknown constraint type!"); 8551 8552 // TODO: Support this. 8553 if (OpInfo.isIndirect) { 8554 emitInlineAsmError( 8555 Call, "Don't know how to handle indirect register inputs yet " 8556 "for constraint '" + 8557 Twine(OpInfo.ConstraintCode) + "'"); 8558 return; 8559 } 8560 8561 // Copy the input into the appropriate registers. 8562 if (OpInfo.AssignedRegs.Regs.empty()) { 8563 emitInlineAsmError(Call, 8564 "couldn't allocate input reg for constraint '" + 8565 Twine(OpInfo.ConstraintCode) + "'"); 8566 return; 8567 } 8568 8569 if (DetectWriteToReservedRegister()) 8570 return; 8571 8572 SDLoc dl = getCurSDLoc(); 8573 8574 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8575 &Call); 8576 8577 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8578 dl, DAG, AsmNodeOperands); 8579 break; 8580 } 8581 case InlineAsm::isClobber: 8582 // Add the clobbered value to the operand list, so that the register 8583 // allocator is aware that the physreg got clobbered. 8584 if (!OpInfo.AssignedRegs.Regs.empty()) 8585 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8586 false, 0, getCurSDLoc(), DAG, 8587 AsmNodeOperands); 8588 break; 8589 } 8590 } 8591 8592 // Finish up input operands. Set the input chain and add the flag last. 8593 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8594 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8595 8596 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8597 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8598 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8599 Flag = Chain.getValue(1); 8600 8601 // Do additional work to generate outputs. 8602 8603 SmallVector<EVT, 1> ResultVTs; 8604 SmallVector<SDValue, 1> ResultValues; 8605 SmallVector<SDValue, 8> OutChains; 8606 8607 llvm::Type *CallResultType = Call.getType(); 8608 ArrayRef<Type *> ResultTypes; 8609 if (StructType *StructResult = dyn_cast<StructType>(CallResultType)) 8610 ResultTypes = StructResult->elements(); 8611 else if (!CallResultType->isVoidTy()) 8612 ResultTypes = makeArrayRef(CallResultType); 8613 8614 auto CurResultType = ResultTypes.begin(); 8615 auto handleRegAssign = [&](SDValue V) { 8616 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8617 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8618 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8619 ++CurResultType; 8620 // If the type of the inline asm call site return value is different but has 8621 // same size as the type of the asm output bitcast it. One example of this 8622 // is for vectors with different width / number of elements. This can 8623 // happen for register classes that can contain multiple different value 8624 // types. The preg or vreg allocated may not have the same VT as was 8625 // expected. 8626 // 8627 // This can also happen for a return value that disagrees with the register 8628 // class it is put in, eg. a double in a general-purpose register on a 8629 // 32-bit machine. 8630 if (ResultVT != V.getValueType() && 8631 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8632 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8633 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8634 V.getValueType().isInteger()) { 8635 // If a result value was tied to an input value, the computed result 8636 // may have a wider width than the expected result. Extract the 8637 // relevant portion. 8638 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8639 } 8640 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8641 ResultVTs.push_back(ResultVT); 8642 ResultValues.push_back(V); 8643 }; 8644 8645 // Deal with output operands. 8646 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8647 if (OpInfo.Type == InlineAsm::isOutput) { 8648 SDValue Val; 8649 // Skip trivial output operands. 8650 if (OpInfo.AssignedRegs.Regs.empty()) 8651 continue; 8652 8653 switch (OpInfo.ConstraintType) { 8654 case TargetLowering::C_Register: 8655 case TargetLowering::C_RegisterClass: 8656 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 8657 Chain, &Flag, &Call); 8658 break; 8659 case TargetLowering::C_Immediate: 8660 case TargetLowering::C_Other: 8661 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8662 OpInfo, DAG); 8663 break; 8664 case TargetLowering::C_Memory: 8665 break; // Already handled. 8666 case TargetLowering::C_Unknown: 8667 assert(false && "Unexpected unknown constraint"); 8668 } 8669 8670 // Indirect output manifest as stores. Record output chains. 8671 if (OpInfo.isIndirect) { 8672 const Value *Ptr = OpInfo.CallOperandVal; 8673 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8674 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8675 MachinePointerInfo(Ptr)); 8676 OutChains.push_back(Store); 8677 } else { 8678 // generate CopyFromRegs to associated registers. 8679 assert(!Call.getType()->isVoidTy() && "Bad inline asm!"); 8680 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8681 for (const SDValue &V : Val->op_values()) 8682 handleRegAssign(V); 8683 } else 8684 handleRegAssign(Val); 8685 } 8686 } 8687 } 8688 8689 // Set results. 8690 if (!ResultValues.empty()) { 8691 assert(CurResultType == ResultTypes.end() && 8692 "Mismatch in number of ResultTypes"); 8693 assert(ResultValues.size() == ResultTypes.size() && 8694 "Mismatch in number of output operands in asm result"); 8695 8696 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8697 DAG.getVTList(ResultVTs), ResultValues); 8698 setValue(&Call, V); 8699 } 8700 8701 // Collect store chains. 8702 if (!OutChains.empty()) 8703 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8704 8705 // Only Update Root if inline assembly has a memory effect. 8706 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8707 DAG.setRoot(Chain); 8708 } 8709 8710 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call, 8711 const Twine &Message) { 8712 LLVMContext &Ctx = *DAG.getContext(); 8713 Ctx.emitError(&Call, Message); 8714 8715 // Make sure we leave the DAG in a valid state 8716 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8717 SmallVector<EVT, 1> ValueVTs; 8718 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs); 8719 8720 if (ValueVTs.empty()) 8721 return; 8722 8723 SmallVector<SDValue, 1> Ops; 8724 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8725 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8726 8727 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc())); 8728 } 8729 8730 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8731 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8732 MVT::Other, getRoot(), 8733 getValue(I.getArgOperand(0)), 8734 DAG.getSrcValue(I.getArgOperand(0)))); 8735 } 8736 8737 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8738 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8739 const DataLayout &DL = DAG.getDataLayout(); 8740 SDValue V = DAG.getVAArg( 8741 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8742 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8743 DL.getABITypeAlign(I.getType()).value()); 8744 DAG.setRoot(V.getValue(1)); 8745 8746 if (I.getType()->isPointerTy()) 8747 V = DAG.getPtrExtOrTrunc( 8748 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8749 setValue(&I, V); 8750 } 8751 8752 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8753 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8754 MVT::Other, getRoot(), 8755 getValue(I.getArgOperand(0)), 8756 DAG.getSrcValue(I.getArgOperand(0)))); 8757 } 8758 8759 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8760 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8761 MVT::Other, getRoot(), 8762 getValue(I.getArgOperand(0)), 8763 getValue(I.getArgOperand(1)), 8764 DAG.getSrcValue(I.getArgOperand(0)), 8765 DAG.getSrcValue(I.getArgOperand(1)))); 8766 } 8767 8768 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8769 const Instruction &I, 8770 SDValue Op) { 8771 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8772 if (!Range) 8773 return Op; 8774 8775 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8776 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8777 return Op; 8778 8779 APInt Lo = CR.getUnsignedMin(); 8780 if (!Lo.isMinValue()) 8781 return Op; 8782 8783 APInt Hi = CR.getUnsignedMax(); 8784 unsigned Bits = std::max(Hi.getActiveBits(), 8785 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8786 8787 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8788 8789 SDLoc SL = getCurSDLoc(); 8790 8791 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8792 DAG.getValueType(SmallVT)); 8793 unsigned NumVals = Op.getNode()->getNumValues(); 8794 if (NumVals == 1) 8795 return ZExt; 8796 8797 SmallVector<SDValue, 4> Ops; 8798 8799 Ops.push_back(ZExt); 8800 for (unsigned I = 1; I != NumVals; ++I) 8801 Ops.push_back(Op.getValue(I)); 8802 8803 return DAG.getMergeValues(Ops, SL); 8804 } 8805 8806 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8807 /// the call being lowered. 8808 /// 8809 /// This is a helper for lowering intrinsics that follow a target calling 8810 /// convention or require stack pointer adjustment. Only a subset of the 8811 /// intrinsic's operands need to participate in the calling convention. 8812 void SelectionDAGBuilder::populateCallLoweringInfo( 8813 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8814 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8815 bool IsPatchPoint) { 8816 TargetLowering::ArgListTy Args; 8817 Args.reserve(NumArgs); 8818 8819 // Populate the argument list. 8820 // Attributes for args start at offset 1, after the return attribute. 8821 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8822 ArgI != ArgE; ++ArgI) { 8823 const Value *V = Call->getOperand(ArgI); 8824 8825 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8826 8827 TargetLowering::ArgListEntry Entry; 8828 Entry.Node = getValue(V); 8829 Entry.Ty = V->getType(); 8830 Entry.setAttributes(Call, ArgI); 8831 Args.push_back(Entry); 8832 } 8833 8834 CLI.setDebugLoc(getCurSDLoc()) 8835 .setChain(getRoot()) 8836 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8837 .setDiscardResult(Call->use_empty()) 8838 .setIsPatchPoint(IsPatchPoint) 8839 .setIsPreallocated( 8840 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0); 8841 } 8842 8843 /// Add a stack map intrinsic call's live variable operands to a stackmap 8844 /// or patchpoint target node's operand list. 8845 /// 8846 /// Constants are converted to TargetConstants purely as an optimization to 8847 /// avoid constant materialization and register allocation. 8848 /// 8849 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8850 /// generate addess computation nodes, and so FinalizeISel can convert the 8851 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8852 /// address materialization and register allocation, but may also be required 8853 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8854 /// alloca in the entry block, then the runtime may assume that the alloca's 8855 /// StackMap location can be read immediately after compilation and that the 8856 /// location is valid at any point during execution (this is similar to the 8857 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8858 /// only available in a register, then the runtime would need to trap when 8859 /// execution reaches the StackMap in order to read the alloca's location. 8860 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx, 8861 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8862 SelectionDAGBuilder &Builder) { 8863 for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) { 8864 SDValue OpVal = Builder.getValue(Call.getArgOperand(i)); 8865 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8866 Ops.push_back( 8867 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8868 Ops.push_back( 8869 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8870 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8871 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8872 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8873 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8874 } else 8875 Ops.push_back(OpVal); 8876 } 8877 } 8878 8879 /// Lower llvm.experimental.stackmap directly to its target opcode. 8880 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8881 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8882 // [live variables...]) 8883 8884 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8885 8886 SDValue Chain, InFlag, Callee, NullPtr; 8887 SmallVector<SDValue, 32> Ops; 8888 8889 SDLoc DL = getCurSDLoc(); 8890 Callee = getValue(CI.getCalledOperand()); 8891 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8892 8893 // The stackmap intrinsic only records the live variables (the arguments 8894 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8895 // intrinsic, this won't be lowered to a function call. This means we don't 8896 // have to worry about calling conventions and target specific lowering code. 8897 // Instead we perform the call lowering right here. 8898 // 8899 // chain, flag = CALLSEQ_START(chain, 0, 0) 8900 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8901 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8902 // 8903 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8904 InFlag = Chain.getValue(1); 8905 8906 // Add the <id> and <numBytes> constants. 8907 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8908 Ops.push_back(DAG.getTargetConstant( 8909 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8910 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8911 Ops.push_back(DAG.getTargetConstant( 8912 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8913 MVT::i32)); 8914 8915 // Push live variables for the stack map. 8916 addStackMapLiveVars(CI, 2, DL, Ops, *this); 8917 8918 // We are not pushing any register mask info here on the operands list, 8919 // because the stackmap doesn't clobber anything. 8920 8921 // Push the chain and the glue flag. 8922 Ops.push_back(Chain); 8923 Ops.push_back(InFlag); 8924 8925 // Create the STACKMAP node. 8926 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8927 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8928 Chain = SDValue(SM, 0); 8929 InFlag = Chain.getValue(1); 8930 8931 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8932 8933 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8934 8935 // Set the root to the target-lowered call chain. 8936 DAG.setRoot(Chain); 8937 8938 // Inform the Frame Information that we have a stackmap in this function. 8939 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8940 } 8941 8942 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8943 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB, 8944 const BasicBlock *EHPadBB) { 8945 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8946 // i32 <numBytes>, 8947 // i8* <target>, 8948 // i32 <numArgs>, 8949 // [Args...], 8950 // [live variables...]) 8951 8952 CallingConv::ID CC = CB.getCallingConv(); 8953 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8954 bool HasDef = !CB.getType()->isVoidTy(); 8955 SDLoc dl = getCurSDLoc(); 8956 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos)); 8957 8958 // Handle immediate and symbolic callees. 8959 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8960 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8961 /*isTarget=*/true); 8962 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8963 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8964 SDLoc(SymbolicCallee), 8965 SymbolicCallee->getValueType(0)); 8966 8967 // Get the real number of arguments participating in the call <numArgs> 8968 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos)); 8969 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8970 8971 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8972 // Intrinsics include all meta-operands up to but not including CC. 8973 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8974 assert(CB.arg_size() >= NumMetaOpers + NumArgs && 8975 "Not enough arguments provided to the patchpoint intrinsic"); 8976 8977 // For AnyRegCC the arguments are lowered later on manually. 8978 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8979 Type *ReturnTy = 8980 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType(); 8981 8982 TargetLowering::CallLoweringInfo CLI(DAG); 8983 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee, 8984 ReturnTy, true); 8985 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8986 8987 SDNode *CallEnd = Result.second.getNode(); 8988 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8989 CallEnd = CallEnd->getOperand(0).getNode(); 8990 8991 /// Get a call instruction from the call sequence chain. 8992 /// Tail calls are not allowed. 8993 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8994 "Expected a callseq node."); 8995 SDNode *Call = CallEnd->getOperand(0).getNode(); 8996 bool HasGlue = Call->getGluedNode(); 8997 8998 // Replace the target specific call node with the patchable intrinsic. 8999 SmallVector<SDValue, 8> Ops; 9000 9001 // Add the <id> and <numBytes> constants. 9002 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos)); 9003 Ops.push_back(DAG.getTargetConstant( 9004 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 9005 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos)); 9006 Ops.push_back(DAG.getTargetConstant( 9007 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 9008 MVT::i32)); 9009 9010 // Add the callee. 9011 Ops.push_back(Callee); 9012 9013 // Adjust <numArgs> to account for any arguments that have been passed on the 9014 // stack instead. 9015 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 9016 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 9017 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 9018 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 9019 9020 // Add the calling convention 9021 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 9022 9023 // Add the arguments we omitted previously. The register allocator should 9024 // place these in any free register. 9025 if (IsAnyRegCC) 9026 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 9027 Ops.push_back(getValue(CB.getArgOperand(i))); 9028 9029 // Push the arguments from the call instruction up to the register mask. 9030 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 9031 Ops.append(Call->op_begin() + 2, e); 9032 9033 // Push live variables for the stack map. 9034 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this); 9035 9036 // Push the register mask info. 9037 if (HasGlue) 9038 Ops.push_back(*(Call->op_end()-2)); 9039 else 9040 Ops.push_back(*(Call->op_end()-1)); 9041 9042 // Push the chain (this is originally the first operand of the call, but 9043 // becomes now the last or second to last operand). 9044 Ops.push_back(*(Call->op_begin())); 9045 9046 // Push the glue flag (last operand). 9047 if (HasGlue) 9048 Ops.push_back(*(Call->op_end()-1)); 9049 9050 SDVTList NodeTys; 9051 if (IsAnyRegCC && HasDef) { 9052 // Create the return types based on the intrinsic definition 9053 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9054 SmallVector<EVT, 3> ValueVTs; 9055 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs); 9056 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 9057 9058 // There is always a chain and a glue type at the end 9059 ValueVTs.push_back(MVT::Other); 9060 ValueVTs.push_back(MVT::Glue); 9061 NodeTys = DAG.getVTList(ValueVTs); 9062 } else 9063 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 9064 9065 // Replace the target specific call node with a PATCHPOINT node. 9066 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 9067 dl, NodeTys, Ops); 9068 9069 // Update the NodeMap. 9070 if (HasDef) { 9071 if (IsAnyRegCC) 9072 setValue(&CB, SDValue(MN, 0)); 9073 else 9074 setValue(&CB, Result.first); 9075 } 9076 9077 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 9078 // call sequence. Furthermore the location of the chain and glue can change 9079 // when the AnyReg calling convention is used and the intrinsic returns a 9080 // value. 9081 if (IsAnyRegCC && HasDef) { 9082 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 9083 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 9084 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 9085 } else 9086 DAG.ReplaceAllUsesWith(Call, MN); 9087 DAG.DeleteNode(Call); 9088 9089 // Inform the Frame Information that we have a patchpoint in this function. 9090 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 9091 } 9092 9093 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 9094 unsigned Intrinsic) { 9095 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9096 SDValue Op1 = getValue(I.getArgOperand(0)); 9097 SDValue Op2; 9098 if (I.getNumArgOperands() > 1) 9099 Op2 = getValue(I.getArgOperand(1)); 9100 SDLoc dl = getCurSDLoc(); 9101 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 9102 SDValue Res; 9103 SDNodeFlags SDFlags; 9104 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) 9105 SDFlags.copyFMF(*FPMO); 9106 9107 switch (Intrinsic) { 9108 case Intrinsic::vector_reduce_fadd: 9109 if (SDFlags.hasAllowReassociation()) 9110 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 9111 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags), 9112 SDFlags); 9113 else 9114 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags); 9115 break; 9116 case Intrinsic::vector_reduce_fmul: 9117 if (SDFlags.hasAllowReassociation()) 9118 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 9119 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags), 9120 SDFlags); 9121 else 9122 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags); 9123 break; 9124 case Intrinsic::vector_reduce_add: 9125 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 9126 break; 9127 case Intrinsic::vector_reduce_mul: 9128 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 9129 break; 9130 case Intrinsic::vector_reduce_and: 9131 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 9132 break; 9133 case Intrinsic::vector_reduce_or: 9134 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 9135 break; 9136 case Intrinsic::vector_reduce_xor: 9137 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 9138 break; 9139 case Intrinsic::vector_reduce_smax: 9140 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 9141 break; 9142 case Intrinsic::vector_reduce_smin: 9143 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 9144 break; 9145 case Intrinsic::vector_reduce_umax: 9146 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 9147 break; 9148 case Intrinsic::vector_reduce_umin: 9149 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 9150 break; 9151 case Intrinsic::vector_reduce_fmax: 9152 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 9153 break; 9154 case Intrinsic::vector_reduce_fmin: 9155 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 9156 break; 9157 default: 9158 llvm_unreachable("Unhandled vector reduce intrinsic"); 9159 } 9160 setValue(&I, Res); 9161 } 9162 9163 /// Returns an AttributeList representing the attributes applied to the return 9164 /// value of the given call. 9165 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 9166 SmallVector<Attribute::AttrKind, 2> Attrs; 9167 if (CLI.RetSExt) 9168 Attrs.push_back(Attribute::SExt); 9169 if (CLI.RetZExt) 9170 Attrs.push_back(Attribute::ZExt); 9171 if (CLI.IsInReg) 9172 Attrs.push_back(Attribute::InReg); 9173 9174 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 9175 Attrs); 9176 } 9177 9178 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 9179 /// implementation, which just calls LowerCall. 9180 /// FIXME: When all targets are 9181 /// migrated to using LowerCall, this hook should be integrated into SDISel. 9182 std::pair<SDValue, SDValue> 9183 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 9184 // Handle the incoming return values from the call. 9185 CLI.Ins.clear(); 9186 Type *OrigRetTy = CLI.RetTy; 9187 SmallVector<EVT, 4> RetTys; 9188 SmallVector<uint64_t, 4> Offsets; 9189 auto &DL = CLI.DAG.getDataLayout(); 9190 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 9191 9192 if (CLI.IsPostTypeLegalization) { 9193 // If we are lowering a libcall after legalization, split the return type. 9194 SmallVector<EVT, 4> OldRetTys; 9195 SmallVector<uint64_t, 4> OldOffsets; 9196 RetTys.swap(OldRetTys); 9197 Offsets.swap(OldOffsets); 9198 9199 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 9200 EVT RetVT = OldRetTys[i]; 9201 uint64_t Offset = OldOffsets[i]; 9202 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 9203 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 9204 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 9205 RetTys.append(NumRegs, RegisterVT); 9206 for (unsigned j = 0; j != NumRegs; ++j) 9207 Offsets.push_back(Offset + j * RegisterVTByteSZ); 9208 } 9209 } 9210 9211 SmallVector<ISD::OutputArg, 4> Outs; 9212 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9213 9214 bool CanLowerReturn = 9215 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9216 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9217 9218 SDValue DemoteStackSlot; 9219 int DemoteStackIdx = -100; 9220 if (!CanLowerReturn) { 9221 // FIXME: equivalent assert? 9222 // assert(!CS.hasInAllocaArgument() && 9223 // "sret demotion is incompatible with inalloca"); 9224 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9225 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy); 9226 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9227 DemoteStackIdx = 9228 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false); 9229 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9230 DL.getAllocaAddrSpace()); 9231 9232 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9233 ArgListEntry Entry; 9234 Entry.Node = DemoteStackSlot; 9235 Entry.Ty = StackSlotPtrType; 9236 Entry.IsSExt = false; 9237 Entry.IsZExt = false; 9238 Entry.IsInReg = false; 9239 Entry.IsSRet = true; 9240 Entry.IsNest = false; 9241 Entry.IsByVal = false; 9242 Entry.IsByRef = false; 9243 Entry.IsReturned = false; 9244 Entry.IsSwiftSelf = false; 9245 Entry.IsSwiftError = false; 9246 Entry.IsCFGuardTarget = false; 9247 Entry.Alignment = Alignment; 9248 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9249 CLI.NumFixedArgs += 1; 9250 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9251 9252 // sret demotion isn't compatible with tail-calls, since the sret argument 9253 // points into the callers stack frame. 9254 CLI.IsTailCall = false; 9255 } else { 9256 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9257 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9258 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9259 ISD::ArgFlagsTy Flags; 9260 if (NeedsRegBlock) { 9261 Flags.setInConsecutiveRegs(); 9262 if (I == RetTys.size() - 1) 9263 Flags.setInConsecutiveRegsLast(); 9264 } 9265 EVT VT = RetTys[I]; 9266 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9267 CLI.CallConv, VT); 9268 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9269 CLI.CallConv, VT); 9270 for (unsigned i = 0; i != NumRegs; ++i) { 9271 ISD::InputArg MyFlags; 9272 MyFlags.Flags = Flags; 9273 MyFlags.VT = RegisterVT; 9274 MyFlags.ArgVT = VT; 9275 MyFlags.Used = CLI.IsReturnValueUsed; 9276 if (CLI.RetTy->isPointerTy()) { 9277 MyFlags.Flags.setPointer(); 9278 MyFlags.Flags.setPointerAddrSpace( 9279 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9280 } 9281 if (CLI.RetSExt) 9282 MyFlags.Flags.setSExt(); 9283 if (CLI.RetZExt) 9284 MyFlags.Flags.setZExt(); 9285 if (CLI.IsInReg) 9286 MyFlags.Flags.setInReg(); 9287 CLI.Ins.push_back(MyFlags); 9288 } 9289 } 9290 } 9291 9292 // We push in swifterror return as the last element of CLI.Ins. 9293 ArgListTy &Args = CLI.getArgs(); 9294 if (supportSwiftError()) { 9295 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9296 if (Args[i].IsSwiftError) { 9297 ISD::InputArg MyFlags; 9298 MyFlags.VT = getPointerTy(DL); 9299 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9300 MyFlags.Flags.setSwiftError(); 9301 CLI.Ins.push_back(MyFlags); 9302 } 9303 } 9304 } 9305 9306 // Handle all of the outgoing arguments. 9307 CLI.Outs.clear(); 9308 CLI.OutVals.clear(); 9309 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9310 SmallVector<EVT, 4> ValueVTs; 9311 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9312 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9313 Type *FinalType = Args[i].Ty; 9314 if (Args[i].IsByVal) 9315 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9316 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9317 FinalType, CLI.CallConv, CLI.IsVarArg); 9318 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9319 ++Value) { 9320 EVT VT = ValueVTs[Value]; 9321 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9322 SDValue Op = SDValue(Args[i].Node.getNode(), 9323 Args[i].Node.getResNo() + Value); 9324 ISD::ArgFlagsTy Flags; 9325 9326 // Certain targets (such as MIPS), may have a different ABI alignment 9327 // for a type depending on the context. Give the target a chance to 9328 // specify the alignment it wants. 9329 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9330 9331 if (Args[i].Ty->isPointerTy()) { 9332 Flags.setPointer(); 9333 Flags.setPointerAddrSpace( 9334 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9335 } 9336 if (Args[i].IsZExt) 9337 Flags.setZExt(); 9338 if (Args[i].IsSExt) 9339 Flags.setSExt(); 9340 if (Args[i].IsInReg) { 9341 // If we are using vectorcall calling convention, a structure that is 9342 // passed InReg - is surely an HVA 9343 if (CLI.CallConv == CallingConv::X86_VectorCall && 9344 isa<StructType>(FinalType)) { 9345 // The first value of a structure is marked 9346 if (0 == Value) 9347 Flags.setHvaStart(); 9348 Flags.setHva(); 9349 } 9350 // Set InReg Flag 9351 Flags.setInReg(); 9352 } 9353 if (Args[i].IsSRet) 9354 Flags.setSRet(); 9355 if (Args[i].IsSwiftSelf) 9356 Flags.setSwiftSelf(); 9357 if (Args[i].IsSwiftError) 9358 Flags.setSwiftError(); 9359 if (Args[i].IsCFGuardTarget) 9360 Flags.setCFGuardTarget(); 9361 if (Args[i].IsByVal) 9362 Flags.setByVal(); 9363 if (Args[i].IsByRef) 9364 Flags.setByRef(); 9365 if (Args[i].IsPreallocated) { 9366 Flags.setPreallocated(); 9367 // Set the byval flag for CCAssignFn callbacks that don't know about 9368 // preallocated. This way we can know how many bytes we should've 9369 // allocated and how many bytes a callee cleanup function will pop. If 9370 // we port preallocated to more targets, we'll have to add custom 9371 // preallocated handling in the various CC lowering callbacks. 9372 Flags.setByVal(); 9373 } 9374 if (Args[i].IsInAlloca) { 9375 Flags.setInAlloca(); 9376 // Set the byval flag for CCAssignFn callbacks that don't know about 9377 // inalloca. This way we can know how many bytes we should've allocated 9378 // and how many bytes a callee cleanup function will pop. If we port 9379 // inalloca to more targets, we'll have to add custom inalloca handling 9380 // in the various CC lowering callbacks. 9381 Flags.setByVal(); 9382 } 9383 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) { 9384 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9385 Type *ElementTy = Ty->getElementType(); 9386 9387 unsigned FrameSize = DL.getTypeAllocSize( 9388 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9389 Flags.setByValSize(FrameSize); 9390 9391 // info is not there but there are cases it cannot get right. 9392 Align FrameAlign; 9393 if (auto MA = Args[i].Alignment) 9394 FrameAlign = *MA; 9395 else 9396 FrameAlign = Align(getByValTypeAlignment(ElementTy, DL)); 9397 Flags.setByValAlign(FrameAlign); 9398 } 9399 if (Args[i].IsNest) 9400 Flags.setNest(); 9401 if (NeedsRegBlock) 9402 Flags.setInConsecutiveRegs(); 9403 Flags.setOrigAlign(OriginalAlignment); 9404 9405 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9406 CLI.CallConv, VT); 9407 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9408 CLI.CallConv, VT); 9409 SmallVector<SDValue, 4> Parts(NumParts); 9410 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9411 9412 if (Args[i].IsSExt) 9413 ExtendKind = ISD::SIGN_EXTEND; 9414 else if (Args[i].IsZExt) 9415 ExtendKind = ISD::ZERO_EXTEND; 9416 9417 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9418 // for now. 9419 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9420 CanLowerReturn) { 9421 assert((CLI.RetTy == Args[i].Ty || 9422 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9423 CLI.RetTy->getPointerAddressSpace() == 9424 Args[i].Ty->getPointerAddressSpace())) && 9425 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9426 // Before passing 'returned' to the target lowering code, ensure that 9427 // either the register MVT and the actual EVT are the same size or that 9428 // the return value and argument are extended in the same way; in these 9429 // cases it's safe to pass the argument register value unchanged as the 9430 // return register value (although it's at the target's option whether 9431 // to do so) 9432 // TODO: allow code generation to take advantage of partially preserved 9433 // registers rather than clobbering the entire register when the 9434 // parameter extension method is not compatible with the return 9435 // extension method 9436 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9437 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9438 CLI.RetZExt == Args[i].IsZExt)) 9439 Flags.setReturned(); 9440 } 9441 9442 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB, 9443 CLI.CallConv, ExtendKind); 9444 9445 for (unsigned j = 0; j != NumParts; ++j) { 9446 // if it isn't first piece, alignment must be 1 9447 // For scalable vectors the scalable part is currently handled 9448 // by individual targets, so we just use the known minimum size here. 9449 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9450 i < CLI.NumFixedArgs, i, 9451 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9452 if (NumParts > 1 && j == 0) 9453 MyFlags.Flags.setSplit(); 9454 else if (j != 0) { 9455 MyFlags.Flags.setOrigAlign(Align(1)); 9456 if (j == NumParts - 1) 9457 MyFlags.Flags.setSplitEnd(); 9458 } 9459 9460 CLI.Outs.push_back(MyFlags); 9461 CLI.OutVals.push_back(Parts[j]); 9462 } 9463 9464 if (NeedsRegBlock && Value == NumValues - 1) 9465 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9466 } 9467 } 9468 9469 SmallVector<SDValue, 4> InVals; 9470 CLI.Chain = LowerCall(CLI, InVals); 9471 9472 // Update CLI.InVals to use outside of this function. 9473 CLI.InVals = InVals; 9474 9475 // Verify that the target's LowerCall behaved as expected. 9476 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9477 "LowerCall didn't return a valid chain!"); 9478 assert((!CLI.IsTailCall || InVals.empty()) && 9479 "LowerCall emitted a return value for a tail call!"); 9480 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9481 "LowerCall didn't emit the correct number of values!"); 9482 9483 // For a tail call, the return value is merely live-out and there aren't 9484 // any nodes in the DAG representing it. Return a special value to 9485 // indicate that a tail call has been emitted and no more Instructions 9486 // should be processed in the current block. 9487 if (CLI.IsTailCall) { 9488 CLI.DAG.setRoot(CLI.Chain); 9489 return std::make_pair(SDValue(), SDValue()); 9490 } 9491 9492 #ifndef NDEBUG 9493 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9494 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9495 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9496 "LowerCall emitted a value with the wrong type!"); 9497 } 9498 #endif 9499 9500 SmallVector<SDValue, 4> ReturnValues; 9501 if (!CanLowerReturn) { 9502 // The instruction result is the result of loading from the 9503 // hidden sret parameter. 9504 SmallVector<EVT, 1> PVTs; 9505 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9506 9507 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9508 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9509 EVT PtrVT = PVTs[0]; 9510 9511 unsigned NumValues = RetTys.size(); 9512 ReturnValues.resize(NumValues); 9513 SmallVector<SDValue, 4> Chains(NumValues); 9514 9515 // An aggregate return value cannot wrap around the address space, so 9516 // offsets to its parts don't wrap either. 9517 SDNodeFlags Flags; 9518 Flags.setNoUnsignedWrap(true); 9519 9520 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9521 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx); 9522 for (unsigned i = 0; i < NumValues; ++i) { 9523 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9524 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9525 PtrVT), Flags); 9526 SDValue L = CLI.DAG.getLoad( 9527 RetTys[i], CLI.DL, CLI.Chain, Add, 9528 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9529 DemoteStackIdx, Offsets[i]), 9530 HiddenSRetAlign); 9531 ReturnValues[i] = L; 9532 Chains[i] = L.getValue(1); 9533 } 9534 9535 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9536 } else { 9537 // Collect the legal value parts into potentially illegal values 9538 // that correspond to the original function's return values. 9539 Optional<ISD::NodeType> AssertOp; 9540 if (CLI.RetSExt) 9541 AssertOp = ISD::AssertSext; 9542 else if (CLI.RetZExt) 9543 AssertOp = ISD::AssertZext; 9544 unsigned CurReg = 0; 9545 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9546 EVT VT = RetTys[I]; 9547 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9548 CLI.CallConv, VT); 9549 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9550 CLI.CallConv, VT); 9551 9552 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9553 NumRegs, RegisterVT, VT, nullptr, 9554 CLI.CallConv, AssertOp)); 9555 CurReg += NumRegs; 9556 } 9557 9558 // For a function returning void, there is no return value. We can't create 9559 // such a node, so we just return a null return value in that case. In 9560 // that case, nothing will actually look at the value. 9561 if (ReturnValues.empty()) 9562 return std::make_pair(SDValue(), CLI.Chain); 9563 } 9564 9565 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9566 CLI.DAG.getVTList(RetTys), ReturnValues); 9567 return std::make_pair(Res, CLI.Chain); 9568 } 9569 9570 /// Places new result values for the node in Results (their number 9571 /// and types must exactly match those of the original return values of 9572 /// the node), or leaves Results empty, which indicates that the node is not 9573 /// to be custom lowered after all. 9574 void TargetLowering::LowerOperationWrapper(SDNode *N, 9575 SmallVectorImpl<SDValue> &Results, 9576 SelectionDAG &DAG) const { 9577 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 9578 9579 if (!Res.getNode()) 9580 return; 9581 9582 // If the original node has one result, take the return value from 9583 // LowerOperation as is. It might not be result number 0. 9584 if (N->getNumValues() == 1) { 9585 Results.push_back(Res); 9586 return; 9587 } 9588 9589 // If the original node has multiple results, then the return node should 9590 // have the same number of results. 9591 assert((N->getNumValues() == Res->getNumValues()) && 9592 "Lowering returned the wrong number of results!"); 9593 9594 // Places new result values base on N result number. 9595 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 9596 Results.push_back(Res.getValue(I)); 9597 } 9598 9599 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9600 llvm_unreachable("LowerOperation not implemented for this target!"); 9601 } 9602 9603 void 9604 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9605 SDValue Op = getNonRegisterValue(V); 9606 assert((Op.getOpcode() != ISD::CopyFromReg || 9607 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9608 "Copy from a reg to the same reg!"); 9609 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9610 9611 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9612 // If this is an InlineAsm we have to match the registers required, not the 9613 // notional registers required by the type. 9614 9615 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9616 None); // This is not an ABI copy. 9617 SDValue Chain = DAG.getEntryNode(); 9618 9619 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9620 FuncInfo.PreferredExtendType.end()) 9621 ? ISD::ANY_EXTEND 9622 : FuncInfo.PreferredExtendType[V]; 9623 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9624 PendingExports.push_back(Chain); 9625 } 9626 9627 #include "llvm/CodeGen/SelectionDAGISel.h" 9628 9629 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9630 /// entry block, return true. This includes arguments used by switches, since 9631 /// the switch may expand into multiple basic blocks. 9632 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9633 // With FastISel active, we may be splitting blocks, so force creation 9634 // of virtual registers for all non-dead arguments. 9635 if (FastISel) 9636 return A->use_empty(); 9637 9638 const BasicBlock &Entry = A->getParent()->front(); 9639 for (const User *U : A->users()) 9640 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9641 return false; // Use not in entry block. 9642 9643 return true; 9644 } 9645 9646 using ArgCopyElisionMapTy = 9647 DenseMap<const Argument *, 9648 std::pair<const AllocaInst *, const StoreInst *>>; 9649 9650 /// Scan the entry block of the function in FuncInfo for arguments that look 9651 /// like copies into a local alloca. Record any copied arguments in 9652 /// ArgCopyElisionCandidates. 9653 static void 9654 findArgumentCopyElisionCandidates(const DataLayout &DL, 9655 FunctionLoweringInfo *FuncInfo, 9656 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9657 // Record the state of every static alloca used in the entry block. Argument 9658 // allocas are all used in the entry block, so we need approximately as many 9659 // entries as we have arguments. 9660 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9661 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9662 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9663 StaticAllocas.reserve(NumArgs * 2); 9664 9665 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9666 if (!V) 9667 return nullptr; 9668 V = V->stripPointerCasts(); 9669 const auto *AI = dyn_cast<AllocaInst>(V); 9670 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9671 return nullptr; 9672 auto Iter = StaticAllocas.insert({AI, Unknown}); 9673 return &Iter.first->second; 9674 }; 9675 9676 // Look for stores of arguments to static allocas. Look through bitcasts and 9677 // GEPs to handle type coercions, as long as the alloca is fully initialized 9678 // by the store. Any non-store use of an alloca escapes it and any subsequent 9679 // unanalyzed store might write it. 9680 // FIXME: Handle structs initialized with multiple stores. 9681 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9682 // Look for stores, and handle non-store uses conservatively. 9683 const auto *SI = dyn_cast<StoreInst>(&I); 9684 if (!SI) { 9685 // We will look through cast uses, so ignore them completely. 9686 if (I.isCast()) 9687 continue; 9688 // Ignore debug info and pseudo op intrinsics, they don't escape or store 9689 // to allocas. 9690 if (I.isDebugOrPseudoInst()) 9691 continue; 9692 // This is an unknown instruction. Assume it escapes or writes to all 9693 // static alloca operands. 9694 for (const Use &U : I.operands()) { 9695 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9696 *Info = StaticAllocaInfo::Clobbered; 9697 } 9698 continue; 9699 } 9700 9701 // If the stored value is a static alloca, mark it as escaped. 9702 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9703 *Info = StaticAllocaInfo::Clobbered; 9704 9705 // Check if the destination is a static alloca. 9706 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9707 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9708 if (!Info) 9709 continue; 9710 const AllocaInst *AI = cast<AllocaInst>(Dst); 9711 9712 // Skip allocas that have been initialized or clobbered. 9713 if (*Info != StaticAllocaInfo::Unknown) 9714 continue; 9715 9716 // Check if the stored value is an argument, and that this store fully 9717 // initializes the alloca. Don't elide copies from the same argument twice. 9718 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9719 const auto *Arg = dyn_cast<Argument>(Val); 9720 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() || 9721 Arg->getType()->isEmptyTy() || 9722 DL.getTypeStoreSize(Arg->getType()) != 9723 DL.getTypeAllocSize(AI->getAllocatedType()) || 9724 ArgCopyElisionCandidates.count(Arg)) { 9725 *Info = StaticAllocaInfo::Clobbered; 9726 continue; 9727 } 9728 9729 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9730 << '\n'); 9731 9732 // Mark this alloca and store for argument copy elision. 9733 *Info = StaticAllocaInfo::Elidable; 9734 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9735 9736 // Stop scanning if we've seen all arguments. This will happen early in -O0 9737 // builds, which is useful, because -O0 builds have large entry blocks and 9738 // many allocas. 9739 if (ArgCopyElisionCandidates.size() == NumArgs) 9740 break; 9741 } 9742 } 9743 9744 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9745 /// ArgVal is a load from a suitable fixed stack object. 9746 static void tryToElideArgumentCopy( 9747 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9748 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9749 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9750 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9751 SDValue ArgVal, bool &ArgHasUses) { 9752 // Check if this is a load from a fixed stack object. 9753 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9754 if (!LNode) 9755 return; 9756 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9757 if (!FINode) 9758 return; 9759 9760 // Check that the fixed stack object is the right size and alignment. 9761 // Look at the alignment that the user wrote on the alloca instead of looking 9762 // at the stack object. 9763 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9764 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9765 const AllocaInst *AI = ArgCopyIter->second.first; 9766 int FixedIndex = FINode->getIndex(); 9767 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9768 int OldIndex = AllocaIndex; 9769 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9770 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9771 LLVM_DEBUG( 9772 dbgs() << " argument copy elision failed due to bad fixed stack " 9773 "object size\n"); 9774 return; 9775 } 9776 Align RequiredAlignment = AI->getAlign(); 9777 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) { 9778 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9779 "greater than stack argument alignment (" 9780 << DebugStr(RequiredAlignment) << " vs " 9781 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n"); 9782 return; 9783 } 9784 9785 // Perform the elision. Delete the old stack object and replace its only use 9786 // in the variable info map. Mark the stack object as mutable. 9787 LLVM_DEBUG({ 9788 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9789 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9790 << '\n'; 9791 }); 9792 MFI.RemoveStackObject(OldIndex); 9793 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9794 AllocaIndex = FixedIndex; 9795 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9796 Chains.push_back(ArgVal.getValue(1)); 9797 9798 // Avoid emitting code for the store implementing the copy. 9799 const StoreInst *SI = ArgCopyIter->second.second; 9800 ElidedArgCopyInstrs.insert(SI); 9801 9802 // Check for uses of the argument again so that we can avoid exporting ArgVal 9803 // if it is't used by anything other than the store. 9804 for (const Value *U : Arg.users()) { 9805 if (U != SI) { 9806 ArgHasUses = true; 9807 break; 9808 } 9809 } 9810 } 9811 9812 void SelectionDAGISel::LowerArguments(const Function &F) { 9813 SelectionDAG &DAG = SDB->DAG; 9814 SDLoc dl = SDB->getCurSDLoc(); 9815 const DataLayout &DL = DAG.getDataLayout(); 9816 SmallVector<ISD::InputArg, 16> Ins; 9817 9818 // In Naked functions we aren't going to save any registers. 9819 if (F.hasFnAttribute(Attribute::Naked)) 9820 return; 9821 9822 if (!FuncInfo->CanLowerReturn) { 9823 // Put in an sret pointer parameter before all the other parameters. 9824 SmallVector<EVT, 1> ValueVTs; 9825 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9826 F.getReturnType()->getPointerTo( 9827 DAG.getDataLayout().getAllocaAddrSpace()), 9828 ValueVTs); 9829 9830 // NOTE: Assuming that a pointer will never break down to more than one VT 9831 // or one register. 9832 ISD::ArgFlagsTy Flags; 9833 Flags.setSRet(); 9834 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9835 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9836 ISD::InputArg::NoArgIndex, 0); 9837 Ins.push_back(RetArg); 9838 } 9839 9840 // Look for stores of arguments to static allocas. Mark such arguments with a 9841 // flag to ask the target to give us the memory location of that argument if 9842 // available. 9843 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9844 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9845 ArgCopyElisionCandidates); 9846 9847 // Set up the incoming argument description vector. 9848 for (const Argument &Arg : F.args()) { 9849 unsigned ArgNo = Arg.getArgNo(); 9850 SmallVector<EVT, 4> ValueVTs; 9851 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9852 bool isArgValueUsed = !Arg.use_empty(); 9853 unsigned PartBase = 0; 9854 Type *FinalType = Arg.getType(); 9855 if (Arg.hasAttribute(Attribute::ByVal)) 9856 FinalType = Arg.getParamByValType(); 9857 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9858 FinalType, F.getCallingConv(), F.isVarArg()); 9859 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9860 Value != NumValues; ++Value) { 9861 EVT VT = ValueVTs[Value]; 9862 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9863 ISD::ArgFlagsTy Flags; 9864 9865 // Certain targets (such as MIPS), may have a different ABI alignment 9866 // for a type depending on the context. Give the target a chance to 9867 // specify the alignment it wants. 9868 const Align OriginalAlignment( 9869 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9870 9871 if (Arg.getType()->isPointerTy()) { 9872 Flags.setPointer(); 9873 Flags.setPointerAddrSpace( 9874 cast<PointerType>(Arg.getType())->getAddressSpace()); 9875 } 9876 if (Arg.hasAttribute(Attribute::ZExt)) 9877 Flags.setZExt(); 9878 if (Arg.hasAttribute(Attribute::SExt)) 9879 Flags.setSExt(); 9880 if (Arg.hasAttribute(Attribute::InReg)) { 9881 // If we are using vectorcall calling convention, a structure that is 9882 // passed InReg - is surely an HVA 9883 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9884 isa<StructType>(Arg.getType())) { 9885 // The first value of a structure is marked 9886 if (0 == Value) 9887 Flags.setHvaStart(); 9888 Flags.setHva(); 9889 } 9890 // Set InReg Flag 9891 Flags.setInReg(); 9892 } 9893 if (Arg.hasAttribute(Attribute::StructRet)) 9894 Flags.setSRet(); 9895 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9896 Flags.setSwiftSelf(); 9897 if (Arg.hasAttribute(Attribute::SwiftError)) 9898 Flags.setSwiftError(); 9899 if (Arg.hasAttribute(Attribute::ByVal)) 9900 Flags.setByVal(); 9901 if (Arg.hasAttribute(Attribute::ByRef)) 9902 Flags.setByRef(); 9903 if (Arg.hasAttribute(Attribute::InAlloca)) { 9904 Flags.setInAlloca(); 9905 // Set the byval flag for CCAssignFn callbacks that don't know about 9906 // inalloca. This way we can know how many bytes we should've allocated 9907 // and how many bytes a callee cleanup function will pop. If we port 9908 // inalloca to more targets, we'll have to add custom inalloca handling 9909 // in the various CC lowering callbacks. 9910 Flags.setByVal(); 9911 } 9912 if (Arg.hasAttribute(Attribute::Preallocated)) { 9913 Flags.setPreallocated(); 9914 // Set the byval flag for CCAssignFn callbacks that don't know about 9915 // preallocated. This way we can know how many bytes we should've 9916 // allocated and how many bytes a callee cleanup function will pop. If 9917 // we port preallocated to more targets, we'll have to add custom 9918 // preallocated handling in the various CC lowering callbacks. 9919 Flags.setByVal(); 9920 } 9921 9922 Type *ArgMemTy = nullptr; 9923 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() || 9924 Flags.isByRef()) { 9925 if (!ArgMemTy) 9926 ArgMemTy = Arg.getPointeeInMemoryValueType(); 9927 9928 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy); 9929 9930 // For in-memory arguments, size and alignment should be passed from FE. 9931 // BE will guess if this info is not there but there are cases it cannot 9932 // get right. 9933 MaybeAlign MemAlign = Arg.getParamAlign(); 9934 if (!MemAlign) 9935 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL)); 9936 9937 if (Flags.isByRef()) { 9938 Flags.setByRefSize(MemSize); 9939 Flags.setByRefAlign(*MemAlign); 9940 } else { 9941 Flags.setByValSize(MemSize); 9942 Flags.setByValAlign(*MemAlign); 9943 } 9944 } 9945 9946 if (Arg.hasAttribute(Attribute::Nest)) 9947 Flags.setNest(); 9948 if (NeedsRegBlock) 9949 Flags.setInConsecutiveRegs(); 9950 Flags.setOrigAlign(OriginalAlignment); 9951 if (ArgCopyElisionCandidates.count(&Arg)) 9952 Flags.setCopyElisionCandidate(); 9953 if (Arg.hasAttribute(Attribute::Returned)) 9954 Flags.setReturned(); 9955 9956 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9957 *CurDAG->getContext(), F.getCallingConv(), VT); 9958 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9959 *CurDAG->getContext(), F.getCallingConv(), VT); 9960 for (unsigned i = 0; i != NumRegs; ++i) { 9961 // For scalable vectors, use the minimum size; individual targets 9962 // are responsible for handling scalable vector arguments and 9963 // return values. 9964 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9965 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9966 if (NumRegs > 1 && i == 0) 9967 MyFlags.Flags.setSplit(); 9968 // if it isn't first piece, alignment must be 1 9969 else if (i > 0) { 9970 MyFlags.Flags.setOrigAlign(Align(1)); 9971 if (i == NumRegs - 1) 9972 MyFlags.Flags.setSplitEnd(); 9973 } 9974 Ins.push_back(MyFlags); 9975 } 9976 if (NeedsRegBlock && Value == NumValues - 1) 9977 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9978 PartBase += VT.getStoreSize().getKnownMinSize(); 9979 } 9980 } 9981 9982 // Call the target to set up the argument values. 9983 SmallVector<SDValue, 8> InVals; 9984 SDValue NewRoot = TLI->LowerFormalArguments( 9985 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9986 9987 // Verify that the target's LowerFormalArguments behaved as expected. 9988 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9989 "LowerFormalArguments didn't return a valid chain!"); 9990 assert(InVals.size() == Ins.size() && 9991 "LowerFormalArguments didn't emit the correct number of values!"); 9992 LLVM_DEBUG({ 9993 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9994 assert(InVals[i].getNode() && 9995 "LowerFormalArguments emitted a null value!"); 9996 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9997 "LowerFormalArguments emitted a value with the wrong type!"); 9998 } 9999 }); 10000 10001 // Update the DAG with the new chain value resulting from argument lowering. 10002 DAG.setRoot(NewRoot); 10003 10004 // Set up the argument values. 10005 unsigned i = 0; 10006 if (!FuncInfo->CanLowerReturn) { 10007 // Create a virtual register for the sret pointer, and put in a copy 10008 // from the sret argument into it. 10009 SmallVector<EVT, 1> ValueVTs; 10010 ComputeValueVTs(*TLI, DAG.getDataLayout(), 10011 F.getReturnType()->getPointerTo( 10012 DAG.getDataLayout().getAllocaAddrSpace()), 10013 ValueVTs); 10014 MVT VT = ValueVTs[0].getSimpleVT(); 10015 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 10016 Optional<ISD::NodeType> AssertOp = None; 10017 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 10018 nullptr, F.getCallingConv(), AssertOp); 10019 10020 MachineFunction& MF = SDB->DAG.getMachineFunction(); 10021 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 10022 Register SRetReg = 10023 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 10024 FuncInfo->DemoteRegister = SRetReg; 10025 NewRoot = 10026 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 10027 DAG.setRoot(NewRoot); 10028 10029 // i indexes lowered arguments. Bump it past the hidden sret argument. 10030 ++i; 10031 } 10032 10033 SmallVector<SDValue, 4> Chains; 10034 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 10035 for (const Argument &Arg : F.args()) { 10036 SmallVector<SDValue, 4> ArgValues; 10037 SmallVector<EVT, 4> ValueVTs; 10038 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 10039 unsigned NumValues = ValueVTs.size(); 10040 if (NumValues == 0) 10041 continue; 10042 10043 bool ArgHasUses = !Arg.use_empty(); 10044 10045 // Elide the copying store if the target loaded this argument from a 10046 // suitable fixed stack object. 10047 if (Ins[i].Flags.isCopyElisionCandidate()) { 10048 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 10049 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 10050 InVals[i], ArgHasUses); 10051 } 10052 10053 // If this argument is unused then remember its value. It is used to generate 10054 // debugging information. 10055 bool isSwiftErrorArg = 10056 TLI->supportSwiftError() && 10057 Arg.hasAttribute(Attribute::SwiftError); 10058 if (!ArgHasUses && !isSwiftErrorArg) { 10059 SDB->setUnusedArgValue(&Arg, InVals[i]); 10060 10061 // Also remember any frame index for use in FastISel. 10062 if (FrameIndexSDNode *FI = 10063 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 10064 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10065 } 10066 10067 for (unsigned Val = 0; Val != NumValues; ++Val) { 10068 EVT VT = ValueVTs[Val]; 10069 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 10070 F.getCallingConv(), VT); 10071 unsigned NumParts = TLI->getNumRegistersForCallingConv( 10072 *CurDAG->getContext(), F.getCallingConv(), VT); 10073 10074 // Even an apparent 'unused' swifterror argument needs to be returned. So 10075 // we do generate a copy for it that can be used on return from the 10076 // function. 10077 if (ArgHasUses || isSwiftErrorArg) { 10078 Optional<ISD::NodeType> AssertOp; 10079 if (Arg.hasAttribute(Attribute::SExt)) 10080 AssertOp = ISD::AssertSext; 10081 else if (Arg.hasAttribute(Attribute::ZExt)) 10082 AssertOp = ISD::AssertZext; 10083 10084 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 10085 PartVT, VT, nullptr, 10086 F.getCallingConv(), AssertOp)); 10087 } 10088 10089 i += NumParts; 10090 } 10091 10092 // We don't need to do anything else for unused arguments. 10093 if (ArgValues.empty()) 10094 continue; 10095 10096 // Note down frame index. 10097 if (FrameIndexSDNode *FI = 10098 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 10099 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10100 10101 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 10102 SDB->getCurSDLoc()); 10103 10104 SDB->setValue(&Arg, Res); 10105 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 10106 // We want to associate the argument with the frame index, among 10107 // involved operands, that correspond to the lowest address. The 10108 // getCopyFromParts function, called earlier, is swapping the order of 10109 // the operands to BUILD_PAIR depending on endianness. The result of 10110 // that swapping is that the least significant bits of the argument will 10111 // be in the first operand of the BUILD_PAIR node, and the most 10112 // significant bits will be in the second operand. 10113 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 10114 if (LoadSDNode *LNode = 10115 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 10116 if (FrameIndexSDNode *FI = 10117 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 10118 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 10119 } 10120 10121 // Analyses past this point are naive and don't expect an assertion. 10122 if (Res.getOpcode() == ISD::AssertZext) 10123 Res = Res.getOperand(0); 10124 10125 // Update the SwiftErrorVRegDefMap. 10126 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 10127 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10128 if (Register::isVirtualRegister(Reg)) 10129 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 10130 Reg); 10131 } 10132 10133 // If this argument is live outside of the entry block, insert a copy from 10134 // wherever we got it to the vreg that other BB's will reference it as. 10135 if (Res.getOpcode() == ISD::CopyFromReg) { 10136 // If we can, though, try to skip creating an unnecessary vreg. 10137 // FIXME: This isn't very clean... it would be nice to make this more 10138 // general. 10139 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 10140 if (Register::isVirtualRegister(Reg)) { 10141 FuncInfo->ValueMap[&Arg] = Reg; 10142 continue; 10143 } 10144 } 10145 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 10146 FuncInfo->InitializeRegForValue(&Arg); 10147 SDB->CopyToExportRegsIfNeeded(&Arg); 10148 } 10149 } 10150 10151 if (!Chains.empty()) { 10152 Chains.push_back(NewRoot); 10153 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 10154 } 10155 10156 DAG.setRoot(NewRoot); 10157 10158 assert(i == InVals.size() && "Argument register count mismatch!"); 10159 10160 // If any argument copy elisions occurred and we have debug info, update the 10161 // stale frame indices used in the dbg.declare variable info table. 10162 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 10163 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 10164 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 10165 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 10166 if (I != ArgCopyElisionFrameIndexMap.end()) 10167 VI.Slot = I->second; 10168 } 10169 } 10170 10171 // Finally, if the target has anything special to do, allow it to do so. 10172 emitFunctionEntryCode(); 10173 } 10174 10175 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 10176 /// ensure constants are generated when needed. Remember the virtual registers 10177 /// that need to be added to the Machine PHI nodes as input. We cannot just 10178 /// directly add them, because expansion might result in multiple MBB's for one 10179 /// BB. As such, the start of the BB might correspond to a different MBB than 10180 /// the end. 10181 void 10182 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 10183 const Instruction *TI = LLVMBB->getTerminator(); 10184 10185 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 10186 10187 // Check PHI nodes in successors that expect a value to be available from this 10188 // block. 10189 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 10190 const BasicBlock *SuccBB = TI->getSuccessor(succ); 10191 if (!isa<PHINode>(SuccBB->begin())) continue; 10192 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 10193 10194 // If this terminator has multiple identical successors (common for 10195 // switches), only handle each succ once. 10196 if (!SuccsHandled.insert(SuccMBB).second) 10197 continue; 10198 10199 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 10200 10201 // At this point we know that there is a 1-1 correspondence between LLVM PHI 10202 // nodes and Machine PHI nodes, but the incoming operands have not been 10203 // emitted yet. 10204 for (const PHINode &PN : SuccBB->phis()) { 10205 // Ignore dead phi's. 10206 if (PN.use_empty()) 10207 continue; 10208 10209 // Skip empty types 10210 if (PN.getType()->isEmptyTy()) 10211 continue; 10212 10213 unsigned Reg; 10214 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 10215 10216 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 10217 unsigned &RegOut = ConstantsOut[C]; 10218 if (RegOut == 0) { 10219 RegOut = FuncInfo.CreateRegs(C); 10220 CopyValueToVirtualRegister(C, RegOut); 10221 } 10222 Reg = RegOut; 10223 } else { 10224 DenseMap<const Value *, Register>::iterator I = 10225 FuncInfo.ValueMap.find(PHIOp); 10226 if (I != FuncInfo.ValueMap.end()) 10227 Reg = I->second; 10228 else { 10229 assert(isa<AllocaInst>(PHIOp) && 10230 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 10231 "Didn't codegen value into a register!??"); 10232 Reg = FuncInfo.CreateRegs(PHIOp); 10233 CopyValueToVirtualRegister(PHIOp, Reg); 10234 } 10235 } 10236 10237 // Remember that this register needs to added to the machine PHI node as 10238 // the input for this MBB. 10239 SmallVector<EVT, 4> ValueVTs; 10240 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10241 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 10242 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 10243 EVT VT = ValueVTs[vti]; 10244 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 10245 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 10246 FuncInfo.PHINodesToUpdate.push_back( 10247 std::make_pair(&*MBBI++, Reg + i)); 10248 Reg += NumRegisters; 10249 } 10250 } 10251 } 10252 10253 ConstantsOut.clear(); 10254 } 10255 10256 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 10257 /// is 0. 10258 MachineBasicBlock * 10259 SelectionDAGBuilder::StackProtectorDescriptor:: 10260 AddSuccessorMBB(const BasicBlock *BB, 10261 MachineBasicBlock *ParentMBB, 10262 bool IsLikely, 10263 MachineBasicBlock *SuccMBB) { 10264 // If SuccBB has not been created yet, create it. 10265 if (!SuccMBB) { 10266 MachineFunction *MF = ParentMBB->getParent(); 10267 MachineFunction::iterator BBI(ParentMBB); 10268 SuccMBB = MF->CreateMachineBasicBlock(BB); 10269 MF->insert(++BBI, SuccMBB); 10270 } 10271 // Add it as a successor of ParentMBB. 10272 ParentMBB->addSuccessor( 10273 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10274 return SuccMBB; 10275 } 10276 10277 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10278 MachineFunction::iterator I(MBB); 10279 if (++I == FuncInfo.MF->end()) 10280 return nullptr; 10281 return &*I; 10282 } 10283 10284 /// During lowering new call nodes can be created (such as memset, etc.). 10285 /// Those will become new roots of the current DAG, but complications arise 10286 /// when they are tail calls. In such cases, the call lowering will update 10287 /// the root, but the builder still needs to know that a tail call has been 10288 /// lowered in order to avoid generating an additional return. 10289 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10290 // If the node is null, we do have a tail call. 10291 if (MaybeTC.getNode() != nullptr) 10292 DAG.setRoot(MaybeTC); 10293 else 10294 HasTailCall = true; 10295 } 10296 10297 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10298 MachineBasicBlock *SwitchMBB, 10299 MachineBasicBlock *DefaultMBB) { 10300 MachineFunction *CurMF = FuncInfo.MF; 10301 MachineBasicBlock *NextMBB = nullptr; 10302 MachineFunction::iterator BBI(W.MBB); 10303 if (++BBI != FuncInfo.MF->end()) 10304 NextMBB = &*BBI; 10305 10306 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10307 10308 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10309 10310 if (Size == 2 && W.MBB == SwitchMBB) { 10311 // If any two of the cases has the same destination, and if one value 10312 // is the same as the other, but has one bit unset that the other has set, 10313 // use bit manipulation to do two compares at once. For example: 10314 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10315 // TODO: This could be extended to merge any 2 cases in switches with 3 10316 // cases. 10317 // TODO: Handle cases where W.CaseBB != SwitchBB. 10318 CaseCluster &Small = *W.FirstCluster; 10319 CaseCluster &Big = *W.LastCluster; 10320 10321 if (Small.Low == Small.High && Big.Low == Big.High && 10322 Small.MBB == Big.MBB) { 10323 const APInt &SmallValue = Small.Low->getValue(); 10324 const APInt &BigValue = Big.Low->getValue(); 10325 10326 // Check that there is only one bit different. 10327 APInt CommonBit = BigValue ^ SmallValue; 10328 if (CommonBit.isPowerOf2()) { 10329 SDValue CondLHS = getValue(Cond); 10330 EVT VT = CondLHS.getValueType(); 10331 SDLoc DL = getCurSDLoc(); 10332 10333 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10334 DAG.getConstant(CommonBit, DL, VT)); 10335 SDValue Cond = DAG.getSetCC( 10336 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10337 ISD::SETEQ); 10338 10339 // Update successor info. 10340 // Both Small and Big will jump to Small.BB, so we sum up the 10341 // probabilities. 10342 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10343 if (BPI) 10344 addSuccessorWithProb( 10345 SwitchMBB, DefaultMBB, 10346 // The default destination is the first successor in IR. 10347 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10348 else 10349 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10350 10351 // Insert the true branch. 10352 SDValue BrCond = 10353 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10354 DAG.getBasicBlock(Small.MBB)); 10355 // Insert the false branch. 10356 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10357 DAG.getBasicBlock(DefaultMBB)); 10358 10359 DAG.setRoot(BrCond); 10360 return; 10361 } 10362 } 10363 } 10364 10365 if (TM.getOptLevel() != CodeGenOpt::None) { 10366 // Here, we order cases by probability so the most likely case will be 10367 // checked first. However, two clusters can have the same probability in 10368 // which case their relative ordering is non-deterministic. So we use Low 10369 // as a tie-breaker as clusters are guaranteed to never overlap. 10370 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10371 [](const CaseCluster &a, const CaseCluster &b) { 10372 return a.Prob != b.Prob ? 10373 a.Prob > b.Prob : 10374 a.Low->getValue().slt(b.Low->getValue()); 10375 }); 10376 10377 // Rearrange the case blocks so that the last one falls through if possible 10378 // without changing the order of probabilities. 10379 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10380 --I; 10381 if (I->Prob > W.LastCluster->Prob) 10382 break; 10383 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10384 std::swap(*I, *W.LastCluster); 10385 break; 10386 } 10387 } 10388 } 10389 10390 // Compute total probability. 10391 BranchProbability DefaultProb = W.DefaultProb; 10392 BranchProbability UnhandledProbs = DefaultProb; 10393 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10394 UnhandledProbs += I->Prob; 10395 10396 MachineBasicBlock *CurMBB = W.MBB; 10397 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10398 bool FallthroughUnreachable = false; 10399 MachineBasicBlock *Fallthrough; 10400 if (I == W.LastCluster) { 10401 // For the last cluster, fall through to the default destination. 10402 Fallthrough = DefaultMBB; 10403 FallthroughUnreachable = isa<UnreachableInst>( 10404 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10405 } else { 10406 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10407 CurMF->insert(BBI, Fallthrough); 10408 // Put Cond in a virtual register to make it available from the new blocks. 10409 ExportFromCurrentBlock(Cond); 10410 } 10411 UnhandledProbs -= I->Prob; 10412 10413 switch (I->Kind) { 10414 case CC_JumpTable: { 10415 // FIXME: Optimize away range check based on pivot comparisons. 10416 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10417 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10418 10419 // The jump block hasn't been inserted yet; insert it here. 10420 MachineBasicBlock *JumpMBB = JT->MBB; 10421 CurMF->insert(BBI, JumpMBB); 10422 10423 auto JumpProb = I->Prob; 10424 auto FallthroughProb = UnhandledProbs; 10425 10426 // If the default statement is a target of the jump table, we evenly 10427 // distribute the default probability to successors of CurMBB. Also 10428 // update the probability on the edge from JumpMBB to Fallthrough. 10429 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10430 SE = JumpMBB->succ_end(); 10431 SI != SE; ++SI) { 10432 if (*SI == DefaultMBB) { 10433 JumpProb += DefaultProb / 2; 10434 FallthroughProb -= DefaultProb / 2; 10435 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10436 JumpMBB->normalizeSuccProbs(); 10437 break; 10438 } 10439 } 10440 10441 if (FallthroughUnreachable) { 10442 // Skip the range check if the fallthrough block is unreachable. 10443 JTH->OmitRangeCheck = true; 10444 } 10445 10446 if (!JTH->OmitRangeCheck) 10447 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10448 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10449 CurMBB->normalizeSuccProbs(); 10450 10451 // The jump table header will be inserted in our current block, do the 10452 // range check, and fall through to our fallthrough block. 10453 JTH->HeaderBB = CurMBB; 10454 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10455 10456 // If we're in the right place, emit the jump table header right now. 10457 if (CurMBB == SwitchMBB) { 10458 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10459 JTH->Emitted = true; 10460 } 10461 break; 10462 } 10463 case CC_BitTests: { 10464 // FIXME: Optimize away range check based on pivot comparisons. 10465 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10466 10467 // The bit test blocks haven't been inserted yet; insert them here. 10468 for (BitTestCase &BTC : BTB->Cases) 10469 CurMF->insert(BBI, BTC.ThisBB); 10470 10471 // Fill in fields of the BitTestBlock. 10472 BTB->Parent = CurMBB; 10473 BTB->Default = Fallthrough; 10474 10475 BTB->DefaultProb = UnhandledProbs; 10476 // If the cases in bit test don't form a contiguous range, we evenly 10477 // distribute the probability on the edge to Fallthrough to two 10478 // successors of CurMBB. 10479 if (!BTB->ContiguousRange) { 10480 BTB->Prob += DefaultProb / 2; 10481 BTB->DefaultProb -= DefaultProb / 2; 10482 } 10483 10484 if (FallthroughUnreachable) { 10485 // Skip the range check if the fallthrough block is unreachable. 10486 BTB->OmitRangeCheck = true; 10487 } 10488 10489 // If we're in the right place, emit the bit test header right now. 10490 if (CurMBB == SwitchMBB) { 10491 visitBitTestHeader(*BTB, SwitchMBB); 10492 BTB->Emitted = true; 10493 } 10494 break; 10495 } 10496 case CC_Range: { 10497 const Value *RHS, *LHS, *MHS; 10498 ISD::CondCode CC; 10499 if (I->Low == I->High) { 10500 // Check Cond == I->Low. 10501 CC = ISD::SETEQ; 10502 LHS = Cond; 10503 RHS=I->Low; 10504 MHS = nullptr; 10505 } else { 10506 // Check I->Low <= Cond <= I->High. 10507 CC = ISD::SETLE; 10508 LHS = I->Low; 10509 MHS = Cond; 10510 RHS = I->High; 10511 } 10512 10513 // If Fallthrough is unreachable, fold away the comparison. 10514 if (FallthroughUnreachable) 10515 CC = ISD::SETTRUE; 10516 10517 // The false probability is the sum of all unhandled cases. 10518 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10519 getCurSDLoc(), I->Prob, UnhandledProbs); 10520 10521 if (CurMBB == SwitchMBB) 10522 visitSwitchCase(CB, SwitchMBB); 10523 else 10524 SL->SwitchCases.push_back(CB); 10525 10526 break; 10527 } 10528 } 10529 CurMBB = Fallthrough; 10530 } 10531 } 10532 10533 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10534 CaseClusterIt First, 10535 CaseClusterIt Last) { 10536 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10537 if (X.Prob != CC.Prob) 10538 return X.Prob > CC.Prob; 10539 10540 // Ties are broken by comparing the case value. 10541 return X.Low->getValue().slt(CC.Low->getValue()); 10542 }); 10543 } 10544 10545 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10546 const SwitchWorkListItem &W, 10547 Value *Cond, 10548 MachineBasicBlock *SwitchMBB) { 10549 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10550 "Clusters not sorted?"); 10551 10552 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10553 10554 // Balance the tree based on branch probabilities to create a near-optimal (in 10555 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10556 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10557 CaseClusterIt LastLeft = W.FirstCluster; 10558 CaseClusterIt FirstRight = W.LastCluster; 10559 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10560 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10561 10562 // Move LastLeft and FirstRight towards each other from opposite directions to 10563 // find a partitioning of the clusters which balances the probability on both 10564 // sides. If LeftProb and RightProb are equal, alternate which side is 10565 // taken to ensure 0-probability nodes are distributed evenly. 10566 unsigned I = 0; 10567 while (LastLeft + 1 < FirstRight) { 10568 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10569 LeftProb += (++LastLeft)->Prob; 10570 else 10571 RightProb += (--FirstRight)->Prob; 10572 I++; 10573 } 10574 10575 while (true) { 10576 // Our binary search tree differs from a typical BST in that ours can have up 10577 // to three values in each leaf. The pivot selection above doesn't take that 10578 // into account, which means the tree might require more nodes and be less 10579 // efficient. We compensate for this here. 10580 10581 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10582 unsigned NumRight = W.LastCluster - FirstRight + 1; 10583 10584 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10585 // If one side has less than 3 clusters, and the other has more than 3, 10586 // consider taking a cluster from the other side. 10587 10588 if (NumLeft < NumRight) { 10589 // Consider moving the first cluster on the right to the left side. 10590 CaseCluster &CC = *FirstRight; 10591 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10592 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10593 if (LeftSideRank <= RightSideRank) { 10594 // Moving the cluster to the left does not demote it. 10595 ++LastLeft; 10596 ++FirstRight; 10597 continue; 10598 } 10599 } else { 10600 assert(NumRight < NumLeft); 10601 // Consider moving the last element on the left to the right side. 10602 CaseCluster &CC = *LastLeft; 10603 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10604 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10605 if (RightSideRank <= LeftSideRank) { 10606 // Moving the cluster to the right does not demot it. 10607 --LastLeft; 10608 --FirstRight; 10609 continue; 10610 } 10611 } 10612 } 10613 break; 10614 } 10615 10616 assert(LastLeft + 1 == FirstRight); 10617 assert(LastLeft >= W.FirstCluster); 10618 assert(FirstRight <= W.LastCluster); 10619 10620 // Use the first element on the right as pivot since we will make less-than 10621 // comparisons against it. 10622 CaseClusterIt PivotCluster = FirstRight; 10623 assert(PivotCluster > W.FirstCluster); 10624 assert(PivotCluster <= W.LastCluster); 10625 10626 CaseClusterIt FirstLeft = W.FirstCluster; 10627 CaseClusterIt LastRight = W.LastCluster; 10628 10629 const ConstantInt *Pivot = PivotCluster->Low; 10630 10631 // New blocks will be inserted immediately after the current one. 10632 MachineFunction::iterator BBI(W.MBB); 10633 ++BBI; 10634 10635 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10636 // we can branch to its destination directly if it's squeezed exactly in 10637 // between the known lower bound and Pivot - 1. 10638 MachineBasicBlock *LeftMBB; 10639 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10640 FirstLeft->Low == W.GE && 10641 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10642 LeftMBB = FirstLeft->MBB; 10643 } else { 10644 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10645 FuncInfo.MF->insert(BBI, LeftMBB); 10646 WorkList.push_back( 10647 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10648 // Put Cond in a virtual register to make it available from the new blocks. 10649 ExportFromCurrentBlock(Cond); 10650 } 10651 10652 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10653 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10654 // directly if RHS.High equals the current upper bound. 10655 MachineBasicBlock *RightMBB; 10656 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10657 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10658 RightMBB = FirstRight->MBB; 10659 } else { 10660 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10661 FuncInfo.MF->insert(BBI, RightMBB); 10662 WorkList.push_back( 10663 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10664 // Put Cond in a virtual register to make it available from the new blocks. 10665 ExportFromCurrentBlock(Cond); 10666 } 10667 10668 // Create the CaseBlock record that will be used to lower the branch. 10669 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10670 getCurSDLoc(), LeftProb, RightProb); 10671 10672 if (W.MBB == SwitchMBB) 10673 visitSwitchCase(CB, SwitchMBB); 10674 else 10675 SL->SwitchCases.push_back(CB); 10676 } 10677 10678 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10679 // from the swith statement. 10680 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10681 BranchProbability PeeledCaseProb) { 10682 if (PeeledCaseProb == BranchProbability::getOne()) 10683 return BranchProbability::getZero(); 10684 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10685 10686 uint32_t Numerator = CaseProb.getNumerator(); 10687 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10688 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10689 } 10690 10691 // Try to peel the top probability case if it exceeds the threshold. 10692 // Return current MachineBasicBlock for the switch statement if the peeling 10693 // does not occur. 10694 // If the peeling is performed, return the newly created MachineBasicBlock 10695 // for the peeled switch statement. Also update Clusters to remove the peeled 10696 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10697 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10698 const SwitchInst &SI, CaseClusterVector &Clusters, 10699 BranchProbability &PeeledCaseProb) { 10700 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10701 // Don't perform if there is only one cluster or optimizing for size. 10702 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10703 TM.getOptLevel() == CodeGenOpt::None || 10704 SwitchMBB->getParent()->getFunction().hasMinSize()) 10705 return SwitchMBB; 10706 10707 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10708 unsigned PeeledCaseIndex = 0; 10709 bool SwitchPeeled = false; 10710 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10711 CaseCluster &CC = Clusters[Index]; 10712 if (CC.Prob < TopCaseProb) 10713 continue; 10714 TopCaseProb = CC.Prob; 10715 PeeledCaseIndex = Index; 10716 SwitchPeeled = true; 10717 } 10718 if (!SwitchPeeled) 10719 return SwitchMBB; 10720 10721 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10722 << TopCaseProb << "\n"); 10723 10724 // Record the MBB for the peeled switch statement. 10725 MachineFunction::iterator BBI(SwitchMBB); 10726 ++BBI; 10727 MachineBasicBlock *PeeledSwitchMBB = 10728 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10729 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10730 10731 ExportFromCurrentBlock(SI.getCondition()); 10732 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10733 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10734 nullptr, nullptr, TopCaseProb.getCompl()}; 10735 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10736 10737 Clusters.erase(PeeledCaseIt); 10738 for (CaseCluster &CC : Clusters) { 10739 LLVM_DEBUG( 10740 dbgs() << "Scale the probablity for one cluster, before scaling: " 10741 << CC.Prob << "\n"); 10742 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10743 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10744 } 10745 PeeledCaseProb = TopCaseProb; 10746 return PeeledSwitchMBB; 10747 } 10748 10749 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10750 // Extract cases from the switch. 10751 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10752 CaseClusterVector Clusters; 10753 Clusters.reserve(SI.getNumCases()); 10754 for (auto I : SI.cases()) { 10755 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10756 const ConstantInt *CaseVal = I.getCaseValue(); 10757 BranchProbability Prob = 10758 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10759 : BranchProbability(1, SI.getNumCases() + 1); 10760 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10761 } 10762 10763 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10764 10765 // Cluster adjacent cases with the same destination. We do this at all 10766 // optimization levels because it's cheap to do and will make codegen faster 10767 // if there are many clusters. 10768 sortAndRangeify(Clusters); 10769 10770 // The branch probablity of the peeled case. 10771 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10772 MachineBasicBlock *PeeledSwitchMBB = 10773 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10774 10775 // If there is only the default destination, jump there directly. 10776 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10777 if (Clusters.empty()) { 10778 assert(PeeledSwitchMBB == SwitchMBB); 10779 SwitchMBB->addSuccessor(DefaultMBB); 10780 if (DefaultMBB != NextBlock(SwitchMBB)) { 10781 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10782 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10783 } 10784 return; 10785 } 10786 10787 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10788 SL->findBitTestClusters(Clusters, &SI); 10789 10790 LLVM_DEBUG({ 10791 dbgs() << "Case clusters: "; 10792 for (const CaseCluster &C : Clusters) { 10793 if (C.Kind == CC_JumpTable) 10794 dbgs() << "JT:"; 10795 if (C.Kind == CC_BitTests) 10796 dbgs() << "BT:"; 10797 10798 C.Low->getValue().print(dbgs(), true); 10799 if (C.Low != C.High) { 10800 dbgs() << '-'; 10801 C.High->getValue().print(dbgs(), true); 10802 } 10803 dbgs() << ' '; 10804 } 10805 dbgs() << '\n'; 10806 }); 10807 10808 assert(!Clusters.empty()); 10809 SwitchWorkList WorkList; 10810 CaseClusterIt First = Clusters.begin(); 10811 CaseClusterIt Last = Clusters.end() - 1; 10812 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10813 // Scale the branchprobability for DefaultMBB if the peel occurs and 10814 // DefaultMBB is not replaced. 10815 if (PeeledCaseProb != BranchProbability::getZero() && 10816 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10817 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10818 WorkList.push_back( 10819 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10820 10821 while (!WorkList.empty()) { 10822 SwitchWorkListItem W = WorkList.pop_back_val(); 10823 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10824 10825 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10826 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10827 // For optimized builds, lower large range as a balanced binary tree. 10828 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10829 continue; 10830 } 10831 10832 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10833 } 10834 } 10835 10836 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10837 SmallVector<EVT, 4> ValueVTs; 10838 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 10839 ValueVTs); 10840 unsigned NumValues = ValueVTs.size(); 10841 if (NumValues == 0) return; 10842 10843 SmallVector<SDValue, 4> Values(NumValues); 10844 SDValue Op = getValue(I.getOperand(0)); 10845 10846 for (unsigned i = 0; i != NumValues; ++i) 10847 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i], 10848 SDValue(Op.getNode(), Op.getResNo() + i)); 10849 10850 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 10851 DAG.getVTList(ValueVTs), Values)); 10852 } 10853