1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements routines for translating from LLVM IR into SelectionDAG IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "SelectionDAGBuilder.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/BitVector.h" 19 #include "llvm/ADT/DenseMap.h" 20 #include "llvm/ADT/None.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Triple.h" 28 #include "llvm/ADT/Twine.h" 29 #include "llvm/Analysis/AliasAnalysis.h" 30 #include "llvm/Analysis/BlockFrequencyInfo.h" 31 #include "llvm/Analysis/BranchProbabilityInfo.h" 32 #include "llvm/Analysis/ConstantFolding.h" 33 #include "llvm/Analysis/EHPersonalities.h" 34 #include "llvm/Analysis/Loads.h" 35 #include "llvm/Analysis/MemoryLocation.h" 36 #include "llvm/Analysis/ProfileSummaryInfo.h" 37 #include "llvm/Analysis/TargetLibraryInfo.h" 38 #include "llvm/Analysis/ValueTracking.h" 39 #include "llvm/Analysis/VectorUtils.h" 40 #include "llvm/CodeGen/Analysis.h" 41 #include "llvm/CodeGen/FunctionLoweringInfo.h" 42 #include "llvm/CodeGen/GCMetadata.h" 43 #include "llvm/CodeGen/ISDOpcodes.h" 44 #include "llvm/CodeGen/MachineBasicBlock.h" 45 #include "llvm/CodeGen/MachineFrameInfo.h" 46 #include "llvm/CodeGen/MachineFunction.h" 47 #include "llvm/CodeGen/MachineInstr.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineJumpTableInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineOperand.h" 53 #include "llvm/CodeGen/MachineRegisterInfo.h" 54 #include "llvm/CodeGen/RuntimeLibcalls.h" 55 #include "llvm/CodeGen/SelectionDAG.h" 56 #include "llvm/CodeGen/SelectionDAGNodes.h" 57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 58 #include "llvm/CodeGen/StackMaps.h" 59 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 60 #include "llvm/CodeGen/TargetFrameLowering.h" 61 #include "llvm/CodeGen/TargetInstrInfo.h" 62 #include "llvm/CodeGen/TargetLowering.h" 63 #include "llvm/CodeGen/TargetOpcodes.h" 64 #include "llvm/CodeGen/TargetRegisterInfo.h" 65 #include "llvm/CodeGen/TargetSubtargetInfo.h" 66 #include "llvm/CodeGen/ValueTypes.h" 67 #include "llvm/CodeGen/WinEHFuncInfo.h" 68 #include "llvm/IR/Argument.h" 69 #include "llvm/IR/Attributes.h" 70 #include "llvm/IR/BasicBlock.h" 71 #include "llvm/IR/CFG.h" 72 #include "llvm/IR/CallSite.h" 73 #include "llvm/IR/CallingConv.h" 74 #include "llvm/IR/Constant.h" 75 #include "llvm/IR/ConstantRange.h" 76 #include "llvm/IR/Constants.h" 77 #include "llvm/IR/DataLayout.h" 78 #include "llvm/IR/DebugInfoMetadata.h" 79 #include "llvm/IR/DebugLoc.h" 80 #include "llvm/IR/DerivedTypes.h" 81 #include "llvm/IR/Function.h" 82 #include "llvm/IR/GetElementPtrTypeIterator.h" 83 #include "llvm/IR/InlineAsm.h" 84 #include "llvm/IR/InstrTypes.h" 85 #include "llvm/IR/Instruction.h" 86 #include "llvm/IR/Instructions.h" 87 #include "llvm/IR/IntrinsicInst.h" 88 #include "llvm/IR/Intrinsics.h" 89 #include "llvm/IR/IntrinsicsAArch64.h" 90 #include "llvm/IR/IntrinsicsWebAssembly.h" 91 #include "llvm/IR/LLVMContext.h" 92 #include "llvm/IR/Metadata.h" 93 #include "llvm/IR/Module.h" 94 #include "llvm/IR/Operator.h" 95 #include "llvm/IR/PatternMatch.h" 96 #include "llvm/IR/Statepoint.h" 97 #include "llvm/IR/Type.h" 98 #include "llvm/IR/User.h" 99 #include "llvm/IR/Value.h" 100 #include "llvm/MC/MCContext.h" 101 #include "llvm/MC/MCSymbol.h" 102 #include "llvm/Support/AtomicOrdering.h" 103 #include "llvm/Support/BranchProbability.h" 104 #include "llvm/Support/Casting.h" 105 #include "llvm/Support/CodeGen.h" 106 #include "llvm/Support/CommandLine.h" 107 #include "llvm/Support/Compiler.h" 108 #include "llvm/Support/Debug.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/MachineValueType.h" 111 #include "llvm/Support/MathExtras.h" 112 #include "llvm/Support/raw_ostream.h" 113 #include "llvm/Target/TargetIntrinsicInfo.h" 114 #include "llvm/Target/TargetMachine.h" 115 #include "llvm/Target/TargetOptions.h" 116 #include "llvm/Transforms/Utils/Local.h" 117 #include <algorithm> 118 #include <cassert> 119 #include <cstddef> 120 #include <cstdint> 121 #include <cstring> 122 #include <iterator> 123 #include <limits> 124 #include <numeric> 125 #include <tuple> 126 #include <utility> 127 #include <vector> 128 129 using namespace llvm; 130 using namespace PatternMatch; 131 using namespace SwitchCG; 132 133 #define DEBUG_TYPE "isel" 134 135 /// LimitFloatPrecision - Generate low-precision inline sequences for 136 /// some float libcalls (6, 8 or 12 bits). 137 static unsigned LimitFloatPrecision; 138 139 static cl::opt<unsigned, true> 140 LimitFPPrecision("limit-float-precision", 141 cl::desc("Generate low-precision inline sequences " 142 "for some float libcalls"), 143 cl::location(LimitFloatPrecision), cl::Hidden, 144 cl::init(0)); 145 146 static cl::opt<unsigned> SwitchPeelThreshold( 147 "switch-peel-threshold", cl::Hidden, cl::init(66), 148 cl::desc("Set the case probability threshold for peeling the case from a " 149 "switch statement. A value greater than 100 will void this " 150 "optimization")); 151 152 // Limit the width of DAG chains. This is important in general to prevent 153 // DAG-based analysis from blowing up. For example, alias analysis and 154 // load clustering may not complete in reasonable time. It is difficult to 155 // recognize and avoid this situation within each individual analysis, and 156 // future analyses are likely to have the same behavior. Limiting DAG width is 157 // the safe approach and will be especially important with global DAGs. 158 // 159 // MaxParallelChains default is arbitrarily high to avoid affecting 160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 161 // sequence over this should have been converted to llvm.memcpy by the 162 // frontend. It is easy to induce this behavior with .ll code such as: 163 // %buffer = alloca [4096 x i8] 164 // %data = load [4096 x i8]* %argPtr 165 // store [4096 x i8] %data, [4096 x i8]* %buffer 166 static const unsigned MaxParallelChains = 64; 167 168 // Return the calling convention if the Value passed requires ABI mangling as it 169 // is a parameter to a function or a return value from a function which is not 170 // an intrinsic. 171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 172 if (auto *R = dyn_cast<ReturnInst>(V)) 173 return R->getParent()->getParent()->getCallingConv(); 174 175 if (auto *CI = dyn_cast<CallInst>(V)) { 176 const bool IsInlineAsm = CI->isInlineAsm(); 177 const bool IsIndirectFunctionCall = 178 !IsInlineAsm && !CI->getCalledFunction(); 179 180 // It is possible that the call instruction is an inline asm statement or an 181 // indirect function call in which case the return value of 182 // getCalledFunction() would be nullptr. 183 const bool IsInstrinsicCall = 184 !IsInlineAsm && !IsIndirectFunctionCall && 185 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 186 187 if (!IsInlineAsm && !IsInstrinsicCall) 188 return CI->getCallingConv(); 189 } 190 191 return None; 192 } 193 194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 195 const SDValue *Parts, unsigned NumParts, 196 MVT PartVT, EVT ValueVT, const Value *V, 197 Optional<CallingConv::ID> CC); 198 199 /// getCopyFromParts - Create a value that contains the specified legal parts 200 /// combined into the value they represent. If the parts combine to a type 201 /// larger than ValueVT then AssertOp can be used to specify whether the extra 202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 203 /// (ISD::AssertSext). 204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 205 const SDValue *Parts, unsigned NumParts, 206 MVT PartVT, EVT ValueVT, const Value *V, 207 Optional<CallingConv::ID> CC = None, 208 Optional<ISD::NodeType> AssertOp = None) { 209 if (ValueVT.isVector()) 210 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 211 CC); 212 213 assert(NumParts > 0 && "No parts to assemble!"); 214 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 215 SDValue Val = Parts[0]; 216 217 if (NumParts > 1) { 218 // Assemble the value from multiple parts. 219 if (ValueVT.isInteger()) { 220 unsigned PartBits = PartVT.getSizeInBits(); 221 unsigned ValueBits = ValueVT.getSizeInBits(); 222 223 // Assemble the power of 2 part. 224 unsigned RoundParts = 225 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 226 unsigned RoundBits = PartBits * RoundParts; 227 EVT RoundVT = RoundBits == ValueBits ? 228 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 229 SDValue Lo, Hi; 230 231 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 232 233 if (RoundParts > 2) { 234 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 235 PartVT, HalfVT, V); 236 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 237 RoundParts / 2, PartVT, HalfVT, V); 238 } else { 239 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 240 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 241 } 242 243 if (DAG.getDataLayout().isBigEndian()) 244 std::swap(Lo, Hi); 245 246 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 247 248 if (RoundParts < NumParts) { 249 // Assemble the trailing non-power-of-2 part. 250 unsigned OddParts = NumParts - RoundParts; 251 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 252 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 253 OddVT, V, CC); 254 255 // Combine the round and odd parts. 256 Lo = Val; 257 if (DAG.getDataLayout().isBigEndian()) 258 std::swap(Lo, Hi); 259 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 260 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 261 Hi = 262 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 263 DAG.getConstant(Lo.getValueSizeInBits(), DL, 264 TLI.getPointerTy(DAG.getDataLayout()))); 265 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 266 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 267 } 268 } else if (PartVT.isFloatingPoint()) { 269 // FP split into multiple FP parts (for ppcf128) 270 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 271 "Unexpected split"); 272 SDValue Lo, Hi; 273 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 274 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 275 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 276 std::swap(Lo, Hi); 277 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 278 } else { 279 // FP split into integer parts (soft fp) 280 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 281 !PartVT.isVector() && "Unexpected split"); 282 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 283 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 284 } 285 } 286 287 // There is now one part, held in Val. Correct it to match ValueVT. 288 // PartEVT is the type of the register class that holds the value. 289 // ValueVT is the type of the inline asm operation. 290 EVT PartEVT = Val.getValueType(); 291 292 if (PartEVT == ValueVT) 293 return Val; 294 295 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 296 ValueVT.bitsLT(PartEVT)) { 297 // For an FP value in an integer part, we need to truncate to the right 298 // width first. 299 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 300 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 301 } 302 303 // Handle types that have the same size. 304 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 306 307 // Handle types with different sizes. 308 if (PartEVT.isInteger() && ValueVT.isInteger()) { 309 if (ValueVT.bitsLT(PartEVT)) { 310 // For a truncate, see if we have any information to 311 // indicate whether the truncated bits will always be 312 // zero or sign-extension. 313 if (AssertOp.hasValue()) 314 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 315 DAG.getValueType(ValueVT)); 316 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 317 } 318 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 319 } 320 321 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 322 // FP_ROUND's are always exact here. 323 if (ValueVT.bitsLT(Val.getValueType())) 324 return DAG.getNode( 325 ISD::FP_ROUND, DL, ValueVT, Val, 326 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 327 328 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 329 } 330 331 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 332 // then truncating. 333 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 334 ValueVT.bitsLT(PartEVT)) { 335 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 336 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 337 } 338 339 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 340 } 341 342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 343 const Twine &ErrMsg) { 344 const Instruction *I = dyn_cast_or_null<Instruction>(V); 345 if (!V) 346 return Ctx.emitError(ErrMsg); 347 348 const char *AsmError = ", possible invalid constraint for vector type"; 349 if (const CallInst *CI = dyn_cast<CallInst>(I)) 350 if (isa<InlineAsm>(CI->getCalledValue())) 351 return Ctx.emitError(I, ErrMsg + AsmError); 352 353 return Ctx.emitError(I, ErrMsg); 354 } 355 356 /// getCopyFromPartsVector - Create a value that contains the specified legal 357 /// parts combined into the value they represent. If the parts combine to a 358 /// type larger than ValueVT then AssertOp can be used to specify whether the 359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 360 /// ValueVT (ISD::AssertSext). 361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 362 const SDValue *Parts, unsigned NumParts, 363 MVT PartVT, EVT ValueVT, const Value *V, 364 Optional<CallingConv::ID> CallConv) { 365 assert(ValueVT.isVector() && "Not a vector value"); 366 assert(NumParts > 0 && "No parts to assemble!"); 367 const bool IsABIRegCopy = CallConv.hasValue(); 368 369 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 370 SDValue Val = Parts[0]; 371 372 // Handle a multi-element vector. 373 if (NumParts > 1) { 374 EVT IntermediateVT; 375 MVT RegisterVT; 376 unsigned NumIntermediates; 377 unsigned NumRegs; 378 379 if (IsABIRegCopy) { 380 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 381 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } else { 384 NumRegs = 385 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 386 NumIntermediates, RegisterVT); 387 } 388 389 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 390 NumParts = NumRegs; // Silence a compiler warning. 391 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 392 assert(RegisterVT.getSizeInBits() == 393 Parts[0].getSimpleValueType().getSizeInBits() && 394 "Part type sizes don't match!"); 395 396 // Assemble the parts into intermediate operands. 397 SmallVector<SDValue, 8> Ops(NumIntermediates); 398 if (NumIntermediates == NumParts) { 399 // If the register was not expanded, truncate or copy the value, 400 // as appropriate. 401 for (unsigned i = 0; i != NumParts; ++i) 402 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 403 PartVT, IntermediateVT, V); 404 } else if (NumParts > 0) { 405 // If the intermediate type was expanded, build the intermediate 406 // operands from the parts. 407 assert(NumParts % NumIntermediates == 0 && 408 "Must expand into a divisible number of parts!"); 409 unsigned Factor = NumParts / NumIntermediates; 410 for (unsigned i = 0; i != NumIntermediates; ++i) 411 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 412 PartVT, IntermediateVT, V); 413 } 414 415 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 416 // intermediate operands. 417 EVT BuiltVectorTy = 418 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 419 (IntermediateVT.isVector() 420 ? IntermediateVT.getVectorNumElements() * NumParts 421 : NumIntermediates)); 422 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 423 : ISD::BUILD_VECTOR, 424 DL, BuiltVectorTy, Ops); 425 } 426 427 // There is now one part, held in Val. Correct it to match ValueVT. 428 EVT PartEVT = Val.getValueType(); 429 430 if (PartEVT == ValueVT) 431 return Val; 432 433 if (PartEVT.isVector()) { 434 // If the element type of the source/dest vectors are the same, but the 435 // parts vector has more elements than the value vector, then we have a 436 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 437 // elements we want. 438 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 439 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 440 "Cannot narrow, it would be a lossy transformation"); 441 return DAG.getNode( 442 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 443 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 444 } 445 446 // Vector/Vector bitcast. 447 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 448 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 449 450 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 451 "Cannot handle this kind of promotion"); 452 // Promoted vector extract 453 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 454 455 } 456 457 // Trivial bitcast if the types are the same size and the destination 458 // vector type is legal. 459 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 460 TLI.isTypeLegal(ValueVT)) 461 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 462 463 if (ValueVT.getVectorNumElements() != 1) { 464 // Certain ABIs require that vectors are passed as integers. For vectors 465 // are the same size, this is an obvious bitcast. 466 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 467 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 468 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 469 // Bitcast Val back the original type and extract the corresponding 470 // vector we want. 471 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 472 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 473 ValueVT.getVectorElementType(), Elts); 474 Val = DAG.getBitcast(WiderVecType, Val); 475 return DAG.getNode( 476 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 477 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 478 } 479 480 diagnosePossiblyInvalidConstraint( 481 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 482 return DAG.getUNDEF(ValueVT); 483 } 484 485 // Handle cases such as i8 -> <1 x i1> 486 EVT ValueSVT = ValueVT.getVectorElementType(); 487 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 488 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 489 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 490 491 return DAG.getBuildVector(ValueVT, DL, Val); 492 } 493 494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 495 SDValue Val, SDValue *Parts, unsigned NumParts, 496 MVT PartVT, const Value *V, 497 Optional<CallingConv::ID> CallConv); 498 499 /// getCopyToParts - Create a series of nodes that contain the specified value 500 /// split into legal parts. If the parts contain more bits than Val, then, for 501 /// integers, ExtendKind can be used to specify how to generate the extra bits. 502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 503 SDValue *Parts, unsigned NumParts, MVT PartVT, 504 const Value *V, 505 Optional<CallingConv::ID> CallConv = None, 506 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 507 EVT ValueVT = Val.getValueType(); 508 509 // Handle the vector case separately. 510 if (ValueVT.isVector()) 511 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 512 CallConv); 513 514 unsigned PartBits = PartVT.getSizeInBits(); 515 unsigned OrigNumParts = NumParts; 516 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 517 "Copying to an illegal type!"); 518 519 if (NumParts == 0) 520 return; 521 522 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 523 EVT PartEVT = PartVT; 524 if (PartEVT == ValueVT) { 525 assert(NumParts == 1 && "No-op copy with multiple parts!"); 526 Parts[0] = Val; 527 return; 528 } 529 530 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 531 // If the parts cover more bits than the value has, promote the value. 532 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 533 assert(NumParts == 1 && "Do not know what to promote to!"); 534 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 535 } else { 536 if (ValueVT.isFloatingPoint()) { 537 // FP values need to be bitcast, then extended if they are being put 538 // into a larger container. 539 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 540 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 541 } 542 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 543 ValueVT.isInteger() && 544 "Unknown mismatch!"); 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 546 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 547 if (PartVT == MVT::x86mmx) 548 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 549 } 550 } else if (PartBits == ValueVT.getSizeInBits()) { 551 // Different types of the same size. 552 assert(NumParts == 1 && PartEVT != ValueVT); 553 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 554 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 555 // If the parts cover less bits than value has, truncate the value. 556 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 557 ValueVT.isInteger() && 558 "Unknown mismatch!"); 559 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 560 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 561 if (PartVT == MVT::x86mmx) 562 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 563 } 564 565 // The value may have changed - recompute ValueVT. 566 ValueVT = Val.getValueType(); 567 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 568 "Failed to tile the value with PartVT!"); 569 570 if (NumParts == 1) { 571 if (PartEVT != ValueVT) { 572 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 573 "scalar-to-vector conversion failed"); 574 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 575 } 576 577 Parts[0] = Val; 578 return; 579 } 580 581 // Expand the value into multiple parts. 582 if (NumParts & (NumParts - 1)) { 583 // The number of parts is not a power of 2. Split off and copy the tail. 584 assert(PartVT.isInteger() && ValueVT.isInteger() && 585 "Do not know what to expand to!"); 586 unsigned RoundParts = 1 << Log2_32(NumParts); 587 unsigned RoundBits = RoundParts * PartBits; 588 unsigned OddParts = NumParts - RoundParts; 589 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 590 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 591 592 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 593 CallConv); 594 595 if (DAG.getDataLayout().isBigEndian()) 596 // The odd parts were reversed by getCopyToParts - unreverse them. 597 std::reverse(Parts + RoundParts, Parts + NumParts); 598 599 NumParts = RoundParts; 600 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 601 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 602 } 603 604 // The number of parts is a power of 2. Repeatedly bisect the value using 605 // EXTRACT_ELEMENT. 606 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 607 EVT::getIntegerVT(*DAG.getContext(), 608 ValueVT.getSizeInBits()), 609 Val); 610 611 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 612 for (unsigned i = 0; i < NumParts; i += StepSize) { 613 unsigned ThisBits = StepSize * PartBits / 2; 614 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 615 SDValue &Part0 = Parts[i]; 616 SDValue &Part1 = Parts[i+StepSize/2]; 617 618 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 619 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 620 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 621 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 622 623 if (ThisBits == PartBits && ThisVT != PartVT) { 624 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 625 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 626 } 627 } 628 } 629 630 if (DAG.getDataLayout().isBigEndian()) 631 std::reverse(Parts, Parts + OrigNumParts); 632 } 633 634 static SDValue widenVectorToPartType(SelectionDAG &DAG, 635 SDValue Val, const SDLoc &DL, EVT PartVT) { 636 if (!PartVT.isVector()) 637 return SDValue(); 638 639 EVT ValueVT = Val.getValueType(); 640 unsigned PartNumElts = PartVT.getVectorNumElements(); 641 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 642 if (PartNumElts > ValueNumElts && 643 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 644 EVT ElementVT = PartVT.getVectorElementType(); 645 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 646 // undef elements. 647 SmallVector<SDValue, 16> Ops; 648 DAG.ExtractVectorElements(Val, Ops); 649 SDValue EltUndef = DAG.getUNDEF(ElementVT); 650 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 651 Ops.push_back(EltUndef); 652 653 // FIXME: Use CONCAT for 2x -> 4x. 654 return DAG.getBuildVector(PartVT, DL, Ops); 655 } 656 657 return SDValue(); 658 } 659 660 /// getCopyToPartsVector - Create a series of nodes that contain the specified 661 /// value split into legal parts. 662 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 663 SDValue Val, SDValue *Parts, unsigned NumParts, 664 MVT PartVT, const Value *V, 665 Optional<CallingConv::ID> CallConv) { 666 EVT ValueVT = Val.getValueType(); 667 assert(ValueVT.isVector() && "Not a vector"); 668 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 669 const bool IsABIRegCopy = CallConv.hasValue(); 670 671 if (NumParts == 1) { 672 EVT PartEVT = PartVT; 673 if (PartEVT == ValueVT) { 674 // Nothing to do. 675 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 676 // Bitconvert vector->vector case. 677 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 678 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 679 Val = Widened; 680 } else if (PartVT.isVector() && 681 PartEVT.getVectorElementType().bitsGE( 682 ValueVT.getVectorElementType()) && 683 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 684 685 // Promoted vector extract 686 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 687 } else { 688 if (ValueVT.getVectorNumElements() == 1) { 689 Val = DAG.getNode( 690 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 691 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 692 } else { 693 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 694 "lossy conversion of vector to scalar type"); 695 EVT IntermediateType = 696 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 697 Val = DAG.getBitcast(IntermediateType, Val); 698 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 699 } 700 } 701 702 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 703 Parts[0] = Val; 704 return; 705 } 706 707 // Handle a multi-element vector. 708 EVT IntermediateVT; 709 MVT RegisterVT; 710 unsigned NumIntermediates; 711 unsigned NumRegs; 712 if (IsABIRegCopy) { 713 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 714 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 715 NumIntermediates, RegisterVT); 716 } else { 717 NumRegs = 718 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 719 NumIntermediates, RegisterVT); 720 } 721 722 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 723 NumParts = NumRegs; // Silence a compiler warning. 724 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 725 726 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 727 IntermediateVT.getVectorNumElements() : 1; 728 729 // Convert the vector to the appropriate type if necessary. 730 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 731 732 EVT BuiltVectorTy = EVT::getVectorVT( 733 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 734 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 735 if (ValueVT != BuiltVectorTy) { 736 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 737 Val = Widened; 738 739 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 740 } 741 742 // Split the vector into intermediate operands. 743 SmallVector<SDValue, 8> Ops(NumIntermediates); 744 for (unsigned i = 0; i != NumIntermediates; ++i) { 745 if (IntermediateVT.isVector()) { 746 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 747 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 748 } else { 749 Ops[i] = DAG.getNode( 750 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 751 DAG.getConstant(i, DL, IdxVT)); 752 } 753 } 754 755 // Split the intermediate operands into legal parts. 756 if (NumParts == NumIntermediates) { 757 // If the register was not expanded, promote or copy the value, 758 // as appropriate. 759 for (unsigned i = 0; i != NumParts; ++i) 760 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 761 } else if (NumParts > 0) { 762 // If the intermediate type was expanded, split each the value into 763 // legal parts. 764 assert(NumIntermediates != 0 && "division by zero"); 765 assert(NumParts % NumIntermediates == 0 && 766 "Must expand into a divisible number of parts!"); 767 unsigned Factor = NumParts / NumIntermediates; 768 for (unsigned i = 0; i != NumIntermediates; ++i) 769 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 770 CallConv); 771 } 772 } 773 774 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 775 EVT valuevt, Optional<CallingConv::ID> CC) 776 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 777 RegCount(1, regs.size()), CallConv(CC) {} 778 779 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 780 const DataLayout &DL, unsigned Reg, Type *Ty, 781 Optional<CallingConv::ID> CC) { 782 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 783 784 CallConv = CC; 785 786 for (EVT ValueVT : ValueVTs) { 787 unsigned NumRegs = 788 isABIMangled() 789 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 790 : TLI.getNumRegisters(Context, ValueVT); 791 MVT RegisterVT = 792 isABIMangled() 793 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 794 : TLI.getRegisterType(Context, ValueVT); 795 for (unsigned i = 0; i != NumRegs; ++i) 796 Regs.push_back(Reg + i); 797 RegVTs.push_back(RegisterVT); 798 RegCount.push_back(NumRegs); 799 Reg += NumRegs; 800 } 801 } 802 803 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 804 FunctionLoweringInfo &FuncInfo, 805 const SDLoc &dl, SDValue &Chain, 806 SDValue *Flag, const Value *V) const { 807 // A Value with type {} or [0 x %t] needs no registers. 808 if (ValueVTs.empty()) 809 return SDValue(); 810 811 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 812 813 // Assemble the legal parts into the final values. 814 SmallVector<SDValue, 4> Values(ValueVTs.size()); 815 SmallVector<SDValue, 8> Parts; 816 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 817 // Copy the legal parts from the registers. 818 EVT ValueVT = ValueVTs[Value]; 819 unsigned NumRegs = RegCount[Value]; 820 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 821 *DAG.getContext(), 822 CallConv.getValue(), RegVTs[Value]) 823 : RegVTs[Value]; 824 825 Parts.resize(NumRegs); 826 for (unsigned i = 0; i != NumRegs; ++i) { 827 SDValue P; 828 if (!Flag) { 829 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 830 } else { 831 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 832 *Flag = P.getValue(2); 833 } 834 835 Chain = P.getValue(1); 836 Parts[i] = P; 837 838 // If the source register was virtual and if we know something about it, 839 // add an assert node. 840 if (!Register::isVirtualRegister(Regs[Part + i]) || 841 !RegisterVT.isInteger()) 842 continue; 843 844 const FunctionLoweringInfo::LiveOutInfo *LOI = 845 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 846 if (!LOI) 847 continue; 848 849 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 850 unsigned NumSignBits = LOI->NumSignBits; 851 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 852 853 if (NumZeroBits == RegSize) { 854 // The current value is a zero. 855 // Explicitly express that as it would be easier for 856 // optimizations to kick in. 857 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 858 continue; 859 } 860 861 // FIXME: We capture more information than the dag can represent. For 862 // now, just use the tightest assertzext/assertsext possible. 863 bool isSExt; 864 EVT FromVT(MVT::Other); 865 if (NumZeroBits) { 866 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 867 isSExt = false; 868 } else if (NumSignBits > 1) { 869 FromVT = 870 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 871 isSExt = true; 872 } else { 873 continue; 874 } 875 // Add an assertion node. 876 assert(FromVT != MVT::Other); 877 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 878 RegisterVT, P, DAG.getValueType(FromVT)); 879 } 880 881 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 882 RegisterVT, ValueVT, V, CallConv); 883 Part += NumRegs; 884 Parts.clear(); 885 } 886 887 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 888 } 889 890 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 891 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 892 const Value *V, 893 ISD::NodeType PreferredExtendType) const { 894 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 895 ISD::NodeType ExtendKind = PreferredExtendType; 896 897 // Get the list of the values's legal parts. 898 unsigned NumRegs = Regs.size(); 899 SmallVector<SDValue, 8> Parts(NumRegs); 900 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 901 unsigned NumParts = RegCount[Value]; 902 903 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 904 *DAG.getContext(), 905 CallConv.getValue(), RegVTs[Value]) 906 : RegVTs[Value]; 907 908 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 909 ExtendKind = ISD::ZERO_EXTEND; 910 911 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 912 NumParts, RegisterVT, V, CallConv, ExtendKind); 913 Part += NumParts; 914 } 915 916 // Copy the parts into the registers. 917 SmallVector<SDValue, 8> Chains(NumRegs); 918 for (unsigned i = 0; i != NumRegs; ++i) { 919 SDValue Part; 920 if (!Flag) { 921 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 922 } else { 923 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 924 *Flag = Part.getValue(1); 925 } 926 927 Chains[i] = Part.getValue(0); 928 } 929 930 if (NumRegs == 1 || Flag) 931 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 932 // flagged to it. That is the CopyToReg nodes and the user are considered 933 // a single scheduling unit. If we create a TokenFactor and return it as 934 // chain, then the TokenFactor is both a predecessor (operand) of the 935 // user as well as a successor (the TF operands are flagged to the user). 936 // c1, f1 = CopyToReg 937 // c2, f2 = CopyToReg 938 // c3 = TokenFactor c1, c2 939 // ... 940 // = op c3, ..., f2 941 Chain = Chains[NumRegs-1]; 942 else 943 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 944 } 945 946 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 947 unsigned MatchingIdx, const SDLoc &dl, 948 SelectionDAG &DAG, 949 std::vector<SDValue> &Ops) const { 950 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 951 952 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 953 if (HasMatching) 954 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 955 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 956 // Put the register class of the virtual registers in the flag word. That 957 // way, later passes can recompute register class constraints for inline 958 // assembly as well as normal instructions. 959 // Don't do this for tied operands that can use the regclass information 960 // from the def. 961 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 962 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 963 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 964 } 965 966 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 967 Ops.push_back(Res); 968 969 if (Code == InlineAsm::Kind_Clobber) { 970 // Clobbers should always have a 1:1 mapping with registers, and may 971 // reference registers that have illegal (e.g. vector) types. Hence, we 972 // shouldn't try to apply any sort of splitting logic to them. 973 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 974 "No 1:1 mapping from clobbers to regs?"); 975 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 976 (void)SP; 977 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 978 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 979 assert( 980 (Regs[I] != SP || 981 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 982 "If we clobbered the stack pointer, MFI should know about it."); 983 } 984 return; 985 } 986 987 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 988 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 989 MVT RegisterVT = RegVTs[Value]; 990 for (unsigned i = 0; i != NumRegs; ++i) { 991 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 992 unsigned TheReg = Regs[Reg++]; 993 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 994 } 995 } 996 } 997 998 SmallVector<std::pair<unsigned, unsigned>, 4> 999 RegsForValue::getRegsAndSizes() const { 1000 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 1001 unsigned I = 0; 1002 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 1003 unsigned RegCount = std::get<0>(CountAndVT); 1004 MVT RegisterVT = std::get<1>(CountAndVT); 1005 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1006 for (unsigned E = I + RegCount; I != E; ++I) 1007 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1008 } 1009 return OutVec; 1010 } 1011 1012 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1013 const TargetLibraryInfo *li) { 1014 AA = aa; 1015 GFI = gfi; 1016 LibInfo = li; 1017 DL = &DAG.getDataLayout(); 1018 Context = DAG.getContext(); 1019 LPadToCallSiteMap.clear(); 1020 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1021 } 1022 1023 void SelectionDAGBuilder::clear() { 1024 NodeMap.clear(); 1025 UnusedArgNodeMap.clear(); 1026 PendingLoads.clear(); 1027 PendingExports.clear(); 1028 CurInst = nullptr; 1029 HasTailCall = false; 1030 SDNodeOrder = LowestSDNodeOrder; 1031 StatepointLowering.clear(); 1032 } 1033 1034 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1035 DanglingDebugInfoMap.clear(); 1036 } 1037 1038 SDValue SelectionDAGBuilder::getRoot() { 1039 if (PendingLoads.empty()) 1040 return DAG.getRoot(); 1041 1042 if (PendingLoads.size() == 1) { 1043 SDValue Root = PendingLoads[0]; 1044 DAG.setRoot(Root); 1045 PendingLoads.clear(); 1046 return Root; 1047 } 1048 1049 // Otherwise, we have to make a token factor node. 1050 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1051 PendingLoads.clear(); 1052 DAG.setRoot(Root); 1053 return Root; 1054 } 1055 1056 SDValue SelectionDAGBuilder::getControlRoot() { 1057 SDValue Root = DAG.getRoot(); 1058 1059 if (PendingExports.empty()) 1060 return Root; 1061 1062 // Turn all of the CopyToReg chains into one factored node. 1063 if (Root.getOpcode() != ISD::EntryToken) { 1064 unsigned i = 0, e = PendingExports.size(); 1065 for (; i != e; ++i) { 1066 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1067 if (PendingExports[i].getNode()->getOperand(0) == Root) 1068 break; // Don't add the root if we already indirectly depend on it. 1069 } 1070 1071 if (i == e) 1072 PendingExports.push_back(Root); 1073 } 1074 1075 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1076 PendingExports); 1077 PendingExports.clear(); 1078 DAG.setRoot(Root); 1079 return Root; 1080 } 1081 1082 void SelectionDAGBuilder::visit(const Instruction &I) { 1083 // Set up outgoing PHI node register values before emitting the terminator. 1084 if (I.isTerminator()) { 1085 HandlePHINodesInSuccessorBlocks(I.getParent()); 1086 } 1087 1088 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1089 if (!isa<DbgInfoIntrinsic>(I)) 1090 ++SDNodeOrder; 1091 1092 CurInst = &I; 1093 1094 visit(I.getOpcode(), I); 1095 1096 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1097 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1098 // maps to this instruction. 1099 // TODO: We could handle all flags (nsw, etc) here. 1100 // TODO: If an IR instruction maps to >1 node, only the final node will have 1101 // flags set. 1102 if (SDNode *Node = getNodeForIRValue(&I)) { 1103 SDNodeFlags IncomingFlags; 1104 IncomingFlags.copyFMF(*FPMO); 1105 if (!Node->getFlags().isDefined()) 1106 Node->setFlags(IncomingFlags); 1107 else 1108 Node->intersectFlagsWith(IncomingFlags); 1109 } 1110 } 1111 // Constrained FP intrinsics with fpexcept.ignore should also get 1112 // the NoFPExcept flag. 1113 if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I)) 1114 if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore) 1115 if (SDNode *Node = getNodeForIRValue(&I)) { 1116 SDNodeFlags Flags = Node->getFlags(); 1117 Flags.setNoFPExcept(true); 1118 Node->setFlags(Flags); 1119 } 1120 1121 if (!I.isTerminator() && !HasTailCall && 1122 !isStatepoint(&I)) // statepoints handle their exports internally 1123 CopyToExportRegsIfNeeded(&I); 1124 1125 CurInst = nullptr; 1126 } 1127 1128 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1129 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1130 } 1131 1132 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1133 // Note: this doesn't use InstVisitor, because it has to work with 1134 // ConstantExpr's in addition to instructions. 1135 switch (Opcode) { 1136 default: llvm_unreachable("Unknown instruction type encountered!"); 1137 // Build the switch statement using the Instruction.def file. 1138 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1139 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1140 #include "llvm/IR/Instruction.def" 1141 } 1142 } 1143 1144 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1145 const DIExpression *Expr) { 1146 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1147 const DbgValueInst *DI = DDI.getDI(); 1148 DIVariable *DanglingVariable = DI->getVariable(); 1149 DIExpression *DanglingExpr = DI->getExpression(); 1150 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1151 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1152 return true; 1153 } 1154 return false; 1155 }; 1156 1157 for (auto &DDIMI : DanglingDebugInfoMap) { 1158 DanglingDebugInfoVector &DDIV = DDIMI.second; 1159 1160 // If debug info is to be dropped, run it through final checks to see 1161 // whether it can be salvaged. 1162 for (auto &DDI : DDIV) 1163 if (isMatchingDbgValue(DDI)) 1164 salvageUnresolvedDbgValue(DDI); 1165 1166 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1167 } 1168 } 1169 1170 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1171 // generate the debug data structures now that we've seen its definition. 1172 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1173 SDValue Val) { 1174 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1175 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1176 return; 1177 1178 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1179 for (auto &DDI : DDIV) { 1180 const DbgValueInst *DI = DDI.getDI(); 1181 assert(DI && "Ill-formed DanglingDebugInfo"); 1182 DebugLoc dl = DDI.getdl(); 1183 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1184 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1185 DILocalVariable *Variable = DI->getVariable(); 1186 DIExpression *Expr = DI->getExpression(); 1187 assert(Variable->isValidLocationForIntrinsic(dl) && 1188 "Expected inlined-at fields to agree"); 1189 SDDbgValue *SDV; 1190 if (Val.getNode()) { 1191 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1192 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1193 // we couldn't resolve it directly when examining the DbgValue intrinsic 1194 // in the first place we should not be more successful here). Unless we 1195 // have some test case that prove this to be correct we should avoid 1196 // calling EmitFuncArgumentDbgValue here. 1197 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1198 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1199 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1200 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1201 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1202 // inserted after the definition of Val when emitting the instructions 1203 // after ISel. An alternative could be to teach 1204 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1205 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1206 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1207 << ValSDNodeOrder << "\n"); 1208 SDV = getDbgValue(Val, Variable, Expr, dl, 1209 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1210 DAG.AddDbgValue(SDV, Val.getNode(), false); 1211 } else 1212 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1213 << "in EmitFuncArgumentDbgValue\n"); 1214 } else { 1215 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1216 auto Undef = 1217 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1218 auto SDV = 1219 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1220 DAG.AddDbgValue(SDV, nullptr, false); 1221 } 1222 } 1223 DDIV.clear(); 1224 } 1225 1226 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1227 Value *V = DDI.getDI()->getValue(); 1228 DILocalVariable *Var = DDI.getDI()->getVariable(); 1229 DIExpression *Expr = DDI.getDI()->getExpression(); 1230 DebugLoc DL = DDI.getdl(); 1231 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1232 unsigned SDOrder = DDI.getSDNodeOrder(); 1233 1234 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1235 // that DW_OP_stack_value is desired. 1236 assert(isa<DbgValueInst>(DDI.getDI())); 1237 bool StackValue = true; 1238 1239 // Can this Value can be encoded without any further work? 1240 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1241 return; 1242 1243 // Attempt to salvage back through as many instructions as possible. Bail if 1244 // a non-instruction is seen, such as a constant expression or global 1245 // variable. FIXME: Further work could recover those too. 1246 while (isa<Instruction>(V)) { 1247 Instruction &VAsInst = *cast<Instruction>(V); 1248 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1249 1250 // If we cannot salvage any further, and haven't yet found a suitable debug 1251 // expression, bail out. 1252 if (!NewExpr) 1253 break; 1254 1255 // New value and expr now represent this debuginfo. 1256 V = VAsInst.getOperand(0); 1257 Expr = NewExpr; 1258 1259 // Some kind of simplification occurred: check whether the operand of the 1260 // salvaged debug expression can be encoded in this DAG. 1261 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1262 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1263 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1264 return; 1265 } 1266 } 1267 1268 // This was the final opportunity to salvage this debug information, and it 1269 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1270 // any earlier variable location. 1271 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1272 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1273 DAG.AddDbgValue(SDV, nullptr, false); 1274 1275 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1276 << "\n"); 1277 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1278 << "\n"); 1279 } 1280 1281 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1282 DIExpression *Expr, DebugLoc dl, 1283 DebugLoc InstDL, unsigned Order) { 1284 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1285 SDDbgValue *SDV; 1286 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1287 isa<ConstantPointerNull>(V)) { 1288 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1289 DAG.AddDbgValue(SDV, nullptr, false); 1290 return true; 1291 } 1292 1293 // If the Value is a frame index, we can create a FrameIndex debug value 1294 // without relying on the DAG at all. 1295 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1296 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1297 if (SI != FuncInfo.StaticAllocaMap.end()) { 1298 auto SDV = 1299 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1300 /*IsIndirect*/ false, dl, SDNodeOrder); 1301 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1302 // is still available even if the SDNode gets optimized out. 1303 DAG.AddDbgValue(SDV, nullptr, false); 1304 return true; 1305 } 1306 } 1307 1308 // Do not use getValue() in here; we don't want to generate code at 1309 // this point if it hasn't been done yet. 1310 SDValue N = NodeMap[V]; 1311 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1312 N = UnusedArgNodeMap[V]; 1313 if (N.getNode()) { 1314 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1315 return true; 1316 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1317 DAG.AddDbgValue(SDV, N.getNode(), false); 1318 return true; 1319 } 1320 1321 // Special rules apply for the first dbg.values of parameter variables in a 1322 // function. Identify them by the fact they reference Argument Values, that 1323 // they're parameters, and they are parameters of the current function. We 1324 // need to let them dangle until they get an SDNode. 1325 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1326 !InstDL.getInlinedAt(); 1327 if (!IsParamOfFunc) { 1328 // The value is not used in this block yet (or it would have an SDNode). 1329 // We still want the value to appear for the user if possible -- if it has 1330 // an associated VReg, we can refer to that instead. 1331 auto VMI = FuncInfo.ValueMap.find(V); 1332 if (VMI != FuncInfo.ValueMap.end()) { 1333 unsigned Reg = VMI->second; 1334 // If this is a PHI node, it may be split up into several MI PHI nodes 1335 // (in FunctionLoweringInfo::set). 1336 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1337 V->getType(), None); 1338 if (RFV.occupiesMultipleRegs()) { 1339 unsigned Offset = 0; 1340 unsigned BitsToDescribe = 0; 1341 if (auto VarSize = Var->getSizeInBits()) 1342 BitsToDescribe = *VarSize; 1343 if (auto Fragment = Expr->getFragmentInfo()) 1344 BitsToDescribe = Fragment->SizeInBits; 1345 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1346 unsigned RegisterSize = RegAndSize.second; 1347 // Bail out if all bits are described already. 1348 if (Offset >= BitsToDescribe) 1349 break; 1350 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1351 ? BitsToDescribe - Offset 1352 : RegisterSize; 1353 auto FragmentExpr = DIExpression::createFragmentExpression( 1354 Expr, Offset, FragmentSize); 1355 if (!FragmentExpr) 1356 continue; 1357 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1358 false, dl, SDNodeOrder); 1359 DAG.AddDbgValue(SDV, nullptr, false); 1360 Offset += RegisterSize; 1361 } 1362 } else { 1363 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1364 DAG.AddDbgValue(SDV, nullptr, false); 1365 } 1366 return true; 1367 } 1368 } 1369 1370 return false; 1371 } 1372 1373 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1374 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1375 for (auto &Pair : DanglingDebugInfoMap) 1376 for (auto &DDI : Pair.second) 1377 salvageUnresolvedDbgValue(DDI); 1378 clearDanglingDebugInfo(); 1379 } 1380 1381 /// getCopyFromRegs - If there was virtual register allocated for the value V 1382 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1383 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1384 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1385 SDValue Result; 1386 1387 if (It != FuncInfo.ValueMap.end()) { 1388 unsigned InReg = It->second; 1389 1390 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1391 DAG.getDataLayout(), InReg, Ty, 1392 None); // This is not an ABI copy. 1393 SDValue Chain = DAG.getEntryNode(); 1394 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1395 V); 1396 resolveDanglingDebugInfo(V, Result); 1397 } 1398 1399 return Result; 1400 } 1401 1402 /// getValue - Return an SDValue for the given Value. 1403 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1404 // If we already have an SDValue for this value, use it. It's important 1405 // to do this first, so that we don't create a CopyFromReg if we already 1406 // have a regular SDValue. 1407 SDValue &N = NodeMap[V]; 1408 if (N.getNode()) return N; 1409 1410 // If there's a virtual register allocated and initialized for this 1411 // value, use it. 1412 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1413 return copyFromReg; 1414 1415 // Otherwise create a new SDValue and remember it. 1416 SDValue Val = getValueImpl(V); 1417 NodeMap[V] = Val; 1418 resolveDanglingDebugInfo(V, Val); 1419 return Val; 1420 } 1421 1422 // Return true if SDValue exists for the given Value 1423 bool SelectionDAGBuilder::findValue(const Value *V) const { 1424 return (NodeMap.find(V) != NodeMap.end()) || 1425 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1426 } 1427 1428 /// getNonRegisterValue - Return an SDValue for the given Value, but 1429 /// don't look in FuncInfo.ValueMap for a virtual register. 1430 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1431 // If we already have an SDValue for this value, use it. 1432 SDValue &N = NodeMap[V]; 1433 if (N.getNode()) { 1434 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1435 // Remove the debug location from the node as the node is about to be used 1436 // in a location which may differ from the original debug location. This 1437 // is relevant to Constant and ConstantFP nodes because they can appear 1438 // as constant expressions inside PHI nodes. 1439 N->setDebugLoc(DebugLoc()); 1440 } 1441 return N; 1442 } 1443 1444 // Otherwise create a new SDValue and remember it. 1445 SDValue Val = getValueImpl(V); 1446 NodeMap[V] = Val; 1447 resolveDanglingDebugInfo(V, Val); 1448 return Val; 1449 } 1450 1451 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1452 /// Create an SDValue for the given value. 1453 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1455 1456 if (const Constant *C = dyn_cast<Constant>(V)) { 1457 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1458 1459 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1460 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1461 1462 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1463 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1464 1465 if (isa<ConstantPointerNull>(C)) { 1466 unsigned AS = V->getType()->getPointerAddressSpace(); 1467 return DAG.getConstant(0, getCurSDLoc(), 1468 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1469 } 1470 1471 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1472 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1473 1474 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1475 return DAG.getUNDEF(VT); 1476 1477 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1478 visit(CE->getOpcode(), *CE); 1479 SDValue N1 = NodeMap[V]; 1480 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1481 return N1; 1482 } 1483 1484 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1485 SmallVector<SDValue, 4> Constants; 1486 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1487 OI != OE; ++OI) { 1488 SDNode *Val = getValue(*OI).getNode(); 1489 // If the operand is an empty aggregate, there are no values. 1490 if (!Val) continue; 1491 // Add each leaf value from the operand to the Constants list 1492 // to form a flattened list of all the values. 1493 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1494 Constants.push_back(SDValue(Val, i)); 1495 } 1496 1497 return DAG.getMergeValues(Constants, getCurSDLoc()); 1498 } 1499 1500 if (const ConstantDataSequential *CDS = 1501 dyn_cast<ConstantDataSequential>(C)) { 1502 SmallVector<SDValue, 4> Ops; 1503 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1504 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1505 // Add each leaf value from the operand to the Constants list 1506 // to form a flattened list of all the values. 1507 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1508 Ops.push_back(SDValue(Val, i)); 1509 } 1510 1511 if (isa<ArrayType>(CDS->getType())) 1512 return DAG.getMergeValues(Ops, getCurSDLoc()); 1513 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1514 } 1515 1516 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1517 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1518 "Unknown struct or array constant!"); 1519 1520 SmallVector<EVT, 4> ValueVTs; 1521 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1522 unsigned NumElts = ValueVTs.size(); 1523 if (NumElts == 0) 1524 return SDValue(); // empty struct 1525 SmallVector<SDValue, 4> Constants(NumElts); 1526 for (unsigned i = 0; i != NumElts; ++i) { 1527 EVT EltVT = ValueVTs[i]; 1528 if (isa<UndefValue>(C)) 1529 Constants[i] = DAG.getUNDEF(EltVT); 1530 else if (EltVT.isFloatingPoint()) 1531 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1532 else 1533 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1534 } 1535 1536 return DAG.getMergeValues(Constants, getCurSDLoc()); 1537 } 1538 1539 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1540 return DAG.getBlockAddress(BA, VT); 1541 1542 VectorType *VecTy = cast<VectorType>(V->getType()); 1543 unsigned NumElements = VecTy->getNumElements(); 1544 1545 // Now that we know the number and type of the elements, get that number of 1546 // elements into the Ops array based on what kind of constant it is. 1547 SmallVector<SDValue, 16> Ops; 1548 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1549 for (unsigned i = 0; i != NumElements; ++i) 1550 Ops.push_back(getValue(CV->getOperand(i))); 1551 } else { 1552 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1553 EVT EltVT = 1554 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1555 1556 SDValue Op; 1557 if (EltVT.isFloatingPoint()) 1558 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1559 else 1560 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1561 Ops.assign(NumElements, Op); 1562 } 1563 1564 // Create a BUILD_VECTOR node. 1565 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1566 } 1567 1568 // If this is a static alloca, generate it as the frameindex instead of 1569 // computation. 1570 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1571 DenseMap<const AllocaInst*, int>::iterator SI = 1572 FuncInfo.StaticAllocaMap.find(AI); 1573 if (SI != FuncInfo.StaticAllocaMap.end()) 1574 return DAG.getFrameIndex(SI->second, 1575 TLI.getFrameIndexTy(DAG.getDataLayout())); 1576 } 1577 1578 // If this is an instruction which fast-isel has deferred, select it now. 1579 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1580 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1581 1582 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1583 Inst->getType(), getABIRegCopyCC(V)); 1584 SDValue Chain = DAG.getEntryNode(); 1585 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1586 } 1587 1588 llvm_unreachable("Can't get register for value!"); 1589 } 1590 1591 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1592 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1593 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1594 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1595 bool IsSEH = isAsynchronousEHPersonality(Pers); 1596 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1597 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1598 if (!IsSEH) 1599 CatchPadMBB->setIsEHScopeEntry(); 1600 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1601 if (IsMSVCCXX || IsCoreCLR) 1602 CatchPadMBB->setIsEHFuncletEntry(); 1603 // Wasm does not need catchpads anymore 1604 if (!IsWasmCXX) 1605 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1606 getControlRoot())); 1607 } 1608 1609 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1610 // Update machine-CFG edge. 1611 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1612 FuncInfo.MBB->addSuccessor(TargetMBB); 1613 1614 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1615 bool IsSEH = isAsynchronousEHPersonality(Pers); 1616 if (IsSEH) { 1617 // If this is not a fall-through branch or optimizations are switched off, 1618 // emit the branch. 1619 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1620 TM.getOptLevel() == CodeGenOpt::None) 1621 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1622 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1623 return; 1624 } 1625 1626 // Figure out the funclet membership for the catchret's successor. 1627 // This will be used by the FuncletLayout pass to determine how to order the 1628 // BB's. 1629 // A 'catchret' returns to the outer scope's color. 1630 Value *ParentPad = I.getCatchSwitchParentPad(); 1631 const BasicBlock *SuccessorColor; 1632 if (isa<ConstantTokenNone>(ParentPad)) 1633 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1634 else 1635 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1636 assert(SuccessorColor && "No parent funclet for catchret!"); 1637 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1638 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1639 1640 // Create the terminator node. 1641 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1642 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1643 DAG.getBasicBlock(SuccessorColorMBB)); 1644 DAG.setRoot(Ret); 1645 } 1646 1647 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1648 // Don't emit any special code for the cleanuppad instruction. It just marks 1649 // the start of an EH scope/funclet. 1650 FuncInfo.MBB->setIsEHScopeEntry(); 1651 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1652 if (Pers != EHPersonality::Wasm_CXX) { 1653 FuncInfo.MBB->setIsEHFuncletEntry(); 1654 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1655 } 1656 } 1657 1658 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1659 // the control flow always stops at the single catch pad, as it does for a 1660 // cleanup pad. In case the exception caught is not of the types the catch pad 1661 // catches, it will be rethrown by a rethrow. 1662 static void findWasmUnwindDestinations( 1663 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1664 BranchProbability Prob, 1665 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1666 &UnwindDests) { 1667 while (EHPadBB) { 1668 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1669 if (isa<CleanupPadInst>(Pad)) { 1670 // Stop on cleanup pads. 1671 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1672 UnwindDests.back().first->setIsEHScopeEntry(); 1673 break; 1674 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1675 // Add the catchpad handlers to the possible destinations. We don't 1676 // continue to the unwind destination of the catchswitch for wasm. 1677 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1678 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1679 UnwindDests.back().first->setIsEHScopeEntry(); 1680 } 1681 break; 1682 } else { 1683 continue; 1684 } 1685 } 1686 } 1687 1688 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1689 /// many places it could ultimately go. In the IR, we have a single unwind 1690 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1691 /// This function skips over imaginary basic blocks that hold catchswitch 1692 /// instructions, and finds all the "real" machine 1693 /// basic block destinations. As those destinations may not be successors of 1694 /// EHPadBB, here we also calculate the edge probability to those destinations. 1695 /// The passed-in Prob is the edge probability to EHPadBB. 1696 static void findUnwindDestinations( 1697 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1698 BranchProbability Prob, 1699 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1700 &UnwindDests) { 1701 EHPersonality Personality = 1702 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1703 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1704 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1705 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1706 bool IsSEH = isAsynchronousEHPersonality(Personality); 1707 1708 if (IsWasmCXX) { 1709 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1710 assert(UnwindDests.size() <= 1 && 1711 "There should be at most one unwind destination for wasm"); 1712 return; 1713 } 1714 1715 while (EHPadBB) { 1716 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1717 BasicBlock *NewEHPadBB = nullptr; 1718 if (isa<LandingPadInst>(Pad)) { 1719 // Stop on landingpads. They are not funclets. 1720 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1721 break; 1722 } else if (isa<CleanupPadInst>(Pad)) { 1723 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1724 // personalities. 1725 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1726 UnwindDests.back().first->setIsEHScopeEntry(); 1727 UnwindDests.back().first->setIsEHFuncletEntry(); 1728 break; 1729 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1730 // Add the catchpad handlers to the possible destinations. 1731 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1732 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1733 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1734 if (IsMSVCCXX || IsCoreCLR) 1735 UnwindDests.back().first->setIsEHFuncletEntry(); 1736 if (!IsSEH) 1737 UnwindDests.back().first->setIsEHScopeEntry(); 1738 } 1739 NewEHPadBB = CatchSwitch->getUnwindDest(); 1740 } else { 1741 continue; 1742 } 1743 1744 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1745 if (BPI && NewEHPadBB) 1746 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1747 EHPadBB = NewEHPadBB; 1748 } 1749 } 1750 1751 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1752 // Update successor info. 1753 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1754 auto UnwindDest = I.getUnwindDest(); 1755 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1756 BranchProbability UnwindDestProb = 1757 (BPI && UnwindDest) 1758 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1759 : BranchProbability::getZero(); 1760 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1761 for (auto &UnwindDest : UnwindDests) { 1762 UnwindDest.first->setIsEHPad(); 1763 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1764 } 1765 FuncInfo.MBB->normalizeSuccProbs(); 1766 1767 // Create the terminator node. 1768 SDValue Ret = 1769 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1770 DAG.setRoot(Ret); 1771 } 1772 1773 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1774 report_fatal_error("visitCatchSwitch not yet implemented!"); 1775 } 1776 1777 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1778 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1779 auto &DL = DAG.getDataLayout(); 1780 SDValue Chain = getControlRoot(); 1781 SmallVector<ISD::OutputArg, 8> Outs; 1782 SmallVector<SDValue, 8> OutVals; 1783 1784 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1785 // lower 1786 // 1787 // %val = call <ty> @llvm.experimental.deoptimize() 1788 // ret <ty> %val 1789 // 1790 // differently. 1791 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1792 LowerDeoptimizingReturn(); 1793 return; 1794 } 1795 1796 if (!FuncInfo.CanLowerReturn) { 1797 unsigned DemoteReg = FuncInfo.DemoteRegister; 1798 const Function *F = I.getParent()->getParent(); 1799 1800 // Emit a store of the return value through the virtual register. 1801 // Leave Outs empty so that LowerReturn won't try to load return 1802 // registers the usual way. 1803 SmallVector<EVT, 1> PtrValueVTs; 1804 ComputeValueVTs(TLI, DL, 1805 F->getReturnType()->getPointerTo( 1806 DAG.getDataLayout().getAllocaAddrSpace()), 1807 PtrValueVTs); 1808 1809 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1810 DemoteReg, PtrValueVTs[0]); 1811 SDValue RetOp = getValue(I.getOperand(0)); 1812 1813 SmallVector<EVT, 4> ValueVTs, MemVTs; 1814 SmallVector<uint64_t, 4> Offsets; 1815 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1816 &Offsets); 1817 unsigned NumValues = ValueVTs.size(); 1818 1819 SmallVector<SDValue, 4> Chains(NumValues); 1820 for (unsigned i = 0; i != NumValues; ++i) { 1821 // An aggregate return value cannot wrap around the address space, so 1822 // offsets to its parts don't wrap either. 1823 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1824 1825 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1826 if (MemVTs[i] != ValueVTs[i]) 1827 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1828 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1829 // FIXME: better loc info would be nice. 1830 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1831 } 1832 1833 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1834 MVT::Other, Chains); 1835 } else if (I.getNumOperands() != 0) { 1836 SmallVector<EVT, 4> ValueVTs; 1837 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1838 unsigned NumValues = ValueVTs.size(); 1839 if (NumValues) { 1840 SDValue RetOp = getValue(I.getOperand(0)); 1841 1842 const Function *F = I.getParent()->getParent(); 1843 1844 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1845 I.getOperand(0)->getType(), F->getCallingConv(), 1846 /*IsVarArg*/ false); 1847 1848 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1849 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1850 Attribute::SExt)) 1851 ExtendKind = ISD::SIGN_EXTEND; 1852 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1853 Attribute::ZExt)) 1854 ExtendKind = ISD::ZERO_EXTEND; 1855 1856 LLVMContext &Context = F->getContext(); 1857 bool RetInReg = F->getAttributes().hasAttribute( 1858 AttributeList::ReturnIndex, Attribute::InReg); 1859 1860 for (unsigned j = 0; j != NumValues; ++j) { 1861 EVT VT = ValueVTs[j]; 1862 1863 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1864 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1865 1866 CallingConv::ID CC = F->getCallingConv(); 1867 1868 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1869 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1870 SmallVector<SDValue, 4> Parts(NumParts); 1871 getCopyToParts(DAG, getCurSDLoc(), 1872 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1873 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1874 1875 // 'inreg' on function refers to return value 1876 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1877 if (RetInReg) 1878 Flags.setInReg(); 1879 1880 if (I.getOperand(0)->getType()->isPointerTy()) { 1881 Flags.setPointer(); 1882 Flags.setPointerAddrSpace( 1883 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1884 } 1885 1886 if (NeedsRegBlock) { 1887 Flags.setInConsecutiveRegs(); 1888 if (j == NumValues - 1) 1889 Flags.setInConsecutiveRegsLast(); 1890 } 1891 1892 // Propagate extension type if any 1893 if (ExtendKind == ISD::SIGN_EXTEND) 1894 Flags.setSExt(); 1895 else if (ExtendKind == ISD::ZERO_EXTEND) 1896 Flags.setZExt(); 1897 1898 for (unsigned i = 0; i < NumParts; ++i) { 1899 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1900 VT, /*isfixed=*/true, 0, 0)); 1901 OutVals.push_back(Parts[i]); 1902 } 1903 } 1904 } 1905 } 1906 1907 // Push in swifterror virtual register as the last element of Outs. This makes 1908 // sure swifterror virtual register will be returned in the swifterror 1909 // physical register. 1910 const Function *F = I.getParent()->getParent(); 1911 if (TLI.supportSwiftError() && 1912 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1913 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1914 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1915 Flags.setSwiftError(); 1916 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1917 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1918 true /*isfixed*/, 1 /*origidx*/, 1919 0 /*partOffs*/)); 1920 // Create SDNode for the swifterror virtual register. 1921 OutVals.push_back( 1922 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1923 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1924 EVT(TLI.getPointerTy(DL)))); 1925 } 1926 1927 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1928 CallingConv::ID CallConv = 1929 DAG.getMachineFunction().getFunction().getCallingConv(); 1930 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1931 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1932 1933 // Verify that the target's LowerReturn behaved as expected. 1934 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1935 "LowerReturn didn't return a valid chain!"); 1936 1937 // Update the DAG with the new chain value resulting from return lowering. 1938 DAG.setRoot(Chain); 1939 } 1940 1941 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1942 /// created for it, emit nodes to copy the value into the virtual 1943 /// registers. 1944 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1945 // Skip empty types 1946 if (V->getType()->isEmptyTy()) 1947 return; 1948 1949 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1950 if (VMI != FuncInfo.ValueMap.end()) { 1951 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1952 CopyValueToVirtualRegister(V, VMI->second); 1953 } 1954 } 1955 1956 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1957 /// the current basic block, add it to ValueMap now so that we'll get a 1958 /// CopyTo/FromReg. 1959 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1960 // No need to export constants. 1961 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1962 1963 // Already exported? 1964 if (FuncInfo.isExportedInst(V)) return; 1965 1966 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1967 CopyValueToVirtualRegister(V, Reg); 1968 } 1969 1970 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1971 const BasicBlock *FromBB) { 1972 // The operands of the setcc have to be in this block. We don't know 1973 // how to export them from some other block. 1974 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1975 // Can export from current BB. 1976 if (VI->getParent() == FromBB) 1977 return true; 1978 1979 // Is already exported, noop. 1980 return FuncInfo.isExportedInst(V); 1981 } 1982 1983 // If this is an argument, we can export it if the BB is the entry block or 1984 // if it is already exported. 1985 if (isa<Argument>(V)) { 1986 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1987 return true; 1988 1989 // Otherwise, can only export this if it is already exported. 1990 return FuncInfo.isExportedInst(V); 1991 } 1992 1993 // Otherwise, constants can always be exported. 1994 return true; 1995 } 1996 1997 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1998 BranchProbability 1999 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 2000 const MachineBasicBlock *Dst) const { 2001 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2002 const BasicBlock *SrcBB = Src->getBasicBlock(); 2003 const BasicBlock *DstBB = Dst->getBasicBlock(); 2004 if (!BPI) { 2005 // If BPI is not available, set the default probability as 1 / N, where N is 2006 // the number of successors. 2007 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 2008 return BranchProbability(1, SuccSize); 2009 } 2010 return BPI->getEdgeProbability(SrcBB, DstBB); 2011 } 2012 2013 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2014 MachineBasicBlock *Dst, 2015 BranchProbability Prob) { 2016 if (!FuncInfo.BPI) 2017 Src->addSuccessorWithoutProb(Dst); 2018 else { 2019 if (Prob.isUnknown()) 2020 Prob = getEdgeProbability(Src, Dst); 2021 Src->addSuccessor(Dst, Prob); 2022 } 2023 } 2024 2025 static bool InBlock(const Value *V, const BasicBlock *BB) { 2026 if (const Instruction *I = dyn_cast<Instruction>(V)) 2027 return I->getParent() == BB; 2028 return true; 2029 } 2030 2031 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2032 /// This function emits a branch and is used at the leaves of an OR or an 2033 /// AND operator tree. 2034 void 2035 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2036 MachineBasicBlock *TBB, 2037 MachineBasicBlock *FBB, 2038 MachineBasicBlock *CurBB, 2039 MachineBasicBlock *SwitchBB, 2040 BranchProbability TProb, 2041 BranchProbability FProb, 2042 bool InvertCond) { 2043 const BasicBlock *BB = CurBB->getBasicBlock(); 2044 2045 // If the leaf of the tree is a comparison, merge the condition into 2046 // the caseblock. 2047 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2048 // The operands of the cmp have to be in this block. We don't know 2049 // how to export them from some other block. If this is the first block 2050 // of the sequence, no exporting is needed. 2051 if (CurBB == SwitchBB || 2052 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2053 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2054 ISD::CondCode Condition; 2055 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2056 ICmpInst::Predicate Pred = 2057 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2058 Condition = getICmpCondCode(Pred); 2059 } else { 2060 const FCmpInst *FC = cast<FCmpInst>(Cond); 2061 FCmpInst::Predicate Pred = 2062 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2063 Condition = getFCmpCondCode(Pred); 2064 if (TM.Options.NoNaNsFPMath) 2065 Condition = getFCmpCodeWithoutNaN(Condition); 2066 } 2067 2068 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2069 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2070 SL->SwitchCases.push_back(CB); 2071 return; 2072 } 2073 } 2074 2075 // Create a CaseBlock record representing this branch. 2076 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2077 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2078 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2079 SL->SwitchCases.push_back(CB); 2080 } 2081 2082 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2083 MachineBasicBlock *TBB, 2084 MachineBasicBlock *FBB, 2085 MachineBasicBlock *CurBB, 2086 MachineBasicBlock *SwitchBB, 2087 Instruction::BinaryOps Opc, 2088 BranchProbability TProb, 2089 BranchProbability FProb, 2090 bool InvertCond) { 2091 // Skip over not part of the tree and remember to invert op and operands at 2092 // next level. 2093 Value *NotCond; 2094 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2095 InBlock(NotCond, CurBB->getBasicBlock())) { 2096 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2097 !InvertCond); 2098 return; 2099 } 2100 2101 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2102 // Compute the effective opcode for Cond, taking into account whether it needs 2103 // to be inverted, e.g. 2104 // and (not (or A, B)), C 2105 // gets lowered as 2106 // and (and (not A, not B), C) 2107 unsigned BOpc = 0; 2108 if (BOp) { 2109 BOpc = BOp->getOpcode(); 2110 if (InvertCond) { 2111 if (BOpc == Instruction::And) 2112 BOpc = Instruction::Or; 2113 else if (BOpc == Instruction::Or) 2114 BOpc = Instruction::And; 2115 } 2116 } 2117 2118 // If this node is not part of the or/and tree, emit it as a branch. 2119 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2120 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2121 BOp->getParent() != CurBB->getBasicBlock() || 2122 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2123 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2124 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2125 TProb, FProb, InvertCond); 2126 return; 2127 } 2128 2129 // Create TmpBB after CurBB. 2130 MachineFunction::iterator BBI(CurBB); 2131 MachineFunction &MF = DAG.getMachineFunction(); 2132 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2133 CurBB->getParent()->insert(++BBI, TmpBB); 2134 2135 if (Opc == Instruction::Or) { 2136 // Codegen X | Y as: 2137 // BB1: 2138 // jmp_if_X TBB 2139 // jmp TmpBB 2140 // TmpBB: 2141 // jmp_if_Y TBB 2142 // jmp FBB 2143 // 2144 2145 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2146 // The requirement is that 2147 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2148 // = TrueProb for original BB. 2149 // Assuming the original probabilities are A and B, one choice is to set 2150 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2151 // A/(1+B) and 2B/(1+B). This choice assumes that 2152 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2153 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2154 // TmpBB, but the math is more complicated. 2155 2156 auto NewTrueProb = TProb / 2; 2157 auto NewFalseProb = TProb / 2 + FProb; 2158 // Emit the LHS condition. 2159 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2160 NewTrueProb, NewFalseProb, InvertCond); 2161 2162 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2163 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2164 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2165 // Emit the RHS condition into TmpBB. 2166 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2167 Probs[0], Probs[1], InvertCond); 2168 } else { 2169 assert(Opc == Instruction::And && "Unknown merge op!"); 2170 // Codegen X & Y as: 2171 // BB1: 2172 // jmp_if_X TmpBB 2173 // jmp FBB 2174 // TmpBB: 2175 // jmp_if_Y TBB 2176 // jmp FBB 2177 // 2178 // This requires creation of TmpBB after CurBB. 2179 2180 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2181 // The requirement is that 2182 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2183 // = FalseProb for original BB. 2184 // Assuming the original probabilities are A and B, one choice is to set 2185 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2186 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2187 // TrueProb for BB1 * FalseProb for TmpBB. 2188 2189 auto NewTrueProb = TProb + FProb / 2; 2190 auto NewFalseProb = FProb / 2; 2191 // Emit the LHS condition. 2192 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2193 NewTrueProb, NewFalseProb, InvertCond); 2194 2195 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2196 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2197 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2198 // Emit the RHS condition into TmpBB. 2199 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2200 Probs[0], Probs[1], InvertCond); 2201 } 2202 } 2203 2204 /// If the set of cases should be emitted as a series of branches, return true. 2205 /// If we should emit this as a bunch of and/or'd together conditions, return 2206 /// false. 2207 bool 2208 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2209 if (Cases.size() != 2) return true; 2210 2211 // If this is two comparisons of the same values or'd or and'd together, they 2212 // will get folded into a single comparison, so don't emit two blocks. 2213 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2214 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2215 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2216 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2217 return false; 2218 } 2219 2220 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2221 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2222 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2223 Cases[0].CC == Cases[1].CC && 2224 isa<Constant>(Cases[0].CmpRHS) && 2225 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2226 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2227 return false; 2228 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2229 return false; 2230 } 2231 2232 return true; 2233 } 2234 2235 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2236 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2237 2238 // Update machine-CFG edges. 2239 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2240 2241 if (I.isUnconditional()) { 2242 // Update machine-CFG edges. 2243 BrMBB->addSuccessor(Succ0MBB); 2244 2245 // If this is not a fall-through branch or optimizations are switched off, 2246 // emit the branch. 2247 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2248 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2249 MVT::Other, getControlRoot(), 2250 DAG.getBasicBlock(Succ0MBB))); 2251 2252 return; 2253 } 2254 2255 // If this condition is one of the special cases we handle, do special stuff 2256 // now. 2257 const Value *CondVal = I.getCondition(); 2258 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2259 2260 // If this is a series of conditions that are or'd or and'd together, emit 2261 // this as a sequence of branches instead of setcc's with and/or operations. 2262 // As long as jumps are not expensive, this should improve performance. 2263 // For example, instead of something like: 2264 // cmp A, B 2265 // C = seteq 2266 // cmp D, E 2267 // F = setle 2268 // or C, F 2269 // jnz foo 2270 // Emit: 2271 // cmp A, B 2272 // je foo 2273 // cmp D, E 2274 // jle foo 2275 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2276 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2277 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2278 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2279 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2280 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2281 Opcode, 2282 getEdgeProbability(BrMBB, Succ0MBB), 2283 getEdgeProbability(BrMBB, Succ1MBB), 2284 /*InvertCond=*/false); 2285 // If the compares in later blocks need to use values not currently 2286 // exported from this block, export them now. This block should always 2287 // be the first entry. 2288 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2289 2290 // Allow some cases to be rejected. 2291 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2292 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2293 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2294 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2295 } 2296 2297 // Emit the branch for this block. 2298 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2299 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2300 return; 2301 } 2302 2303 // Okay, we decided not to do this, remove any inserted MBB's and clear 2304 // SwitchCases. 2305 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2306 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2307 2308 SL->SwitchCases.clear(); 2309 } 2310 } 2311 2312 // Create a CaseBlock record representing this branch. 2313 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2314 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2315 2316 // Use visitSwitchCase to actually insert the fast branch sequence for this 2317 // cond branch. 2318 visitSwitchCase(CB, BrMBB); 2319 } 2320 2321 /// visitSwitchCase - Emits the necessary code to represent a single node in 2322 /// the binary search tree resulting from lowering a switch instruction. 2323 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2324 MachineBasicBlock *SwitchBB) { 2325 SDValue Cond; 2326 SDValue CondLHS = getValue(CB.CmpLHS); 2327 SDLoc dl = CB.DL; 2328 2329 if (CB.CC == ISD::SETTRUE) { 2330 // Branch or fall through to TrueBB. 2331 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2332 SwitchBB->normalizeSuccProbs(); 2333 if (CB.TrueBB != NextBlock(SwitchBB)) { 2334 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2335 DAG.getBasicBlock(CB.TrueBB))); 2336 } 2337 return; 2338 } 2339 2340 auto &TLI = DAG.getTargetLoweringInfo(); 2341 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2342 2343 // Build the setcc now. 2344 if (!CB.CmpMHS) { 2345 // Fold "(X == true)" to X and "(X == false)" to !X to 2346 // handle common cases produced by branch lowering. 2347 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2348 CB.CC == ISD::SETEQ) 2349 Cond = CondLHS; 2350 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2351 CB.CC == ISD::SETEQ) { 2352 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2353 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2354 } else { 2355 SDValue CondRHS = getValue(CB.CmpRHS); 2356 2357 // If a pointer's DAG type is larger than its memory type then the DAG 2358 // values are zero-extended. This breaks signed comparisons so truncate 2359 // back to the underlying type before doing the compare. 2360 if (CondLHS.getValueType() != MemVT) { 2361 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2362 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2363 } 2364 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2365 } 2366 } else { 2367 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2368 2369 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2370 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2371 2372 SDValue CmpOp = getValue(CB.CmpMHS); 2373 EVT VT = CmpOp.getValueType(); 2374 2375 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2376 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2377 ISD::SETLE); 2378 } else { 2379 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2380 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2381 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2382 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2383 } 2384 } 2385 2386 // Update successor info 2387 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2388 // TrueBB and FalseBB are always different unless the incoming IR is 2389 // degenerate. This only happens when running llc on weird IR. 2390 if (CB.TrueBB != CB.FalseBB) 2391 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2392 SwitchBB->normalizeSuccProbs(); 2393 2394 // If the lhs block is the next block, invert the condition so that we can 2395 // fall through to the lhs instead of the rhs block. 2396 if (CB.TrueBB == NextBlock(SwitchBB)) { 2397 std::swap(CB.TrueBB, CB.FalseBB); 2398 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2399 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2400 } 2401 2402 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2403 MVT::Other, getControlRoot(), Cond, 2404 DAG.getBasicBlock(CB.TrueBB)); 2405 2406 // Insert the false branch. Do this even if it's a fall through branch, 2407 // this makes it easier to do DAG optimizations which require inverting 2408 // the branch condition. 2409 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2410 DAG.getBasicBlock(CB.FalseBB)); 2411 2412 DAG.setRoot(BrCond); 2413 } 2414 2415 /// visitJumpTable - Emit JumpTable node in the current MBB 2416 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2417 // Emit the code for the jump table 2418 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2419 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2420 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2421 JT.Reg, PTy); 2422 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2423 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2424 MVT::Other, Index.getValue(1), 2425 Table, Index); 2426 DAG.setRoot(BrJumpTable); 2427 } 2428 2429 /// visitJumpTableHeader - This function emits necessary code to produce index 2430 /// in the JumpTable from switch case. 2431 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2432 JumpTableHeader &JTH, 2433 MachineBasicBlock *SwitchBB) { 2434 SDLoc dl = getCurSDLoc(); 2435 2436 // Subtract the lowest switch case value from the value being switched on. 2437 SDValue SwitchOp = getValue(JTH.SValue); 2438 EVT VT = SwitchOp.getValueType(); 2439 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2440 DAG.getConstant(JTH.First, dl, VT)); 2441 2442 // The SDNode we just created, which holds the value being switched on minus 2443 // the smallest case value, needs to be copied to a virtual register so it 2444 // can be used as an index into the jump table in a subsequent basic block. 2445 // This value may be smaller or larger than the target's pointer type, and 2446 // therefore require extension or truncating. 2447 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2448 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2449 2450 unsigned JumpTableReg = 2451 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2452 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2453 JumpTableReg, SwitchOp); 2454 JT.Reg = JumpTableReg; 2455 2456 if (!JTH.OmitRangeCheck) { 2457 // Emit the range check for the jump table, and branch to the default block 2458 // for the switch statement if the value being switched on exceeds the 2459 // largest case in the switch. 2460 SDValue CMP = DAG.getSetCC( 2461 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2462 Sub.getValueType()), 2463 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2464 2465 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2466 MVT::Other, CopyTo, CMP, 2467 DAG.getBasicBlock(JT.Default)); 2468 2469 // Avoid emitting unnecessary branches to the next block. 2470 if (JT.MBB != NextBlock(SwitchBB)) 2471 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2472 DAG.getBasicBlock(JT.MBB)); 2473 2474 DAG.setRoot(BrCond); 2475 } else { 2476 // Avoid emitting unnecessary branches to the next block. 2477 if (JT.MBB != NextBlock(SwitchBB)) 2478 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2479 DAG.getBasicBlock(JT.MBB))); 2480 else 2481 DAG.setRoot(CopyTo); 2482 } 2483 } 2484 2485 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2486 /// variable if there exists one. 2487 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2488 SDValue &Chain) { 2489 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2490 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2491 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2492 MachineFunction &MF = DAG.getMachineFunction(); 2493 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2494 MachineSDNode *Node = 2495 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2496 if (Global) { 2497 MachinePointerInfo MPInfo(Global); 2498 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2499 MachineMemOperand::MODereferenceable; 2500 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2501 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2502 DAG.setNodeMemRefs(Node, {MemRef}); 2503 } 2504 if (PtrTy != PtrMemTy) 2505 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2506 return SDValue(Node, 0); 2507 } 2508 2509 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2510 /// tail spliced into a stack protector check success bb. 2511 /// 2512 /// For a high level explanation of how this fits into the stack protector 2513 /// generation see the comment on the declaration of class 2514 /// StackProtectorDescriptor. 2515 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2516 MachineBasicBlock *ParentBB) { 2517 2518 // First create the loads to the guard/stack slot for the comparison. 2519 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2520 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2521 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2522 2523 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2524 int FI = MFI.getStackProtectorIndex(); 2525 2526 SDValue Guard; 2527 SDLoc dl = getCurSDLoc(); 2528 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2529 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2530 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2531 2532 // Generate code to load the content of the guard slot. 2533 SDValue GuardVal = DAG.getLoad( 2534 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2535 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2536 MachineMemOperand::MOVolatile); 2537 2538 if (TLI.useStackGuardXorFP()) 2539 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2540 2541 // Retrieve guard check function, nullptr if instrumentation is inlined. 2542 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2543 // The target provides a guard check function to validate the guard value. 2544 // Generate a call to that function with the content of the guard slot as 2545 // argument. 2546 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2547 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2548 2549 TargetLowering::ArgListTy Args; 2550 TargetLowering::ArgListEntry Entry; 2551 Entry.Node = GuardVal; 2552 Entry.Ty = FnTy->getParamType(0); 2553 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2554 Entry.IsInReg = true; 2555 Args.push_back(Entry); 2556 2557 TargetLowering::CallLoweringInfo CLI(DAG); 2558 CLI.setDebugLoc(getCurSDLoc()) 2559 .setChain(DAG.getEntryNode()) 2560 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2561 getValue(GuardCheckFn), std::move(Args)); 2562 2563 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2564 DAG.setRoot(Result.second); 2565 return; 2566 } 2567 2568 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2569 // Otherwise, emit a volatile load to retrieve the stack guard value. 2570 SDValue Chain = DAG.getEntryNode(); 2571 if (TLI.useLoadStackGuardNode()) { 2572 Guard = getLoadStackGuard(DAG, dl, Chain); 2573 } else { 2574 const Value *IRGuard = TLI.getSDagStackGuard(M); 2575 SDValue GuardPtr = getValue(IRGuard); 2576 2577 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2578 MachinePointerInfo(IRGuard, 0), Align, 2579 MachineMemOperand::MOVolatile); 2580 } 2581 2582 // Perform the comparison via a subtract/getsetcc. 2583 EVT VT = Guard.getValueType(); 2584 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2585 2586 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2587 *DAG.getContext(), 2588 Sub.getValueType()), 2589 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2590 2591 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2592 // branch to failure MBB. 2593 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2594 MVT::Other, GuardVal.getOperand(0), 2595 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2596 // Otherwise branch to success MBB. 2597 SDValue Br = DAG.getNode(ISD::BR, dl, 2598 MVT::Other, BrCond, 2599 DAG.getBasicBlock(SPD.getSuccessMBB())); 2600 2601 DAG.setRoot(Br); 2602 } 2603 2604 /// Codegen the failure basic block for a stack protector check. 2605 /// 2606 /// A failure stack protector machine basic block consists simply of a call to 2607 /// __stack_chk_fail(). 2608 /// 2609 /// For a high level explanation of how this fits into the stack protector 2610 /// generation see the comment on the declaration of class 2611 /// StackProtectorDescriptor. 2612 void 2613 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2614 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2615 TargetLowering::MakeLibCallOptions CallOptions; 2616 CallOptions.setDiscardResult(true); 2617 SDValue Chain = 2618 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2619 None, CallOptions, getCurSDLoc()).second; 2620 // On PS4, the "return address" must still be within the calling function, 2621 // even if it's at the very end, so emit an explicit TRAP here. 2622 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2623 if (TM.getTargetTriple().isPS4CPU()) 2624 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2625 2626 DAG.setRoot(Chain); 2627 } 2628 2629 /// visitBitTestHeader - This function emits necessary code to produce value 2630 /// suitable for "bit tests" 2631 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2632 MachineBasicBlock *SwitchBB) { 2633 SDLoc dl = getCurSDLoc(); 2634 2635 // Subtract the minimum value. 2636 SDValue SwitchOp = getValue(B.SValue); 2637 EVT VT = SwitchOp.getValueType(); 2638 SDValue RangeSub = 2639 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2640 2641 // Determine the type of the test operands. 2642 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2643 bool UsePtrType = false; 2644 if (!TLI.isTypeLegal(VT)) { 2645 UsePtrType = true; 2646 } else { 2647 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2648 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2649 // Switch table case range are encoded into series of masks. 2650 // Just use pointer type, it's guaranteed to fit. 2651 UsePtrType = true; 2652 break; 2653 } 2654 } 2655 SDValue Sub = RangeSub; 2656 if (UsePtrType) { 2657 VT = TLI.getPointerTy(DAG.getDataLayout()); 2658 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2659 } 2660 2661 B.RegVT = VT.getSimpleVT(); 2662 B.Reg = FuncInfo.CreateReg(B.RegVT); 2663 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2664 2665 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2666 2667 if (!B.OmitRangeCheck) 2668 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2669 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2670 SwitchBB->normalizeSuccProbs(); 2671 2672 SDValue Root = CopyTo; 2673 if (!B.OmitRangeCheck) { 2674 // Conditional branch to the default block. 2675 SDValue RangeCmp = DAG.getSetCC(dl, 2676 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2677 RangeSub.getValueType()), 2678 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2679 ISD::SETUGT); 2680 2681 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2682 DAG.getBasicBlock(B.Default)); 2683 } 2684 2685 // Avoid emitting unnecessary branches to the next block. 2686 if (MBB != NextBlock(SwitchBB)) 2687 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2688 2689 DAG.setRoot(Root); 2690 } 2691 2692 /// visitBitTestCase - this function produces one "bit test" 2693 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2694 MachineBasicBlock* NextMBB, 2695 BranchProbability BranchProbToNext, 2696 unsigned Reg, 2697 BitTestCase &B, 2698 MachineBasicBlock *SwitchBB) { 2699 SDLoc dl = getCurSDLoc(); 2700 MVT VT = BB.RegVT; 2701 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2702 SDValue Cmp; 2703 unsigned PopCount = countPopulation(B.Mask); 2704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2705 if (PopCount == 1) { 2706 // Testing for a single bit; just compare the shift count with what it 2707 // would need to be to shift a 1 bit in that position. 2708 Cmp = DAG.getSetCC( 2709 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2710 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2711 ISD::SETEQ); 2712 } else if (PopCount == BB.Range) { 2713 // There is only one zero bit in the range, test for it directly. 2714 Cmp = DAG.getSetCC( 2715 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2716 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2717 ISD::SETNE); 2718 } else { 2719 // Make desired shift 2720 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2721 DAG.getConstant(1, dl, VT), ShiftOp); 2722 2723 // Emit bit tests and jumps 2724 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2725 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2726 Cmp = DAG.getSetCC( 2727 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2728 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2729 } 2730 2731 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2732 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2733 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2734 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2735 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2736 // one as they are relative probabilities (and thus work more like weights), 2737 // and hence we need to normalize them to let the sum of them become one. 2738 SwitchBB->normalizeSuccProbs(); 2739 2740 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2741 MVT::Other, getControlRoot(), 2742 Cmp, DAG.getBasicBlock(B.TargetBB)); 2743 2744 // Avoid emitting unnecessary branches to the next block. 2745 if (NextMBB != NextBlock(SwitchBB)) 2746 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2747 DAG.getBasicBlock(NextMBB)); 2748 2749 DAG.setRoot(BrAnd); 2750 } 2751 2752 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2753 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2754 2755 // Retrieve successors. Look through artificial IR level blocks like 2756 // catchswitch for successors. 2757 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2758 const BasicBlock *EHPadBB = I.getSuccessor(1); 2759 2760 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2761 // have to do anything here to lower funclet bundles. 2762 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 2763 LLVMContext::OB_funclet, 2764 LLVMContext::OB_cfguardtarget}) && 2765 "Cannot lower invokes with arbitrary operand bundles yet!"); 2766 2767 const Value *Callee(I.getCalledValue()); 2768 const Function *Fn = dyn_cast<Function>(Callee); 2769 if (isa<InlineAsm>(Callee)) 2770 visitInlineAsm(&I); 2771 else if (Fn && Fn->isIntrinsic()) { 2772 switch (Fn->getIntrinsicID()) { 2773 default: 2774 llvm_unreachable("Cannot invoke this intrinsic"); 2775 case Intrinsic::donothing: 2776 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2777 break; 2778 case Intrinsic::experimental_patchpoint_void: 2779 case Intrinsic::experimental_patchpoint_i64: 2780 visitPatchpoint(&I, EHPadBB); 2781 break; 2782 case Intrinsic::experimental_gc_statepoint: 2783 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2784 break; 2785 case Intrinsic::wasm_rethrow_in_catch: { 2786 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2787 // special because it can be invoked, so we manually lower it to a DAG 2788 // node here. 2789 SmallVector<SDValue, 8> Ops; 2790 Ops.push_back(getRoot()); // inchain 2791 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2792 Ops.push_back( 2793 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2794 TLI.getPointerTy(DAG.getDataLayout()))); 2795 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2796 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2797 break; 2798 } 2799 } 2800 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2801 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2802 // Eventually we will support lowering the @llvm.experimental.deoptimize 2803 // intrinsic, and right now there are no plans to support other intrinsics 2804 // with deopt state. 2805 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2806 } else { 2807 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2808 } 2809 2810 // If the value of the invoke is used outside of its defining block, make it 2811 // available as a virtual register. 2812 // We already took care of the exported value for the statepoint instruction 2813 // during call to the LowerStatepoint. 2814 if (!isStatepoint(I)) { 2815 CopyToExportRegsIfNeeded(&I); 2816 } 2817 2818 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2819 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2820 BranchProbability EHPadBBProb = 2821 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2822 : BranchProbability::getZero(); 2823 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2824 2825 // Update successor info. 2826 addSuccessorWithProb(InvokeMBB, Return); 2827 for (auto &UnwindDest : UnwindDests) { 2828 UnwindDest.first->setIsEHPad(); 2829 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2830 } 2831 InvokeMBB->normalizeSuccProbs(); 2832 2833 // Drop into normal successor. 2834 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2835 DAG.getBasicBlock(Return))); 2836 } 2837 2838 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2839 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2840 2841 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2842 // have to do anything here to lower funclet bundles. 2843 assert(!I.hasOperandBundlesOtherThan( 2844 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2845 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2846 2847 assert(isa<InlineAsm>(I.getCalledValue()) && 2848 "Only know how to handle inlineasm callbr"); 2849 visitInlineAsm(&I); 2850 2851 // Retrieve successors. 2852 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2853 2854 // Update successor info. 2855 addSuccessorWithProb(CallBrMBB, Return); 2856 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2857 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2858 addSuccessorWithProb(CallBrMBB, Target); 2859 } 2860 CallBrMBB->normalizeSuccProbs(); 2861 2862 // Drop into default successor. 2863 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2864 MVT::Other, getControlRoot(), 2865 DAG.getBasicBlock(Return))); 2866 } 2867 2868 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2869 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2870 } 2871 2872 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2873 assert(FuncInfo.MBB->isEHPad() && 2874 "Call to landingpad not in landing pad!"); 2875 2876 // If there aren't registers to copy the values into (e.g., during SjLj 2877 // exceptions), then don't bother to create these DAG nodes. 2878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2879 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2880 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2881 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2882 return; 2883 2884 // If landingpad's return type is token type, we don't create DAG nodes 2885 // for its exception pointer and selector value. The extraction of exception 2886 // pointer or selector value from token type landingpads is not currently 2887 // supported. 2888 if (LP.getType()->isTokenTy()) 2889 return; 2890 2891 SmallVector<EVT, 2> ValueVTs; 2892 SDLoc dl = getCurSDLoc(); 2893 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2894 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2895 2896 // Get the two live-in registers as SDValues. The physregs have already been 2897 // copied into virtual registers. 2898 SDValue Ops[2]; 2899 if (FuncInfo.ExceptionPointerVirtReg) { 2900 Ops[0] = DAG.getZExtOrTrunc( 2901 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2902 FuncInfo.ExceptionPointerVirtReg, 2903 TLI.getPointerTy(DAG.getDataLayout())), 2904 dl, ValueVTs[0]); 2905 } else { 2906 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2907 } 2908 Ops[1] = DAG.getZExtOrTrunc( 2909 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2910 FuncInfo.ExceptionSelectorVirtReg, 2911 TLI.getPointerTy(DAG.getDataLayout())), 2912 dl, ValueVTs[1]); 2913 2914 // Merge into one. 2915 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2916 DAG.getVTList(ValueVTs), Ops); 2917 setValue(&LP, Res); 2918 } 2919 2920 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2921 MachineBasicBlock *Last) { 2922 // Update JTCases. 2923 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2924 if (SL->JTCases[i].first.HeaderBB == First) 2925 SL->JTCases[i].first.HeaderBB = Last; 2926 2927 // Update BitTestCases. 2928 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2929 if (SL->BitTestCases[i].Parent == First) 2930 SL->BitTestCases[i].Parent = Last; 2931 } 2932 2933 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2934 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2935 2936 // Update machine-CFG edges with unique successors. 2937 SmallSet<BasicBlock*, 32> Done; 2938 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2939 BasicBlock *BB = I.getSuccessor(i); 2940 bool Inserted = Done.insert(BB).second; 2941 if (!Inserted) 2942 continue; 2943 2944 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2945 addSuccessorWithProb(IndirectBrMBB, Succ); 2946 } 2947 IndirectBrMBB->normalizeSuccProbs(); 2948 2949 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2950 MVT::Other, getControlRoot(), 2951 getValue(I.getAddress()))); 2952 } 2953 2954 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2955 if (!DAG.getTarget().Options.TrapUnreachable) 2956 return; 2957 2958 // We may be able to ignore unreachable behind a noreturn call. 2959 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2960 const BasicBlock &BB = *I.getParent(); 2961 if (&I != &BB.front()) { 2962 BasicBlock::const_iterator PredI = 2963 std::prev(BasicBlock::const_iterator(&I)); 2964 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2965 if (Call->doesNotReturn()) 2966 return; 2967 } 2968 } 2969 } 2970 2971 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2972 } 2973 2974 void SelectionDAGBuilder::visitFSub(const User &I) { 2975 // -0.0 - X --> fneg 2976 Type *Ty = I.getType(); 2977 if (isa<Constant>(I.getOperand(0)) && 2978 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2979 SDValue Op2 = getValue(I.getOperand(1)); 2980 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2981 Op2.getValueType(), Op2)); 2982 return; 2983 } 2984 2985 visitBinary(I, ISD::FSUB); 2986 } 2987 2988 /// Checks if the given instruction performs a vector reduction, in which case 2989 /// we have the freedom to alter the elements in the result as long as the 2990 /// reduction of them stays unchanged. 2991 static bool isVectorReductionOp(const User *I) { 2992 const Instruction *Inst = dyn_cast<Instruction>(I); 2993 if (!Inst || !Inst->getType()->isVectorTy()) 2994 return false; 2995 2996 auto OpCode = Inst->getOpcode(); 2997 switch (OpCode) { 2998 case Instruction::Add: 2999 case Instruction::Mul: 3000 case Instruction::And: 3001 case Instruction::Or: 3002 case Instruction::Xor: 3003 break; 3004 case Instruction::FAdd: 3005 case Instruction::FMul: 3006 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3007 if (FPOp->getFastMathFlags().isFast()) 3008 break; 3009 LLVM_FALLTHROUGH; 3010 default: 3011 return false; 3012 } 3013 3014 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3015 // Ensure the reduction size is a power of 2. 3016 if (!isPowerOf2_32(ElemNum)) 3017 return false; 3018 3019 unsigned ElemNumToReduce = ElemNum; 3020 3021 // Do DFS search on the def-use chain from the given instruction. We only 3022 // allow four kinds of operations during the search until we reach the 3023 // instruction that extracts the first element from the vector: 3024 // 3025 // 1. The reduction operation of the same opcode as the given instruction. 3026 // 3027 // 2. PHI node. 3028 // 3029 // 3. ShuffleVector instruction together with a reduction operation that 3030 // does a partial reduction. 3031 // 3032 // 4. ExtractElement that extracts the first element from the vector, and we 3033 // stop searching the def-use chain here. 3034 // 3035 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3036 // from 1-3 to the stack to continue the DFS. The given instruction is not 3037 // a reduction operation if we meet any other instructions other than those 3038 // listed above. 3039 3040 SmallVector<const User *, 16> UsersToVisit{Inst}; 3041 SmallPtrSet<const User *, 16> Visited; 3042 bool ReduxExtracted = false; 3043 3044 while (!UsersToVisit.empty()) { 3045 auto User = UsersToVisit.back(); 3046 UsersToVisit.pop_back(); 3047 if (!Visited.insert(User).second) 3048 continue; 3049 3050 for (const auto *U : User->users()) { 3051 auto Inst = dyn_cast<Instruction>(U); 3052 if (!Inst) 3053 return false; 3054 3055 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3056 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3057 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3058 return false; 3059 UsersToVisit.push_back(U); 3060 } else if (const ShuffleVectorInst *ShufInst = 3061 dyn_cast<ShuffleVectorInst>(U)) { 3062 // Detect the following pattern: A ShuffleVector instruction together 3063 // with a reduction that do partial reduction on the first and second 3064 // ElemNumToReduce / 2 elements, and store the result in 3065 // ElemNumToReduce / 2 elements in another vector. 3066 3067 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3068 if (ResultElements < ElemNum) 3069 return false; 3070 3071 if (ElemNumToReduce == 1) 3072 return false; 3073 if (!isa<UndefValue>(U->getOperand(1))) 3074 return false; 3075 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3076 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3077 return false; 3078 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3079 if (ShufInst->getMaskValue(i) != -1) 3080 return false; 3081 3082 // There is only one user of this ShuffleVector instruction, which 3083 // must be a reduction operation. 3084 if (!U->hasOneUse()) 3085 return false; 3086 3087 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3088 if (!U2 || U2->getOpcode() != OpCode) 3089 return false; 3090 3091 // Check operands of the reduction operation. 3092 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3093 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3094 UsersToVisit.push_back(U2); 3095 ElemNumToReduce /= 2; 3096 } else 3097 return false; 3098 } else if (isa<ExtractElementInst>(U)) { 3099 // At this moment we should have reduced all elements in the vector. 3100 if (ElemNumToReduce != 1) 3101 return false; 3102 3103 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3104 if (!Val || !Val->isZero()) 3105 return false; 3106 3107 ReduxExtracted = true; 3108 } else 3109 return false; 3110 } 3111 } 3112 return ReduxExtracted; 3113 } 3114 3115 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3116 SDNodeFlags Flags; 3117 3118 SDValue Op = getValue(I.getOperand(0)); 3119 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3120 Op, Flags); 3121 setValue(&I, UnNodeValue); 3122 } 3123 3124 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3125 SDNodeFlags Flags; 3126 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3127 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3128 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3129 } 3130 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3131 Flags.setExact(ExactOp->isExact()); 3132 } 3133 if (isVectorReductionOp(&I)) { 3134 Flags.setVectorReduction(true); 3135 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3136 3137 // If no flags are set we will propagate the incoming flags, if any flags 3138 // are set, we will intersect them with the incoming flag and so we need to 3139 // copy the FMF flags here. 3140 if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) { 3141 Flags.copyFMF(*FPOp); 3142 } 3143 } 3144 3145 SDValue Op1 = getValue(I.getOperand(0)); 3146 SDValue Op2 = getValue(I.getOperand(1)); 3147 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3148 Op1, Op2, Flags); 3149 setValue(&I, BinNodeValue); 3150 } 3151 3152 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3153 SDValue Op1 = getValue(I.getOperand(0)); 3154 SDValue Op2 = getValue(I.getOperand(1)); 3155 3156 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3157 Op1.getValueType(), DAG.getDataLayout()); 3158 3159 // Coerce the shift amount to the right type if we can. 3160 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3161 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3162 unsigned Op2Size = Op2.getValueSizeInBits(); 3163 SDLoc DL = getCurSDLoc(); 3164 3165 // If the operand is smaller than the shift count type, promote it. 3166 if (ShiftSize > Op2Size) 3167 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3168 3169 // If the operand is larger than the shift count type but the shift 3170 // count type has enough bits to represent any shift value, truncate 3171 // it now. This is a common case and it exposes the truncate to 3172 // optimization early. 3173 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3174 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3175 // Otherwise we'll need to temporarily settle for some other convenient 3176 // type. Type legalization will make adjustments once the shiftee is split. 3177 else 3178 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3179 } 3180 3181 bool nuw = false; 3182 bool nsw = false; 3183 bool exact = false; 3184 3185 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3186 3187 if (const OverflowingBinaryOperator *OFBinOp = 3188 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3189 nuw = OFBinOp->hasNoUnsignedWrap(); 3190 nsw = OFBinOp->hasNoSignedWrap(); 3191 } 3192 if (const PossiblyExactOperator *ExactOp = 3193 dyn_cast<const PossiblyExactOperator>(&I)) 3194 exact = ExactOp->isExact(); 3195 } 3196 SDNodeFlags Flags; 3197 Flags.setExact(exact); 3198 Flags.setNoSignedWrap(nsw); 3199 Flags.setNoUnsignedWrap(nuw); 3200 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3201 Flags); 3202 setValue(&I, Res); 3203 } 3204 3205 void SelectionDAGBuilder::visitSDiv(const User &I) { 3206 SDValue Op1 = getValue(I.getOperand(0)); 3207 SDValue Op2 = getValue(I.getOperand(1)); 3208 3209 SDNodeFlags Flags; 3210 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3211 cast<PossiblyExactOperator>(&I)->isExact()); 3212 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3213 Op2, Flags)); 3214 } 3215 3216 void SelectionDAGBuilder::visitICmp(const User &I) { 3217 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3218 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3219 predicate = IC->getPredicate(); 3220 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3221 predicate = ICmpInst::Predicate(IC->getPredicate()); 3222 SDValue Op1 = getValue(I.getOperand(0)); 3223 SDValue Op2 = getValue(I.getOperand(1)); 3224 ISD::CondCode Opcode = getICmpCondCode(predicate); 3225 3226 auto &TLI = DAG.getTargetLoweringInfo(); 3227 EVT MemVT = 3228 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3229 3230 // If a pointer's DAG type is larger than its memory type then the DAG values 3231 // are zero-extended. This breaks signed comparisons so truncate back to the 3232 // underlying type before doing the compare. 3233 if (Op1.getValueType() != MemVT) { 3234 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3235 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3236 } 3237 3238 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3239 I.getType()); 3240 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3241 } 3242 3243 void SelectionDAGBuilder::visitFCmp(const User &I) { 3244 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3245 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3246 predicate = FC->getPredicate(); 3247 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3248 predicate = FCmpInst::Predicate(FC->getPredicate()); 3249 SDValue Op1 = getValue(I.getOperand(0)); 3250 SDValue Op2 = getValue(I.getOperand(1)); 3251 3252 ISD::CondCode Condition = getFCmpCondCode(predicate); 3253 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3254 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3255 Condition = getFCmpCodeWithoutNaN(Condition); 3256 3257 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3258 I.getType()); 3259 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3260 } 3261 3262 // Check if the condition of the select has one use or two users that are both 3263 // selects with the same condition. 3264 static bool hasOnlySelectUsers(const Value *Cond) { 3265 return llvm::all_of(Cond->users(), [](const Value *V) { 3266 return isa<SelectInst>(V); 3267 }); 3268 } 3269 3270 void SelectionDAGBuilder::visitSelect(const User &I) { 3271 SmallVector<EVT, 4> ValueVTs; 3272 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3273 ValueVTs); 3274 unsigned NumValues = ValueVTs.size(); 3275 if (NumValues == 0) return; 3276 3277 SmallVector<SDValue, 4> Values(NumValues); 3278 SDValue Cond = getValue(I.getOperand(0)); 3279 SDValue LHSVal = getValue(I.getOperand(1)); 3280 SDValue RHSVal = getValue(I.getOperand(2)); 3281 auto BaseOps = {Cond}; 3282 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3283 ISD::VSELECT : ISD::SELECT; 3284 3285 bool IsUnaryAbs = false; 3286 3287 // Min/max matching is only viable if all output VTs are the same. 3288 if (is_splat(ValueVTs)) { 3289 EVT VT = ValueVTs[0]; 3290 LLVMContext &Ctx = *DAG.getContext(); 3291 auto &TLI = DAG.getTargetLoweringInfo(); 3292 3293 // We care about the legality of the operation after it has been type 3294 // legalized. 3295 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3296 VT = TLI.getTypeToTransformTo(Ctx, VT); 3297 3298 // If the vselect is legal, assume we want to leave this as a vector setcc + 3299 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3300 // min/max is legal on the scalar type. 3301 bool UseScalarMinMax = VT.isVector() && 3302 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3303 3304 Value *LHS, *RHS; 3305 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3306 ISD::NodeType Opc = ISD::DELETED_NODE; 3307 switch (SPR.Flavor) { 3308 case SPF_UMAX: Opc = ISD::UMAX; break; 3309 case SPF_UMIN: Opc = ISD::UMIN; break; 3310 case SPF_SMAX: Opc = ISD::SMAX; break; 3311 case SPF_SMIN: Opc = ISD::SMIN; break; 3312 case SPF_FMINNUM: 3313 switch (SPR.NaNBehavior) { 3314 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3315 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3316 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3317 case SPNB_RETURNS_ANY: { 3318 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3319 Opc = ISD::FMINNUM; 3320 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3321 Opc = ISD::FMINIMUM; 3322 else if (UseScalarMinMax) 3323 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3324 ISD::FMINNUM : ISD::FMINIMUM; 3325 break; 3326 } 3327 } 3328 break; 3329 case SPF_FMAXNUM: 3330 switch (SPR.NaNBehavior) { 3331 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3332 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3333 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3334 case SPNB_RETURNS_ANY: 3335 3336 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3337 Opc = ISD::FMAXNUM; 3338 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3339 Opc = ISD::FMAXIMUM; 3340 else if (UseScalarMinMax) 3341 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3342 ISD::FMAXNUM : ISD::FMAXIMUM; 3343 break; 3344 } 3345 break; 3346 case SPF_ABS: 3347 IsUnaryAbs = true; 3348 Opc = ISD::ABS; 3349 break; 3350 case SPF_NABS: 3351 // TODO: we need to produce sub(0, abs(X)). 3352 default: break; 3353 } 3354 3355 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3356 (TLI.isOperationLegalOrCustom(Opc, VT) || 3357 (UseScalarMinMax && 3358 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3359 // If the underlying comparison instruction is used by any other 3360 // instruction, the consumed instructions won't be destroyed, so it is 3361 // not profitable to convert to a min/max. 3362 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3363 OpCode = Opc; 3364 LHSVal = getValue(LHS); 3365 RHSVal = getValue(RHS); 3366 BaseOps = {}; 3367 } 3368 3369 if (IsUnaryAbs) { 3370 OpCode = Opc; 3371 LHSVal = getValue(LHS); 3372 BaseOps = {}; 3373 } 3374 } 3375 3376 if (IsUnaryAbs) { 3377 for (unsigned i = 0; i != NumValues; ++i) { 3378 Values[i] = 3379 DAG.getNode(OpCode, getCurSDLoc(), 3380 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3381 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3382 } 3383 } else { 3384 for (unsigned i = 0; i != NumValues; ++i) { 3385 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3386 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3387 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3388 Values[i] = DAG.getNode( 3389 OpCode, getCurSDLoc(), 3390 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3391 } 3392 } 3393 3394 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3395 DAG.getVTList(ValueVTs), Values)); 3396 } 3397 3398 void SelectionDAGBuilder::visitTrunc(const User &I) { 3399 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3400 SDValue N = getValue(I.getOperand(0)); 3401 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3402 I.getType()); 3403 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3404 } 3405 3406 void SelectionDAGBuilder::visitZExt(const User &I) { 3407 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3408 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3409 SDValue N = getValue(I.getOperand(0)); 3410 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3411 I.getType()); 3412 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3413 } 3414 3415 void SelectionDAGBuilder::visitSExt(const User &I) { 3416 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3417 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3418 SDValue N = getValue(I.getOperand(0)); 3419 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3420 I.getType()); 3421 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3422 } 3423 3424 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3425 // FPTrunc is never a no-op cast, no need to check 3426 SDValue N = getValue(I.getOperand(0)); 3427 SDLoc dl = getCurSDLoc(); 3428 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3429 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3430 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3431 DAG.getTargetConstant( 3432 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3433 } 3434 3435 void SelectionDAGBuilder::visitFPExt(const User &I) { 3436 // FPExt is never a no-op cast, no need to check 3437 SDValue N = getValue(I.getOperand(0)); 3438 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3439 I.getType()); 3440 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3441 } 3442 3443 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3444 // FPToUI is never a no-op cast, no need to check 3445 SDValue N = getValue(I.getOperand(0)); 3446 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3447 I.getType()); 3448 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3449 } 3450 3451 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3452 // FPToSI is never a no-op cast, no need to check 3453 SDValue N = getValue(I.getOperand(0)); 3454 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3455 I.getType()); 3456 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3457 } 3458 3459 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3460 // UIToFP is never a no-op cast, no need to check 3461 SDValue N = getValue(I.getOperand(0)); 3462 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3463 I.getType()); 3464 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3465 } 3466 3467 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3468 // SIToFP is never a no-op cast, no need to check 3469 SDValue N = getValue(I.getOperand(0)); 3470 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3471 I.getType()); 3472 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3473 } 3474 3475 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3476 // What to do depends on the size of the integer and the size of the pointer. 3477 // We can either truncate, zero extend, or no-op, accordingly. 3478 SDValue N = getValue(I.getOperand(0)); 3479 auto &TLI = DAG.getTargetLoweringInfo(); 3480 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3481 I.getType()); 3482 EVT PtrMemVT = 3483 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3484 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3485 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3486 setValue(&I, N); 3487 } 3488 3489 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3490 // What to do depends on the size of the integer and the size of the pointer. 3491 // We can either truncate, zero extend, or no-op, accordingly. 3492 SDValue N = getValue(I.getOperand(0)); 3493 auto &TLI = DAG.getTargetLoweringInfo(); 3494 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3495 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3496 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3497 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3498 setValue(&I, N); 3499 } 3500 3501 void SelectionDAGBuilder::visitBitCast(const User &I) { 3502 SDValue N = getValue(I.getOperand(0)); 3503 SDLoc dl = getCurSDLoc(); 3504 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3505 I.getType()); 3506 3507 // BitCast assures us that source and destination are the same size so this is 3508 // either a BITCAST or a no-op. 3509 if (DestVT != N.getValueType()) 3510 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3511 DestVT, N)); // convert types. 3512 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3513 // might fold any kind of constant expression to an integer constant and that 3514 // is not what we are looking for. Only recognize a bitcast of a genuine 3515 // constant integer as an opaque constant. 3516 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3517 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3518 /*isOpaque*/true)); 3519 else 3520 setValue(&I, N); // noop cast. 3521 } 3522 3523 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3524 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3525 const Value *SV = I.getOperand(0); 3526 SDValue N = getValue(SV); 3527 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3528 3529 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3530 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3531 3532 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3533 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3534 3535 setValue(&I, N); 3536 } 3537 3538 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3539 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3540 SDValue InVec = getValue(I.getOperand(0)); 3541 SDValue InVal = getValue(I.getOperand(1)); 3542 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3543 TLI.getVectorIdxTy(DAG.getDataLayout())); 3544 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3545 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3546 InVec, InVal, InIdx)); 3547 } 3548 3549 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3551 SDValue InVec = getValue(I.getOperand(0)); 3552 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3553 TLI.getVectorIdxTy(DAG.getDataLayout())); 3554 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3555 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3556 InVec, InIdx)); 3557 } 3558 3559 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3560 SDValue Src1 = getValue(I.getOperand(0)); 3561 SDValue Src2 = getValue(I.getOperand(1)); 3562 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3563 SDLoc DL = getCurSDLoc(); 3564 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3565 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3566 EVT SrcVT = Src1.getValueType(); 3567 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3568 3569 if (MaskV->isNullValue() && VT.isScalableVector()) { 3570 // Canonical splat form of first element of first input vector. 3571 SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3572 SrcVT.getScalarType(), Src1, 3573 DAG.getConstant(0, DL, 3574 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3575 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3576 return; 3577 } 3578 3579 // For now, we only handle splats for scalable vectors. 3580 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3581 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3582 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3583 3584 SmallVector<int, 8> Mask; 3585 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3586 unsigned MaskNumElts = Mask.size(); 3587 3588 if (SrcNumElts == MaskNumElts) { 3589 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3590 return; 3591 } 3592 3593 // Normalize the shuffle vector since mask and vector length don't match. 3594 if (SrcNumElts < MaskNumElts) { 3595 // Mask is longer than the source vectors. We can use concatenate vector to 3596 // make the mask and vectors lengths match. 3597 3598 if (MaskNumElts % SrcNumElts == 0) { 3599 // Mask length is a multiple of the source vector length. 3600 // Check if the shuffle is some kind of concatenation of the input 3601 // vectors. 3602 unsigned NumConcat = MaskNumElts / SrcNumElts; 3603 bool IsConcat = true; 3604 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3605 for (unsigned i = 0; i != MaskNumElts; ++i) { 3606 int Idx = Mask[i]; 3607 if (Idx < 0) 3608 continue; 3609 // Ensure the indices in each SrcVT sized piece are sequential and that 3610 // the same source is used for the whole piece. 3611 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3612 (ConcatSrcs[i / SrcNumElts] >= 0 && 3613 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3614 IsConcat = false; 3615 break; 3616 } 3617 // Remember which source this index came from. 3618 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3619 } 3620 3621 // The shuffle is concatenating multiple vectors together. Just emit 3622 // a CONCAT_VECTORS operation. 3623 if (IsConcat) { 3624 SmallVector<SDValue, 8> ConcatOps; 3625 for (auto Src : ConcatSrcs) { 3626 if (Src < 0) 3627 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3628 else if (Src == 0) 3629 ConcatOps.push_back(Src1); 3630 else 3631 ConcatOps.push_back(Src2); 3632 } 3633 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3634 return; 3635 } 3636 } 3637 3638 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3639 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3640 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3641 PaddedMaskNumElts); 3642 3643 // Pad both vectors with undefs to make them the same length as the mask. 3644 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3645 3646 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3647 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3648 MOps1[0] = Src1; 3649 MOps2[0] = Src2; 3650 3651 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3652 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3653 3654 // Readjust mask for new input vector length. 3655 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3656 for (unsigned i = 0; i != MaskNumElts; ++i) { 3657 int Idx = Mask[i]; 3658 if (Idx >= (int)SrcNumElts) 3659 Idx -= SrcNumElts - PaddedMaskNumElts; 3660 MappedOps[i] = Idx; 3661 } 3662 3663 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3664 3665 // If the concatenated vector was padded, extract a subvector with the 3666 // correct number of elements. 3667 if (MaskNumElts != PaddedMaskNumElts) 3668 Result = DAG.getNode( 3669 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3670 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3671 3672 setValue(&I, Result); 3673 return; 3674 } 3675 3676 if (SrcNumElts > MaskNumElts) { 3677 // Analyze the access pattern of the vector to see if we can extract 3678 // two subvectors and do the shuffle. 3679 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3680 bool CanExtract = true; 3681 for (int Idx : Mask) { 3682 unsigned Input = 0; 3683 if (Idx < 0) 3684 continue; 3685 3686 if (Idx >= (int)SrcNumElts) { 3687 Input = 1; 3688 Idx -= SrcNumElts; 3689 } 3690 3691 // If all the indices come from the same MaskNumElts sized portion of 3692 // the sources we can use extract. Also make sure the extract wouldn't 3693 // extract past the end of the source. 3694 int NewStartIdx = alignDown(Idx, MaskNumElts); 3695 if (NewStartIdx + MaskNumElts > SrcNumElts || 3696 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3697 CanExtract = false; 3698 // Make sure we always update StartIdx as we use it to track if all 3699 // elements are undef. 3700 StartIdx[Input] = NewStartIdx; 3701 } 3702 3703 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3704 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3705 return; 3706 } 3707 if (CanExtract) { 3708 // Extract appropriate subvector and generate a vector shuffle 3709 for (unsigned Input = 0; Input < 2; ++Input) { 3710 SDValue &Src = Input == 0 ? Src1 : Src2; 3711 if (StartIdx[Input] < 0) 3712 Src = DAG.getUNDEF(VT); 3713 else { 3714 Src = DAG.getNode( 3715 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3716 DAG.getConstant(StartIdx[Input], DL, 3717 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3718 } 3719 } 3720 3721 // Calculate new mask. 3722 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3723 for (int &Idx : MappedOps) { 3724 if (Idx >= (int)SrcNumElts) 3725 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3726 else if (Idx >= 0) 3727 Idx -= StartIdx[0]; 3728 } 3729 3730 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3731 return; 3732 } 3733 } 3734 3735 // We can't use either concat vectors or extract subvectors so fall back to 3736 // replacing the shuffle with extract and build vector. 3737 // to insert and build vector. 3738 EVT EltVT = VT.getVectorElementType(); 3739 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3740 SmallVector<SDValue,8> Ops; 3741 for (int Idx : Mask) { 3742 SDValue Res; 3743 3744 if (Idx < 0) { 3745 Res = DAG.getUNDEF(EltVT); 3746 } else { 3747 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3748 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3749 3750 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3751 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3752 } 3753 3754 Ops.push_back(Res); 3755 } 3756 3757 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3758 } 3759 3760 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3761 ArrayRef<unsigned> Indices; 3762 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3763 Indices = IV->getIndices(); 3764 else 3765 Indices = cast<ConstantExpr>(&I)->getIndices(); 3766 3767 const Value *Op0 = I.getOperand(0); 3768 const Value *Op1 = I.getOperand(1); 3769 Type *AggTy = I.getType(); 3770 Type *ValTy = Op1->getType(); 3771 bool IntoUndef = isa<UndefValue>(Op0); 3772 bool FromUndef = isa<UndefValue>(Op1); 3773 3774 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3775 3776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3777 SmallVector<EVT, 4> AggValueVTs; 3778 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3779 SmallVector<EVT, 4> ValValueVTs; 3780 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3781 3782 unsigned NumAggValues = AggValueVTs.size(); 3783 unsigned NumValValues = ValValueVTs.size(); 3784 SmallVector<SDValue, 4> Values(NumAggValues); 3785 3786 // Ignore an insertvalue that produces an empty object 3787 if (!NumAggValues) { 3788 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3789 return; 3790 } 3791 3792 SDValue Agg = getValue(Op0); 3793 unsigned i = 0; 3794 // Copy the beginning value(s) from the original aggregate. 3795 for (; i != LinearIndex; ++i) 3796 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3797 SDValue(Agg.getNode(), Agg.getResNo() + i); 3798 // Copy values from the inserted value(s). 3799 if (NumValValues) { 3800 SDValue Val = getValue(Op1); 3801 for (; i != LinearIndex + NumValValues; ++i) 3802 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3803 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3804 } 3805 // Copy remaining value(s) from the original aggregate. 3806 for (; i != NumAggValues; ++i) 3807 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3808 SDValue(Agg.getNode(), Agg.getResNo() + i); 3809 3810 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3811 DAG.getVTList(AggValueVTs), Values)); 3812 } 3813 3814 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3815 ArrayRef<unsigned> Indices; 3816 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3817 Indices = EV->getIndices(); 3818 else 3819 Indices = cast<ConstantExpr>(&I)->getIndices(); 3820 3821 const Value *Op0 = I.getOperand(0); 3822 Type *AggTy = Op0->getType(); 3823 Type *ValTy = I.getType(); 3824 bool OutOfUndef = isa<UndefValue>(Op0); 3825 3826 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3827 3828 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3829 SmallVector<EVT, 4> ValValueVTs; 3830 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3831 3832 unsigned NumValValues = ValValueVTs.size(); 3833 3834 // Ignore a extractvalue that produces an empty object 3835 if (!NumValValues) { 3836 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3837 return; 3838 } 3839 3840 SmallVector<SDValue, 4> Values(NumValValues); 3841 3842 SDValue Agg = getValue(Op0); 3843 // Copy out the selected value(s). 3844 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3845 Values[i - LinearIndex] = 3846 OutOfUndef ? 3847 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3848 SDValue(Agg.getNode(), Agg.getResNo() + i); 3849 3850 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3851 DAG.getVTList(ValValueVTs), Values)); 3852 } 3853 3854 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3855 Value *Op0 = I.getOperand(0); 3856 // Note that the pointer operand may be a vector of pointers. Take the scalar 3857 // element which holds a pointer. 3858 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3859 SDValue N = getValue(Op0); 3860 SDLoc dl = getCurSDLoc(); 3861 auto &TLI = DAG.getTargetLoweringInfo(); 3862 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3863 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3864 3865 // Normalize Vector GEP - all scalar operands should be converted to the 3866 // splat vector. 3867 unsigned VectorWidth = I.getType()->isVectorTy() ? 3868 I.getType()->getVectorNumElements() : 0; 3869 3870 if (VectorWidth && !N.getValueType().isVector()) { 3871 LLVMContext &Context = *DAG.getContext(); 3872 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3873 N = DAG.getSplatBuildVector(VT, dl, N); 3874 } 3875 3876 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3877 GTI != E; ++GTI) { 3878 const Value *Idx = GTI.getOperand(); 3879 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3880 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3881 if (Field) { 3882 // N = N + Offset 3883 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3884 3885 // In an inbounds GEP with an offset that is nonnegative even when 3886 // interpreted as signed, assume there is no unsigned overflow. 3887 SDNodeFlags Flags; 3888 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3889 Flags.setNoUnsignedWrap(true); 3890 3891 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3892 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3893 } 3894 } else { 3895 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3896 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3897 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3898 3899 // If this is a scalar constant or a splat vector of constants, 3900 // handle it quickly. 3901 const auto *C = dyn_cast<Constant>(Idx); 3902 if (C && isa<VectorType>(C->getType())) 3903 C = C->getSplatValue(); 3904 3905 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) { 3906 if (CI->isZero()) 3907 continue; 3908 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3909 LLVMContext &Context = *DAG.getContext(); 3910 SDValue OffsVal = VectorWidth ? 3911 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3912 DAG.getConstant(Offs, dl, IdxTy); 3913 3914 // In an inbounds GEP with an offset that is nonnegative even when 3915 // interpreted as signed, assume there is no unsigned overflow. 3916 SDNodeFlags Flags; 3917 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3918 Flags.setNoUnsignedWrap(true); 3919 3920 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3921 3922 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3923 continue; 3924 } 3925 3926 // N = N + Idx * ElementSize; 3927 SDValue IdxN = getValue(Idx); 3928 3929 if (!IdxN.getValueType().isVector() && VectorWidth) { 3930 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3931 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3932 } 3933 3934 // If the index is smaller or larger than intptr_t, truncate or extend 3935 // it. 3936 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3937 3938 // If this is a multiply by a power of two, turn it into a shl 3939 // immediately. This is a very common case. 3940 if (ElementSize != 1) { 3941 if (ElementSize.isPowerOf2()) { 3942 unsigned Amt = ElementSize.logBase2(); 3943 IdxN = DAG.getNode(ISD::SHL, dl, 3944 N.getValueType(), IdxN, 3945 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3946 } else { 3947 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3948 IdxN.getValueType()); 3949 IdxN = DAG.getNode(ISD::MUL, dl, 3950 N.getValueType(), IdxN, Scale); 3951 } 3952 } 3953 3954 N = DAG.getNode(ISD::ADD, dl, 3955 N.getValueType(), N, IdxN); 3956 } 3957 } 3958 3959 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3960 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3961 3962 setValue(&I, N); 3963 } 3964 3965 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3966 // If this is a fixed sized alloca in the entry block of the function, 3967 // allocate it statically on the stack. 3968 if (FuncInfo.StaticAllocaMap.count(&I)) 3969 return; // getValue will auto-populate this. 3970 3971 SDLoc dl = getCurSDLoc(); 3972 Type *Ty = I.getAllocatedType(); 3973 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3974 auto &DL = DAG.getDataLayout(); 3975 uint64_t TySize = DL.getTypeAllocSize(Ty); 3976 unsigned Align = 3977 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3978 3979 SDValue AllocSize = getValue(I.getArraySize()); 3980 3981 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3982 if (AllocSize.getValueType() != IntPtr) 3983 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3984 3985 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3986 AllocSize, 3987 DAG.getConstant(TySize, dl, IntPtr)); 3988 3989 // Handle alignment. If the requested alignment is less than or equal to 3990 // the stack alignment, ignore it. If the size is greater than or equal to 3991 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3992 unsigned StackAlign = 3993 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3994 if (Align <= StackAlign) 3995 Align = 0; 3996 3997 // Round the size of the allocation up to the stack alignment size 3998 // by add SA-1 to the size. This doesn't overflow because we're computing 3999 // an address inside an alloca. 4000 SDNodeFlags Flags; 4001 Flags.setNoUnsignedWrap(true); 4002 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 4003 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 4004 4005 // Mask out the low bits for alignment purposes. 4006 AllocSize = 4007 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 4008 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 4009 4010 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 4011 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 4012 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 4013 setValue(&I, DSA); 4014 DAG.setRoot(DSA.getValue(1)); 4015 4016 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 4017 } 4018 4019 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 4020 if (I.isAtomic()) 4021 return visitAtomicLoad(I); 4022 4023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4024 const Value *SV = I.getOperand(0); 4025 if (TLI.supportSwiftError()) { 4026 // Swifterror values can come from either a function parameter with 4027 // swifterror attribute or an alloca with swifterror attribute. 4028 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4029 if (Arg->hasSwiftErrorAttr()) 4030 return visitLoadFromSwiftError(I); 4031 } 4032 4033 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4034 if (Alloca->isSwiftError()) 4035 return visitLoadFromSwiftError(I); 4036 } 4037 } 4038 4039 SDValue Ptr = getValue(SV); 4040 4041 Type *Ty = I.getType(); 4042 4043 bool isVolatile = I.isVolatile(); 4044 bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal); 4045 bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load); 4046 bool isDereferenceable = 4047 isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout()); 4048 unsigned Alignment = I.getAlignment(); 4049 4050 AAMDNodes AAInfo; 4051 I.getAAMetadata(AAInfo); 4052 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4053 4054 SmallVector<EVT, 4> ValueVTs, MemVTs; 4055 SmallVector<uint64_t, 4> Offsets; 4056 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4057 unsigned NumValues = ValueVTs.size(); 4058 if (NumValues == 0) 4059 return; 4060 4061 SDValue Root; 4062 bool ConstantMemory = false; 4063 if (isVolatile || NumValues > MaxParallelChains) 4064 // Serialize volatile loads with other side effects. 4065 Root = getRoot(); 4066 else if (AA && 4067 AA->pointsToConstantMemory(MemoryLocation( 4068 SV, 4069 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4070 AAInfo))) { 4071 // Do not serialize (non-volatile) loads of constant memory with anything. 4072 Root = DAG.getEntryNode(); 4073 ConstantMemory = true; 4074 } else { 4075 // Do not serialize non-volatile loads against each other. 4076 Root = DAG.getRoot(); 4077 } 4078 4079 SDLoc dl = getCurSDLoc(); 4080 4081 if (isVolatile) 4082 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4083 4084 // An aggregate load cannot wrap around the address space, so offsets to its 4085 // parts don't wrap either. 4086 SDNodeFlags Flags; 4087 Flags.setNoUnsignedWrap(true); 4088 4089 SmallVector<SDValue, 4> Values(NumValues); 4090 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4091 EVT PtrVT = Ptr.getValueType(); 4092 unsigned ChainI = 0; 4093 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4094 // Serializing loads here may result in excessive register pressure, and 4095 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4096 // could recover a bit by hoisting nodes upward in the chain by recognizing 4097 // they are side-effect free or do not alias. The optimizer should really 4098 // avoid this case by converting large object/array copies to llvm.memcpy 4099 // (MaxParallelChains should always remain as failsafe). 4100 if (ChainI == MaxParallelChains) { 4101 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4102 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4103 makeArrayRef(Chains.data(), ChainI)); 4104 Root = Chain; 4105 ChainI = 0; 4106 } 4107 SDValue A = DAG.getNode(ISD::ADD, dl, 4108 PtrVT, Ptr, 4109 DAG.getConstant(Offsets[i], dl, PtrVT), 4110 Flags); 4111 auto MMOFlags = MachineMemOperand::MONone; 4112 if (isVolatile) 4113 MMOFlags |= MachineMemOperand::MOVolatile; 4114 if (isNonTemporal) 4115 MMOFlags |= MachineMemOperand::MONonTemporal; 4116 if (isInvariant) 4117 MMOFlags |= MachineMemOperand::MOInvariant; 4118 if (isDereferenceable) 4119 MMOFlags |= MachineMemOperand::MODereferenceable; 4120 MMOFlags |= TLI.getMMOFlags(I); 4121 4122 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4123 MachinePointerInfo(SV, Offsets[i]), Alignment, 4124 MMOFlags, AAInfo, Ranges); 4125 Chains[ChainI] = L.getValue(1); 4126 4127 if (MemVTs[i] != ValueVTs[i]) 4128 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4129 4130 Values[i] = L; 4131 } 4132 4133 if (!ConstantMemory) { 4134 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4135 makeArrayRef(Chains.data(), ChainI)); 4136 if (isVolatile) 4137 DAG.setRoot(Chain); 4138 else 4139 PendingLoads.push_back(Chain); 4140 } 4141 4142 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4143 DAG.getVTList(ValueVTs), Values)); 4144 } 4145 4146 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4147 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4148 "call visitStoreToSwiftError when backend supports swifterror"); 4149 4150 SmallVector<EVT, 4> ValueVTs; 4151 SmallVector<uint64_t, 4> Offsets; 4152 const Value *SrcV = I.getOperand(0); 4153 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4154 SrcV->getType(), ValueVTs, &Offsets); 4155 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4156 "expect a single EVT for swifterror"); 4157 4158 SDValue Src = getValue(SrcV); 4159 // Create a virtual register, then update the virtual register. 4160 Register VReg = 4161 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4162 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4163 // Chain can be getRoot or getControlRoot. 4164 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4165 SDValue(Src.getNode(), Src.getResNo())); 4166 DAG.setRoot(CopyNode); 4167 } 4168 4169 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4170 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4171 "call visitLoadFromSwiftError when backend supports swifterror"); 4172 4173 assert(!I.isVolatile() && 4174 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4175 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4176 "Support volatile, non temporal, invariant for load_from_swift_error"); 4177 4178 const Value *SV = I.getOperand(0); 4179 Type *Ty = I.getType(); 4180 AAMDNodes AAInfo; 4181 I.getAAMetadata(AAInfo); 4182 assert( 4183 (!AA || 4184 !AA->pointsToConstantMemory(MemoryLocation( 4185 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4186 AAInfo))) && 4187 "load_from_swift_error should not be constant memory"); 4188 4189 SmallVector<EVT, 4> ValueVTs; 4190 SmallVector<uint64_t, 4> Offsets; 4191 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4192 ValueVTs, &Offsets); 4193 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4194 "expect a single EVT for swifterror"); 4195 4196 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4197 SDValue L = DAG.getCopyFromReg( 4198 getRoot(), getCurSDLoc(), 4199 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4200 4201 setValue(&I, L); 4202 } 4203 4204 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4205 if (I.isAtomic()) 4206 return visitAtomicStore(I); 4207 4208 const Value *SrcV = I.getOperand(0); 4209 const Value *PtrV = I.getOperand(1); 4210 4211 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4212 if (TLI.supportSwiftError()) { 4213 // Swifterror values can come from either a function parameter with 4214 // swifterror attribute or an alloca with swifterror attribute. 4215 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4216 if (Arg->hasSwiftErrorAttr()) 4217 return visitStoreToSwiftError(I); 4218 } 4219 4220 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4221 if (Alloca->isSwiftError()) 4222 return visitStoreToSwiftError(I); 4223 } 4224 } 4225 4226 SmallVector<EVT, 4> ValueVTs, MemVTs; 4227 SmallVector<uint64_t, 4> Offsets; 4228 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4229 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4230 unsigned NumValues = ValueVTs.size(); 4231 if (NumValues == 0) 4232 return; 4233 4234 // Get the lowered operands. Note that we do this after 4235 // checking if NumResults is zero, because with zero results 4236 // the operands won't have values in the map. 4237 SDValue Src = getValue(SrcV); 4238 SDValue Ptr = getValue(PtrV); 4239 4240 SDValue Root = getRoot(); 4241 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4242 SDLoc dl = getCurSDLoc(); 4243 unsigned Alignment = I.getAlignment(); 4244 AAMDNodes AAInfo; 4245 I.getAAMetadata(AAInfo); 4246 4247 auto MMOFlags = MachineMemOperand::MONone; 4248 if (I.isVolatile()) 4249 MMOFlags |= MachineMemOperand::MOVolatile; 4250 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4251 MMOFlags |= MachineMemOperand::MONonTemporal; 4252 MMOFlags |= TLI.getMMOFlags(I); 4253 4254 // An aggregate load cannot wrap around the address space, so offsets to its 4255 // parts don't wrap either. 4256 SDNodeFlags Flags; 4257 Flags.setNoUnsignedWrap(true); 4258 4259 unsigned ChainI = 0; 4260 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4261 // See visitLoad comments. 4262 if (ChainI == MaxParallelChains) { 4263 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4264 makeArrayRef(Chains.data(), ChainI)); 4265 Root = Chain; 4266 ChainI = 0; 4267 } 4268 SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags); 4269 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4270 if (MemVTs[i] != ValueVTs[i]) 4271 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4272 SDValue St = 4273 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4274 Alignment, MMOFlags, AAInfo); 4275 Chains[ChainI] = St; 4276 } 4277 4278 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4279 makeArrayRef(Chains.data(), ChainI)); 4280 DAG.setRoot(StoreNode); 4281 } 4282 4283 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4284 bool IsCompressing) { 4285 SDLoc sdl = getCurSDLoc(); 4286 4287 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4288 unsigned& Alignment) { 4289 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4290 Src0 = I.getArgOperand(0); 4291 Ptr = I.getArgOperand(1); 4292 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4293 Mask = I.getArgOperand(3); 4294 }; 4295 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4296 unsigned& Alignment) { 4297 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4298 Src0 = I.getArgOperand(0); 4299 Ptr = I.getArgOperand(1); 4300 Mask = I.getArgOperand(2); 4301 Alignment = 0; 4302 }; 4303 4304 Value *PtrOperand, *MaskOperand, *Src0Operand; 4305 unsigned Alignment; 4306 if (IsCompressing) 4307 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4308 else 4309 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4310 4311 SDValue Ptr = getValue(PtrOperand); 4312 SDValue Src0 = getValue(Src0Operand); 4313 SDValue Mask = getValue(MaskOperand); 4314 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4315 4316 EVT VT = Src0.getValueType(); 4317 if (!Alignment) 4318 Alignment = DAG.getEVTAlignment(VT); 4319 4320 AAMDNodes AAInfo; 4321 I.getAAMetadata(AAInfo); 4322 4323 MachineMemOperand *MMO = 4324 DAG.getMachineFunction(). 4325 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4326 MachineMemOperand::MOStore, 4327 // TODO: Make MachineMemOperands aware of scalable 4328 // vectors. 4329 VT.getStoreSize().getKnownMinSize(), 4330 Alignment, AAInfo); 4331 SDValue StoreNode = 4332 DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO, 4333 ISD::UNINDEXED, false /* Truncating */, IsCompressing); 4334 DAG.setRoot(StoreNode); 4335 setValue(&I, StoreNode); 4336 } 4337 4338 // Get a uniform base for the Gather/Scatter intrinsic. 4339 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4340 // We try to represent it as a base pointer + vector of indices. 4341 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4342 // The first operand of the GEP may be a single pointer or a vector of pointers 4343 // Example: 4344 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4345 // or 4346 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4347 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4348 // 4349 // When the first GEP operand is a single pointer - it is the uniform base we 4350 // are looking for. If first operand of the GEP is a splat vector - we 4351 // extract the splat value and use it as a uniform base. 4352 // In all other cases the function returns 'false'. 4353 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4354 ISD::MemIndexType &IndexType, SDValue &Scale, 4355 SelectionDAGBuilder *SDB) { 4356 SelectionDAG& DAG = SDB->DAG; 4357 LLVMContext &Context = *DAG.getContext(); 4358 4359 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4360 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4361 if (!GEP) 4362 return false; 4363 4364 const Value *GEPPtr = GEP->getPointerOperand(); 4365 if (!GEPPtr->getType()->isVectorTy()) 4366 Ptr = GEPPtr; 4367 else if (!(Ptr = getSplatValue(GEPPtr))) 4368 return false; 4369 4370 unsigned FinalIndex = GEP->getNumOperands() - 1; 4371 Value *IndexVal = GEP->getOperand(FinalIndex); 4372 gep_type_iterator GTI = gep_type_begin(*GEP); 4373 4374 // Ensure all the other indices are 0. 4375 for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) { 4376 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4377 if (!C) 4378 return false; 4379 if (isa<VectorType>(C->getType())) 4380 C = C->getSplatValue(); 4381 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4382 if (!CI || !CI->isZero()) 4383 return false; 4384 } 4385 4386 // The operands of the GEP may be defined in another basic block. 4387 // In this case we'll not find nodes for the operands. 4388 if (!SDB->findValue(Ptr)) 4389 return false; 4390 Constant *C = dyn_cast<Constant>(IndexVal); 4391 if (!C && !SDB->findValue(IndexVal)) 4392 return false; 4393 4394 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4395 const DataLayout &DL = DAG.getDataLayout(); 4396 StructType *STy = GTI.getStructTypeOrNull(); 4397 4398 if (STy) { 4399 const StructLayout *SL = DL.getStructLayout(STy); 4400 if (isa<VectorType>(C->getType())) { 4401 C = C->getSplatValue(); 4402 // FIXME: If getSplatValue may return nullptr for a structure? 4403 // If not, the following check can be removed. 4404 if (!C) 4405 return false; 4406 } 4407 auto *CI = cast<ConstantInt>(C); 4408 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4409 Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()), 4410 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4411 } else { 4412 Scale = DAG.getTargetConstant( 4413 DL.getTypeAllocSize(GEP->getResultElementType()), 4414 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4415 Index = SDB->getValue(IndexVal); 4416 } 4417 Base = SDB->getValue(Ptr); 4418 IndexType = ISD::SIGNED_SCALED; 4419 4420 if (STy || !Index.getValueType().isVector()) { 4421 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4422 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4423 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4424 } 4425 return true; 4426 } 4427 4428 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4429 SDLoc sdl = getCurSDLoc(); 4430 4431 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask) 4432 const Value *Ptr = I.getArgOperand(1); 4433 SDValue Src0 = getValue(I.getArgOperand(0)); 4434 SDValue Mask = getValue(I.getArgOperand(3)); 4435 EVT VT = Src0.getValueType(); 4436 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4437 if (!Alignment) 4438 Alignment = DAG.getEVTAlignment(VT); 4439 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4440 4441 AAMDNodes AAInfo; 4442 I.getAAMetadata(AAInfo); 4443 4444 SDValue Base; 4445 SDValue Index; 4446 ISD::MemIndexType IndexType; 4447 SDValue Scale; 4448 const Value *BasePtr = Ptr; 4449 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4450 this); 4451 4452 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4453 MachineMemOperand *MMO = DAG.getMachineFunction(). 4454 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4455 MachineMemOperand::MOStore, 4456 // TODO: Make MachineMemOperands aware of scalable 4457 // vectors. 4458 VT.getStoreSize().getKnownMinSize(), 4459 Alignment, AAInfo); 4460 if (!UniformBase) { 4461 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4462 Index = getValue(Ptr); 4463 IndexType = ISD::SIGNED_SCALED; 4464 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4465 } 4466 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4467 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4468 Ops, MMO, IndexType); 4469 DAG.setRoot(Scatter); 4470 setValue(&I, Scatter); 4471 } 4472 4473 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4474 SDLoc sdl = getCurSDLoc(); 4475 4476 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4477 unsigned& Alignment) { 4478 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4479 Ptr = I.getArgOperand(0); 4480 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4481 Mask = I.getArgOperand(2); 4482 Src0 = I.getArgOperand(3); 4483 }; 4484 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4485 unsigned& Alignment) { 4486 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4487 Ptr = I.getArgOperand(0); 4488 Alignment = 0; 4489 Mask = I.getArgOperand(1); 4490 Src0 = I.getArgOperand(2); 4491 }; 4492 4493 Value *PtrOperand, *MaskOperand, *Src0Operand; 4494 unsigned Alignment; 4495 if (IsExpanding) 4496 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4497 else 4498 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4499 4500 SDValue Ptr = getValue(PtrOperand); 4501 SDValue Src0 = getValue(Src0Operand); 4502 SDValue Mask = getValue(MaskOperand); 4503 SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); 4504 4505 EVT VT = Src0.getValueType(); 4506 if (!Alignment) 4507 Alignment = DAG.getEVTAlignment(VT); 4508 4509 AAMDNodes AAInfo; 4510 I.getAAMetadata(AAInfo); 4511 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4512 4513 // Do not serialize masked loads of constant memory with anything. 4514 MemoryLocation ML; 4515 if (VT.isScalableVector()) 4516 ML = MemoryLocation(PtrOperand); 4517 else 4518 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4519 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4520 AAInfo); 4521 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4522 4523 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4524 4525 MachineMemOperand *MMO = 4526 DAG.getMachineFunction(). 4527 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4528 MachineMemOperand::MOLoad, 4529 // TODO: Make MachineMemOperands aware of scalable 4530 // vectors. 4531 VT.getStoreSize().getKnownMinSize(), 4532 Alignment, AAInfo, Ranges); 4533 4534 SDValue Load = 4535 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO, 4536 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding); 4537 if (AddToChain) 4538 PendingLoads.push_back(Load.getValue(1)); 4539 setValue(&I, Load); 4540 } 4541 4542 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4543 SDLoc sdl = getCurSDLoc(); 4544 4545 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4546 const Value *Ptr = I.getArgOperand(0); 4547 SDValue Src0 = getValue(I.getArgOperand(3)); 4548 SDValue Mask = getValue(I.getArgOperand(2)); 4549 4550 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4551 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4552 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4553 if (!Alignment) 4554 Alignment = DAG.getEVTAlignment(VT); 4555 4556 AAMDNodes AAInfo; 4557 I.getAAMetadata(AAInfo); 4558 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4559 4560 SDValue Root = DAG.getRoot(); 4561 SDValue Base; 4562 SDValue Index; 4563 ISD::MemIndexType IndexType; 4564 SDValue Scale; 4565 const Value *BasePtr = Ptr; 4566 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4567 this); 4568 bool ConstantMemory = false; 4569 if (UniformBase && AA && 4570 AA->pointsToConstantMemory( 4571 MemoryLocation(BasePtr, 4572 LocationSize::precise( 4573 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4574 AAInfo))) { 4575 // Do not serialize (non-volatile) loads of constant memory with anything. 4576 Root = DAG.getEntryNode(); 4577 ConstantMemory = true; 4578 } 4579 4580 MachineMemOperand *MMO = 4581 DAG.getMachineFunction(). 4582 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4583 MachineMemOperand::MOLoad, 4584 // TODO: Make MachineMemOperands aware of scalable 4585 // vectors. 4586 VT.getStoreSize().getKnownMinSize(), 4587 Alignment, AAInfo, Ranges); 4588 4589 if (!UniformBase) { 4590 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4591 Index = getValue(Ptr); 4592 IndexType = ISD::SIGNED_SCALED; 4593 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4594 } 4595 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4596 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4597 Ops, MMO, IndexType); 4598 4599 SDValue OutChain = Gather.getValue(1); 4600 if (!ConstantMemory) 4601 PendingLoads.push_back(OutChain); 4602 setValue(&I, Gather); 4603 } 4604 4605 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4606 SDLoc dl = getCurSDLoc(); 4607 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4608 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4609 SyncScope::ID SSID = I.getSyncScopeID(); 4610 4611 SDValue InChain = getRoot(); 4612 4613 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4614 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4615 4616 auto Alignment = DAG.getEVTAlignment(MemVT); 4617 4618 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4619 if (I.isVolatile()) 4620 Flags |= MachineMemOperand::MOVolatile; 4621 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4622 4623 MachineFunction &MF = DAG.getMachineFunction(); 4624 MachineMemOperand *MMO = 4625 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4626 Flags, MemVT.getStoreSize(), Alignment, 4627 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4628 FailureOrdering); 4629 4630 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4631 dl, MemVT, VTs, InChain, 4632 getValue(I.getPointerOperand()), 4633 getValue(I.getCompareOperand()), 4634 getValue(I.getNewValOperand()), MMO); 4635 4636 SDValue OutChain = L.getValue(2); 4637 4638 setValue(&I, L); 4639 DAG.setRoot(OutChain); 4640 } 4641 4642 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4643 SDLoc dl = getCurSDLoc(); 4644 ISD::NodeType NT; 4645 switch (I.getOperation()) { 4646 default: llvm_unreachable("Unknown atomicrmw operation"); 4647 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4648 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4649 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4650 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4651 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4652 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4653 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4654 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4655 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4656 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4657 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4658 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4659 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4660 } 4661 AtomicOrdering Ordering = I.getOrdering(); 4662 SyncScope::ID SSID = I.getSyncScopeID(); 4663 4664 SDValue InChain = getRoot(); 4665 4666 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4667 auto Alignment = DAG.getEVTAlignment(MemVT); 4668 4669 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4670 if (I.isVolatile()) 4671 Flags |= MachineMemOperand::MOVolatile; 4672 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4673 4674 MachineFunction &MF = DAG.getMachineFunction(); 4675 MachineMemOperand *MMO = 4676 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4677 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4678 nullptr, SSID, Ordering); 4679 4680 SDValue L = 4681 DAG.getAtomic(NT, dl, MemVT, InChain, 4682 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4683 MMO); 4684 4685 SDValue OutChain = L.getValue(1); 4686 4687 setValue(&I, L); 4688 DAG.setRoot(OutChain); 4689 } 4690 4691 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4692 SDLoc dl = getCurSDLoc(); 4693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4694 SDValue Ops[3]; 4695 Ops[0] = getRoot(); 4696 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl, 4697 TLI.getFenceOperandTy(DAG.getDataLayout())); 4698 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl, 4699 TLI.getFenceOperandTy(DAG.getDataLayout())); 4700 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4701 } 4702 4703 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4704 SDLoc dl = getCurSDLoc(); 4705 AtomicOrdering Order = I.getOrdering(); 4706 SyncScope::ID SSID = I.getSyncScopeID(); 4707 4708 SDValue InChain = getRoot(); 4709 4710 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4711 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4712 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4713 4714 if (!TLI.supportsUnalignedAtomics() && 4715 I.getAlignment() < MemVT.getSizeInBits() / 8) 4716 report_fatal_error("Cannot generate unaligned atomic load"); 4717 4718 auto Flags = MachineMemOperand::MOLoad; 4719 if (I.isVolatile()) 4720 Flags |= MachineMemOperand::MOVolatile; 4721 if (I.hasMetadata(LLVMContext::MD_invariant_load)) 4722 Flags |= MachineMemOperand::MOInvariant; 4723 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(), 4724 DAG.getDataLayout())) 4725 Flags |= MachineMemOperand::MODereferenceable; 4726 4727 Flags |= TLI.getMMOFlags(I); 4728 4729 MachineMemOperand *MMO = 4730 DAG.getMachineFunction(). 4731 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4732 Flags, MemVT.getStoreSize(), 4733 I.getAlignment() ? I.getAlignment() : 4734 DAG.getEVTAlignment(MemVT), 4735 AAMDNodes(), nullptr, SSID, Order); 4736 4737 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4738 4739 SDValue Ptr = getValue(I.getPointerOperand()); 4740 4741 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4742 // TODO: Once this is better exercised by tests, it should be merged with 4743 // the normal path for loads to prevent future divergence. 4744 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4745 if (MemVT != VT) 4746 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4747 4748 setValue(&I, L); 4749 SDValue OutChain = L.getValue(1); 4750 if (!I.isUnordered()) 4751 DAG.setRoot(OutChain); 4752 else 4753 PendingLoads.push_back(OutChain); 4754 return; 4755 } 4756 4757 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4758 Ptr, MMO); 4759 4760 SDValue OutChain = L.getValue(1); 4761 if (MemVT != VT) 4762 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4763 4764 setValue(&I, L); 4765 DAG.setRoot(OutChain); 4766 } 4767 4768 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4769 SDLoc dl = getCurSDLoc(); 4770 4771 AtomicOrdering Ordering = I.getOrdering(); 4772 SyncScope::ID SSID = I.getSyncScopeID(); 4773 4774 SDValue InChain = getRoot(); 4775 4776 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4777 EVT MemVT = 4778 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4779 4780 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4781 report_fatal_error("Cannot generate unaligned atomic store"); 4782 4783 auto Flags = MachineMemOperand::MOStore; 4784 if (I.isVolatile()) 4785 Flags |= MachineMemOperand::MOVolatile; 4786 Flags |= TLI.getMMOFlags(I); 4787 4788 MachineFunction &MF = DAG.getMachineFunction(); 4789 MachineMemOperand *MMO = 4790 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4791 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4792 nullptr, SSID, Ordering); 4793 4794 SDValue Val = getValue(I.getValueOperand()); 4795 if (Val.getValueType() != MemVT) 4796 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4797 SDValue Ptr = getValue(I.getPointerOperand()); 4798 4799 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4800 // TODO: Once this is better exercised by tests, it should be merged with 4801 // the normal path for stores to prevent future divergence. 4802 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4803 DAG.setRoot(S); 4804 return; 4805 } 4806 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4807 Ptr, Val, MMO); 4808 4809 4810 DAG.setRoot(OutChain); 4811 } 4812 4813 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4814 /// node. 4815 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4816 unsigned Intrinsic) { 4817 // Ignore the callsite's attributes. A specific call site may be marked with 4818 // readnone, but the lowering code will expect the chain based on the 4819 // definition. 4820 const Function *F = I.getCalledFunction(); 4821 bool HasChain = !F->doesNotAccessMemory(); 4822 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4823 4824 // Build the operand list. 4825 SmallVector<SDValue, 8> Ops; 4826 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4827 if (OnlyLoad) { 4828 // We don't need to serialize loads against other loads. 4829 Ops.push_back(DAG.getRoot()); 4830 } else { 4831 Ops.push_back(getRoot()); 4832 } 4833 } 4834 4835 // Info is set by getTgtMemInstrinsic 4836 TargetLowering::IntrinsicInfo Info; 4837 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4838 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4839 DAG.getMachineFunction(), 4840 Intrinsic); 4841 4842 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4843 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4844 Info.opc == ISD::INTRINSIC_W_CHAIN) 4845 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4846 TLI.getPointerTy(DAG.getDataLayout()))); 4847 4848 // Add all operands of the call to the operand list. 4849 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4850 const Value *Arg = I.getArgOperand(i); 4851 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4852 Ops.push_back(getValue(Arg)); 4853 continue; 4854 } 4855 4856 // Use TargetConstant instead of a regular constant for immarg. 4857 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4858 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4859 assert(CI->getBitWidth() <= 64 && 4860 "large intrinsic immediates not handled"); 4861 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4862 } else { 4863 Ops.push_back( 4864 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4865 } 4866 } 4867 4868 SmallVector<EVT, 4> ValueVTs; 4869 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4870 4871 if (HasChain) 4872 ValueVTs.push_back(MVT::Other); 4873 4874 SDVTList VTs = DAG.getVTList(ValueVTs); 4875 4876 // Create the node. 4877 SDValue Result; 4878 if (IsTgtIntrinsic) { 4879 // This is target intrinsic that touches memory 4880 AAMDNodes AAInfo; 4881 I.getAAMetadata(AAInfo); 4882 Result = DAG.getMemIntrinsicNode( 4883 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4884 MachinePointerInfo(Info.ptrVal, Info.offset), 4885 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4886 } else if (!HasChain) { 4887 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4888 } else if (!I.getType()->isVoidTy()) { 4889 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4890 } else { 4891 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4892 } 4893 4894 if (HasChain) { 4895 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4896 if (OnlyLoad) 4897 PendingLoads.push_back(Chain); 4898 else 4899 DAG.setRoot(Chain); 4900 } 4901 4902 if (!I.getType()->isVoidTy()) { 4903 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4904 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4905 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4906 } else 4907 Result = lowerRangeToAssertZExt(DAG, I, Result); 4908 4909 setValue(&I, Result); 4910 } 4911 } 4912 4913 /// GetSignificand - Get the significand and build it into a floating-point 4914 /// number with exponent of 1: 4915 /// 4916 /// Op = (Op & 0x007fffff) | 0x3f800000; 4917 /// 4918 /// where Op is the hexadecimal representation of floating point value. 4919 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4920 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4921 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4922 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4923 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4924 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4925 } 4926 4927 /// GetExponent - Get the exponent: 4928 /// 4929 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4930 /// 4931 /// where Op is the hexadecimal representation of floating point value. 4932 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4933 const TargetLowering &TLI, const SDLoc &dl) { 4934 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4935 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4936 SDValue t1 = DAG.getNode( 4937 ISD::SRL, dl, MVT::i32, t0, 4938 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4939 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4940 DAG.getConstant(127, dl, MVT::i32)); 4941 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4942 } 4943 4944 /// getF32Constant - Get 32-bit floating point constant. 4945 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4946 const SDLoc &dl) { 4947 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4948 MVT::f32); 4949 } 4950 4951 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4952 SelectionDAG &DAG) { 4953 // TODO: What fast-math-flags should be set on the floating-point nodes? 4954 4955 // IntegerPartOfX = ((int32_t)(t0); 4956 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4957 4958 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4959 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4960 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4961 4962 // IntegerPartOfX <<= 23; 4963 IntegerPartOfX = DAG.getNode( 4964 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4965 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4966 DAG.getDataLayout()))); 4967 4968 SDValue TwoToFractionalPartOfX; 4969 if (LimitFloatPrecision <= 6) { 4970 // For floating-point precision of 6: 4971 // 4972 // TwoToFractionalPartOfX = 4973 // 0.997535578f + 4974 // (0.735607626f + 0.252464424f * x) * x; 4975 // 4976 // error 0.0144103317, which is 6 bits 4977 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4978 getF32Constant(DAG, 0x3e814304, dl)); 4979 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4980 getF32Constant(DAG, 0x3f3c50c8, dl)); 4981 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4982 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4983 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4984 } else if (LimitFloatPrecision <= 12) { 4985 // For floating-point precision of 12: 4986 // 4987 // TwoToFractionalPartOfX = 4988 // 0.999892986f + 4989 // (0.696457318f + 4990 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4991 // 4992 // error 0.000107046256, which is 13 to 14 bits 4993 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4994 getF32Constant(DAG, 0x3da235e3, dl)); 4995 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4996 getF32Constant(DAG, 0x3e65b8f3, dl)); 4997 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4998 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4999 getF32Constant(DAG, 0x3f324b07, dl)); 5000 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5001 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5002 getF32Constant(DAG, 0x3f7ff8fd, dl)); 5003 } else { // LimitFloatPrecision <= 18 5004 // For floating-point precision of 18: 5005 // 5006 // TwoToFractionalPartOfX = 5007 // 0.999999982f + 5008 // (0.693148872f + 5009 // (0.240227044f + 5010 // (0.554906021e-1f + 5011 // (0.961591928e-2f + 5012 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 5013 // error 2.47208000*10^(-7), which is better than 18 bits 5014 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5015 getF32Constant(DAG, 0x3924b03e, dl)); 5016 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5017 getF32Constant(DAG, 0x3ab24b87, dl)); 5018 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5019 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5020 getF32Constant(DAG, 0x3c1d8c17, dl)); 5021 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5022 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5023 getF32Constant(DAG, 0x3d634a1d, dl)); 5024 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5025 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5026 getF32Constant(DAG, 0x3e75fe14, dl)); 5027 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5028 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 5029 getF32Constant(DAG, 0x3f317234, dl)); 5030 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 5031 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 5032 getF32Constant(DAG, 0x3f800000, dl)); 5033 } 5034 5035 // Add the exponent into the result in integer domain. 5036 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 5037 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 5038 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 5039 } 5040 5041 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 5042 /// limited-precision mode. 5043 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5044 const TargetLowering &TLI) { 5045 if (Op.getValueType() == MVT::f32 && 5046 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5047 5048 // Put the exponent in the right bit position for later addition to the 5049 // final result: 5050 // 5051 // t0 = Op * log2(e) 5052 5053 // TODO: What fast-math-flags should be set here? 5054 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 5055 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5056 return getLimitedPrecisionExp2(t0, dl, DAG); 5057 } 5058 5059 // No special expansion. 5060 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5061 } 5062 5063 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5064 /// limited-precision mode. 5065 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5066 const TargetLowering &TLI) { 5067 // TODO: What fast-math-flags should be set on the floating-point nodes? 5068 5069 if (Op.getValueType() == MVT::f32 && 5070 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5071 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5072 5073 // Scale the exponent by log(2). 5074 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5075 SDValue LogOfExponent = 5076 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5077 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5078 5079 // Get the significand and build it into a floating-point number with 5080 // exponent of 1. 5081 SDValue X = GetSignificand(DAG, Op1, dl); 5082 5083 SDValue LogOfMantissa; 5084 if (LimitFloatPrecision <= 6) { 5085 // For floating-point precision of 6: 5086 // 5087 // LogofMantissa = 5088 // -1.1609546f + 5089 // (1.4034025f - 0.23903021f * x) * x; 5090 // 5091 // error 0.0034276066, which is better than 8 bits 5092 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5093 getF32Constant(DAG, 0xbe74c456, dl)); 5094 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5095 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5096 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5097 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5098 getF32Constant(DAG, 0x3f949a29, dl)); 5099 } else if (LimitFloatPrecision <= 12) { 5100 // For floating-point precision of 12: 5101 // 5102 // LogOfMantissa = 5103 // -1.7417939f + 5104 // (2.8212026f + 5105 // (-1.4699568f + 5106 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5107 // 5108 // error 0.000061011436, which is 14 bits 5109 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5110 getF32Constant(DAG, 0xbd67b6d6, dl)); 5111 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5112 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5113 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5114 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5115 getF32Constant(DAG, 0x3fbc278b, dl)); 5116 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5117 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5118 getF32Constant(DAG, 0x40348e95, dl)); 5119 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5120 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5121 getF32Constant(DAG, 0x3fdef31a, dl)); 5122 } else { // LimitFloatPrecision <= 18 5123 // For floating-point precision of 18: 5124 // 5125 // LogOfMantissa = 5126 // -2.1072184f + 5127 // (4.2372794f + 5128 // (-3.7029485f + 5129 // (2.2781945f + 5130 // (-0.87823314f + 5131 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5132 // 5133 // error 0.0000023660568, which is better than 18 bits 5134 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5135 getF32Constant(DAG, 0xbc91e5ac, dl)); 5136 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5137 getF32Constant(DAG, 0x3e4350aa, dl)); 5138 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5139 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5140 getF32Constant(DAG, 0x3f60d3e3, dl)); 5141 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5142 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5143 getF32Constant(DAG, 0x4011cdf0, dl)); 5144 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5145 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5146 getF32Constant(DAG, 0x406cfd1c, dl)); 5147 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5148 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5149 getF32Constant(DAG, 0x408797cb, dl)); 5150 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5151 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5152 getF32Constant(DAG, 0x4006dcab, dl)); 5153 } 5154 5155 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5156 } 5157 5158 // No special expansion. 5159 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5160 } 5161 5162 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5163 /// limited-precision mode. 5164 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5165 const TargetLowering &TLI) { 5166 // TODO: What fast-math-flags should be set on the floating-point nodes? 5167 5168 if (Op.getValueType() == MVT::f32 && 5169 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5170 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5171 5172 // Get the exponent. 5173 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5174 5175 // Get the significand and build it into a floating-point number with 5176 // exponent of 1. 5177 SDValue X = GetSignificand(DAG, Op1, dl); 5178 5179 // Different possible minimax approximations of significand in 5180 // floating-point for various degrees of accuracy over [1,2]. 5181 SDValue Log2ofMantissa; 5182 if (LimitFloatPrecision <= 6) { 5183 // For floating-point precision of 6: 5184 // 5185 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5186 // 5187 // error 0.0049451742, which is more than 7 bits 5188 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5189 getF32Constant(DAG, 0xbeb08fe0, dl)); 5190 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5191 getF32Constant(DAG, 0x40019463, dl)); 5192 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5193 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5194 getF32Constant(DAG, 0x3fd6633d, dl)); 5195 } else if (LimitFloatPrecision <= 12) { 5196 // For floating-point precision of 12: 5197 // 5198 // Log2ofMantissa = 5199 // -2.51285454f + 5200 // (4.07009056f + 5201 // (-2.12067489f + 5202 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5203 // 5204 // error 0.0000876136000, which is better than 13 bits 5205 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5206 getF32Constant(DAG, 0xbda7262e, dl)); 5207 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5208 getF32Constant(DAG, 0x3f25280b, dl)); 5209 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5210 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5211 getF32Constant(DAG, 0x4007b923, dl)); 5212 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5213 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5214 getF32Constant(DAG, 0x40823e2f, dl)); 5215 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5216 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5217 getF32Constant(DAG, 0x4020d29c, dl)); 5218 } else { // LimitFloatPrecision <= 18 5219 // For floating-point precision of 18: 5220 // 5221 // Log2ofMantissa = 5222 // -3.0400495f + 5223 // (6.1129976f + 5224 // (-5.3420409f + 5225 // (3.2865683f + 5226 // (-1.2669343f + 5227 // (0.27515199f - 5228 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5229 // 5230 // error 0.0000018516, which is better than 18 bits 5231 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5232 getF32Constant(DAG, 0xbcd2769e, dl)); 5233 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5234 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5235 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5236 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5237 getF32Constant(DAG, 0x3fa22ae7, dl)); 5238 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5239 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5240 getF32Constant(DAG, 0x40525723, dl)); 5241 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5242 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5243 getF32Constant(DAG, 0x40aaf200, dl)); 5244 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5245 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5246 getF32Constant(DAG, 0x40c39dad, dl)); 5247 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5248 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5249 getF32Constant(DAG, 0x4042902c, dl)); 5250 } 5251 5252 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5253 } 5254 5255 // No special expansion. 5256 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5257 } 5258 5259 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5260 /// limited-precision mode. 5261 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5262 const TargetLowering &TLI) { 5263 // TODO: What fast-math-flags should be set on the floating-point nodes? 5264 5265 if (Op.getValueType() == MVT::f32 && 5266 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5267 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5268 5269 // Scale the exponent by log10(2) [0.30102999f]. 5270 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5271 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5272 getF32Constant(DAG, 0x3e9a209a, dl)); 5273 5274 // Get the significand and build it into a floating-point number with 5275 // exponent of 1. 5276 SDValue X = GetSignificand(DAG, Op1, dl); 5277 5278 SDValue Log10ofMantissa; 5279 if (LimitFloatPrecision <= 6) { 5280 // For floating-point precision of 6: 5281 // 5282 // Log10ofMantissa = 5283 // -0.50419619f + 5284 // (0.60948995f - 0.10380950f * x) * x; 5285 // 5286 // error 0.0014886165, which is 6 bits 5287 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5288 getF32Constant(DAG, 0xbdd49a13, dl)); 5289 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5290 getF32Constant(DAG, 0x3f1c0789, dl)); 5291 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5292 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5293 getF32Constant(DAG, 0x3f011300, dl)); 5294 } else if (LimitFloatPrecision <= 12) { 5295 // For floating-point precision of 12: 5296 // 5297 // Log10ofMantissa = 5298 // -0.64831180f + 5299 // (0.91751397f + 5300 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5301 // 5302 // error 0.00019228036, which is better than 12 bits 5303 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5304 getF32Constant(DAG, 0x3d431f31, dl)); 5305 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5306 getF32Constant(DAG, 0x3ea21fb2, dl)); 5307 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5308 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5309 getF32Constant(DAG, 0x3f6ae232, dl)); 5310 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5311 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5312 getF32Constant(DAG, 0x3f25f7c3, dl)); 5313 } else { // LimitFloatPrecision <= 18 5314 // For floating-point precision of 18: 5315 // 5316 // Log10ofMantissa = 5317 // -0.84299375f + 5318 // (1.5327582f + 5319 // (-1.0688956f + 5320 // (0.49102474f + 5321 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5322 // 5323 // error 0.0000037995730, which is better than 18 bits 5324 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5325 getF32Constant(DAG, 0x3c5d51ce, dl)); 5326 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5327 getF32Constant(DAG, 0x3e00685a, dl)); 5328 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5329 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5330 getF32Constant(DAG, 0x3efb6798, dl)); 5331 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5332 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5333 getF32Constant(DAG, 0x3f88d192, dl)); 5334 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5335 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5336 getF32Constant(DAG, 0x3fc4316c, dl)); 5337 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5338 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5339 getF32Constant(DAG, 0x3f57ce70, dl)); 5340 } 5341 5342 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5343 } 5344 5345 // No special expansion. 5346 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5347 } 5348 5349 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5350 /// limited-precision mode. 5351 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5352 const TargetLowering &TLI) { 5353 if (Op.getValueType() == MVT::f32 && 5354 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5355 return getLimitedPrecisionExp2(Op, dl, DAG); 5356 5357 // No special expansion. 5358 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5359 } 5360 5361 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5362 /// limited-precision mode with x == 10.0f. 5363 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5364 SelectionDAG &DAG, const TargetLowering &TLI) { 5365 bool IsExp10 = false; 5366 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5367 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5368 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5369 APFloat Ten(10.0f); 5370 IsExp10 = LHSC->isExactlyValue(Ten); 5371 } 5372 } 5373 5374 // TODO: What fast-math-flags should be set on the FMUL node? 5375 if (IsExp10) { 5376 // Put the exponent in the right bit position for later addition to the 5377 // final result: 5378 // 5379 // #define LOG2OF10 3.3219281f 5380 // t0 = Op * LOG2OF10; 5381 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5382 getF32Constant(DAG, 0x40549a78, dl)); 5383 return getLimitedPrecisionExp2(t0, dl, DAG); 5384 } 5385 5386 // No special expansion. 5387 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5388 } 5389 5390 /// ExpandPowI - Expand a llvm.powi intrinsic. 5391 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5392 SelectionDAG &DAG) { 5393 // If RHS is a constant, we can expand this out to a multiplication tree, 5394 // otherwise we end up lowering to a call to __powidf2 (for example). When 5395 // optimizing for size, we only want to do this if the expansion would produce 5396 // a small number of multiplies, otherwise we do the full expansion. 5397 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5398 // Get the exponent as a positive value. 5399 unsigned Val = RHSC->getSExtValue(); 5400 if ((int)Val < 0) Val = -Val; 5401 5402 // powi(x, 0) -> 1.0 5403 if (Val == 0) 5404 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5405 5406 bool OptForSize = DAG.shouldOptForSize(); 5407 if (!OptForSize || 5408 // If optimizing for size, don't insert too many multiplies. 5409 // This inserts up to 5 multiplies. 5410 countPopulation(Val) + Log2_32(Val) < 7) { 5411 // We use the simple binary decomposition method to generate the multiply 5412 // sequence. There are more optimal ways to do this (for example, 5413 // powi(x,15) generates one more multiply than it should), but this has 5414 // the benefit of being both really simple and much better than a libcall. 5415 SDValue Res; // Logically starts equal to 1.0 5416 SDValue CurSquare = LHS; 5417 // TODO: Intrinsics should have fast-math-flags that propagate to these 5418 // nodes. 5419 while (Val) { 5420 if (Val & 1) { 5421 if (Res.getNode()) 5422 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5423 else 5424 Res = CurSquare; // 1.0*CurSquare. 5425 } 5426 5427 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5428 CurSquare, CurSquare); 5429 Val >>= 1; 5430 } 5431 5432 // If the original was negative, invert the result, producing 1/(x*x*x). 5433 if (RHSC->getSExtValue() < 0) 5434 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5435 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5436 return Res; 5437 } 5438 } 5439 5440 // Otherwise, expand to a libcall. 5441 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5442 } 5443 5444 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5445 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5446 static void 5447 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5448 const SDValue &N) { 5449 switch (N.getOpcode()) { 5450 case ISD::CopyFromReg: { 5451 SDValue Op = N.getOperand(1); 5452 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5453 Op.getValueType().getSizeInBits()); 5454 return; 5455 } 5456 case ISD::BITCAST: 5457 case ISD::AssertZext: 5458 case ISD::AssertSext: 5459 case ISD::TRUNCATE: 5460 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5461 return; 5462 case ISD::BUILD_PAIR: 5463 case ISD::BUILD_VECTOR: 5464 case ISD::CONCAT_VECTORS: 5465 for (SDValue Op : N->op_values()) 5466 getUnderlyingArgRegs(Regs, Op); 5467 return; 5468 default: 5469 return; 5470 } 5471 } 5472 5473 /// If the DbgValueInst is a dbg_value of a function argument, create the 5474 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5475 /// instruction selection, they will be inserted to the entry BB. 5476 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5477 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5478 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5479 const Argument *Arg = dyn_cast<Argument>(V); 5480 if (!Arg) 5481 return false; 5482 5483 if (!IsDbgDeclare) { 5484 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5485 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5486 // the entry block. 5487 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5488 if (!IsInEntryBlock) 5489 return false; 5490 5491 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5492 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5493 // variable that also is a param. 5494 // 5495 // Although, if we are at the top of the entry block already, we can still 5496 // emit using ArgDbgValue. This might catch some situations when the 5497 // dbg.value refers to an argument that isn't used in the entry block, so 5498 // any CopyToReg node would be optimized out and the only way to express 5499 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5500 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5501 // we should only emit as ArgDbgValue if the Variable is an argument to the 5502 // current function, and the dbg.value intrinsic is found in the entry 5503 // block. 5504 bool VariableIsFunctionInputArg = Variable->isParameter() && 5505 !DL->getInlinedAt(); 5506 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5507 if (!IsInPrologue && !VariableIsFunctionInputArg) 5508 return false; 5509 5510 // Here we assume that a function argument on IR level only can be used to 5511 // describe one input parameter on source level. If we for example have 5512 // source code like this 5513 // 5514 // struct A { long x, y; }; 5515 // void foo(struct A a, long b) { 5516 // ... 5517 // b = a.x; 5518 // ... 5519 // } 5520 // 5521 // and IR like this 5522 // 5523 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5524 // entry: 5525 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5526 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5527 // call void @llvm.dbg.value(metadata i32 %b, "b", 5528 // ... 5529 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5530 // ... 5531 // 5532 // then the last dbg.value is describing a parameter "b" using a value that 5533 // is an argument. But since we already has used %a1 to describe a parameter 5534 // we should not handle that last dbg.value here (that would result in an 5535 // incorrect hoisting of the DBG_VALUE to the function entry). 5536 // Notice that we allow one dbg.value per IR level argument, to accommodate 5537 // for the situation with fragments above. 5538 if (VariableIsFunctionInputArg) { 5539 unsigned ArgNo = Arg->getArgNo(); 5540 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5541 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5542 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5543 return false; 5544 FuncInfo.DescribedArgs.set(ArgNo); 5545 } 5546 } 5547 5548 MachineFunction &MF = DAG.getMachineFunction(); 5549 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5550 5551 Optional<MachineOperand> Op; 5552 // Some arguments' frame index is recorded during argument lowering. 5553 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5554 if (FI != std::numeric_limits<int>::max()) 5555 Op = MachineOperand::CreateFI(FI); 5556 5557 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5558 if (!Op && N.getNode()) { 5559 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5560 Register Reg; 5561 if (ArgRegsAndSizes.size() == 1) 5562 Reg = ArgRegsAndSizes.front().first; 5563 5564 if (Reg && Reg.isVirtual()) { 5565 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5566 Register PR = RegInfo.getLiveInPhysReg(Reg); 5567 if (PR) 5568 Reg = PR; 5569 } 5570 if (Reg) { 5571 Op = MachineOperand::CreateReg(Reg, false); 5572 } 5573 } 5574 5575 if (!Op && N.getNode()) { 5576 // Check if frame index is available. 5577 SDValue LCandidate = peekThroughBitcasts(N); 5578 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5579 if (FrameIndexSDNode *FINode = 5580 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5581 Op = MachineOperand::CreateFI(FINode->getIndex()); 5582 } 5583 5584 if (!Op) { 5585 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5586 auto splitMultiRegDbgValue 5587 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5588 unsigned Offset = 0; 5589 for (auto RegAndSize : SplitRegs) { 5590 // If the expression is already a fragment, the current register 5591 // offset+size might extend beyond the fragment. In this case, only 5592 // the register bits that are inside the fragment are relevant. 5593 int RegFragmentSizeInBits = RegAndSize.second; 5594 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) { 5595 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits; 5596 // The register is entirely outside the expression fragment, 5597 // so is irrelevant for debug info. 5598 if (Offset >= ExprFragmentSizeInBits) 5599 break; 5600 // The register is partially outside the expression fragment, only 5601 // the low bits within the fragment are relevant for debug info. 5602 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) { 5603 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset; 5604 } 5605 } 5606 5607 auto FragmentExpr = DIExpression::createFragmentExpression( 5608 Expr, Offset, RegFragmentSizeInBits); 5609 Offset += RegAndSize.second; 5610 // If a valid fragment expression cannot be created, the variable's 5611 // correct value cannot be determined and so it is set as Undef. 5612 if (!FragmentExpr) { 5613 SDDbgValue *SDV = DAG.getConstantDbgValue( 5614 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder); 5615 DAG.AddDbgValue(SDV, nullptr, false); 5616 continue; 5617 } 5618 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5619 FuncInfo.ArgDbgValues.push_back( 5620 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5621 RegAndSize.first, Variable, *FragmentExpr)); 5622 } 5623 }; 5624 5625 // Check if ValueMap has reg number. 5626 DenseMap<const Value *, unsigned>::const_iterator 5627 VMI = FuncInfo.ValueMap.find(V); 5628 if (VMI != FuncInfo.ValueMap.end()) { 5629 const auto &TLI = DAG.getTargetLoweringInfo(); 5630 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5631 V->getType(), getABIRegCopyCC(V)); 5632 if (RFV.occupiesMultipleRegs()) { 5633 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5634 return true; 5635 } 5636 5637 Op = MachineOperand::CreateReg(VMI->second, false); 5638 } else if (ArgRegsAndSizes.size() > 1) { 5639 // This was split due to the calling convention, and no virtual register 5640 // mapping exists for the value. 5641 splitMultiRegDbgValue(ArgRegsAndSizes); 5642 return true; 5643 } 5644 } 5645 5646 if (!Op) 5647 return false; 5648 5649 assert(Variable->isValidLocationForIntrinsic(DL) && 5650 "Expected inlined-at fields to agree"); 5651 5652 // If the argument arrives in a stack slot, then what the IR thought was a 5653 // normal Value is actually in memory, and we must add a deref to load it. 5654 if (Op->isFI()) { 5655 int FI = Op->getIndex(); 5656 unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI); 5657 if (Expr->isImplicit()) { 5658 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size}; 5659 Expr = DIExpression::prependOpcodes(Expr, Ops); 5660 } else { 5661 Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore); 5662 } 5663 } 5664 5665 // If this location was specified with a dbg.declare, then it and its 5666 // expression calculate the address of the variable. Append a deref to 5667 // force it to be a memory location. 5668 if (IsDbgDeclare) 5669 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 5670 5671 FuncInfo.ArgDbgValues.push_back( 5672 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5673 *Op, Variable, Expr)); 5674 5675 return true; 5676 } 5677 5678 /// Return the appropriate SDDbgValue based on N. 5679 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5680 DILocalVariable *Variable, 5681 DIExpression *Expr, 5682 const DebugLoc &dl, 5683 unsigned DbgSDNodeOrder) { 5684 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5685 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5686 // stack slot locations. 5687 // 5688 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5689 // debug values here after optimization: 5690 // 5691 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5692 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5693 // 5694 // Both describe the direct values of their associated variables. 5695 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5696 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5697 } 5698 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5699 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5700 } 5701 5702 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5703 switch (Intrinsic) { 5704 case Intrinsic::smul_fix: 5705 return ISD::SMULFIX; 5706 case Intrinsic::umul_fix: 5707 return ISD::UMULFIX; 5708 default: 5709 llvm_unreachable("Unhandled fixed point intrinsic"); 5710 } 5711 } 5712 5713 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5714 const char *FunctionName) { 5715 assert(FunctionName && "FunctionName must not be nullptr"); 5716 SDValue Callee = DAG.getExternalSymbol( 5717 FunctionName, 5718 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5719 LowerCallTo(&I, Callee, I.isTailCall()); 5720 } 5721 5722 /// Lower the call to the specified intrinsic function. 5723 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5724 unsigned Intrinsic) { 5725 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5726 SDLoc sdl = getCurSDLoc(); 5727 DebugLoc dl = getCurDebugLoc(); 5728 SDValue Res; 5729 5730 switch (Intrinsic) { 5731 default: 5732 // By default, turn this into a target intrinsic node. 5733 visitTargetIntrinsic(I, Intrinsic); 5734 return; 5735 case Intrinsic::vastart: visitVAStart(I); return; 5736 case Intrinsic::vaend: visitVAEnd(I); return; 5737 case Intrinsic::vacopy: visitVACopy(I); return; 5738 case Intrinsic::returnaddress: 5739 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5740 TLI.getPointerTy(DAG.getDataLayout()), 5741 getValue(I.getArgOperand(0)))); 5742 return; 5743 case Intrinsic::addressofreturnaddress: 5744 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5745 TLI.getPointerTy(DAG.getDataLayout()))); 5746 return; 5747 case Intrinsic::sponentry: 5748 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5749 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5750 return; 5751 case Intrinsic::frameaddress: 5752 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5753 TLI.getFrameIndexTy(DAG.getDataLayout()), 5754 getValue(I.getArgOperand(0)))); 5755 return; 5756 case Intrinsic::read_register: { 5757 Value *Reg = I.getArgOperand(0); 5758 SDValue Chain = getRoot(); 5759 SDValue RegName = 5760 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5761 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5762 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5763 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5764 setValue(&I, Res); 5765 DAG.setRoot(Res.getValue(1)); 5766 return; 5767 } 5768 case Intrinsic::write_register: { 5769 Value *Reg = I.getArgOperand(0); 5770 Value *RegValue = I.getArgOperand(1); 5771 SDValue Chain = getRoot(); 5772 SDValue RegName = 5773 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5774 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5775 RegName, getValue(RegValue))); 5776 return; 5777 } 5778 case Intrinsic::memcpy: { 5779 const auto &MCI = cast<MemCpyInst>(I); 5780 SDValue Op1 = getValue(I.getArgOperand(0)); 5781 SDValue Op2 = getValue(I.getArgOperand(1)); 5782 SDValue Op3 = getValue(I.getArgOperand(2)); 5783 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5784 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5785 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5786 unsigned Align = MinAlign(DstAlign, SrcAlign); 5787 bool isVol = MCI.isVolatile(); 5788 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5789 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5790 // node. 5791 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5792 false, isTC, 5793 MachinePointerInfo(I.getArgOperand(0)), 5794 MachinePointerInfo(I.getArgOperand(1))); 5795 updateDAGForMaybeTailCall(MC); 5796 return; 5797 } 5798 case Intrinsic::memset: { 5799 const auto &MSI = cast<MemSetInst>(I); 5800 SDValue Op1 = getValue(I.getArgOperand(0)); 5801 SDValue Op2 = getValue(I.getArgOperand(1)); 5802 SDValue Op3 = getValue(I.getArgOperand(2)); 5803 // @llvm.memset defines 0 and 1 to both mean no alignment. 5804 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5805 bool isVol = MSI.isVolatile(); 5806 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5807 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5808 isTC, MachinePointerInfo(I.getArgOperand(0))); 5809 updateDAGForMaybeTailCall(MS); 5810 return; 5811 } 5812 case Intrinsic::memmove: { 5813 const auto &MMI = cast<MemMoveInst>(I); 5814 SDValue Op1 = getValue(I.getArgOperand(0)); 5815 SDValue Op2 = getValue(I.getArgOperand(1)); 5816 SDValue Op3 = getValue(I.getArgOperand(2)); 5817 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5818 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5819 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5820 unsigned Align = MinAlign(DstAlign, SrcAlign); 5821 bool isVol = MMI.isVolatile(); 5822 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5823 // FIXME: Support passing different dest/src alignments to the memmove DAG 5824 // node. 5825 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5826 isTC, MachinePointerInfo(I.getArgOperand(0)), 5827 MachinePointerInfo(I.getArgOperand(1))); 5828 updateDAGForMaybeTailCall(MM); 5829 return; 5830 } 5831 case Intrinsic::memcpy_element_unordered_atomic: { 5832 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5833 SDValue Dst = getValue(MI.getRawDest()); 5834 SDValue Src = getValue(MI.getRawSource()); 5835 SDValue Length = getValue(MI.getLength()); 5836 5837 unsigned DstAlign = MI.getDestAlignment(); 5838 unsigned SrcAlign = MI.getSourceAlignment(); 5839 Type *LengthTy = MI.getLength()->getType(); 5840 unsigned ElemSz = MI.getElementSizeInBytes(); 5841 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5842 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5843 SrcAlign, Length, LengthTy, ElemSz, isTC, 5844 MachinePointerInfo(MI.getRawDest()), 5845 MachinePointerInfo(MI.getRawSource())); 5846 updateDAGForMaybeTailCall(MC); 5847 return; 5848 } 5849 case Intrinsic::memmove_element_unordered_atomic: { 5850 auto &MI = cast<AtomicMemMoveInst>(I); 5851 SDValue Dst = getValue(MI.getRawDest()); 5852 SDValue Src = getValue(MI.getRawSource()); 5853 SDValue Length = getValue(MI.getLength()); 5854 5855 unsigned DstAlign = MI.getDestAlignment(); 5856 unsigned SrcAlign = MI.getSourceAlignment(); 5857 Type *LengthTy = MI.getLength()->getType(); 5858 unsigned ElemSz = MI.getElementSizeInBytes(); 5859 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5860 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5861 SrcAlign, Length, LengthTy, ElemSz, isTC, 5862 MachinePointerInfo(MI.getRawDest()), 5863 MachinePointerInfo(MI.getRawSource())); 5864 updateDAGForMaybeTailCall(MC); 5865 return; 5866 } 5867 case Intrinsic::memset_element_unordered_atomic: { 5868 auto &MI = cast<AtomicMemSetInst>(I); 5869 SDValue Dst = getValue(MI.getRawDest()); 5870 SDValue Val = getValue(MI.getValue()); 5871 SDValue Length = getValue(MI.getLength()); 5872 5873 unsigned DstAlign = MI.getDestAlignment(); 5874 Type *LengthTy = MI.getLength()->getType(); 5875 unsigned ElemSz = MI.getElementSizeInBytes(); 5876 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5877 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5878 LengthTy, ElemSz, isTC, 5879 MachinePointerInfo(MI.getRawDest())); 5880 updateDAGForMaybeTailCall(MC); 5881 return; 5882 } 5883 case Intrinsic::dbg_addr: 5884 case Intrinsic::dbg_declare: { 5885 const auto &DI = cast<DbgVariableIntrinsic>(I); 5886 DILocalVariable *Variable = DI.getVariable(); 5887 DIExpression *Expression = DI.getExpression(); 5888 dropDanglingDebugInfo(Variable, Expression); 5889 assert(Variable && "Missing variable"); 5890 5891 // Check if address has undef value. 5892 const Value *Address = DI.getVariableLocation(); 5893 if (!Address || isa<UndefValue>(Address) || 5894 (Address->use_empty() && !isa<Argument>(Address))) { 5895 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5896 return; 5897 } 5898 5899 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5900 5901 // Check if this variable can be described by a frame index, typically 5902 // either as a static alloca or a byval parameter. 5903 int FI = std::numeric_limits<int>::max(); 5904 if (const auto *AI = 5905 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5906 if (AI->isStaticAlloca()) { 5907 auto I = FuncInfo.StaticAllocaMap.find(AI); 5908 if (I != FuncInfo.StaticAllocaMap.end()) 5909 FI = I->second; 5910 } 5911 } else if (const auto *Arg = dyn_cast<Argument>( 5912 Address->stripInBoundsConstantOffsets())) { 5913 FI = FuncInfo.getArgumentFrameIndex(Arg); 5914 } 5915 5916 // llvm.dbg.addr is control dependent and always generates indirect 5917 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5918 // the MachineFunction variable table. 5919 if (FI != std::numeric_limits<int>::max()) { 5920 if (Intrinsic == Intrinsic::dbg_addr) { 5921 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5922 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5923 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5924 } 5925 return; 5926 } 5927 5928 SDValue &N = NodeMap[Address]; 5929 if (!N.getNode() && isa<Argument>(Address)) 5930 // Check unused arguments map. 5931 N = UnusedArgNodeMap[Address]; 5932 SDDbgValue *SDV; 5933 if (N.getNode()) { 5934 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5935 Address = BCI->getOperand(0); 5936 // Parameters are handled specially. 5937 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5938 if (isParameter && FINode) { 5939 // Byval parameter. We have a frame index at this point. 5940 SDV = 5941 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5942 /*IsIndirect*/ true, dl, SDNodeOrder); 5943 } else if (isa<Argument>(Address)) { 5944 // Address is an argument, so try to emit its dbg value using 5945 // virtual register info from the FuncInfo.ValueMap. 5946 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5947 return; 5948 } else { 5949 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5950 true, dl, SDNodeOrder); 5951 } 5952 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5953 } else { 5954 // If Address is an argument then try to emit its dbg value using 5955 // virtual register info from the FuncInfo.ValueMap. 5956 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5957 N)) { 5958 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\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)); 6083 return; 6084 case Intrinsic::log2: 6085 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6086 return; 6087 case Intrinsic::log10: 6088 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6089 return; 6090 case Intrinsic::exp: 6091 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6092 return; 6093 case Intrinsic::exp2: 6094 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6095 return; 6096 case Intrinsic::pow: 6097 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6098 getValue(I.getArgOperand(1)), DAG, TLI)); 6099 return; 6100 case Intrinsic::sqrt: 6101 case Intrinsic::fabs: 6102 case Intrinsic::sin: 6103 case Intrinsic::cos: 6104 case Intrinsic::floor: 6105 case Intrinsic::ceil: 6106 case Intrinsic::trunc: 6107 case Intrinsic::rint: 6108 case Intrinsic::nearbyint: 6109 case Intrinsic::round: 6110 case Intrinsic::canonicalize: { 6111 unsigned Opcode; 6112 switch (Intrinsic) { 6113 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6114 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6115 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6116 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6117 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6118 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6119 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6120 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6121 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6122 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6123 case Intrinsic::round: Opcode = ISD::FROUND; break; 6124 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6125 } 6126 6127 setValue(&I, DAG.getNode(Opcode, sdl, 6128 getValue(I.getArgOperand(0)).getValueType(), 6129 getValue(I.getArgOperand(0)))); 6130 return; 6131 } 6132 case Intrinsic::lround: 6133 case Intrinsic::llround: 6134 case Intrinsic::lrint: 6135 case Intrinsic::llrint: { 6136 unsigned Opcode; 6137 switch (Intrinsic) { 6138 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6139 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6140 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6141 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6142 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6143 } 6144 6145 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6146 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6147 getValue(I.getArgOperand(0)))); 6148 return; 6149 } 6150 case Intrinsic::minnum: 6151 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6152 getValue(I.getArgOperand(0)).getValueType(), 6153 getValue(I.getArgOperand(0)), 6154 getValue(I.getArgOperand(1)))); 6155 return; 6156 case Intrinsic::maxnum: 6157 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6158 getValue(I.getArgOperand(0)).getValueType(), 6159 getValue(I.getArgOperand(0)), 6160 getValue(I.getArgOperand(1)))); 6161 return; 6162 case Intrinsic::minimum: 6163 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6164 getValue(I.getArgOperand(0)).getValueType(), 6165 getValue(I.getArgOperand(0)), 6166 getValue(I.getArgOperand(1)))); 6167 return; 6168 case Intrinsic::maximum: 6169 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6170 getValue(I.getArgOperand(0)).getValueType(), 6171 getValue(I.getArgOperand(0)), 6172 getValue(I.getArgOperand(1)))); 6173 return; 6174 case Intrinsic::copysign: 6175 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6176 getValue(I.getArgOperand(0)).getValueType(), 6177 getValue(I.getArgOperand(0)), 6178 getValue(I.getArgOperand(1)))); 6179 return; 6180 case Intrinsic::fma: 6181 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6182 getValue(I.getArgOperand(0)).getValueType(), 6183 getValue(I.getArgOperand(0)), 6184 getValue(I.getArgOperand(1)), 6185 getValue(I.getArgOperand(2)))); 6186 return; 6187 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6188 case Intrinsic::INTRINSIC: 6189 #include "llvm/IR/ConstrainedOps.def" 6190 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6191 return; 6192 case Intrinsic::fmuladd: { 6193 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6194 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6195 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 6196 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6197 getValue(I.getArgOperand(0)).getValueType(), 6198 getValue(I.getArgOperand(0)), 6199 getValue(I.getArgOperand(1)), 6200 getValue(I.getArgOperand(2)))); 6201 } else { 6202 // TODO: Intrinsic calls should have fast-math-flags. 6203 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6204 getValue(I.getArgOperand(0)).getValueType(), 6205 getValue(I.getArgOperand(0)), 6206 getValue(I.getArgOperand(1))); 6207 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6208 getValue(I.getArgOperand(0)).getValueType(), 6209 Mul, 6210 getValue(I.getArgOperand(2))); 6211 setValue(&I, Add); 6212 } 6213 return; 6214 } 6215 case Intrinsic::convert_to_fp16: 6216 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6217 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6218 getValue(I.getArgOperand(0)), 6219 DAG.getTargetConstant(0, sdl, 6220 MVT::i32)))); 6221 return; 6222 case Intrinsic::convert_from_fp16: 6223 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6224 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6225 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6226 getValue(I.getArgOperand(0))))); 6227 return; 6228 case Intrinsic::pcmarker: { 6229 SDValue Tmp = getValue(I.getArgOperand(0)); 6230 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6231 return; 6232 } 6233 case Intrinsic::readcyclecounter: { 6234 SDValue Op = getRoot(); 6235 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6236 DAG.getVTList(MVT::i64, MVT::Other), Op); 6237 setValue(&I, Res); 6238 DAG.setRoot(Res.getValue(1)); 6239 return; 6240 } 6241 case Intrinsic::bitreverse: 6242 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6243 getValue(I.getArgOperand(0)).getValueType(), 6244 getValue(I.getArgOperand(0)))); 6245 return; 6246 case Intrinsic::bswap: 6247 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6248 getValue(I.getArgOperand(0)).getValueType(), 6249 getValue(I.getArgOperand(0)))); 6250 return; 6251 case Intrinsic::cttz: { 6252 SDValue Arg = getValue(I.getArgOperand(0)); 6253 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6254 EVT Ty = Arg.getValueType(); 6255 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6256 sdl, Ty, Arg)); 6257 return; 6258 } 6259 case Intrinsic::ctlz: { 6260 SDValue Arg = getValue(I.getArgOperand(0)); 6261 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6262 EVT Ty = Arg.getValueType(); 6263 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6264 sdl, Ty, Arg)); 6265 return; 6266 } 6267 case Intrinsic::ctpop: { 6268 SDValue Arg = getValue(I.getArgOperand(0)); 6269 EVT Ty = Arg.getValueType(); 6270 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6271 return; 6272 } 6273 case Intrinsic::fshl: 6274 case Intrinsic::fshr: { 6275 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6276 SDValue X = getValue(I.getArgOperand(0)); 6277 SDValue Y = getValue(I.getArgOperand(1)); 6278 SDValue Z = getValue(I.getArgOperand(2)); 6279 EVT VT = X.getValueType(); 6280 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6281 SDValue Zero = DAG.getConstant(0, sdl, VT); 6282 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6283 6284 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6285 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6286 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6287 return; 6288 } 6289 6290 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6291 // avoid the select that is necessary in the general case to filter out 6292 // the 0-shift possibility that leads to UB. 6293 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6294 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6295 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6296 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6297 return; 6298 } 6299 6300 // Some targets only rotate one way. Try the opposite direction. 6301 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6302 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6303 // Negate the shift amount because it is safe to ignore the high bits. 6304 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6305 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6306 return; 6307 } 6308 6309 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6310 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6311 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6312 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6313 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6314 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6315 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6316 return; 6317 } 6318 6319 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6320 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6321 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6322 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6323 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6324 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6325 6326 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6327 // and that is undefined. We must compare and select to avoid UB. 6328 EVT CCVT = MVT::i1; 6329 if (VT.isVector()) 6330 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6331 6332 // For fshl, 0-shift returns the 1st arg (X). 6333 // For fshr, 0-shift returns the 2nd arg (Y). 6334 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6335 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6336 return; 6337 } 6338 case Intrinsic::sadd_sat: { 6339 SDValue Op1 = getValue(I.getArgOperand(0)); 6340 SDValue Op2 = getValue(I.getArgOperand(1)); 6341 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6342 return; 6343 } 6344 case Intrinsic::uadd_sat: { 6345 SDValue Op1 = getValue(I.getArgOperand(0)); 6346 SDValue Op2 = getValue(I.getArgOperand(1)); 6347 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6348 return; 6349 } 6350 case Intrinsic::ssub_sat: { 6351 SDValue Op1 = getValue(I.getArgOperand(0)); 6352 SDValue Op2 = getValue(I.getArgOperand(1)); 6353 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6354 return; 6355 } 6356 case Intrinsic::usub_sat: { 6357 SDValue Op1 = getValue(I.getArgOperand(0)); 6358 SDValue Op2 = getValue(I.getArgOperand(1)); 6359 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6360 return; 6361 } 6362 case Intrinsic::smul_fix: 6363 case Intrinsic::umul_fix: { 6364 SDValue Op1 = getValue(I.getArgOperand(0)); 6365 SDValue Op2 = getValue(I.getArgOperand(1)); 6366 SDValue Op3 = getValue(I.getArgOperand(2)); 6367 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6368 Op1.getValueType(), Op1, Op2, Op3)); 6369 return; 6370 } 6371 case Intrinsic::smul_fix_sat: { 6372 SDValue Op1 = getValue(I.getArgOperand(0)); 6373 SDValue Op2 = getValue(I.getArgOperand(1)); 6374 SDValue Op3 = getValue(I.getArgOperand(2)); 6375 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6376 Op3)); 6377 return; 6378 } 6379 case Intrinsic::umul_fix_sat: { 6380 SDValue Op1 = getValue(I.getArgOperand(0)); 6381 SDValue Op2 = getValue(I.getArgOperand(1)); 6382 SDValue Op3 = getValue(I.getArgOperand(2)); 6383 setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6384 Op3)); 6385 return; 6386 } 6387 case Intrinsic::stacksave: { 6388 SDValue Op = getRoot(); 6389 Res = DAG.getNode( 6390 ISD::STACKSAVE, sdl, 6391 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6392 setValue(&I, Res); 6393 DAG.setRoot(Res.getValue(1)); 6394 return; 6395 } 6396 case Intrinsic::stackrestore: 6397 Res = getValue(I.getArgOperand(0)); 6398 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6399 return; 6400 case Intrinsic::get_dynamic_area_offset: { 6401 SDValue Op = getRoot(); 6402 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6403 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6404 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6405 // target. 6406 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6407 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6408 " intrinsic!"); 6409 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6410 Op); 6411 DAG.setRoot(Op); 6412 setValue(&I, Res); 6413 return; 6414 } 6415 case Intrinsic::stackguard: { 6416 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6417 MachineFunction &MF = DAG.getMachineFunction(); 6418 const Module &M = *MF.getFunction().getParent(); 6419 SDValue Chain = getRoot(); 6420 if (TLI.useLoadStackGuardNode()) { 6421 Res = getLoadStackGuard(DAG, sdl, Chain); 6422 } else { 6423 const Value *Global = TLI.getSDagStackGuard(M); 6424 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6425 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6426 MachinePointerInfo(Global, 0), Align, 6427 MachineMemOperand::MOVolatile); 6428 } 6429 if (TLI.useStackGuardXorFP()) 6430 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6431 DAG.setRoot(Chain); 6432 setValue(&I, Res); 6433 return; 6434 } 6435 case Intrinsic::stackprotector: { 6436 // Emit code into the DAG to store the stack guard onto the stack. 6437 MachineFunction &MF = DAG.getMachineFunction(); 6438 MachineFrameInfo &MFI = MF.getFrameInfo(); 6439 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6440 SDValue Src, Chain = getRoot(); 6441 6442 if (TLI.useLoadStackGuardNode()) 6443 Src = getLoadStackGuard(DAG, sdl, Chain); 6444 else 6445 Src = getValue(I.getArgOperand(0)); // The guard's value. 6446 6447 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6448 6449 int FI = FuncInfo.StaticAllocaMap[Slot]; 6450 MFI.setStackProtectorIndex(FI); 6451 6452 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6453 6454 // Store the stack protector onto the stack. 6455 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6456 DAG.getMachineFunction(), FI), 6457 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6458 setValue(&I, Res); 6459 DAG.setRoot(Res); 6460 return; 6461 } 6462 case Intrinsic::objectsize: 6463 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6464 6465 case Intrinsic::is_constant: 6466 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6467 6468 case Intrinsic::annotation: 6469 case Intrinsic::ptr_annotation: 6470 case Intrinsic::launder_invariant_group: 6471 case Intrinsic::strip_invariant_group: 6472 // Drop the intrinsic, but forward the value 6473 setValue(&I, getValue(I.getOperand(0))); 6474 return; 6475 case Intrinsic::assume: 6476 case Intrinsic::var_annotation: 6477 case Intrinsic::sideeffect: 6478 // Discard annotate attributes, assumptions, and artificial side-effects. 6479 return; 6480 6481 case Intrinsic::codeview_annotation: { 6482 // Emit a label associated with this metadata. 6483 MachineFunction &MF = DAG.getMachineFunction(); 6484 MCSymbol *Label = 6485 MF.getMMI().getContext().createTempSymbol("annotation", true); 6486 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6487 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6488 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6489 DAG.setRoot(Res); 6490 return; 6491 } 6492 6493 case Intrinsic::init_trampoline: { 6494 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6495 6496 SDValue Ops[6]; 6497 Ops[0] = getRoot(); 6498 Ops[1] = getValue(I.getArgOperand(0)); 6499 Ops[2] = getValue(I.getArgOperand(1)); 6500 Ops[3] = getValue(I.getArgOperand(2)); 6501 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6502 Ops[5] = DAG.getSrcValue(F); 6503 6504 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6505 6506 DAG.setRoot(Res); 6507 return; 6508 } 6509 case Intrinsic::adjust_trampoline: 6510 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6511 TLI.getPointerTy(DAG.getDataLayout()), 6512 getValue(I.getArgOperand(0)))); 6513 return; 6514 case Intrinsic::gcroot: { 6515 assert(DAG.getMachineFunction().getFunction().hasGC() && 6516 "only valid in functions with gc specified, enforced by Verifier"); 6517 assert(GFI && "implied by previous"); 6518 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6519 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6520 6521 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6522 GFI->addStackRoot(FI->getIndex(), TypeMap); 6523 return; 6524 } 6525 case Intrinsic::gcread: 6526 case Intrinsic::gcwrite: 6527 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6528 case Intrinsic::flt_rounds: 6529 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6530 return; 6531 6532 case Intrinsic::expect: 6533 // Just replace __builtin_expect(exp, c) with EXP. 6534 setValue(&I, getValue(I.getArgOperand(0))); 6535 return; 6536 6537 case Intrinsic::debugtrap: 6538 case Intrinsic::trap: { 6539 StringRef TrapFuncName = 6540 I.getAttributes() 6541 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6542 .getValueAsString(); 6543 if (TrapFuncName.empty()) { 6544 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6545 ISD::TRAP : ISD::DEBUGTRAP; 6546 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6547 return; 6548 } 6549 TargetLowering::ArgListTy Args; 6550 6551 TargetLowering::CallLoweringInfo CLI(DAG); 6552 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6553 CallingConv::C, I.getType(), 6554 DAG.getExternalSymbol(TrapFuncName.data(), 6555 TLI.getPointerTy(DAG.getDataLayout())), 6556 std::move(Args)); 6557 6558 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6559 DAG.setRoot(Result.second); 6560 return; 6561 } 6562 6563 case Intrinsic::uadd_with_overflow: 6564 case Intrinsic::sadd_with_overflow: 6565 case Intrinsic::usub_with_overflow: 6566 case Intrinsic::ssub_with_overflow: 6567 case Intrinsic::umul_with_overflow: 6568 case Intrinsic::smul_with_overflow: { 6569 ISD::NodeType Op; 6570 switch (Intrinsic) { 6571 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6572 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6573 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6574 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6575 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6576 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6577 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6578 } 6579 SDValue Op1 = getValue(I.getArgOperand(0)); 6580 SDValue Op2 = getValue(I.getArgOperand(1)); 6581 6582 EVT ResultVT = Op1.getValueType(); 6583 EVT OverflowVT = MVT::i1; 6584 if (ResultVT.isVector()) 6585 OverflowVT = EVT::getVectorVT( 6586 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6587 6588 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6589 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6590 return; 6591 } 6592 case Intrinsic::prefetch: { 6593 SDValue Ops[5]; 6594 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6595 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6596 Ops[0] = DAG.getRoot(); 6597 Ops[1] = getValue(I.getArgOperand(0)); 6598 Ops[2] = getValue(I.getArgOperand(1)); 6599 Ops[3] = getValue(I.getArgOperand(2)); 6600 Ops[4] = getValue(I.getArgOperand(3)); 6601 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6602 DAG.getVTList(MVT::Other), Ops, 6603 EVT::getIntegerVT(*Context, 8), 6604 MachinePointerInfo(I.getArgOperand(0)), 6605 0, /* align */ 6606 Flags); 6607 6608 // Chain the prefetch in parallell with any pending loads, to stay out of 6609 // the way of later optimizations. 6610 PendingLoads.push_back(Result); 6611 Result = getRoot(); 6612 DAG.setRoot(Result); 6613 return; 6614 } 6615 case Intrinsic::lifetime_start: 6616 case Intrinsic::lifetime_end: { 6617 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6618 // Stack coloring is not enabled in O0, discard region information. 6619 if (TM.getOptLevel() == CodeGenOpt::None) 6620 return; 6621 6622 const int64_t ObjectSize = 6623 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6624 Value *const ObjectPtr = I.getArgOperand(1); 6625 SmallVector<const Value *, 4> Allocas; 6626 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6627 6628 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6629 E = Allocas.end(); Object != E; ++Object) { 6630 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6631 6632 // Could not find an Alloca. 6633 if (!LifetimeObject) 6634 continue; 6635 6636 // First check that the Alloca is static, otherwise it won't have a 6637 // valid frame index. 6638 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6639 if (SI == FuncInfo.StaticAllocaMap.end()) 6640 return; 6641 6642 const int FrameIndex = SI->second; 6643 int64_t Offset; 6644 if (GetPointerBaseWithConstantOffset( 6645 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6646 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6647 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6648 Offset); 6649 DAG.setRoot(Res); 6650 } 6651 return; 6652 } 6653 case Intrinsic::invariant_start: 6654 // Discard region information. 6655 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6656 return; 6657 case Intrinsic::invariant_end: 6658 // Discard region information. 6659 return; 6660 case Intrinsic::clear_cache: 6661 /// FunctionName may be null. 6662 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6663 lowerCallToExternalSymbol(I, FunctionName); 6664 return; 6665 case Intrinsic::donothing: 6666 // ignore 6667 return; 6668 case Intrinsic::experimental_stackmap: 6669 visitStackmap(I); 6670 return; 6671 case Intrinsic::experimental_patchpoint_void: 6672 case Intrinsic::experimental_patchpoint_i64: 6673 visitPatchpoint(&I); 6674 return; 6675 case Intrinsic::experimental_gc_statepoint: 6676 LowerStatepoint(ImmutableStatepoint(&I)); 6677 return; 6678 case Intrinsic::experimental_gc_result: 6679 visitGCResult(cast<GCResultInst>(I)); 6680 return; 6681 case Intrinsic::experimental_gc_relocate: 6682 visitGCRelocate(cast<GCRelocateInst>(I)); 6683 return; 6684 case Intrinsic::instrprof_increment: 6685 llvm_unreachable("instrprof failed to lower an increment"); 6686 case Intrinsic::instrprof_value_profile: 6687 llvm_unreachable("instrprof failed to lower a value profiling call"); 6688 case Intrinsic::localescape: { 6689 MachineFunction &MF = DAG.getMachineFunction(); 6690 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6691 6692 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6693 // is the same on all targets. 6694 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6695 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6696 if (isa<ConstantPointerNull>(Arg)) 6697 continue; // Skip null pointers. They represent a hole in index space. 6698 AllocaInst *Slot = cast<AllocaInst>(Arg); 6699 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6700 "can only escape static allocas"); 6701 int FI = FuncInfo.StaticAllocaMap[Slot]; 6702 MCSymbol *FrameAllocSym = 6703 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6704 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6705 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6706 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6707 .addSym(FrameAllocSym) 6708 .addFrameIndex(FI); 6709 } 6710 6711 return; 6712 } 6713 6714 case Intrinsic::localrecover: { 6715 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6716 MachineFunction &MF = DAG.getMachineFunction(); 6717 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6718 6719 // Get the symbol that defines the frame offset. 6720 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6721 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6722 unsigned IdxVal = 6723 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6724 MCSymbol *FrameAllocSym = 6725 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6726 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6727 6728 // Create a MCSymbol for the label to avoid any target lowering 6729 // that would make this PC relative. 6730 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6731 SDValue OffsetVal = 6732 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6733 6734 // Add the offset to the FP. 6735 Value *FP = I.getArgOperand(1); 6736 SDValue FPVal = getValue(FP); 6737 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl); 6738 setValue(&I, Add); 6739 6740 return; 6741 } 6742 6743 case Intrinsic::eh_exceptionpointer: 6744 case Intrinsic::eh_exceptioncode: { 6745 // Get the exception pointer vreg, copy from it, and resize it to fit. 6746 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6747 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6748 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6749 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6750 SDValue N = 6751 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6752 if (Intrinsic == Intrinsic::eh_exceptioncode) 6753 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6754 setValue(&I, N); 6755 return; 6756 } 6757 case Intrinsic::xray_customevent: { 6758 // Here we want to make sure that the intrinsic behaves as if it has a 6759 // specific calling convention, and only for x86_64. 6760 // FIXME: Support other platforms later. 6761 const auto &Triple = DAG.getTarget().getTargetTriple(); 6762 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6763 return; 6764 6765 SDLoc DL = getCurSDLoc(); 6766 SmallVector<SDValue, 8> Ops; 6767 6768 // We want to say that we always want the arguments in registers. 6769 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6770 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6771 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6772 SDValue Chain = getRoot(); 6773 Ops.push_back(LogEntryVal); 6774 Ops.push_back(StrSizeVal); 6775 Ops.push_back(Chain); 6776 6777 // We need to enforce the calling convention for the callsite, so that 6778 // argument ordering is enforced correctly, and that register allocation can 6779 // see that some registers may be assumed clobbered and have to preserve 6780 // them across calls to the intrinsic. 6781 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6782 DL, NodeTys, Ops); 6783 SDValue patchableNode = SDValue(MN, 0); 6784 DAG.setRoot(patchableNode); 6785 setValue(&I, patchableNode); 6786 return; 6787 } 6788 case Intrinsic::xray_typedevent: { 6789 // Here we want to make sure that the intrinsic behaves as if it has a 6790 // specific calling convention, and only for x86_64. 6791 // FIXME: Support other platforms later. 6792 const auto &Triple = DAG.getTarget().getTargetTriple(); 6793 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6794 return; 6795 6796 SDLoc DL = getCurSDLoc(); 6797 SmallVector<SDValue, 8> Ops; 6798 6799 // We want to say that we always want the arguments in registers. 6800 // It's unclear to me how manipulating the selection DAG here forces callers 6801 // to provide arguments in registers instead of on the stack. 6802 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6803 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6804 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6805 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6806 SDValue Chain = getRoot(); 6807 Ops.push_back(LogTypeId); 6808 Ops.push_back(LogEntryVal); 6809 Ops.push_back(StrSizeVal); 6810 Ops.push_back(Chain); 6811 6812 // We need to enforce the calling convention for the callsite, so that 6813 // argument ordering is enforced correctly, and that register allocation can 6814 // see that some registers may be assumed clobbered and have to preserve 6815 // them across calls to the intrinsic. 6816 MachineSDNode *MN = DAG.getMachineNode( 6817 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6818 SDValue patchableNode = SDValue(MN, 0); 6819 DAG.setRoot(patchableNode); 6820 setValue(&I, patchableNode); 6821 return; 6822 } 6823 case Intrinsic::experimental_deoptimize: 6824 LowerDeoptimizeCall(&I); 6825 return; 6826 6827 case Intrinsic::experimental_vector_reduce_v2_fadd: 6828 case Intrinsic::experimental_vector_reduce_v2_fmul: 6829 case Intrinsic::experimental_vector_reduce_add: 6830 case Intrinsic::experimental_vector_reduce_mul: 6831 case Intrinsic::experimental_vector_reduce_and: 6832 case Intrinsic::experimental_vector_reduce_or: 6833 case Intrinsic::experimental_vector_reduce_xor: 6834 case Intrinsic::experimental_vector_reduce_smax: 6835 case Intrinsic::experimental_vector_reduce_smin: 6836 case Intrinsic::experimental_vector_reduce_umax: 6837 case Intrinsic::experimental_vector_reduce_umin: 6838 case Intrinsic::experimental_vector_reduce_fmax: 6839 case Intrinsic::experimental_vector_reduce_fmin: 6840 visitVectorReduce(I, Intrinsic); 6841 return; 6842 6843 case Intrinsic::icall_branch_funnel: { 6844 SmallVector<SDValue, 16> Ops; 6845 Ops.push_back(getValue(I.getArgOperand(0))); 6846 6847 int64_t Offset; 6848 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6849 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6850 if (!Base) 6851 report_fatal_error( 6852 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6853 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6854 6855 struct BranchFunnelTarget { 6856 int64_t Offset; 6857 SDValue Target; 6858 }; 6859 SmallVector<BranchFunnelTarget, 8> Targets; 6860 6861 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6862 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6863 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6864 if (ElemBase != Base) 6865 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6866 "to the same GlobalValue"); 6867 6868 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6869 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6870 if (!GA) 6871 report_fatal_error( 6872 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6873 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6874 GA->getGlobal(), getCurSDLoc(), 6875 Val.getValueType(), GA->getOffset())}); 6876 } 6877 llvm::sort(Targets, 6878 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6879 return T1.Offset < T2.Offset; 6880 }); 6881 6882 for (auto &T : Targets) { 6883 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6884 Ops.push_back(T.Target); 6885 } 6886 6887 Ops.push_back(DAG.getRoot()); // Chain 6888 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6889 getCurSDLoc(), MVT::Other, Ops), 6890 0); 6891 DAG.setRoot(N); 6892 setValue(&I, N); 6893 HasTailCall = true; 6894 return; 6895 } 6896 6897 case Intrinsic::wasm_landingpad_index: 6898 // Information this intrinsic contained has been transferred to 6899 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6900 // delete it now. 6901 return; 6902 6903 case Intrinsic::aarch64_settag: 6904 case Intrinsic::aarch64_settag_zero: { 6905 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6906 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6907 SDValue Val = TSI.EmitTargetCodeForSetTag( 6908 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6909 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6910 ZeroMemory); 6911 DAG.setRoot(Val); 6912 setValue(&I, Val); 6913 return; 6914 } 6915 case Intrinsic::ptrmask: { 6916 SDValue Ptr = getValue(I.getOperand(0)); 6917 SDValue Const = getValue(I.getOperand(1)); 6918 6919 EVT DestVT = 6920 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6921 6922 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6923 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6924 return; 6925 } 6926 } 6927 } 6928 6929 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6930 const ConstrainedFPIntrinsic &FPI) { 6931 SDLoc sdl = getCurSDLoc(); 6932 6933 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6934 SmallVector<EVT, 4> ValueVTs; 6935 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6936 ValueVTs.push_back(MVT::Other); // Out chain 6937 6938 // We do not need to serialize constrained FP intrinsics against 6939 // each other or against (nonvolatile) loads, so they can be 6940 // chained like loads. 6941 SDValue Chain = DAG.getRoot(); 6942 SmallVector<SDValue, 4> Opers; 6943 Opers.push_back(Chain); 6944 if (FPI.isUnaryOp()) { 6945 Opers.push_back(getValue(FPI.getArgOperand(0))); 6946 } else if (FPI.isTernaryOp()) { 6947 Opers.push_back(getValue(FPI.getArgOperand(0))); 6948 Opers.push_back(getValue(FPI.getArgOperand(1))); 6949 Opers.push_back(getValue(FPI.getArgOperand(2))); 6950 } else { 6951 Opers.push_back(getValue(FPI.getArgOperand(0))); 6952 Opers.push_back(getValue(FPI.getArgOperand(1))); 6953 } 6954 6955 unsigned Opcode; 6956 switch (FPI.getIntrinsicID()) { 6957 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6958 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 6959 case Intrinsic::INTRINSIC: \ 6960 Opcode = ISD::STRICT_##DAGN; \ 6961 break; 6962 #include "llvm/IR/ConstrainedOps.def" 6963 } 6964 6965 // A few strict DAG nodes carry additional operands that are not 6966 // set up by the default code above. 6967 switch (Opcode) { 6968 default: break; 6969 case ISD::STRICT_FP_ROUND: 6970 Opers.push_back( 6971 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()))); 6972 break; 6973 case ISD::STRICT_FSETCC: 6974 case ISD::STRICT_FSETCCS: { 6975 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI); 6976 Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate()))); 6977 break; 6978 } 6979 } 6980 6981 SDVTList VTs = DAG.getVTList(ValueVTs); 6982 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers); 6983 6984 assert(Result.getNode()->getNumValues() == 2); 6985 // See above -- chain is handled like for loads here. 6986 SDValue OutChain = Result.getValue(1); 6987 PendingLoads.push_back(OutChain); 6988 SDValue FPResult = Result.getValue(0); 6989 setValue(&FPI, FPResult); 6990 } 6991 6992 std::pair<SDValue, SDValue> 6993 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6994 const BasicBlock *EHPadBB) { 6995 MachineFunction &MF = DAG.getMachineFunction(); 6996 MachineModuleInfo &MMI = MF.getMMI(); 6997 MCSymbol *BeginLabel = nullptr; 6998 6999 if (EHPadBB) { 7000 // Insert a label before the invoke call to mark the try range. This can be 7001 // used to detect deletion of the invoke via the MachineModuleInfo. 7002 BeginLabel = MMI.getContext().createTempSymbol(); 7003 7004 // For SjLj, keep track of which landing pads go with which invokes 7005 // so as to maintain the ordering of pads in the LSDA. 7006 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7007 if (CallSiteIndex) { 7008 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7009 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7010 7011 // Now that the call site is handled, stop tracking it. 7012 MMI.setCurrentCallSite(0); 7013 } 7014 7015 // Both PendingLoads and PendingExports must be flushed here; 7016 // this call might not return. 7017 (void)getRoot(); 7018 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7019 7020 CLI.setChain(getRoot()); 7021 } 7022 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7023 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7024 7025 assert((CLI.IsTailCall || Result.second.getNode()) && 7026 "Non-null chain expected with non-tail call!"); 7027 assert((Result.second.getNode() || !Result.first.getNode()) && 7028 "Null value expected with tail call!"); 7029 7030 if (!Result.second.getNode()) { 7031 // As a special case, a null chain means that a tail call has been emitted 7032 // and the DAG root is already updated. 7033 HasTailCall = true; 7034 7035 // Since there's no actual continuation from this block, nothing can be 7036 // relying on us setting vregs for them. 7037 PendingExports.clear(); 7038 } else { 7039 DAG.setRoot(Result.second); 7040 } 7041 7042 if (EHPadBB) { 7043 // Insert a label at the end of the invoke call to mark the try range. This 7044 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7045 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7046 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7047 7048 // Inform MachineModuleInfo of range. 7049 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7050 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7051 // actually use outlined funclets and their LSDA info style. 7052 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7053 assert(CLI.CS); 7054 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7055 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7056 BeginLabel, EndLabel); 7057 } else if (!isScopedEHPersonality(Pers)) { 7058 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7059 } 7060 } 7061 7062 return Result; 7063 } 7064 7065 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7066 bool isTailCall, 7067 const BasicBlock *EHPadBB) { 7068 auto &DL = DAG.getDataLayout(); 7069 FunctionType *FTy = CS.getFunctionType(); 7070 Type *RetTy = CS.getType(); 7071 7072 TargetLowering::ArgListTy Args; 7073 Args.reserve(CS.arg_size()); 7074 7075 const Value *SwiftErrorVal = nullptr; 7076 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7077 7078 if (isTailCall) { 7079 // Avoid emitting tail calls in functions with the disable-tail-calls 7080 // attribute. 7081 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7082 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() == 7083 "true") 7084 isTailCall = false; 7085 7086 // We can't tail call inside a function with a swifterror argument. Lowering 7087 // does not support this yet. It would have to move into the swifterror 7088 // register before the call. 7089 if (TLI.supportSwiftError() && 7090 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7091 isTailCall = false; 7092 } 7093 7094 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7095 i != e; ++i) { 7096 TargetLowering::ArgListEntry Entry; 7097 const Value *V = *i; 7098 7099 // Skip empty types 7100 if (V->getType()->isEmptyTy()) 7101 continue; 7102 7103 SDValue ArgNode = getValue(V); 7104 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7105 7106 Entry.setAttributes(&CS, i - CS.arg_begin()); 7107 7108 // Use swifterror virtual register as input to the call. 7109 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7110 SwiftErrorVal = V; 7111 // We find the virtual register for the actual swifterror argument. 7112 // Instead of using the Value, we use the virtual register instead. 7113 Entry.Node = DAG.getRegister( 7114 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7115 EVT(TLI.getPointerTy(DL))); 7116 } 7117 7118 Args.push_back(Entry); 7119 7120 // If we have an explicit sret argument that is an Instruction, (i.e., it 7121 // might point to function-local memory), we can't meaningfully tail-call. 7122 if (Entry.IsSRet && isa<Instruction>(V)) 7123 isTailCall = false; 7124 } 7125 7126 // If call site has a cfguardtarget operand bundle, create and add an 7127 // additional ArgListEntry. 7128 if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) { 7129 TargetLowering::ArgListEntry Entry; 7130 Value *V = Bundle->Inputs[0]; 7131 SDValue ArgNode = getValue(V); 7132 Entry.Node = ArgNode; 7133 Entry.Ty = V->getType(); 7134 Entry.IsCFGuardTarget = true; 7135 Args.push_back(Entry); 7136 } 7137 7138 // Check if target-independent constraints permit a tail call here. 7139 // Target-dependent constraints are checked within TLI->LowerCallTo. 7140 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7141 isTailCall = false; 7142 7143 // Disable tail calls if there is an swifterror argument. Targets have not 7144 // been updated to support tail calls. 7145 if (TLI.supportSwiftError() && SwiftErrorVal) 7146 isTailCall = false; 7147 7148 TargetLowering::CallLoweringInfo CLI(DAG); 7149 CLI.setDebugLoc(getCurSDLoc()) 7150 .setChain(getRoot()) 7151 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7152 .setTailCall(isTailCall) 7153 .setConvergent(CS.isConvergent()); 7154 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7155 7156 if (Result.first.getNode()) { 7157 const Instruction *Inst = CS.getInstruction(); 7158 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7159 setValue(Inst, Result.first); 7160 } 7161 7162 // The last element of CLI.InVals has the SDValue for swifterror return. 7163 // Here we copy it to a virtual register and update SwiftErrorMap for 7164 // book-keeping. 7165 if (SwiftErrorVal && TLI.supportSwiftError()) { 7166 // Get the last element of InVals. 7167 SDValue Src = CLI.InVals.back(); 7168 Register VReg = SwiftError.getOrCreateVRegDefAt( 7169 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7170 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7171 DAG.setRoot(CopyNode); 7172 } 7173 } 7174 7175 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7176 SelectionDAGBuilder &Builder) { 7177 // Check to see if this load can be trivially constant folded, e.g. if the 7178 // input is from a string literal. 7179 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7180 // Cast pointer to the type we really want to load. 7181 Type *LoadTy = 7182 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7183 if (LoadVT.isVector()) 7184 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7185 7186 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7187 PointerType::getUnqual(LoadTy)); 7188 7189 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7190 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7191 return Builder.getValue(LoadCst); 7192 } 7193 7194 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7195 // still constant memory, the input chain can be the entry node. 7196 SDValue Root; 7197 bool ConstantMemory = false; 7198 7199 // Do not serialize (non-volatile) loads of constant memory with anything. 7200 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7201 Root = Builder.DAG.getEntryNode(); 7202 ConstantMemory = true; 7203 } else { 7204 // Do not serialize non-volatile loads against each other. 7205 Root = Builder.DAG.getRoot(); 7206 } 7207 7208 SDValue Ptr = Builder.getValue(PtrVal); 7209 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7210 Ptr, MachinePointerInfo(PtrVal), 7211 /* Alignment = */ 1); 7212 7213 if (!ConstantMemory) 7214 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7215 return LoadVal; 7216 } 7217 7218 /// Record the value for an instruction that produces an integer result, 7219 /// converting the type where necessary. 7220 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7221 SDValue Value, 7222 bool IsSigned) { 7223 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7224 I.getType(), true); 7225 if (IsSigned) 7226 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7227 else 7228 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7229 setValue(&I, Value); 7230 } 7231 7232 /// See if we can lower a memcmp call into an optimized form. If so, return 7233 /// true and lower it. Otherwise return false, and it will be lowered like a 7234 /// normal call. 7235 /// The caller already checked that \p I calls the appropriate LibFunc with a 7236 /// correct prototype. 7237 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7238 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7239 const Value *Size = I.getArgOperand(2); 7240 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7241 if (CSize && CSize->getZExtValue() == 0) { 7242 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7243 I.getType(), true); 7244 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7245 return true; 7246 } 7247 7248 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7249 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7250 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7251 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7252 if (Res.first.getNode()) { 7253 processIntegerCallValue(I, Res.first, true); 7254 PendingLoads.push_back(Res.second); 7255 return true; 7256 } 7257 7258 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7259 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7260 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7261 return false; 7262 7263 // If the target has a fast compare for the given size, it will return a 7264 // preferred load type for that size. Require that the load VT is legal and 7265 // that the target supports unaligned loads of that type. Otherwise, return 7266 // INVALID. 7267 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7268 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7269 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7270 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7271 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7272 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7273 // TODO: Check alignment of src and dest ptrs. 7274 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7275 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7276 if (!TLI.isTypeLegal(LVT) || 7277 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7278 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7279 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7280 } 7281 7282 return LVT; 7283 }; 7284 7285 // This turns into unaligned loads. We only do this if the target natively 7286 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7287 // we'll only produce a small number of byte loads. 7288 MVT LoadVT; 7289 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7290 switch (NumBitsToCompare) { 7291 default: 7292 return false; 7293 case 16: 7294 LoadVT = MVT::i16; 7295 break; 7296 case 32: 7297 LoadVT = MVT::i32; 7298 break; 7299 case 64: 7300 case 128: 7301 case 256: 7302 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7303 break; 7304 } 7305 7306 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7307 return false; 7308 7309 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7310 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7311 7312 // Bitcast to a wide integer type if the loads are vectors. 7313 if (LoadVT.isVector()) { 7314 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7315 LoadL = DAG.getBitcast(CmpVT, LoadL); 7316 LoadR = DAG.getBitcast(CmpVT, LoadR); 7317 } 7318 7319 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7320 processIntegerCallValue(I, Cmp, false); 7321 return true; 7322 } 7323 7324 /// See if we can lower a memchr call into an optimized form. If so, return 7325 /// true and lower it. Otherwise return false, and it will be lowered like a 7326 /// normal call. 7327 /// The caller already checked that \p I calls the appropriate LibFunc with a 7328 /// correct prototype. 7329 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7330 const Value *Src = I.getArgOperand(0); 7331 const Value *Char = I.getArgOperand(1); 7332 const Value *Length = I.getArgOperand(2); 7333 7334 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7335 std::pair<SDValue, SDValue> Res = 7336 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7337 getValue(Src), getValue(Char), getValue(Length), 7338 MachinePointerInfo(Src)); 7339 if (Res.first.getNode()) { 7340 setValue(&I, Res.first); 7341 PendingLoads.push_back(Res.second); 7342 return true; 7343 } 7344 7345 return false; 7346 } 7347 7348 /// See if we can lower a mempcpy call into an optimized form. If so, return 7349 /// true and lower it. Otherwise return false, and it will be lowered like a 7350 /// normal call. 7351 /// The caller already checked that \p I calls the appropriate LibFunc with a 7352 /// correct prototype. 7353 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7354 SDValue Dst = getValue(I.getArgOperand(0)); 7355 SDValue Src = getValue(I.getArgOperand(1)); 7356 SDValue Size = getValue(I.getArgOperand(2)); 7357 7358 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7359 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7360 unsigned Align = std::min(DstAlign, SrcAlign); 7361 if (Align == 0) // Alignment of one or both could not be inferred. 7362 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7363 7364 bool isVol = false; 7365 SDLoc sdl = getCurSDLoc(); 7366 7367 // In the mempcpy context we need to pass in a false value for isTailCall 7368 // because the return pointer needs to be adjusted by the size of 7369 // the copied memory. 7370 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7371 false, /*isTailCall=*/false, 7372 MachinePointerInfo(I.getArgOperand(0)), 7373 MachinePointerInfo(I.getArgOperand(1))); 7374 assert(MC.getNode() != nullptr && 7375 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7376 DAG.setRoot(MC); 7377 7378 // Check if Size needs to be truncated or extended. 7379 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7380 7381 // Adjust return pointer to point just past the last dst byte. 7382 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7383 Dst, Size); 7384 setValue(&I, DstPlusSize); 7385 return true; 7386 } 7387 7388 /// See if we can lower a strcpy call into an optimized form. If so, return 7389 /// true and lower it, otherwise return false and it will be lowered like a 7390 /// normal call. 7391 /// The caller already checked that \p I calls the appropriate LibFunc with a 7392 /// correct prototype. 7393 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7394 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7395 7396 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7397 std::pair<SDValue, SDValue> Res = 7398 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7399 getValue(Arg0), getValue(Arg1), 7400 MachinePointerInfo(Arg0), 7401 MachinePointerInfo(Arg1), isStpcpy); 7402 if (Res.first.getNode()) { 7403 setValue(&I, Res.first); 7404 DAG.setRoot(Res.second); 7405 return true; 7406 } 7407 7408 return false; 7409 } 7410 7411 /// See if we can lower a strcmp call into an optimized form. If so, return 7412 /// true and lower it, otherwise return false and it will be lowered like a 7413 /// normal call. 7414 /// The caller already checked that \p I calls the appropriate LibFunc with a 7415 /// correct prototype. 7416 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7417 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7418 7419 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7420 std::pair<SDValue, SDValue> Res = 7421 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7422 getValue(Arg0), getValue(Arg1), 7423 MachinePointerInfo(Arg0), 7424 MachinePointerInfo(Arg1)); 7425 if (Res.first.getNode()) { 7426 processIntegerCallValue(I, Res.first, true); 7427 PendingLoads.push_back(Res.second); 7428 return true; 7429 } 7430 7431 return false; 7432 } 7433 7434 /// See if we can lower a strlen call into an optimized form. If so, return 7435 /// true and lower it, otherwise return false and it will be lowered like a 7436 /// normal call. 7437 /// The caller already checked that \p I calls the appropriate LibFunc with a 7438 /// correct prototype. 7439 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7440 const Value *Arg0 = I.getArgOperand(0); 7441 7442 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7443 std::pair<SDValue, SDValue> Res = 7444 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7445 getValue(Arg0), MachinePointerInfo(Arg0)); 7446 if (Res.first.getNode()) { 7447 processIntegerCallValue(I, Res.first, false); 7448 PendingLoads.push_back(Res.second); 7449 return true; 7450 } 7451 7452 return false; 7453 } 7454 7455 /// See if we can lower a strnlen call into an optimized form. If so, return 7456 /// true and lower it, otherwise return false and it will be lowered like a 7457 /// normal call. 7458 /// The caller already checked that \p I calls the appropriate LibFunc with a 7459 /// correct prototype. 7460 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7461 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7462 7463 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7464 std::pair<SDValue, SDValue> Res = 7465 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7466 getValue(Arg0), getValue(Arg1), 7467 MachinePointerInfo(Arg0)); 7468 if (Res.first.getNode()) { 7469 processIntegerCallValue(I, Res.first, false); 7470 PendingLoads.push_back(Res.second); 7471 return true; 7472 } 7473 7474 return false; 7475 } 7476 7477 /// See if we can lower a unary floating-point operation into an SDNode with 7478 /// the specified Opcode. If so, return true and lower it, otherwise return 7479 /// false and it will be lowered like a normal call. 7480 /// The caller already checked that \p I calls the appropriate LibFunc with a 7481 /// correct prototype. 7482 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7483 unsigned Opcode) { 7484 // We already checked this call's prototype; verify it doesn't modify errno. 7485 if (!I.onlyReadsMemory()) 7486 return false; 7487 7488 SDValue Tmp = getValue(I.getArgOperand(0)); 7489 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7490 return true; 7491 } 7492 7493 /// See if we can lower a binary floating-point operation into an SDNode with 7494 /// the specified Opcode. If so, return true and lower it. Otherwise return 7495 /// false, and it will be lowered like a normal call. 7496 /// The caller already checked that \p I calls the appropriate LibFunc with a 7497 /// correct prototype. 7498 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7499 unsigned Opcode) { 7500 // We already checked this call's prototype; verify it doesn't modify errno. 7501 if (!I.onlyReadsMemory()) 7502 return false; 7503 7504 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7505 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7506 EVT VT = Tmp0.getValueType(); 7507 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7508 return true; 7509 } 7510 7511 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7512 // Handle inline assembly differently. 7513 if (isa<InlineAsm>(I.getCalledValue())) { 7514 visitInlineAsm(&I); 7515 return; 7516 } 7517 7518 if (Function *F = I.getCalledFunction()) { 7519 if (F->isDeclaration()) { 7520 // Is this an LLVM intrinsic or a target-specific intrinsic? 7521 unsigned IID = F->getIntrinsicID(); 7522 if (!IID) 7523 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7524 IID = II->getIntrinsicID(F); 7525 7526 if (IID) { 7527 visitIntrinsicCall(I, IID); 7528 return; 7529 } 7530 } 7531 7532 // Check for well-known libc/libm calls. If the function is internal, it 7533 // can't be a library call. Don't do the check if marked as nobuiltin for 7534 // some reason or the call site requires strict floating point semantics. 7535 LibFunc Func; 7536 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7537 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7538 LibInfo->hasOptimizedCodeGen(Func)) { 7539 switch (Func) { 7540 default: break; 7541 case LibFunc_copysign: 7542 case LibFunc_copysignf: 7543 case LibFunc_copysignl: 7544 // We already checked this call's prototype; verify it doesn't modify 7545 // errno. 7546 if (I.onlyReadsMemory()) { 7547 SDValue LHS = getValue(I.getArgOperand(0)); 7548 SDValue RHS = getValue(I.getArgOperand(1)); 7549 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7550 LHS.getValueType(), LHS, RHS)); 7551 return; 7552 } 7553 break; 7554 case LibFunc_fabs: 7555 case LibFunc_fabsf: 7556 case LibFunc_fabsl: 7557 if (visitUnaryFloatCall(I, ISD::FABS)) 7558 return; 7559 break; 7560 case LibFunc_fmin: 7561 case LibFunc_fminf: 7562 case LibFunc_fminl: 7563 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7564 return; 7565 break; 7566 case LibFunc_fmax: 7567 case LibFunc_fmaxf: 7568 case LibFunc_fmaxl: 7569 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7570 return; 7571 break; 7572 case LibFunc_sin: 7573 case LibFunc_sinf: 7574 case LibFunc_sinl: 7575 if (visitUnaryFloatCall(I, ISD::FSIN)) 7576 return; 7577 break; 7578 case LibFunc_cos: 7579 case LibFunc_cosf: 7580 case LibFunc_cosl: 7581 if (visitUnaryFloatCall(I, ISD::FCOS)) 7582 return; 7583 break; 7584 case LibFunc_sqrt: 7585 case LibFunc_sqrtf: 7586 case LibFunc_sqrtl: 7587 case LibFunc_sqrt_finite: 7588 case LibFunc_sqrtf_finite: 7589 case LibFunc_sqrtl_finite: 7590 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7591 return; 7592 break; 7593 case LibFunc_floor: 7594 case LibFunc_floorf: 7595 case LibFunc_floorl: 7596 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7597 return; 7598 break; 7599 case LibFunc_nearbyint: 7600 case LibFunc_nearbyintf: 7601 case LibFunc_nearbyintl: 7602 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7603 return; 7604 break; 7605 case LibFunc_ceil: 7606 case LibFunc_ceilf: 7607 case LibFunc_ceill: 7608 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7609 return; 7610 break; 7611 case LibFunc_rint: 7612 case LibFunc_rintf: 7613 case LibFunc_rintl: 7614 if (visitUnaryFloatCall(I, ISD::FRINT)) 7615 return; 7616 break; 7617 case LibFunc_round: 7618 case LibFunc_roundf: 7619 case LibFunc_roundl: 7620 if (visitUnaryFloatCall(I, ISD::FROUND)) 7621 return; 7622 break; 7623 case LibFunc_trunc: 7624 case LibFunc_truncf: 7625 case LibFunc_truncl: 7626 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7627 return; 7628 break; 7629 case LibFunc_log2: 7630 case LibFunc_log2f: 7631 case LibFunc_log2l: 7632 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7633 return; 7634 break; 7635 case LibFunc_exp2: 7636 case LibFunc_exp2f: 7637 case LibFunc_exp2l: 7638 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7639 return; 7640 break; 7641 case LibFunc_memcmp: 7642 if (visitMemCmpCall(I)) 7643 return; 7644 break; 7645 case LibFunc_mempcpy: 7646 if (visitMemPCpyCall(I)) 7647 return; 7648 break; 7649 case LibFunc_memchr: 7650 if (visitMemChrCall(I)) 7651 return; 7652 break; 7653 case LibFunc_strcpy: 7654 if (visitStrCpyCall(I, false)) 7655 return; 7656 break; 7657 case LibFunc_stpcpy: 7658 if (visitStrCpyCall(I, true)) 7659 return; 7660 break; 7661 case LibFunc_strcmp: 7662 if (visitStrCmpCall(I)) 7663 return; 7664 break; 7665 case LibFunc_strlen: 7666 if (visitStrLenCall(I)) 7667 return; 7668 break; 7669 case LibFunc_strnlen: 7670 if (visitStrNLenCall(I)) 7671 return; 7672 break; 7673 } 7674 } 7675 } 7676 7677 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7678 // have to do anything here to lower funclet bundles. 7679 // CFGuardTarget bundles are lowered in LowerCallTo. 7680 assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt, 7681 LLVMContext::OB_funclet, 7682 LLVMContext::OB_cfguardtarget}) && 7683 "Cannot lower calls with arbitrary operand bundles!"); 7684 7685 SDValue Callee = getValue(I.getCalledValue()); 7686 7687 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7688 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7689 else 7690 // Check if we can potentially perform a tail call. More detailed checking 7691 // is be done within LowerCallTo, after more information about the call is 7692 // known. 7693 LowerCallTo(&I, Callee, I.isTailCall()); 7694 } 7695 7696 namespace { 7697 7698 /// AsmOperandInfo - This contains information for each constraint that we are 7699 /// lowering. 7700 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7701 public: 7702 /// CallOperand - If this is the result output operand or a clobber 7703 /// this is null, otherwise it is the incoming operand to the CallInst. 7704 /// This gets modified as the asm is processed. 7705 SDValue CallOperand; 7706 7707 /// AssignedRegs - If this is a register or register class operand, this 7708 /// contains the set of register corresponding to the operand. 7709 RegsForValue AssignedRegs; 7710 7711 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7712 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7713 } 7714 7715 /// Whether or not this operand accesses memory 7716 bool hasMemory(const TargetLowering &TLI) const { 7717 // Indirect operand accesses access memory. 7718 if (isIndirect) 7719 return true; 7720 7721 for (const auto &Code : Codes) 7722 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7723 return true; 7724 7725 return false; 7726 } 7727 7728 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7729 /// corresponds to. If there is no Value* for this operand, it returns 7730 /// MVT::Other. 7731 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7732 const DataLayout &DL) const { 7733 if (!CallOperandVal) return MVT::Other; 7734 7735 if (isa<BasicBlock>(CallOperandVal)) 7736 return TLI.getPointerTy(DL); 7737 7738 llvm::Type *OpTy = CallOperandVal->getType(); 7739 7740 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7741 // If this is an indirect operand, the operand is a pointer to the 7742 // accessed type. 7743 if (isIndirect) { 7744 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7745 if (!PtrTy) 7746 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7747 OpTy = PtrTy->getElementType(); 7748 } 7749 7750 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7751 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7752 if (STy->getNumElements() == 1) 7753 OpTy = STy->getElementType(0); 7754 7755 // If OpTy is not a single value, it may be a struct/union that we 7756 // can tile with integers. 7757 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7758 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7759 switch (BitSize) { 7760 default: break; 7761 case 1: 7762 case 8: 7763 case 16: 7764 case 32: 7765 case 64: 7766 case 128: 7767 OpTy = IntegerType::get(Context, BitSize); 7768 break; 7769 } 7770 } 7771 7772 return TLI.getValueType(DL, OpTy, true); 7773 } 7774 }; 7775 7776 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7777 7778 } // end anonymous namespace 7779 7780 /// Make sure that the output operand \p OpInfo and its corresponding input 7781 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7782 /// out). 7783 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7784 SDISelAsmOperandInfo &MatchingOpInfo, 7785 SelectionDAG &DAG) { 7786 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7787 return; 7788 7789 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7790 const auto &TLI = DAG.getTargetLoweringInfo(); 7791 7792 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7793 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7794 OpInfo.ConstraintVT); 7795 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7796 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7797 MatchingOpInfo.ConstraintVT); 7798 if ((OpInfo.ConstraintVT.isInteger() != 7799 MatchingOpInfo.ConstraintVT.isInteger()) || 7800 (MatchRC.second != InputRC.second)) { 7801 // FIXME: error out in a more elegant fashion 7802 report_fatal_error("Unsupported asm: input constraint" 7803 " with a matching output constraint of" 7804 " incompatible type!"); 7805 } 7806 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7807 } 7808 7809 /// Get a direct memory input to behave well as an indirect operand. 7810 /// This may introduce stores, hence the need for a \p Chain. 7811 /// \return The (possibly updated) chain. 7812 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7813 SDISelAsmOperandInfo &OpInfo, 7814 SelectionDAG &DAG) { 7815 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7816 7817 // If we don't have an indirect input, put it in the constpool if we can, 7818 // otherwise spill it to a stack slot. 7819 // TODO: This isn't quite right. We need to handle these according to 7820 // the addressing mode that the constraint wants. Also, this may take 7821 // an additional register for the computation and we don't want that 7822 // either. 7823 7824 // If the operand is a float, integer, or vector constant, spill to a 7825 // constant pool entry to get its address. 7826 const Value *OpVal = OpInfo.CallOperandVal; 7827 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7828 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7829 OpInfo.CallOperand = DAG.getConstantPool( 7830 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7831 return Chain; 7832 } 7833 7834 // Otherwise, create a stack slot and emit a store to it before the asm. 7835 Type *Ty = OpVal->getType(); 7836 auto &DL = DAG.getDataLayout(); 7837 uint64_t TySize = DL.getTypeAllocSize(Ty); 7838 unsigned Align = DL.getPrefTypeAlignment(Ty); 7839 MachineFunction &MF = DAG.getMachineFunction(); 7840 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7841 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7842 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7843 MachinePointerInfo::getFixedStack(MF, SSFI), 7844 TLI.getMemValueType(DL, Ty)); 7845 OpInfo.CallOperand = StackSlot; 7846 7847 return Chain; 7848 } 7849 7850 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7851 /// specified operand. We prefer to assign virtual registers, to allow the 7852 /// register allocator to handle the assignment process. However, if the asm 7853 /// uses features that we can't model on machineinstrs, we have SDISel do the 7854 /// allocation. This produces generally horrible, but correct, code. 7855 /// 7856 /// OpInfo describes the operand 7857 /// RefOpInfo describes the matching operand if any, the operand otherwise 7858 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7859 SDISelAsmOperandInfo &OpInfo, 7860 SDISelAsmOperandInfo &RefOpInfo) { 7861 LLVMContext &Context = *DAG.getContext(); 7862 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7863 7864 MachineFunction &MF = DAG.getMachineFunction(); 7865 SmallVector<unsigned, 4> Regs; 7866 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7867 7868 // No work to do for memory operations. 7869 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7870 return; 7871 7872 // If this is a constraint for a single physreg, or a constraint for a 7873 // register class, find it. 7874 unsigned AssignedReg; 7875 const TargetRegisterClass *RC; 7876 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7877 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7878 // RC is unset only on failure. Return immediately. 7879 if (!RC) 7880 return; 7881 7882 // Get the actual register value type. This is important, because the user 7883 // may have asked for (e.g.) the AX register in i32 type. We need to 7884 // remember that AX is actually i16 to get the right extension. 7885 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7886 7887 if (OpInfo.ConstraintVT != MVT::Other) { 7888 // If this is an FP operand in an integer register (or visa versa), or more 7889 // generally if the operand value disagrees with the register class we plan 7890 // to stick it in, fix the operand type. 7891 // 7892 // If this is an input value, the bitcast to the new type is done now. 7893 // Bitcast for output value is done at the end of visitInlineAsm(). 7894 if ((OpInfo.Type == InlineAsm::isOutput || 7895 OpInfo.Type == InlineAsm::isInput) && 7896 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7897 // Try to convert to the first EVT that the reg class contains. If the 7898 // types are identical size, use a bitcast to convert (e.g. two differing 7899 // vector types). Note: output bitcast is done at the end of 7900 // visitInlineAsm(). 7901 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7902 // Exclude indirect inputs while they are unsupported because the code 7903 // to perform the load is missing and thus OpInfo.CallOperand still 7904 // refers to the input address rather than the pointed-to value. 7905 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7906 OpInfo.CallOperand = 7907 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7908 OpInfo.ConstraintVT = RegVT; 7909 // If the operand is an FP value and we want it in integer registers, 7910 // use the corresponding integer type. This turns an f64 value into 7911 // i64, which can be passed with two i32 values on a 32-bit machine. 7912 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7913 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7914 if (OpInfo.Type == InlineAsm::isInput) 7915 OpInfo.CallOperand = 7916 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7917 OpInfo.ConstraintVT = VT; 7918 } 7919 } 7920 } 7921 7922 // No need to allocate a matching input constraint since the constraint it's 7923 // matching to has already been allocated. 7924 if (OpInfo.isMatchingInputConstraint()) 7925 return; 7926 7927 EVT ValueVT = OpInfo.ConstraintVT; 7928 if (OpInfo.ConstraintVT == MVT::Other) 7929 ValueVT = RegVT; 7930 7931 // Initialize NumRegs. 7932 unsigned NumRegs = 1; 7933 if (OpInfo.ConstraintVT != MVT::Other) 7934 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7935 7936 // If this is a constraint for a specific physical register, like {r17}, 7937 // assign it now. 7938 7939 // If this associated to a specific register, initialize iterator to correct 7940 // place. If virtual, make sure we have enough registers 7941 7942 // Initialize iterator if necessary 7943 TargetRegisterClass::iterator I = RC->begin(); 7944 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7945 7946 // Do not check for single registers. 7947 if (AssignedReg) { 7948 for (; *I != AssignedReg; ++I) 7949 assert(I != RC->end() && "AssignedReg should be member of RC"); 7950 } 7951 7952 for (; NumRegs; --NumRegs, ++I) { 7953 assert(I != RC->end() && "Ran out of registers to allocate!"); 7954 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7955 Regs.push_back(R); 7956 } 7957 7958 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7959 } 7960 7961 static unsigned 7962 findMatchingInlineAsmOperand(unsigned OperandNo, 7963 const std::vector<SDValue> &AsmNodeOperands) { 7964 // Scan until we find the definition we already emitted of this operand. 7965 unsigned CurOp = InlineAsm::Op_FirstOperand; 7966 for (; OperandNo; --OperandNo) { 7967 // Advance to the next operand. 7968 unsigned OpFlag = 7969 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7970 assert((InlineAsm::isRegDefKind(OpFlag) || 7971 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7972 InlineAsm::isMemKind(OpFlag)) && 7973 "Skipped past definitions?"); 7974 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7975 } 7976 return CurOp; 7977 } 7978 7979 namespace { 7980 7981 class ExtraFlags { 7982 unsigned Flags = 0; 7983 7984 public: 7985 explicit ExtraFlags(ImmutableCallSite CS) { 7986 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7987 if (IA->hasSideEffects()) 7988 Flags |= InlineAsm::Extra_HasSideEffects; 7989 if (IA->isAlignStack()) 7990 Flags |= InlineAsm::Extra_IsAlignStack; 7991 if (CS.isConvergent()) 7992 Flags |= InlineAsm::Extra_IsConvergent; 7993 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7994 } 7995 7996 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7997 // Ideally, we would only check against memory constraints. However, the 7998 // meaning of an Other constraint can be target-specific and we can't easily 7999 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8000 // for Other constraints as well. 8001 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8002 OpInfo.ConstraintType == TargetLowering::C_Other) { 8003 if (OpInfo.Type == InlineAsm::isInput) 8004 Flags |= InlineAsm::Extra_MayLoad; 8005 else if (OpInfo.Type == InlineAsm::isOutput) 8006 Flags |= InlineAsm::Extra_MayStore; 8007 else if (OpInfo.Type == InlineAsm::isClobber) 8008 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8009 } 8010 } 8011 8012 unsigned get() const { return Flags; } 8013 }; 8014 8015 } // end anonymous namespace 8016 8017 /// visitInlineAsm - Handle a call to an InlineAsm object. 8018 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 8019 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8020 8021 /// ConstraintOperands - Information about all of the constraints. 8022 SDISelAsmOperandInfoVector ConstraintOperands; 8023 8024 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8025 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8026 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 8027 8028 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8029 // AsmDialect, MayLoad, MayStore). 8030 bool HasSideEffect = IA->hasSideEffects(); 8031 ExtraFlags ExtraInfo(CS); 8032 8033 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8034 unsigned ResNo = 0; // ResNo - The result number of the next output. 8035 for (auto &T : TargetConstraints) { 8036 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8037 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8038 8039 // Compute the value type for each operand. 8040 if (OpInfo.Type == InlineAsm::isInput || 8041 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8042 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 8043 8044 // Process the call argument. BasicBlocks are labels, currently appearing 8045 // only in asm's. 8046 const Instruction *I = CS.getInstruction(); 8047 if (isa<CallBrInst>(I) && 8048 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 8049 cast<CallBrInst>(I)->getNumIndirectDests())) { 8050 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8051 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8052 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8053 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8054 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8055 } else { 8056 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8057 } 8058 8059 OpInfo.ConstraintVT = 8060 OpInfo 8061 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8062 .getSimpleVT(); 8063 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8064 // The return value of the call is this value. As such, there is no 8065 // corresponding argument. 8066 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8067 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8068 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8069 DAG.getDataLayout(), STy->getElementType(ResNo)); 8070 } else { 8071 assert(ResNo == 0 && "Asm only has one result!"); 8072 OpInfo.ConstraintVT = 8073 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8074 } 8075 ++ResNo; 8076 } else { 8077 OpInfo.ConstraintVT = MVT::Other; 8078 } 8079 8080 if (!HasSideEffect) 8081 HasSideEffect = OpInfo.hasMemory(TLI); 8082 8083 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8084 // FIXME: Could we compute this on OpInfo rather than T? 8085 8086 // Compute the constraint code and ConstraintType to use. 8087 TLI.ComputeConstraintToUse(T, SDValue()); 8088 8089 if (T.ConstraintType == TargetLowering::C_Immediate && 8090 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8091 // We've delayed emitting a diagnostic like the "n" constraint because 8092 // inlining could cause an integer showing up. 8093 return emitInlineAsmError( 8094 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8095 "integer constant expression"); 8096 8097 ExtraInfo.update(T); 8098 } 8099 8100 8101 // We won't need to flush pending loads if this asm doesn't touch 8102 // memory and is nonvolatile. 8103 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8104 8105 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8106 if (IsCallBr) { 8107 // If this is a callbr we need to flush pending exports since inlineasm_br 8108 // is a terminator. We need to do this before nodes are glued to 8109 // the inlineasm_br node. 8110 Chain = getControlRoot(); 8111 } 8112 8113 // Second pass over the constraints: compute which constraint option to use. 8114 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8115 // If this is an output operand with a matching input operand, look up the 8116 // matching input. If their types mismatch, e.g. one is an integer, the 8117 // other is floating point, or their sizes are different, flag it as an 8118 // error. 8119 if (OpInfo.hasMatchingInput()) { 8120 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8121 patchMatchingInput(OpInfo, Input, DAG); 8122 } 8123 8124 // Compute the constraint code and ConstraintType to use. 8125 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8126 8127 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8128 OpInfo.Type == InlineAsm::isClobber) 8129 continue; 8130 8131 // If this is a memory input, and if the operand is not indirect, do what we 8132 // need to provide an address for the memory input. 8133 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8134 !OpInfo.isIndirect) { 8135 assert((OpInfo.isMultipleAlternative || 8136 (OpInfo.Type == InlineAsm::isInput)) && 8137 "Can only indirectify direct input operands!"); 8138 8139 // Memory operands really want the address of the value. 8140 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8141 8142 // There is no longer a Value* corresponding to this operand. 8143 OpInfo.CallOperandVal = nullptr; 8144 8145 // It is now an indirect operand. 8146 OpInfo.isIndirect = true; 8147 } 8148 8149 } 8150 8151 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8152 std::vector<SDValue> AsmNodeOperands; 8153 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8154 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8155 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8156 8157 // If we have a !srcloc metadata node associated with it, we want to attach 8158 // this to the ultimately generated inline asm machineinstr. To do this, we 8159 // pass in the third operand as this (potentially null) inline asm MDNode. 8160 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8161 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8162 8163 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8164 // bits as operand 3. 8165 AsmNodeOperands.push_back(DAG.getTargetConstant( 8166 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8167 8168 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8169 // this, assign virtual and physical registers for inputs and otput. 8170 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8171 // Assign Registers. 8172 SDISelAsmOperandInfo &RefOpInfo = 8173 OpInfo.isMatchingInputConstraint() 8174 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8175 : OpInfo; 8176 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8177 8178 switch (OpInfo.Type) { 8179 case InlineAsm::isOutput: 8180 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8181 unsigned ConstraintID = 8182 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8183 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8184 "Failed to convert memory constraint code to constraint id."); 8185 8186 // Add information to the INLINEASM node to know about this output. 8187 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8188 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8189 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8190 MVT::i32)); 8191 AsmNodeOperands.push_back(OpInfo.CallOperand); 8192 } else { 8193 // Otherwise, this outputs to a register (directly for C_Register / 8194 // C_RegisterClass, and a target-defined fashion for 8195 // C_Immediate/C_Other). Find a register that we can use. 8196 if (OpInfo.AssignedRegs.Regs.empty()) { 8197 emitInlineAsmError( 8198 CS, "couldn't allocate output register for constraint '" + 8199 Twine(OpInfo.ConstraintCode) + "'"); 8200 return; 8201 } 8202 8203 // Add information to the INLINEASM node to know that this register is 8204 // set. 8205 OpInfo.AssignedRegs.AddInlineAsmOperands( 8206 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8207 : InlineAsm::Kind_RegDef, 8208 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8209 } 8210 break; 8211 8212 case InlineAsm::isInput: { 8213 SDValue InOperandVal = OpInfo.CallOperand; 8214 8215 if (OpInfo.isMatchingInputConstraint()) { 8216 // If this is required to match an output register we have already set, 8217 // just use its register. 8218 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8219 AsmNodeOperands); 8220 unsigned OpFlag = 8221 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8222 if (InlineAsm::isRegDefKind(OpFlag) || 8223 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8224 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8225 if (OpInfo.isIndirect) { 8226 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8227 emitInlineAsmError(CS, "inline asm not supported yet:" 8228 " don't know how to handle tied " 8229 "indirect register inputs"); 8230 return; 8231 } 8232 8233 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8234 SmallVector<unsigned, 4> Regs; 8235 8236 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8237 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8238 MachineRegisterInfo &RegInfo = 8239 DAG.getMachineFunction().getRegInfo(); 8240 for (unsigned i = 0; i != NumRegs; ++i) 8241 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8242 } else { 8243 emitInlineAsmError(CS, "inline asm error: This value type register " 8244 "class is not natively supported!"); 8245 return; 8246 } 8247 8248 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8249 8250 SDLoc dl = getCurSDLoc(); 8251 // Use the produced MatchedRegs object to 8252 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8253 CS.getInstruction()); 8254 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8255 true, OpInfo.getMatchedOperand(), dl, 8256 DAG, AsmNodeOperands); 8257 break; 8258 } 8259 8260 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8261 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8262 "Unexpected number of operands"); 8263 // Add information to the INLINEASM node to know about this input. 8264 // See InlineAsm.h isUseOperandTiedToDef. 8265 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8266 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8267 OpInfo.getMatchedOperand()); 8268 AsmNodeOperands.push_back(DAG.getTargetConstant( 8269 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8270 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8271 break; 8272 } 8273 8274 // Treat indirect 'X' constraint as memory. 8275 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8276 OpInfo.isIndirect) 8277 OpInfo.ConstraintType = TargetLowering::C_Memory; 8278 8279 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8280 OpInfo.ConstraintType == TargetLowering::C_Other) { 8281 std::vector<SDValue> Ops; 8282 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8283 Ops, DAG); 8284 if (Ops.empty()) { 8285 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8286 if (isa<ConstantSDNode>(InOperandVal)) { 8287 emitInlineAsmError(CS, "value out of range for constraint '" + 8288 Twine(OpInfo.ConstraintCode) + "'"); 8289 return; 8290 } 8291 8292 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8293 Twine(OpInfo.ConstraintCode) + "'"); 8294 return; 8295 } 8296 8297 // Add information to the INLINEASM node to know about this input. 8298 unsigned ResOpType = 8299 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8300 AsmNodeOperands.push_back(DAG.getTargetConstant( 8301 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8302 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8303 break; 8304 } 8305 8306 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8307 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8308 assert(InOperandVal.getValueType() == 8309 TLI.getPointerTy(DAG.getDataLayout()) && 8310 "Memory operands expect pointer values"); 8311 8312 unsigned ConstraintID = 8313 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8314 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8315 "Failed to convert memory constraint code to constraint id."); 8316 8317 // Add information to the INLINEASM node to know about this input. 8318 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8319 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8320 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8321 getCurSDLoc(), 8322 MVT::i32)); 8323 AsmNodeOperands.push_back(InOperandVal); 8324 break; 8325 } 8326 8327 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8328 OpInfo.ConstraintType == TargetLowering::C_Register) && 8329 "Unknown constraint type!"); 8330 8331 // TODO: Support this. 8332 if (OpInfo.isIndirect) { 8333 emitInlineAsmError( 8334 CS, "Don't know how to handle indirect register inputs yet " 8335 "for constraint '" + 8336 Twine(OpInfo.ConstraintCode) + "'"); 8337 return; 8338 } 8339 8340 // Copy the input into the appropriate registers. 8341 if (OpInfo.AssignedRegs.Regs.empty()) { 8342 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8343 Twine(OpInfo.ConstraintCode) + "'"); 8344 return; 8345 } 8346 8347 SDLoc dl = getCurSDLoc(); 8348 8349 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8350 Chain, &Flag, CS.getInstruction()); 8351 8352 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8353 dl, DAG, AsmNodeOperands); 8354 break; 8355 } 8356 case InlineAsm::isClobber: 8357 // Add the clobbered value to the operand list, so that the register 8358 // allocator is aware that the physreg got clobbered. 8359 if (!OpInfo.AssignedRegs.Regs.empty()) 8360 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8361 false, 0, getCurSDLoc(), DAG, 8362 AsmNodeOperands); 8363 break; 8364 } 8365 } 8366 8367 // Finish up input operands. Set the input chain and add the flag last. 8368 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8369 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8370 8371 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8372 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8373 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8374 Flag = Chain.getValue(1); 8375 8376 // Do additional work to generate outputs. 8377 8378 SmallVector<EVT, 1> ResultVTs; 8379 SmallVector<SDValue, 1> ResultValues; 8380 SmallVector<SDValue, 8> OutChains; 8381 8382 llvm::Type *CSResultType = CS.getType(); 8383 ArrayRef<Type *> ResultTypes; 8384 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8385 ResultTypes = StructResult->elements(); 8386 else if (!CSResultType->isVoidTy()) 8387 ResultTypes = makeArrayRef(CSResultType); 8388 8389 auto CurResultType = ResultTypes.begin(); 8390 auto handleRegAssign = [&](SDValue V) { 8391 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8392 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8393 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8394 ++CurResultType; 8395 // If the type of the inline asm call site return value is different but has 8396 // same size as the type of the asm output bitcast it. One example of this 8397 // is for vectors with different width / number of elements. This can 8398 // happen for register classes that can contain multiple different value 8399 // types. The preg or vreg allocated may not have the same VT as was 8400 // expected. 8401 // 8402 // This can also happen for a return value that disagrees with the register 8403 // class it is put in, eg. a double in a general-purpose register on a 8404 // 32-bit machine. 8405 if (ResultVT != V.getValueType() && 8406 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8407 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8408 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8409 V.getValueType().isInteger()) { 8410 // If a result value was tied to an input value, the computed result 8411 // may have a wider width than the expected result. Extract the 8412 // relevant portion. 8413 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8414 } 8415 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8416 ResultVTs.push_back(ResultVT); 8417 ResultValues.push_back(V); 8418 }; 8419 8420 // Deal with output operands. 8421 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8422 if (OpInfo.Type == InlineAsm::isOutput) { 8423 SDValue Val; 8424 // Skip trivial output operands. 8425 if (OpInfo.AssignedRegs.Regs.empty()) 8426 continue; 8427 8428 switch (OpInfo.ConstraintType) { 8429 case TargetLowering::C_Register: 8430 case TargetLowering::C_RegisterClass: 8431 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8432 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8433 break; 8434 case TargetLowering::C_Immediate: 8435 case TargetLowering::C_Other: 8436 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8437 OpInfo, DAG); 8438 break; 8439 case TargetLowering::C_Memory: 8440 break; // Already handled. 8441 case TargetLowering::C_Unknown: 8442 assert(false && "Unexpected unknown constraint"); 8443 } 8444 8445 // Indirect output manifest as stores. Record output chains. 8446 if (OpInfo.isIndirect) { 8447 const Value *Ptr = OpInfo.CallOperandVal; 8448 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8449 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8450 MachinePointerInfo(Ptr)); 8451 OutChains.push_back(Store); 8452 } else { 8453 // generate CopyFromRegs to associated registers. 8454 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8455 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8456 for (const SDValue &V : Val->op_values()) 8457 handleRegAssign(V); 8458 } else 8459 handleRegAssign(Val); 8460 } 8461 } 8462 } 8463 8464 // Set results. 8465 if (!ResultValues.empty()) { 8466 assert(CurResultType == ResultTypes.end() && 8467 "Mismatch in number of ResultTypes"); 8468 assert(ResultValues.size() == ResultTypes.size() && 8469 "Mismatch in number of output operands in asm result"); 8470 8471 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8472 DAG.getVTList(ResultVTs), ResultValues); 8473 setValue(CS.getInstruction(), V); 8474 } 8475 8476 // Collect store chains. 8477 if (!OutChains.empty()) 8478 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8479 8480 // Only Update Root if inline assembly has a memory effect. 8481 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8482 DAG.setRoot(Chain); 8483 } 8484 8485 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8486 const Twine &Message) { 8487 LLVMContext &Ctx = *DAG.getContext(); 8488 Ctx.emitError(CS.getInstruction(), Message); 8489 8490 // Make sure we leave the DAG in a valid state 8491 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8492 SmallVector<EVT, 1> ValueVTs; 8493 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8494 8495 if (ValueVTs.empty()) 8496 return; 8497 8498 SmallVector<SDValue, 1> Ops; 8499 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8500 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8501 8502 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8503 } 8504 8505 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8506 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8507 MVT::Other, getRoot(), 8508 getValue(I.getArgOperand(0)), 8509 DAG.getSrcValue(I.getArgOperand(0)))); 8510 } 8511 8512 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8513 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8514 const DataLayout &DL = DAG.getDataLayout(); 8515 SDValue V = DAG.getVAArg( 8516 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8517 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8518 DL.getABITypeAlignment(I.getType())); 8519 DAG.setRoot(V.getValue(1)); 8520 8521 if (I.getType()->isPointerTy()) 8522 V = DAG.getPtrExtOrTrunc( 8523 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8524 setValue(&I, V); 8525 } 8526 8527 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8528 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8529 MVT::Other, getRoot(), 8530 getValue(I.getArgOperand(0)), 8531 DAG.getSrcValue(I.getArgOperand(0)))); 8532 } 8533 8534 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8535 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8536 MVT::Other, getRoot(), 8537 getValue(I.getArgOperand(0)), 8538 getValue(I.getArgOperand(1)), 8539 DAG.getSrcValue(I.getArgOperand(0)), 8540 DAG.getSrcValue(I.getArgOperand(1)))); 8541 } 8542 8543 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8544 const Instruction &I, 8545 SDValue Op) { 8546 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8547 if (!Range) 8548 return Op; 8549 8550 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8551 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8552 return Op; 8553 8554 APInt Lo = CR.getUnsignedMin(); 8555 if (!Lo.isMinValue()) 8556 return Op; 8557 8558 APInt Hi = CR.getUnsignedMax(); 8559 unsigned Bits = std::max(Hi.getActiveBits(), 8560 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8561 8562 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8563 8564 SDLoc SL = getCurSDLoc(); 8565 8566 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8567 DAG.getValueType(SmallVT)); 8568 unsigned NumVals = Op.getNode()->getNumValues(); 8569 if (NumVals == 1) 8570 return ZExt; 8571 8572 SmallVector<SDValue, 4> Ops; 8573 8574 Ops.push_back(ZExt); 8575 for (unsigned I = 1; I != NumVals; ++I) 8576 Ops.push_back(Op.getValue(I)); 8577 8578 return DAG.getMergeValues(Ops, SL); 8579 } 8580 8581 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8582 /// the call being lowered. 8583 /// 8584 /// This is a helper for lowering intrinsics that follow a target calling 8585 /// convention or require stack pointer adjustment. Only a subset of the 8586 /// intrinsic's operands need to participate in the calling convention. 8587 void SelectionDAGBuilder::populateCallLoweringInfo( 8588 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8589 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8590 bool IsPatchPoint) { 8591 TargetLowering::ArgListTy Args; 8592 Args.reserve(NumArgs); 8593 8594 // Populate the argument list. 8595 // Attributes for args start at offset 1, after the return attribute. 8596 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8597 ArgI != ArgE; ++ArgI) { 8598 const Value *V = Call->getOperand(ArgI); 8599 8600 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8601 8602 TargetLowering::ArgListEntry Entry; 8603 Entry.Node = getValue(V); 8604 Entry.Ty = V->getType(); 8605 Entry.setAttributes(Call, ArgI); 8606 Args.push_back(Entry); 8607 } 8608 8609 CLI.setDebugLoc(getCurSDLoc()) 8610 .setChain(getRoot()) 8611 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8612 .setDiscardResult(Call->use_empty()) 8613 .setIsPatchPoint(IsPatchPoint); 8614 } 8615 8616 /// Add a stack map intrinsic call's live variable operands to a stackmap 8617 /// or patchpoint target node's operand list. 8618 /// 8619 /// Constants are converted to TargetConstants purely as an optimization to 8620 /// avoid constant materialization and register allocation. 8621 /// 8622 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8623 /// generate addess computation nodes, and so FinalizeISel can convert the 8624 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8625 /// address materialization and register allocation, but may also be required 8626 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8627 /// alloca in the entry block, then the runtime may assume that the alloca's 8628 /// StackMap location can be read immediately after compilation and that the 8629 /// location is valid at any point during execution (this is similar to the 8630 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8631 /// only available in a register, then the runtime would need to trap when 8632 /// execution reaches the StackMap in order to read the alloca's location. 8633 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8634 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8635 SelectionDAGBuilder &Builder) { 8636 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8637 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8638 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8639 Ops.push_back( 8640 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8641 Ops.push_back( 8642 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8643 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8644 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8645 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8646 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8647 } else 8648 Ops.push_back(OpVal); 8649 } 8650 } 8651 8652 /// Lower llvm.experimental.stackmap directly to its target opcode. 8653 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8654 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8655 // [live variables...]) 8656 8657 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8658 8659 SDValue Chain, InFlag, Callee, NullPtr; 8660 SmallVector<SDValue, 32> Ops; 8661 8662 SDLoc DL = getCurSDLoc(); 8663 Callee = getValue(CI.getCalledValue()); 8664 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8665 8666 // The stackmap intrinsic only records the live variables (the arguments 8667 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8668 // intrinsic, this won't be lowered to a function call. This means we don't 8669 // have to worry about calling conventions and target specific lowering code. 8670 // Instead we perform the call lowering right here. 8671 // 8672 // chain, flag = CALLSEQ_START(chain, 0, 0) 8673 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8674 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8675 // 8676 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8677 InFlag = Chain.getValue(1); 8678 8679 // Add the <id> and <numBytes> constants. 8680 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8681 Ops.push_back(DAG.getTargetConstant( 8682 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8683 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8684 Ops.push_back(DAG.getTargetConstant( 8685 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8686 MVT::i32)); 8687 8688 // Push live variables for the stack map. 8689 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8690 8691 // We are not pushing any register mask info here on the operands list, 8692 // because the stackmap doesn't clobber anything. 8693 8694 // Push the chain and the glue flag. 8695 Ops.push_back(Chain); 8696 Ops.push_back(InFlag); 8697 8698 // Create the STACKMAP node. 8699 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8700 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8701 Chain = SDValue(SM, 0); 8702 InFlag = Chain.getValue(1); 8703 8704 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8705 8706 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8707 8708 // Set the root to the target-lowered call chain. 8709 DAG.setRoot(Chain); 8710 8711 // Inform the Frame Information that we have a stackmap in this function. 8712 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8713 } 8714 8715 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8716 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8717 const BasicBlock *EHPadBB) { 8718 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8719 // i32 <numBytes>, 8720 // i8* <target>, 8721 // i32 <numArgs>, 8722 // [Args...], 8723 // [live variables...]) 8724 8725 CallingConv::ID CC = CS.getCallingConv(); 8726 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8727 bool HasDef = !CS->getType()->isVoidTy(); 8728 SDLoc dl = getCurSDLoc(); 8729 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8730 8731 // Handle immediate and symbolic callees. 8732 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8733 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8734 /*isTarget=*/true); 8735 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8736 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8737 SDLoc(SymbolicCallee), 8738 SymbolicCallee->getValueType(0)); 8739 8740 // Get the real number of arguments participating in the call <numArgs> 8741 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8742 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8743 8744 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8745 // Intrinsics include all meta-operands up to but not including CC. 8746 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8747 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8748 "Not enough arguments provided to the patchpoint intrinsic"); 8749 8750 // For AnyRegCC the arguments are lowered later on manually. 8751 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8752 Type *ReturnTy = 8753 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8754 8755 TargetLowering::CallLoweringInfo CLI(DAG); 8756 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8757 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8758 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8759 8760 SDNode *CallEnd = Result.second.getNode(); 8761 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8762 CallEnd = CallEnd->getOperand(0).getNode(); 8763 8764 /// Get a call instruction from the call sequence chain. 8765 /// Tail calls are not allowed. 8766 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8767 "Expected a callseq node."); 8768 SDNode *Call = CallEnd->getOperand(0).getNode(); 8769 bool HasGlue = Call->getGluedNode(); 8770 8771 // Replace the target specific call node with the patchable intrinsic. 8772 SmallVector<SDValue, 8> Ops; 8773 8774 // Add the <id> and <numBytes> constants. 8775 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8776 Ops.push_back(DAG.getTargetConstant( 8777 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8778 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8779 Ops.push_back(DAG.getTargetConstant( 8780 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8781 MVT::i32)); 8782 8783 // Add the callee. 8784 Ops.push_back(Callee); 8785 8786 // Adjust <numArgs> to account for any arguments that have been passed on the 8787 // stack instead. 8788 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8789 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8790 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8791 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8792 8793 // Add the calling convention 8794 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8795 8796 // Add the arguments we omitted previously. The register allocator should 8797 // place these in any free register. 8798 if (IsAnyRegCC) 8799 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8800 Ops.push_back(getValue(CS.getArgument(i))); 8801 8802 // Push the arguments from the call instruction up to the register mask. 8803 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8804 Ops.append(Call->op_begin() + 2, e); 8805 8806 // Push live variables for the stack map. 8807 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8808 8809 // Push the register mask info. 8810 if (HasGlue) 8811 Ops.push_back(*(Call->op_end()-2)); 8812 else 8813 Ops.push_back(*(Call->op_end()-1)); 8814 8815 // Push the chain (this is originally the first operand of the call, but 8816 // becomes now the last or second to last operand). 8817 Ops.push_back(*(Call->op_begin())); 8818 8819 // Push the glue flag (last operand). 8820 if (HasGlue) 8821 Ops.push_back(*(Call->op_end()-1)); 8822 8823 SDVTList NodeTys; 8824 if (IsAnyRegCC && HasDef) { 8825 // Create the return types based on the intrinsic definition 8826 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8827 SmallVector<EVT, 3> ValueVTs; 8828 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8829 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8830 8831 // There is always a chain and a glue type at the end 8832 ValueVTs.push_back(MVT::Other); 8833 ValueVTs.push_back(MVT::Glue); 8834 NodeTys = DAG.getVTList(ValueVTs); 8835 } else 8836 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8837 8838 // Replace the target specific call node with a PATCHPOINT node. 8839 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8840 dl, NodeTys, Ops); 8841 8842 // Update the NodeMap. 8843 if (HasDef) { 8844 if (IsAnyRegCC) 8845 setValue(CS.getInstruction(), SDValue(MN, 0)); 8846 else 8847 setValue(CS.getInstruction(), Result.first); 8848 } 8849 8850 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8851 // call sequence. Furthermore the location of the chain and glue can change 8852 // when the AnyReg calling convention is used and the intrinsic returns a 8853 // value. 8854 if (IsAnyRegCC && HasDef) { 8855 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8856 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8857 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8858 } else 8859 DAG.ReplaceAllUsesWith(Call, MN); 8860 DAG.DeleteNode(Call); 8861 8862 // Inform the Frame Information that we have a patchpoint in this function. 8863 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8864 } 8865 8866 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8867 unsigned Intrinsic) { 8868 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8869 SDValue Op1 = getValue(I.getArgOperand(0)); 8870 SDValue Op2; 8871 if (I.getNumArgOperands() > 1) 8872 Op2 = getValue(I.getArgOperand(1)); 8873 SDLoc dl = getCurSDLoc(); 8874 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8875 SDValue Res; 8876 FastMathFlags FMF; 8877 if (isa<FPMathOperator>(I)) 8878 FMF = I.getFastMathFlags(); 8879 8880 switch (Intrinsic) { 8881 case Intrinsic::experimental_vector_reduce_v2_fadd: 8882 if (FMF.allowReassoc()) 8883 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8884 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8885 else 8886 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8887 break; 8888 case Intrinsic::experimental_vector_reduce_v2_fmul: 8889 if (FMF.allowReassoc()) 8890 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8891 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8892 else 8893 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8894 break; 8895 case Intrinsic::experimental_vector_reduce_add: 8896 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8897 break; 8898 case Intrinsic::experimental_vector_reduce_mul: 8899 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8900 break; 8901 case Intrinsic::experimental_vector_reduce_and: 8902 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8903 break; 8904 case Intrinsic::experimental_vector_reduce_or: 8905 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8906 break; 8907 case Intrinsic::experimental_vector_reduce_xor: 8908 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8909 break; 8910 case Intrinsic::experimental_vector_reduce_smax: 8911 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8912 break; 8913 case Intrinsic::experimental_vector_reduce_smin: 8914 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8915 break; 8916 case Intrinsic::experimental_vector_reduce_umax: 8917 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8918 break; 8919 case Intrinsic::experimental_vector_reduce_umin: 8920 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8921 break; 8922 case Intrinsic::experimental_vector_reduce_fmax: 8923 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8924 break; 8925 case Intrinsic::experimental_vector_reduce_fmin: 8926 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8927 break; 8928 default: 8929 llvm_unreachable("Unhandled vector reduce intrinsic"); 8930 } 8931 setValue(&I, Res); 8932 } 8933 8934 /// Returns an AttributeList representing the attributes applied to the return 8935 /// value of the given call. 8936 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8937 SmallVector<Attribute::AttrKind, 2> Attrs; 8938 if (CLI.RetSExt) 8939 Attrs.push_back(Attribute::SExt); 8940 if (CLI.RetZExt) 8941 Attrs.push_back(Attribute::ZExt); 8942 if (CLI.IsInReg) 8943 Attrs.push_back(Attribute::InReg); 8944 8945 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8946 Attrs); 8947 } 8948 8949 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8950 /// implementation, which just calls LowerCall. 8951 /// FIXME: When all targets are 8952 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8953 std::pair<SDValue, SDValue> 8954 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8955 // Handle the incoming return values from the call. 8956 CLI.Ins.clear(); 8957 Type *OrigRetTy = CLI.RetTy; 8958 SmallVector<EVT, 4> RetTys; 8959 SmallVector<uint64_t, 4> Offsets; 8960 auto &DL = CLI.DAG.getDataLayout(); 8961 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8962 8963 if (CLI.IsPostTypeLegalization) { 8964 // If we are lowering a libcall after legalization, split the return type. 8965 SmallVector<EVT, 4> OldRetTys; 8966 SmallVector<uint64_t, 4> OldOffsets; 8967 RetTys.swap(OldRetTys); 8968 Offsets.swap(OldOffsets); 8969 8970 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8971 EVT RetVT = OldRetTys[i]; 8972 uint64_t Offset = OldOffsets[i]; 8973 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8974 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8975 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8976 RetTys.append(NumRegs, RegisterVT); 8977 for (unsigned j = 0; j != NumRegs; ++j) 8978 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8979 } 8980 } 8981 8982 SmallVector<ISD::OutputArg, 4> Outs; 8983 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8984 8985 bool CanLowerReturn = 8986 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8987 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8988 8989 SDValue DemoteStackSlot; 8990 int DemoteStackIdx = -100; 8991 if (!CanLowerReturn) { 8992 // FIXME: equivalent assert? 8993 // assert(!CS.hasInAllocaArgument() && 8994 // "sret demotion is incompatible with inalloca"); 8995 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8996 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8997 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8998 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8999 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9000 DL.getAllocaAddrSpace()); 9001 9002 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9003 ArgListEntry Entry; 9004 Entry.Node = DemoteStackSlot; 9005 Entry.Ty = StackSlotPtrType; 9006 Entry.IsSExt = false; 9007 Entry.IsZExt = false; 9008 Entry.IsInReg = false; 9009 Entry.IsSRet = true; 9010 Entry.IsNest = false; 9011 Entry.IsByVal = false; 9012 Entry.IsReturned = false; 9013 Entry.IsSwiftSelf = false; 9014 Entry.IsSwiftError = false; 9015 Entry.IsCFGuardTarget = false; 9016 Entry.Alignment = Align; 9017 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9018 CLI.NumFixedArgs += 1; 9019 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9020 9021 // sret demotion isn't compatible with tail-calls, since the sret argument 9022 // points into the callers stack frame. 9023 CLI.IsTailCall = false; 9024 } else { 9025 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9026 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9027 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9028 ISD::ArgFlagsTy Flags; 9029 if (NeedsRegBlock) { 9030 Flags.setInConsecutiveRegs(); 9031 if (I == RetTys.size() - 1) 9032 Flags.setInConsecutiveRegsLast(); 9033 } 9034 EVT VT = RetTys[I]; 9035 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9036 CLI.CallConv, VT); 9037 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9038 CLI.CallConv, VT); 9039 for (unsigned i = 0; i != NumRegs; ++i) { 9040 ISD::InputArg MyFlags; 9041 MyFlags.Flags = Flags; 9042 MyFlags.VT = RegisterVT; 9043 MyFlags.ArgVT = VT; 9044 MyFlags.Used = CLI.IsReturnValueUsed; 9045 if (CLI.RetTy->isPointerTy()) { 9046 MyFlags.Flags.setPointer(); 9047 MyFlags.Flags.setPointerAddrSpace( 9048 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9049 } 9050 if (CLI.RetSExt) 9051 MyFlags.Flags.setSExt(); 9052 if (CLI.RetZExt) 9053 MyFlags.Flags.setZExt(); 9054 if (CLI.IsInReg) 9055 MyFlags.Flags.setInReg(); 9056 CLI.Ins.push_back(MyFlags); 9057 } 9058 } 9059 } 9060 9061 // We push in swifterror return as the last element of CLI.Ins. 9062 ArgListTy &Args = CLI.getArgs(); 9063 if (supportSwiftError()) { 9064 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9065 if (Args[i].IsSwiftError) { 9066 ISD::InputArg MyFlags; 9067 MyFlags.VT = getPointerTy(DL); 9068 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9069 MyFlags.Flags.setSwiftError(); 9070 CLI.Ins.push_back(MyFlags); 9071 } 9072 } 9073 } 9074 9075 // Handle all of the outgoing arguments. 9076 CLI.Outs.clear(); 9077 CLI.OutVals.clear(); 9078 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9079 SmallVector<EVT, 4> ValueVTs; 9080 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9081 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9082 Type *FinalType = Args[i].Ty; 9083 if (Args[i].IsByVal) 9084 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9085 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9086 FinalType, CLI.CallConv, CLI.IsVarArg); 9087 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9088 ++Value) { 9089 EVT VT = ValueVTs[Value]; 9090 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9091 SDValue Op = SDValue(Args[i].Node.getNode(), 9092 Args[i].Node.getResNo() + Value); 9093 ISD::ArgFlagsTy Flags; 9094 9095 // Certain targets (such as MIPS), may have a different ABI alignment 9096 // for a type depending on the context. Give the target a chance to 9097 // specify the alignment it wants. 9098 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9099 9100 if (Args[i].Ty->isPointerTy()) { 9101 Flags.setPointer(); 9102 Flags.setPointerAddrSpace( 9103 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9104 } 9105 if (Args[i].IsZExt) 9106 Flags.setZExt(); 9107 if (Args[i].IsSExt) 9108 Flags.setSExt(); 9109 if (Args[i].IsInReg) { 9110 // If we are using vectorcall calling convention, a structure that is 9111 // passed InReg - is surely an HVA 9112 if (CLI.CallConv == CallingConv::X86_VectorCall && 9113 isa<StructType>(FinalType)) { 9114 // The first value of a structure is marked 9115 if (0 == Value) 9116 Flags.setHvaStart(); 9117 Flags.setHva(); 9118 } 9119 // Set InReg Flag 9120 Flags.setInReg(); 9121 } 9122 if (Args[i].IsSRet) 9123 Flags.setSRet(); 9124 if (Args[i].IsSwiftSelf) 9125 Flags.setSwiftSelf(); 9126 if (Args[i].IsSwiftError) 9127 Flags.setSwiftError(); 9128 if (Args[i].IsCFGuardTarget) 9129 Flags.setCFGuardTarget(); 9130 if (Args[i].IsByVal) 9131 Flags.setByVal(); 9132 if (Args[i].IsInAlloca) { 9133 Flags.setInAlloca(); 9134 // Set the byval flag for CCAssignFn callbacks that don't know about 9135 // inalloca. This way we can know how many bytes we should've allocated 9136 // and how many bytes a callee cleanup function will pop. If we port 9137 // inalloca to more targets, we'll have to add custom inalloca handling 9138 // in the various CC lowering callbacks. 9139 Flags.setByVal(); 9140 } 9141 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9142 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9143 Type *ElementTy = Ty->getElementType(); 9144 9145 unsigned FrameSize = DL.getTypeAllocSize( 9146 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9147 Flags.setByValSize(FrameSize); 9148 9149 // info is not there but there are cases it cannot get right. 9150 unsigned FrameAlign; 9151 if (Args[i].Alignment) 9152 FrameAlign = Args[i].Alignment; 9153 else 9154 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9155 Flags.setByValAlign(Align(FrameAlign)); 9156 } 9157 if (Args[i].IsNest) 9158 Flags.setNest(); 9159 if (NeedsRegBlock) 9160 Flags.setInConsecutiveRegs(); 9161 Flags.setOrigAlign(OriginalAlignment); 9162 9163 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9164 CLI.CallConv, VT); 9165 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9166 CLI.CallConv, VT); 9167 SmallVector<SDValue, 4> Parts(NumParts); 9168 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9169 9170 if (Args[i].IsSExt) 9171 ExtendKind = ISD::SIGN_EXTEND; 9172 else if (Args[i].IsZExt) 9173 ExtendKind = ISD::ZERO_EXTEND; 9174 9175 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9176 // for now. 9177 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9178 CanLowerReturn) { 9179 assert((CLI.RetTy == Args[i].Ty || 9180 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9181 CLI.RetTy->getPointerAddressSpace() == 9182 Args[i].Ty->getPointerAddressSpace())) && 9183 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9184 // Before passing 'returned' to the target lowering code, ensure that 9185 // either the register MVT and the actual EVT are the same size or that 9186 // the return value and argument are extended in the same way; in these 9187 // cases it's safe to pass the argument register value unchanged as the 9188 // return register value (although it's at the target's option whether 9189 // to do so) 9190 // TODO: allow code generation to take advantage of partially preserved 9191 // registers rather than clobbering the entire register when the 9192 // parameter extension method is not compatible with the return 9193 // extension method 9194 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9195 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9196 CLI.RetZExt == Args[i].IsZExt)) 9197 Flags.setReturned(); 9198 } 9199 9200 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9201 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9202 9203 for (unsigned j = 0; j != NumParts; ++j) { 9204 // if it isn't first piece, alignment must be 1 9205 // For scalable vectors the scalable part is currently handled 9206 // by individual targets, so we just use the known minimum size here. 9207 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9208 i < CLI.NumFixedArgs, i, 9209 j*Parts[j].getValueType().getStoreSize().getKnownMinSize()); 9210 if (NumParts > 1 && j == 0) 9211 MyFlags.Flags.setSplit(); 9212 else if (j != 0) { 9213 MyFlags.Flags.setOrigAlign(Align::None()); 9214 if (j == NumParts - 1) 9215 MyFlags.Flags.setSplitEnd(); 9216 } 9217 9218 CLI.Outs.push_back(MyFlags); 9219 CLI.OutVals.push_back(Parts[j]); 9220 } 9221 9222 if (NeedsRegBlock && Value == NumValues - 1) 9223 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9224 } 9225 } 9226 9227 SmallVector<SDValue, 4> InVals; 9228 CLI.Chain = LowerCall(CLI, InVals); 9229 9230 // Update CLI.InVals to use outside of this function. 9231 CLI.InVals = InVals; 9232 9233 // Verify that the target's LowerCall behaved as expected. 9234 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9235 "LowerCall didn't return a valid chain!"); 9236 assert((!CLI.IsTailCall || InVals.empty()) && 9237 "LowerCall emitted a return value for a tail call!"); 9238 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9239 "LowerCall didn't emit the correct number of values!"); 9240 9241 // For a tail call, the return value is merely live-out and there aren't 9242 // any nodes in the DAG representing it. Return a special value to 9243 // indicate that a tail call has been emitted and no more Instructions 9244 // should be processed in the current block. 9245 if (CLI.IsTailCall) { 9246 CLI.DAG.setRoot(CLI.Chain); 9247 return std::make_pair(SDValue(), SDValue()); 9248 } 9249 9250 #ifndef NDEBUG 9251 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9252 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9253 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9254 "LowerCall emitted a value with the wrong type!"); 9255 } 9256 #endif 9257 9258 SmallVector<SDValue, 4> ReturnValues; 9259 if (!CanLowerReturn) { 9260 // The instruction result is the result of loading from the 9261 // hidden sret parameter. 9262 SmallVector<EVT, 1> PVTs; 9263 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9264 9265 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9266 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9267 EVT PtrVT = PVTs[0]; 9268 9269 unsigned NumValues = RetTys.size(); 9270 ReturnValues.resize(NumValues); 9271 SmallVector<SDValue, 4> Chains(NumValues); 9272 9273 // An aggregate return value cannot wrap around the address space, so 9274 // offsets to its parts don't wrap either. 9275 SDNodeFlags Flags; 9276 Flags.setNoUnsignedWrap(true); 9277 9278 for (unsigned i = 0; i < NumValues; ++i) { 9279 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9280 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9281 PtrVT), Flags); 9282 SDValue L = CLI.DAG.getLoad( 9283 RetTys[i], CLI.DL, CLI.Chain, Add, 9284 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9285 DemoteStackIdx, Offsets[i]), 9286 /* Alignment = */ 1); 9287 ReturnValues[i] = L; 9288 Chains[i] = L.getValue(1); 9289 } 9290 9291 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9292 } else { 9293 // Collect the legal value parts into potentially illegal values 9294 // that correspond to the original function's return values. 9295 Optional<ISD::NodeType> AssertOp; 9296 if (CLI.RetSExt) 9297 AssertOp = ISD::AssertSext; 9298 else if (CLI.RetZExt) 9299 AssertOp = ISD::AssertZext; 9300 unsigned CurReg = 0; 9301 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9302 EVT VT = RetTys[I]; 9303 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9304 CLI.CallConv, VT); 9305 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9306 CLI.CallConv, VT); 9307 9308 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9309 NumRegs, RegisterVT, VT, nullptr, 9310 CLI.CallConv, AssertOp)); 9311 CurReg += NumRegs; 9312 } 9313 9314 // For a function returning void, there is no return value. We can't create 9315 // such a node, so we just return a null return value in that case. In 9316 // that case, nothing will actually look at the value. 9317 if (ReturnValues.empty()) 9318 return std::make_pair(SDValue(), CLI.Chain); 9319 } 9320 9321 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9322 CLI.DAG.getVTList(RetTys), ReturnValues); 9323 return std::make_pair(Res, CLI.Chain); 9324 } 9325 9326 void TargetLowering::LowerOperationWrapper(SDNode *N, 9327 SmallVectorImpl<SDValue> &Results, 9328 SelectionDAG &DAG) const { 9329 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9330 Results.push_back(Res); 9331 } 9332 9333 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9334 llvm_unreachable("LowerOperation not implemented for this target!"); 9335 } 9336 9337 void 9338 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9339 SDValue Op = getNonRegisterValue(V); 9340 assert((Op.getOpcode() != ISD::CopyFromReg || 9341 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9342 "Copy from a reg to the same reg!"); 9343 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9344 9345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9346 // If this is an InlineAsm we have to match the registers required, not the 9347 // notional registers required by the type. 9348 9349 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9350 None); // This is not an ABI copy. 9351 SDValue Chain = DAG.getEntryNode(); 9352 9353 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9354 FuncInfo.PreferredExtendType.end()) 9355 ? ISD::ANY_EXTEND 9356 : FuncInfo.PreferredExtendType[V]; 9357 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9358 PendingExports.push_back(Chain); 9359 } 9360 9361 #include "llvm/CodeGen/SelectionDAGISel.h" 9362 9363 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9364 /// entry block, return true. This includes arguments used by switches, since 9365 /// the switch may expand into multiple basic blocks. 9366 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9367 // With FastISel active, we may be splitting blocks, so force creation 9368 // of virtual registers for all non-dead arguments. 9369 if (FastISel) 9370 return A->use_empty(); 9371 9372 const BasicBlock &Entry = A->getParent()->front(); 9373 for (const User *U : A->users()) 9374 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9375 return false; // Use not in entry block. 9376 9377 return true; 9378 } 9379 9380 using ArgCopyElisionMapTy = 9381 DenseMap<const Argument *, 9382 std::pair<const AllocaInst *, const StoreInst *>>; 9383 9384 /// Scan the entry block of the function in FuncInfo for arguments that look 9385 /// like copies into a local alloca. Record any copied arguments in 9386 /// ArgCopyElisionCandidates. 9387 static void 9388 findArgumentCopyElisionCandidates(const DataLayout &DL, 9389 FunctionLoweringInfo *FuncInfo, 9390 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9391 // Record the state of every static alloca used in the entry block. Argument 9392 // allocas are all used in the entry block, so we need approximately as many 9393 // entries as we have arguments. 9394 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9395 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9396 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9397 StaticAllocas.reserve(NumArgs * 2); 9398 9399 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9400 if (!V) 9401 return nullptr; 9402 V = V->stripPointerCasts(); 9403 const auto *AI = dyn_cast<AllocaInst>(V); 9404 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9405 return nullptr; 9406 auto Iter = StaticAllocas.insert({AI, Unknown}); 9407 return &Iter.first->second; 9408 }; 9409 9410 // Look for stores of arguments to static allocas. Look through bitcasts and 9411 // GEPs to handle type coercions, as long as the alloca is fully initialized 9412 // by the store. Any non-store use of an alloca escapes it and any subsequent 9413 // unanalyzed store might write it. 9414 // FIXME: Handle structs initialized with multiple stores. 9415 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9416 // Look for stores, and handle non-store uses conservatively. 9417 const auto *SI = dyn_cast<StoreInst>(&I); 9418 if (!SI) { 9419 // We will look through cast uses, so ignore them completely. 9420 if (I.isCast()) 9421 continue; 9422 // Ignore debug info intrinsics, they don't escape or store to allocas. 9423 if (isa<DbgInfoIntrinsic>(I)) 9424 continue; 9425 // This is an unknown instruction. Assume it escapes or writes to all 9426 // static alloca operands. 9427 for (const Use &U : I.operands()) { 9428 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9429 *Info = StaticAllocaInfo::Clobbered; 9430 } 9431 continue; 9432 } 9433 9434 // If the stored value is a static alloca, mark it as escaped. 9435 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9436 *Info = StaticAllocaInfo::Clobbered; 9437 9438 // Check if the destination is a static alloca. 9439 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9440 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9441 if (!Info) 9442 continue; 9443 const AllocaInst *AI = cast<AllocaInst>(Dst); 9444 9445 // Skip allocas that have been initialized or clobbered. 9446 if (*Info != StaticAllocaInfo::Unknown) 9447 continue; 9448 9449 // Check if the stored value is an argument, and that this store fully 9450 // initializes the alloca. Don't elide copies from the same argument twice. 9451 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9452 const auto *Arg = dyn_cast<Argument>(Val); 9453 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9454 Arg->getType()->isEmptyTy() || 9455 DL.getTypeStoreSize(Arg->getType()) != 9456 DL.getTypeAllocSize(AI->getAllocatedType()) || 9457 ArgCopyElisionCandidates.count(Arg)) { 9458 *Info = StaticAllocaInfo::Clobbered; 9459 continue; 9460 } 9461 9462 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9463 << '\n'); 9464 9465 // Mark this alloca and store for argument copy elision. 9466 *Info = StaticAllocaInfo::Elidable; 9467 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9468 9469 // Stop scanning if we've seen all arguments. This will happen early in -O0 9470 // builds, which is useful, because -O0 builds have large entry blocks and 9471 // many allocas. 9472 if (ArgCopyElisionCandidates.size() == NumArgs) 9473 break; 9474 } 9475 } 9476 9477 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9478 /// ArgVal is a load from a suitable fixed stack object. 9479 static void tryToElideArgumentCopy( 9480 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains, 9481 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9482 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9483 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9484 SDValue ArgVal, bool &ArgHasUses) { 9485 // Check if this is a load from a fixed stack object. 9486 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9487 if (!LNode) 9488 return; 9489 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9490 if (!FINode) 9491 return; 9492 9493 // Check that the fixed stack object is the right size and alignment. 9494 // Look at the alignment that the user wrote on the alloca instead of looking 9495 // at the stack object. 9496 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9497 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9498 const AllocaInst *AI = ArgCopyIter->second.first; 9499 int FixedIndex = FINode->getIndex(); 9500 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI]; 9501 int OldIndex = AllocaIndex; 9502 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo(); 9503 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9504 LLVM_DEBUG( 9505 dbgs() << " argument copy elision failed due to bad fixed stack " 9506 "object size\n"); 9507 return; 9508 } 9509 unsigned RequiredAlignment = AI->getAlignment(); 9510 if (!RequiredAlignment) { 9511 RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment( 9512 AI->getAllocatedType()); 9513 } 9514 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9515 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9516 "greater than stack argument alignment (" 9517 << RequiredAlignment << " vs " 9518 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9519 return; 9520 } 9521 9522 // Perform the elision. Delete the old stack object and replace its only use 9523 // in the variable info map. Mark the stack object as mutable. 9524 LLVM_DEBUG({ 9525 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9526 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9527 << '\n'; 9528 }); 9529 MFI.RemoveStackObject(OldIndex); 9530 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9531 AllocaIndex = FixedIndex; 9532 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9533 Chains.push_back(ArgVal.getValue(1)); 9534 9535 // Avoid emitting code for the store implementing the copy. 9536 const StoreInst *SI = ArgCopyIter->second.second; 9537 ElidedArgCopyInstrs.insert(SI); 9538 9539 // Check for uses of the argument again so that we can avoid exporting ArgVal 9540 // if it is't used by anything other than the store. 9541 for (const Value *U : Arg.users()) { 9542 if (U != SI) { 9543 ArgHasUses = true; 9544 break; 9545 } 9546 } 9547 } 9548 9549 void SelectionDAGISel::LowerArguments(const Function &F) { 9550 SelectionDAG &DAG = SDB->DAG; 9551 SDLoc dl = SDB->getCurSDLoc(); 9552 const DataLayout &DL = DAG.getDataLayout(); 9553 SmallVector<ISD::InputArg, 16> Ins; 9554 9555 if (!FuncInfo->CanLowerReturn) { 9556 // Put in an sret pointer parameter before all the other parameters. 9557 SmallVector<EVT, 1> ValueVTs; 9558 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9559 F.getReturnType()->getPointerTo( 9560 DAG.getDataLayout().getAllocaAddrSpace()), 9561 ValueVTs); 9562 9563 // NOTE: Assuming that a pointer will never break down to more than one VT 9564 // or one register. 9565 ISD::ArgFlagsTy Flags; 9566 Flags.setSRet(); 9567 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9568 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9569 ISD::InputArg::NoArgIndex, 0); 9570 Ins.push_back(RetArg); 9571 } 9572 9573 // Look for stores of arguments to static allocas. Mark such arguments with a 9574 // flag to ask the target to give us the memory location of that argument if 9575 // available. 9576 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9577 findArgumentCopyElisionCandidates(DL, FuncInfo.get(), 9578 ArgCopyElisionCandidates); 9579 9580 // Set up the incoming argument description vector. 9581 for (const Argument &Arg : F.args()) { 9582 unsigned ArgNo = Arg.getArgNo(); 9583 SmallVector<EVT, 4> ValueVTs; 9584 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9585 bool isArgValueUsed = !Arg.use_empty(); 9586 unsigned PartBase = 0; 9587 Type *FinalType = Arg.getType(); 9588 if (Arg.hasAttribute(Attribute::ByVal)) 9589 FinalType = Arg.getParamByValType(); 9590 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9591 FinalType, F.getCallingConv(), F.isVarArg()); 9592 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9593 Value != NumValues; ++Value) { 9594 EVT VT = ValueVTs[Value]; 9595 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9596 ISD::ArgFlagsTy Flags; 9597 9598 // Certain targets (such as MIPS), may have a different ABI alignment 9599 // for a type depending on the context. Give the target a chance to 9600 // specify the alignment it wants. 9601 const Align OriginalAlignment( 9602 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9603 9604 if (Arg.getType()->isPointerTy()) { 9605 Flags.setPointer(); 9606 Flags.setPointerAddrSpace( 9607 cast<PointerType>(Arg.getType())->getAddressSpace()); 9608 } 9609 if (Arg.hasAttribute(Attribute::ZExt)) 9610 Flags.setZExt(); 9611 if (Arg.hasAttribute(Attribute::SExt)) 9612 Flags.setSExt(); 9613 if (Arg.hasAttribute(Attribute::InReg)) { 9614 // If we are using vectorcall calling convention, a structure that is 9615 // passed InReg - is surely an HVA 9616 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9617 isa<StructType>(Arg.getType())) { 9618 // The first value of a structure is marked 9619 if (0 == Value) 9620 Flags.setHvaStart(); 9621 Flags.setHva(); 9622 } 9623 // Set InReg Flag 9624 Flags.setInReg(); 9625 } 9626 if (Arg.hasAttribute(Attribute::StructRet)) 9627 Flags.setSRet(); 9628 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9629 Flags.setSwiftSelf(); 9630 if (Arg.hasAttribute(Attribute::SwiftError)) 9631 Flags.setSwiftError(); 9632 if (Arg.hasAttribute(Attribute::ByVal)) 9633 Flags.setByVal(); 9634 if (Arg.hasAttribute(Attribute::InAlloca)) { 9635 Flags.setInAlloca(); 9636 // Set the byval flag for CCAssignFn callbacks that don't know about 9637 // inalloca. This way we can know how many bytes we should've allocated 9638 // and how many bytes a callee cleanup function will pop. If we port 9639 // inalloca to more targets, we'll have to add custom inalloca handling 9640 // in the various CC lowering callbacks. 9641 Flags.setByVal(); 9642 } 9643 if (F.getCallingConv() == CallingConv::X86_INTR) { 9644 // IA Interrupt passes frame (1st parameter) by value in the stack. 9645 if (ArgNo == 0) 9646 Flags.setByVal(); 9647 } 9648 if (Flags.isByVal() || Flags.isInAlloca()) { 9649 Type *ElementTy = Arg.getParamByValType(); 9650 9651 // For ByVal, size and alignment should be passed from FE. BE will 9652 // guess if this info is not there but there are cases it cannot get 9653 // right. 9654 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9655 Flags.setByValSize(FrameSize); 9656 9657 unsigned FrameAlign; 9658 if (Arg.getParamAlignment()) 9659 FrameAlign = Arg.getParamAlignment(); 9660 else 9661 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9662 Flags.setByValAlign(Align(FrameAlign)); 9663 } 9664 if (Arg.hasAttribute(Attribute::Nest)) 9665 Flags.setNest(); 9666 if (NeedsRegBlock) 9667 Flags.setInConsecutiveRegs(); 9668 Flags.setOrigAlign(OriginalAlignment); 9669 if (ArgCopyElisionCandidates.count(&Arg)) 9670 Flags.setCopyElisionCandidate(); 9671 if (Arg.hasAttribute(Attribute::Returned)) 9672 Flags.setReturned(); 9673 9674 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9675 *CurDAG->getContext(), F.getCallingConv(), VT); 9676 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9677 *CurDAG->getContext(), F.getCallingConv(), VT); 9678 for (unsigned i = 0; i != NumRegs; ++i) { 9679 // For scalable vectors, use the minimum size; individual targets 9680 // are responsible for handling scalable vector arguments and 9681 // return values. 9682 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9683 ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize()); 9684 if (NumRegs > 1 && i == 0) 9685 MyFlags.Flags.setSplit(); 9686 // if it isn't first piece, alignment must be 1 9687 else if (i > 0) { 9688 MyFlags.Flags.setOrigAlign(Align::None()); 9689 if (i == NumRegs - 1) 9690 MyFlags.Flags.setSplitEnd(); 9691 } 9692 Ins.push_back(MyFlags); 9693 } 9694 if (NeedsRegBlock && Value == NumValues - 1) 9695 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9696 PartBase += VT.getStoreSize().getKnownMinSize(); 9697 } 9698 } 9699 9700 // Call the target to set up the argument values. 9701 SmallVector<SDValue, 8> InVals; 9702 SDValue NewRoot = TLI->LowerFormalArguments( 9703 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9704 9705 // Verify that the target's LowerFormalArguments behaved as expected. 9706 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9707 "LowerFormalArguments didn't return a valid chain!"); 9708 assert(InVals.size() == Ins.size() && 9709 "LowerFormalArguments didn't emit the correct number of values!"); 9710 LLVM_DEBUG({ 9711 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9712 assert(InVals[i].getNode() && 9713 "LowerFormalArguments emitted a null value!"); 9714 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9715 "LowerFormalArguments emitted a value with the wrong type!"); 9716 } 9717 }); 9718 9719 // Update the DAG with the new chain value resulting from argument lowering. 9720 DAG.setRoot(NewRoot); 9721 9722 // Set up the argument values. 9723 unsigned i = 0; 9724 if (!FuncInfo->CanLowerReturn) { 9725 // Create a virtual register for the sret pointer, and put in a copy 9726 // from the sret argument into it. 9727 SmallVector<EVT, 1> ValueVTs; 9728 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9729 F.getReturnType()->getPointerTo( 9730 DAG.getDataLayout().getAllocaAddrSpace()), 9731 ValueVTs); 9732 MVT VT = ValueVTs[0].getSimpleVT(); 9733 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9734 Optional<ISD::NodeType> AssertOp = None; 9735 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9736 nullptr, F.getCallingConv(), AssertOp); 9737 9738 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9739 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9740 Register SRetReg = 9741 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9742 FuncInfo->DemoteRegister = SRetReg; 9743 NewRoot = 9744 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9745 DAG.setRoot(NewRoot); 9746 9747 // i indexes lowered arguments. Bump it past the hidden sret argument. 9748 ++i; 9749 } 9750 9751 SmallVector<SDValue, 4> Chains; 9752 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9753 for (const Argument &Arg : F.args()) { 9754 SmallVector<SDValue, 4> ArgValues; 9755 SmallVector<EVT, 4> ValueVTs; 9756 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9757 unsigned NumValues = ValueVTs.size(); 9758 if (NumValues == 0) 9759 continue; 9760 9761 bool ArgHasUses = !Arg.use_empty(); 9762 9763 // Elide the copying store if the target loaded this argument from a 9764 // suitable fixed stack object. 9765 if (Ins[i].Flags.isCopyElisionCandidate()) { 9766 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9767 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9768 InVals[i], ArgHasUses); 9769 } 9770 9771 // If this argument is unused then remember its value. It is used to generate 9772 // debugging information. 9773 bool isSwiftErrorArg = 9774 TLI->supportSwiftError() && 9775 Arg.hasAttribute(Attribute::SwiftError); 9776 if (!ArgHasUses && !isSwiftErrorArg) { 9777 SDB->setUnusedArgValue(&Arg, InVals[i]); 9778 9779 // Also remember any frame index for use in FastISel. 9780 if (FrameIndexSDNode *FI = 9781 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9782 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9783 } 9784 9785 for (unsigned Val = 0; Val != NumValues; ++Val) { 9786 EVT VT = ValueVTs[Val]; 9787 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9788 F.getCallingConv(), VT); 9789 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9790 *CurDAG->getContext(), F.getCallingConv(), VT); 9791 9792 // Even an apparent 'unused' swifterror argument needs to be returned. So 9793 // we do generate a copy for it that can be used on return from the 9794 // function. 9795 if (ArgHasUses || isSwiftErrorArg) { 9796 Optional<ISD::NodeType> AssertOp; 9797 if (Arg.hasAttribute(Attribute::SExt)) 9798 AssertOp = ISD::AssertSext; 9799 else if (Arg.hasAttribute(Attribute::ZExt)) 9800 AssertOp = ISD::AssertZext; 9801 9802 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9803 PartVT, VT, nullptr, 9804 F.getCallingConv(), AssertOp)); 9805 } 9806 9807 i += NumParts; 9808 } 9809 9810 // We don't need to do anything else for unused arguments. 9811 if (ArgValues.empty()) 9812 continue; 9813 9814 // Note down frame index. 9815 if (FrameIndexSDNode *FI = 9816 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9817 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9818 9819 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9820 SDB->getCurSDLoc()); 9821 9822 SDB->setValue(&Arg, Res); 9823 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9824 // We want to associate the argument with the frame index, among 9825 // involved operands, that correspond to the lowest address. The 9826 // getCopyFromParts function, called earlier, is swapping the order of 9827 // the operands to BUILD_PAIR depending on endianness. The result of 9828 // that swapping is that the least significant bits of the argument will 9829 // be in the first operand of the BUILD_PAIR node, and the most 9830 // significant bits will be in the second operand. 9831 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9832 if (LoadSDNode *LNode = 9833 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9834 if (FrameIndexSDNode *FI = 9835 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9836 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9837 } 9838 9839 // Analyses past this point are naive and don't expect an assertion. 9840 if (Res.getOpcode() == ISD::AssertZext) 9841 Res = Res.getOperand(0); 9842 9843 // Update the SwiftErrorVRegDefMap. 9844 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9845 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9846 if (Register::isVirtualRegister(Reg)) 9847 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9848 Reg); 9849 } 9850 9851 // If this argument is live outside of the entry block, insert a copy from 9852 // wherever we got it to the vreg that other BB's will reference it as. 9853 if (Res.getOpcode() == ISD::CopyFromReg) { 9854 // If we can, though, try to skip creating an unnecessary vreg. 9855 // FIXME: This isn't very clean... it would be nice to make this more 9856 // general. 9857 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9858 if (Register::isVirtualRegister(Reg)) { 9859 FuncInfo->ValueMap[&Arg] = Reg; 9860 continue; 9861 } 9862 } 9863 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9864 FuncInfo->InitializeRegForValue(&Arg); 9865 SDB->CopyToExportRegsIfNeeded(&Arg); 9866 } 9867 } 9868 9869 if (!Chains.empty()) { 9870 Chains.push_back(NewRoot); 9871 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9872 } 9873 9874 DAG.setRoot(NewRoot); 9875 9876 assert(i == InVals.size() && "Argument register count mismatch!"); 9877 9878 // If any argument copy elisions occurred and we have debug info, update the 9879 // stale frame indices used in the dbg.declare variable info table. 9880 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9881 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9882 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9883 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9884 if (I != ArgCopyElisionFrameIndexMap.end()) 9885 VI.Slot = I->second; 9886 } 9887 } 9888 9889 // Finally, if the target has anything special to do, allow it to do so. 9890 EmitFunctionEntryCode(); 9891 } 9892 9893 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9894 /// ensure constants are generated when needed. Remember the virtual registers 9895 /// that need to be added to the Machine PHI nodes as input. We cannot just 9896 /// directly add them, because expansion might result in multiple MBB's for one 9897 /// BB. As such, the start of the BB might correspond to a different MBB than 9898 /// the end. 9899 void 9900 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9901 const Instruction *TI = LLVMBB->getTerminator(); 9902 9903 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9904 9905 // Check PHI nodes in successors that expect a value to be available from this 9906 // block. 9907 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9908 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9909 if (!isa<PHINode>(SuccBB->begin())) continue; 9910 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9911 9912 // If this terminator has multiple identical successors (common for 9913 // switches), only handle each succ once. 9914 if (!SuccsHandled.insert(SuccMBB).second) 9915 continue; 9916 9917 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9918 9919 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9920 // nodes and Machine PHI nodes, but the incoming operands have not been 9921 // emitted yet. 9922 for (const PHINode &PN : SuccBB->phis()) { 9923 // Ignore dead phi's. 9924 if (PN.use_empty()) 9925 continue; 9926 9927 // Skip empty types 9928 if (PN.getType()->isEmptyTy()) 9929 continue; 9930 9931 unsigned Reg; 9932 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9933 9934 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9935 unsigned &RegOut = ConstantsOut[C]; 9936 if (RegOut == 0) { 9937 RegOut = FuncInfo.CreateRegs(C); 9938 CopyValueToVirtualRegister(C, RegOut); 9939 } 9940 Reg = RegOut; 9941 } else { 9942 DenseMap<const Value *, unsigned>::iterator I = 9943 FuncInfo.ValueMap.find(PHIOp); 9944 if (I != FuncInfo.ValueMap.end()) 9945 Reg = I->second; 9946 else { 9947 assert(isa<AllocaInst>(PHIOp) && 9948 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9949 "Didn't codegen value into a register!??"); 9950 Reg = FuncInfo.CreateRegs(PHIOp); 9951 CopyValueToVirtualRegister(PHIOp, Reg); 9952 } 9953 } 9954 9955 // Remember that this register needs to added to the machine PHI node as 9956 // the input for this MBB. 9957 SmallVector<EVT, 4> ValueVTs; 9958 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9959 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9960 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9961 EVT VT = ValueVTs[vti]; 9962 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9963 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9964 FuncInfo.PHINodesToUpdate.push_back( 9965 std::make_pair(&*MBBI++, Reg + i)); 9966 Reg += NumRegisters; 9967 } 9968 } 9969 } 9970 9971 ConstantsOut.clear(); 9972 } 9973 9974 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9975 /// is 0. 9976 MachineBasicBlock * 9977 SelectionDAGBuilder::StackProtectorDescriptor:: 9978 AddSuccessorMBB(const BasicBlock *BB, 9979 MachineBasicBlock *ParentMBB, 9980 bool IsLikely, 9981 MachineBasicBlock *SuccMBB) { 9982 // If SuccBB has not been created yet, create it. 9983 if (!SuccMBB) { 9984 MachineFunction *MF = ParentMBB->getParent(); 9985 MachineFunction::iterator BBI(ParentMBB); 9986 SuccMBB = MF->CreateMachineBasicBlock(BB); 9987 MF->insert(++BBI, SuccMBB); 9988 } 9989 // Add it as a successor of ParentMBB. 9990 ParentMBB->addSuccessor( 9991 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9992 return SuccMBB; 9993 } 9994 9995 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9996 MachineFunction::iterator I(MBB); 9997 if (++I == FuncInfo.MF->end()) 9998 return nullptr; 9999 return &*I; 10000 } 10001 10002 /// During lowering new call nodes can be created (such as memset, etc.). 10003 /// Those will become new roots of the current DAG, but complications arise 10004 /// when they are tail calls. In such cases, the call lowering will update 10005 /// the root, but the builder still needs to know that a tail call has been 10006 /// lowered in order to avoid generating an additional return. 10007 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10008 // If the node is null, we do have a tail call. 10009 if (MaybeTC.getNode() != nullptr) 10010 DAG.setRoot(MaybeTC); 10011 else 10012 HasTailCall = true; 10013 } 10014 10015 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10016 MachineBasicBlock *SwitchMBB, 10017 MachineBasicBlock *DefaultMBB) { 10018 MachineFunction *CurMF = FuncInfo.MF; 10019 MachineBasicBlock *NextMBB = nullptr; 10020 MachineFunction::iterator BBI(W.MBB); 10021 if (++BBI != FuncInfo.MF->end()) 10022 NextMBB = &*BBI; 10023 10024 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10025 10026 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10027 10028 if (Size == 2 && W.MBB == SwitchMBB) { 10029 // If any two of the cases has the same destination, and if one value 10030 // is the same as the other, but has one bit unset that the other has set, 10031 // use bit manipulation to do two compares at once. For example: 10032 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10033 // TODO: This could be extended to merge any 2 cases in switches with 3 10034 // cases. 10035 // TODO: Handle cases where W.CaseBB != SwitchBB. 10036 CaseCluster &Small = *W.FirstCluster; 10037 CaseCluster &Big = *W.LastCluster; 10038 10039 if (Small.Low == Small.High && Big.Low == Big.High && 10040 Small.MBB == Big.MBB) { 10041 const APInt &SmallValue = Small.Low->getValue(); 10042 const APInt &BigValue = Big.Low->getValue(); 10043 10044 // Check that there is only one bit different. 10045 APInt CommonBit = BigValue ^ SmallValue; 10046 if (CommonBit.isPowerOf2()) { 10047 SDValue CondLHS = getValue(Cond); 10048 EVT VT = CondLHS.getValueType(); 10049 SDLoc DL = getCurSDLoc(); 10050 10051 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10052 DAG.getConstant(CommonBit, DL, VT)); 10053 SDValue Cond = DAG.getSetCC( 10054 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10055 ISD::SETEQ); 10056 10057 // Update successor info. 10058 // Both Small and Big will jump to Small.BB, so we sum up the 10059 // probabilities. 10060 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10061 if (BPI) 10062 addSuccessorWithProb( 10063 SwitchMBB, DefaultMBB, 10064 // The default destination is the first successor in IR. 10065 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10066 else 10067 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10068 10069 // Insert the true branch. 10070 SDValue BrCond = 10071 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10072 DAG.getBasicBlock(Small.MBB)); 10073 // Insert the false branch. 10074 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10075 DAG.getBasicBlock(DefaultMBB)); 10076 10077 DAG.setRoot(BrCond); 10078 return; 10079 } 10080 } 10081 } 10082 10083 if (TM.getOptLevel() != CodeGenOpt::None) { 10084 // Here, we order cases by probability so the most likely case will be 10085 // checked first. However, two clusters can have the same probability in 10086 // which case their relative ordering is non-deterministic. So we use Low 10087 // as a tie-breaker as clusters are guaranteed to never overlap. 10088 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10089 [](const CaseCluster &a, const CaseCluster &b) { 10090 return a.Prob != b.Prob ? 10091 a.Prob > b.Prob : 10092 a.Low->getValue().slt(b.Low->getValue()); 10093 }); 10094 10095 // Rearrange the case blocks so that the last one falls through if possible 10096 // without changing the order of probabilities. 10097 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10098 --I; 10099 if (I->Prob > W.LastCluster->Prob) 10100 break; 10101 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10102 std::swap(*I, *W.LastCluster); 10103 break; 10104 } 10105 } 10106 } 10107 10108 // Compute total probability. 10109 BranchProbability DefaultProb = W.DefaultProb; 10110 BranchProbability UnhandledProbs = DefaultProb; 10111 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10112 UnhandledProbs += I->Prob; 10113 10114 MachineBasicBlock *CurMBB = W.MBB; 10115 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10116 bool FallthroughUnreachable = false; 10117 MachineBasicBlock *Fallthrough; 10118 if (I == W.LastCluster) { 10119 // For the last cluster, fall through to the default destination. 10120 Fallthrough = DefaultMBB; 10121 FallthroughUnreachable = isa<UnreachableInst>( 10122 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10123 } else { 10124 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10125 CurMF->insert(BBI, Fallthrough); 10126 // Put Cond in a virtual register to make it available from the new blocks. 10127 ExportFromCurrentBlock(Cond); 10128 } 10129 UnhandledProbs -= I->Prob; 10130 10131 switch (I->Kind) { 10132 case CC_JumpTable: { 10133 // FIXME: Optimize away range check based on pivot comparisons. 10134 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10135 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10136 10137 // The jump block hasn't been inserted yet; insert it here. 10138 MachineBasicBlock *JumpMBB = JT->MBB; 10139 CurMF->insert(BBI, JumpMBB); 10140 10141 auto JumpProb = I->Prob; 10142 auto FallthroughProb = UnhandledProbs; 10143 10144 // If the default statement is a target of the jump table, we evenly 10145 // distribute the default probability to successors of CurMBB. Also 10146 // update the probability on the edge from JumpMBB to Fallthrough. 10147 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10148 SE = JumpMBB->succ_end(); 10149 SI != SE; ++SI) { 10150 if (*SI == DefaultMBB) { 10151 JumpProb += DefaultProb / 2; 10152 FallthroughProb -= DefaultProb / 2; 10153 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10154 JumpMBB->normalizeSuccProbs(); 10155 break; 10156 } 10157 } 10158 10159 if (FallthroughUnreachable) { 10160 // Skip the range check if the fallthrough block is unreachable. 10161 JTH->OmitRangeCheck = true; 10162 } 10163 10164 if (!JTH->OmitRangeCheck) 10165 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10166 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10167 CurMBB->normalizeSuccProbs(); 10168 10169 // The jump table header will be inserted in our current block, do the 10170 // range check, and fall through to our fallthrough block. 10171 JTH->HeaderBB = CurMBB; 10172 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10173 10174 // If we're in the right place, emit the jump table header right now. 10175 if (CurMBB == SwitchMBB) { 10176 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10177 JTH->Emitted = true; 10178 } 10179 break; 10180 } 10181 case CC_BitTests: { 10182 // FIXME: Optimize away range check based on pivot comparisons. 10183 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10184 10185 // The bit test blocks haven't been inserted yet; insert them here. 10186 for (BitTestCase &BTC : BTB->Cases) 10187 CurMF->insert(BBI, BTC.ThisBB); 10188 10189 // Fill in fields of the BitTestBlock. 10190 BTB->Parent = CurMBB; 10191 BTB->Default = Fallthrough; 10192 10193 BTB->DefaultProb = UnhandledProbs; 10194 // If the cases in bit test don't form a contiguous range, we evenly 10195 // distribute the probability on the edge to Fallthrough to two 10196 // successors of CurMBB. 10197 if (!BTB->ContiguousRange) { 10198 BTB->Prob += DefaultProb / 2; 10199 BTB->DefaultProb -= DefaultProb / 2; 10200 } 10201 10202 if (FallthroughUnreachable) { 10203 // Skip the range check if the fallthrough block is unreachable. 10204 BTB->OmitRangeCheck = true; 10205 } 10206 10207 // If we're in the right place, emit the bit test header right now. 10208 if (CurMBB == SwitchMBB) { 10209 visitBitTestHeader(*BTB, SwitchMBB); 10210 BTB->Emitted = true; 10211 } 10212 break; 10213 } 10214 case CC_Range: { 10215 const Value *RHS, *LHS, *MHS; 10216 ISD::CondCode CC; 10217 if (I->Low == I->High) { 10218 // Check Cond == I->Low. 10219 CC = ISD::SETEQ; 10220 LHS = Cond; 10221 RHS=I->Low; 10222 MHS = nullptr; 10223 } else { 10224 // Check I->Low <= Cond <= I->High. 10225 CC = ISD::SETLE; 10226 LHS = I->Low; 10227 MHS = Cond; 10228 RHS = I->High; 10229 } 10230 10231 // If Fallthrough is unreachable, fold away the comparison. 10232 if (FallthroughUnreachable) 10233 CC = ISD::SETTRUE; 10234 10235 // The false probability is the sum of all unhandled cases. 10236 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10237 getCurSDLoc(), I->Prob, UnhandledProbs); 10238 10239 if (CurMBB == SwitchMBB) 10240 visitSwitchCase(CB, SwitchMBB); 10241 else 10242 SL->SwitchCases.push_back(CB); 10243 10244 break; 10245 } 10246 } 10247 CurMBB = Fallthrough; 10248 } 10249 } 10250 10251 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10252 CaseClusterIt First, 10253 CaseClusterIt Last) { 10254 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10255 if (X.Prob != CC.Prob) 10256 return X.Prob > CC.Prob; 10257 10258 // Ties are broken by comparing the case value. 10259 return X.Low->getValue().slt(CC.Low->getValue()); 10260 }); 10261 } 10262 10263 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10264 const SwitchWorkListItem &W, 10265 Value *Cond, 10266 MachineBasicBlock *SwitchMBB) { 10267 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10268 "Clusters not sorted?"); 10269 10270 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10271 10272 // Balance the tree based on branch probabilities to create a near-optimal (in 10273 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10274 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10275 CaseClusterIt LastLeft = W.FirstCluster; 10276 CaseClusterIt FirstRight = W.LastCluster; 10277 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10278 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10279 10280 // Move LastLeft and FirstRight towards each other from opposite directions to 10281 // find a partitioning of the clusters which balances the probability on both 10282 // sides. If LeftProb and RightProb are equal, alternate which side is 10283 // taken to ensure 0-probability nodes are distributed evenly. 10284 unsigned I = 0; 10285 while (LastLeft + 1 < FirstRight) { 10286 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10287 LeftProb += (++LastLeft)->Prob; 10288 else 10289 RightProb += (--FirstRight)->Prob; 10290 I++; 10291 } 10292 10293 while (true) { 10294 // Our binary search tree differs from a typical BST in that ours can have up 10295 // to three values in each leaf. The pivot selection above doesn't take that 10296 // into account, which means the tree might require more nodes and be less 10297 // efficient. We compensate for this here. 10298 10299 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10300 unsigned NumRight = W.LastCluster - FirstRight + 1; 10301 10302 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10303 // If one side has less than 3 clusters, and the other has more than 3, 10304 // consider taking a cluster from the other side. 10305 10306 if (NumLeft < NumRight) { 10307 // Consider moving the first cluster on the right to the left side. 10308 CaseCluster &CC = *FirstRight; 10309 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10310 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10311 if (LeftSideRank <= RightSideRank) { 10312 // Moving the cluster to the left does not demote it. 10313 ++LastLeft; 10314 ++FirstRight; 10315 continue; 10316 } 10317 } else { 10318 assert(NumRight < NumLeft); 10319 // Consider moving the last element on the left to the right side. 10320 CaseCluster &CC = *LastLeft; 10321 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10322 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10323 if (RightSideRank <= LeftSideRank) { 10324 // Moving the cluster to the right does not demot it. 10325 --LastLeft; 10326 --FirstRight; 10327 continue; 10328 } 10329 } 10330 } 10331 break; 10332 } 10333 10334 assert(LastLeft + 1 == FirstRight); 10335 assert(LastLeft >= W.FirstCluster); 10336 assert(FirstRight <= W.LastCluster); 10337 10338 // Use the first element on the right as pivot since we will make less-than 10339 // comparisons against it. 10340 CaseClusterIt PivotCluster = FirstRight; 10341 assert(PivotCluster > W.FirstCluster); 10342 assert(PivotCluster <= W.LastCluster); 10343 10344 CaseClusterIt FirstLeft = W.FirstCluster; 10345 CaseClusterIt LastRight = W.LastCluster; 10346 10347 const ConstantInt *Pivot = PivotCluster->Low; 10348 10349 // New blocks will be inserted immediately after the current one. 10350 MachineFunction::iterator BBI(W.MBB); 10351 ++BBI; 10352 10353 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10354 // we can branch to its destination directly if it's squeezed exactly in 10355 // between the known lower bound and Pivot - 1. 10356 MachineBasicBlock *LeftMBB; 10357 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10358 FirstLeft->Low == W.GE && 10359 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10360 LeftMBB = FirstLeft->MBB; 10361 } else { 10362 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10363 FuncInfo.MF->insert(BBI, LeftMBB); 10364 WorkList.push_back( 10365 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10366 // Put Cond in a virtual register to make it available from the new blocks. 10367 ExportFromCurrentBlock(Cond); 10368 } 10369 10370 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10371 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10372 // directly if RHS.High equals the current upper bound. 10373 MachineBasicBlock *RightMBB; 10374 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10375 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10376 RightMBB = FirstRight->MBB; 10377 } else { 10378 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10379 FuncInfo.MF->insert(BBI, RightMBB); 10380 WorkList.push_back( 10381 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10382 // Put Cond in a virtual register to make it available from the new blocks. 10383 ExportFromCurrentBlock(Cond); 10384 } 10385 10386 // Create the CaseBlock record that will be used to lower the branch. 10387 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10388 getCurSDLoc(), LeftProb, RightProb); 10389 10390 if (W.MBB == SwitchMBB) 10391 visitSwitchCase(CB, SwitchMBB); 10392 else 10393 SL->SwitchCases.push_back(CB); 10394 } 10395 10396 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10397 // from the swith statement. 10398 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10399 BranchProbability PeeledCaseProb) { 10400 if (PeeledCaseProb == BranchProbability::getOne()) 10401 return BranchProbability::getZero(); 10402 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10403 10404 uint32_t Numerator = CaseProb.getNumerator(); 10405 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10406 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10407 } 10408 10409 // Try to peel the top probability case if it exceeds the threshold. 10410 // Return current MachineBasicBlock for the switch statement if the peeling 10411 // does not occur. 10412 // If the peeling is performed, return the newly created MachineBasicBlock 10413 // for the peeled switch statement. Also update Clusters to remove the peeled 10414 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10415 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10416 const SwitchInst &SI, CaseClusterVector &Clusters, 10417 BranchProbability &PeeledCaseProb) { 10418 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10419 // Don't perform if there is only one cluster or optimizing for size. 10420 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10421 TM.getOptLevel() == CodeGenOpt::None || 10422 SwitchMBB->getParent()->getFunction().hasMinSize()) 10423 return SwitchMBB; 10424 10425 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10426 unsigned PeeledCaseIndex = 0; 10427 bool SwitchPeeled = false; 10428 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10429 CaseCluster &CC = Clusters[Index]; 10430 if (CC.Prob < TopCaseProb) 10431 continue; 10432 TopCaseProb = CC.Prob; 10433 PeeledCaseIndex = Index; 10434 SwitchPeeled = true; 10435 } 10436 if (!SwitchPeeled) 10437 return SwitchMBB; 10438 10439 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10440 << TopCaseProb << "\n"); 10441 10442 // Record the MBB for the peeled switch statement. 10443 MachineFunction::iterator BBI(SwitchMBB); 10444 ++BBI; 10445 MachineBasicBlock *PeeledSwitchMBB = 10446 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10447 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10448 10449 ExportFromCurrentBlock(SI.getCondition()); 10450 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10451 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10452 nullptr, nullptr, TopCaseProb.getCompl()}; 10453 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10454 10455 Clusters.erase(PeeledCaseIt); 10456 for (CaseCluster &CC : Clusters) { 10457 LLVM_DEBUG( 10458 dbgs() << "Scale the probablity for one cluster, before scaling: " 10459 << CC.Prob << "\n"); 10460 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10461 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10462 } 10463 PeeledCaseProb = TopCaseProb; 10464 return PeeledSwitchMBB; 10465 } 10466 10467 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10468 // Extract cases from the switch. 10469 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10470 CaseClusterVector Clusters; 10471 Clusters.reserve(SI.getNumCases()); 10472 for (auto I : SI.cases()) { 10473 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10474 const ConstantInt *CaseVal = I.getCaseValue(); 10475 BranchProbability Prob = 10476 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10477 : BranchProbability(1, SI.getNumCases() + 1); 10478 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10479 } 10480 10481 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10482 10483 // Cluster adjacent cases with the same destination. We do this at all 10484 // optimization levels because it's cheap to do and will make codegen faster 10485 // if there are many clusters. 10486 sortAndRangeify(Clusters); 10487 10488 // The branch probablity of the peeled case. 10489 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10490 MachineBasicBlock *PeeledSwitchMBB = 10491 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10492 10493 // If there is only the default destination, jump there directly. 10494 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10495 if (Clusters.empty()) { 10496 assert(PeeledSwitchMBB == SwitchMBB); 10497 SwitchMBB->addSuccessor(DefaultMBB); 10498 if (DefaultMBB != NextBlock(SwitchMBB)) { 10499 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10500 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10501 } 10502 return; 10503 } 10504 10505 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI()); 10506 SL->findBitTestClusters(Clusters, &SI); 10507 10508 LLVM_DEBUG({ 10509 dbgs() << "Case clusters: "; 10510 for (const CaseCluster &C : Clusters) { 10511 if (C.Kind == CC_JumpTable) 10512 dbgs() << "JT:"; 10513 if (C.Kind == CC_BitTests) 10514 dbgs() << "BT:"; 10515 10516 C.Low->getValue().print(dbgs(), true); 10517 if (C.Low != C.High) { 10518 dbgs() << '-'; 10519 C.High->getValue().print(dbgs(), true); 10520 } 10521 dbgs() << ' '; 10522 } 10523 dbgs() << '\n'; 10524 }); 10525 10526 assert(!Clusters.empty()); 10527 SwitchWorkList WorkList; 10528 CaseClusterIt First = Clusters.begin(); 10529 CaseClusterIt Last = Clusters.end() - 1; 10530 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10531 // Scale the branchprobability for DefaultMBB if the peel occurs and 10532 // DefaultMBB is not replaced. 10533 if (PeeledCaseProb != BranchProbability::getZero() && 10534 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10535 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10536 WorkList.push_back( 10537 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10538 10539 while (!WorkList.empty()) { 10540 SwitchWorkListItem W = WorkList.back(); 10541 WorkList.pop_back(); 10542 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10543 10544 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10545 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10546 // For optimized builds, lower large range as a balanced binary tree. 10547 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10548 continue; 10549 } 10550 10551 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10552 } 10553 } 10554 10555 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) { 10556 SDValue N = getValue(I.getOperand(0)); 10557 setValue(&I, N); 10558 } 10559