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/BranchProbabilityInfo.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/MemoryLocation.h" 35 #include "llvm/Analysis/TargetLibraryInfo.h" 36 #include "llvm/Analysis/ValueTracking.h" 37 #include "llvm/Analysis/VectorUtils.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/FunctionLoweringInfo.h" 40 #include "llvm/CodeGen/GCMetadata.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineJumpTableInfo.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/RuntimeLibcalls.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 56 #include "llvm/CodeGen/StackMaps.h" 57 #include "llvm/CodeGen/SwiftErrorValueTracking.h" 58 #include "llvm/CodeGen/TargetFrameLowering.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/CodeGen/WinEHFuncInfo.h" 66 #include "llvm/IR/Argument.h" 67 #include "llvm/IR/Attributes.h" 68 #include "llvm/IR/BasicBlock.h" 69 #include "llvm/IR/CFG.h" 70 #include "llvm/IR/CallSite.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DebugInfoMetadata.h" 77 #include "llvm/IR/DebugLoc.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/Intrinsics.h" 87 #include "llvm/IR/LLVMContext.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Module.h" 90 #include "llvm/IR/Operator.h" 91 #include "llvm/IR/PatternMatch.h" 92 #include "llvm/IR/Statepoint.h" 93 #include "llvm/IR/Type.h" 94 #include "llvm/IR/User.h" 95 #include "llvm/IR/Value.h" 96 #include "llvm/MC/MCContext.h" 97 #include "llvm/MC/MCSymbol.h" 98 #include "llvm/Support/AtomicOrdering.h" 99 #include "llvm/Support/BranchProbability.h" 100 #include "llvm/Support/Casting.h" 101 #include "llvm/Support/CodeGen.h" 102 #include "llvm/Support/CommandLine.h" 103 #include "llvm/Support/Compiler.h" 104 #include "llvm/Support/Debug.h" 105 #include "llvm/Support/ErrorHandling.h" 106 #include "llvm/Support/MachineValueType.h" 107 #include "llvm/Support/MathExtras.h" 108 #include "llvm/Support/raw_ostream.h" 109 #include "llvm/Target/TargetIntrinsicInfo.h" 110 #include "llvm/Target/TargetMachine.h" 111 #include "llvm/Target/TargetOptions.h" 112 #include "llvm/Transforms/Utils/Local.h" 113 #include <algorithm> 114 #include <cassert> 115 #include <cstddef> 116 #include <cstdint> 117 #include <cstring> 118 #include <iterator> 119 #include <limits> 120 #include <numeric> 121 #include <tuple> 122 #include <utility> 123 #include <vector> 124 125 using namespace llvm; 126 using namespace PatternMatch; 127 using namespace SwitchCG; 128 129 #define DEBUG_TYPE "isel" 130 131 /// LimitFloatPrecision - Generate low-precision inline sequences for 132 /// some float libcalls (6, 8 or 12 bits). 133 static unsigned LimitFloatPrecision; 134 135 static cl::opt<unsigned, true> 136 LimitFPPrecision("limit-float-precision", 137 cl::desc("Generate low-precision inline sequences " 138 "for some float libcalls"), 139 cl::location(LimitFloatPrecision), cl::Hidden, 140 cl::init(0)); 141 142 static cl::opt<unsigned> SwitchPeelThreshold( 143 "switch-peel-threshold", cl::Hidden, cl::init(66), 144 cl::desc("Set the case probability threshold for peeling the case from a " 145 "switch statement. A value greater than 100 will void this " 146 "optimization")); 147 148 // Limit the width of DAG chains. This is important in general to prevent 149 // DAG-based analysis from blowing up. For example, alias analysis and 150 // load clustering may not complete in reasonable time. It is difficult to 151 // recognize and avoid this situation within each individual analysis, and 152 // future analyses are likely to have the same behavior. Limiting DAG width is 153 // the safe approach and will be especially important with global DAGs. 154 // 155 // MaxParallelChains default is arbitrarily high to avoid affecting 156 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 157 // sequence over this should have been converted to llvm.memcpy by the 158 // frontend. It is easy to induce this behavior with .ll code such as: 159 // %buffer = alloca [4096 x i8] 160 // %data = load [4096 x i8]* %argPtr 161 // store [4096 x i8] %data, [4096 x i8]* %buffer 162 static const unsigned MaxParallelChains = 64; 163 164 // Return the calling convention if the Value passed requires ABI mangling as it 165 // is a parameter to a function or a return value from a function which is not 166 // an intrinsic. 167 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 168 if (auto *R = dyn_cast<ReturnInst>(V)) 169 return R->getParent()->getParent()->getCallingConv(); 170 171 if (auto *CI = dyn_cast<CallInst>(V)) { 172 const bool IsInlineAsm = CI->isInlineAsm(); 173 const bool IsIndirectFunctionCall = 174 !IsInlineAsm && !CI->getCalledFunction(); 175 176 // It is possible that the call instruction is an inline asm statement or an 177 // indirect function call in which case the return value of 178 // getCalledFunction() would be nullptr. 179 const bool IsInstrinsicCall = 180 !IsInlineAsm && !IsIndirectFunctionCall && 181 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 182 183 if (!IsInlineAsm && !IsInstrinsicCall) 184 return CI->getCallingConv(); 185 } 186 187 return None; 188 } 189 190 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 191 const SDValue *Parts, unsigned NumParts, 192 MVT PartVT, EVT ValueVT, const Value *V, 193 Optional<CallingConv::ID> CC); 194 195 /// getCopyFromParts - Create a value that contains the specified legal parts 196 /// combined into the value they represent. If the parts combine to a type 197 /// larger than ValueVT then AssertOp can be used to specify whether the extra 198 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 199 /// (ISD::AssertSext). 200 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 201 const SDValue *Parts, unsigned NumParts, 202 MVT PartVT, EVT ValueVT, const Value *V, 203 Optional<CallingConv::ID> CC = None, 204 Optional<ISD::NodeType> AssertOp = None) { 205 if (ValueVT.isVector()) 206 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 207 CC); 208 209 assert(NumParts > 0 && "No parts to assemble!"); 210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 211 SDValue Val = Parts[0]; 212 213 if (NumParts > 1) { 214 // Assemble the value from multiple parts. 215 if (ValueVT.isInteger()) { 216 unsigned PartBits = PartVT.getSizeInBits(); 217 unsigned ValueBits = ValueVT.getSizeInBits(); 218 219 // Assemble the power of 2 part. 220 unsigned RoundParts = 221 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts; 222 unsigned RoundBits = PartBits * RoundParts; 223 EVT RoundVT = RoundBits == ValueBits ? 224 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 225 SDValue Lo, Hi; 226 227 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 228 229 if (RoundParts > 2) { 230 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 231 PartVT, HalfVT, V); 232 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 233 RoundParts / 2, PartVT, HalfVT, V); 234 } else { 235 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 236 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 237 } 238 239 if (DAG.getDataLayout().isBigEndian()) 240 std::swap(Lo, Hi); 241 242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 243 244 if (RoundParts < NumParts) { 245 // Assemble the trailing non-power-of-2 part. 246 unsigned OddParts = NumParts - RoundParts; 247 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 248 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 249 OddVT, V, CC); 250 251 // Combine the round and odd parts. 252 Lo = Val; 253 if (DAG.getDataLayout().isBigEndian()) 254 std::swap(Lo, Hi); 255 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 256 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 257 Hi = 258 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 259 DAG.getConstant(Lo.getValueSizeInBits(), DL, 260 TLI.getPointerTy(DAG.getDataLayout()))); 261 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 262 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 263 } 264 } else if (PartVT.isFloatingPoint()) { 265 // FP split into multiple FP parts (for ppcf128) 266 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 267 "Unexpected split"); 268 SDValue Lo, Hi; 269 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 270 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 271 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 272 std::swap(Lo, Hi); 273 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 274 } else { 275 // FP split into integer parts (soft fp) 276 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 277 !PartVT.isVector() && "Unexpected split"); 278 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 279 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 280 } 281 } 282 283 // There is now one part, held in Val. Correct it to match ValueVT. 284 // PartEVT is the type of the register class that holds the value. 285 // ValueVT is the type of the inline asm operation. 286 EVT PartEVT = Val.getValueType(); 287 288 if (PartEVT == ValueVT) 289 return Val; 290 291 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 292 ValueVT.bitsLT(PartEVT)) { 293 // For an FP value in an integer part, we need to truncate to the right 294 // width first. 295 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 296 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 297 } 298 299 // Handle types that have the same size. 300 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 301 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 302 303 // Handle types with different sizes. 304 if (PartEVT.isInteger() && ValueVT.isInteger()) { 305 if (ValueVT.bitsLT(PartEVT)) { 306 // For a truncate, see if we have any information to 307 // indicate whether the truncated bits will always be 308 // zero or sign-extension. 309 if (AssertOp.hasValue()) 310 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 311 DAG.getValueType(ValueVT)); 312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 313 } 314 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 315 } 316 317 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 318 // FP_ROUND's are always exact here. 319 if (ValueVT.bitsLT(Val.getValueType())) 320 return DAG.getNode( 321 ISD::FP_ROUND, DL, ValueVT, Val, 322 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 323 324 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 325 } 326 327 // Handle MMX to a narrower integer type by bitcasting MMX to integer and 328 // then truncating. 329 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() && 330 ValueVT.bitsLT(PartEVT)) { 331 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val); 332 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 333 } 334 335 report_fatal_error("Unknown mismatch in getCopyFromParts!"); 336 } 337 338 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 339 const Twine &ErrMsg) { 340 const Instruction *I = dyn_cast_or_null<Instruction>(V); 341 if (!V) 342 return Ctx.emitError(ErrMsg); 343 344 const char *AsmError = ", possible invalid constraint for vector type"; 345 if (const CallInst *CI = dyn_cast<CallInst>(I)) 346 if (isa<InlineAsm>(CI->getCalledValue())) 347 return Ctx.emitError(I, ErrMsg + AsmError); 348 349 return Ctx.emitError(I, ErrMsg); 350 } 351 352 /// getCopyFromPartsVector - Create a value that contains the specified legal 353 /// parts combined into the value they represent. If the parts combine to a 354 /// type larger than ValueVT then AssertOp can be used to specify whether the 355 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 356 /// ValueVT (ISD::AssertSext). 357 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 358 const SDValue *Parts, unsigned NumParts, 359 MVT PartVT, EVT ValueVT, const Value *V, 360 Optional<CallingConv::ID> CallConv) { 361 assert(ValueVT.isVector() && "Not a vector value"); 362 assert(NumParts > 0 && "No parts to assemble!"); 363 const bool IsABIRegCopy = CallConv.hasValue(); 364 365 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 366 SDValue Val = Parts[0]; 367 368 // Handle a multi-element vector. 369 if (NumParts > 1) { 370 EVT IntermediateVT; 371 MVT RegisterVT; 372 unsigned NumIntermediates; 373 unsigned NumRegs; 374 375 if (IsABIRegCopy) { 376 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 377 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 378 NumIntermediates, RegisterVT); 379 } else { 380 NumRegs = 381 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 382 NumIntermediates, RegisterVT); 383 } 384 385 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 386 NumParts = NumRegs; // Silence a compiler warning. 387 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 388 assert(RegisterVT.getSizeInBits() == 389 Parts[0].getSimpleValueType().getSizeInBits() && 390 "Part type sizes don't match!"); 391 392 // Assemble the parts into intermediate operands. 393 SmallVector<SDValue, 8> Ops(NumIntermediates); 394 if (NumIntermediates == NumParts) { 395 // If the register was not expanded, truncate or copy the value, 396 // as appropriate. 397 for (unsigned i = 0; i != NumParts; ++i) 398 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 399 PartVT, IntermediateVT, V); 400 } else if (NumParts > 0) { 401 // If the intermediate type was expanded, build the intermediate 402 // operands from the parts. 403 assert(NumParts % NumIntermediates == 0 && 404 "Must expand into a divisible number of parts!"); 405 unsigned Factor = NumParts / NumIntermediates; 406 for (unsigned i = 0; i != NumIntermediates; ++i) 407 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 408 PartVT, IntermediateVT, V); 409 } 410 411 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 412 // intermediate operands. 413 EVT BuiltVectorTy = 414 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 415 (IntermediateVT.isVector() 416 ? IntermediateVT.getVectorNumElements() * NumParts 417 : NumIntermediates)); 418 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 419 : ISD::BUILD_VECTOR, 420 DL, BuiltVectorTy, Ops); 421 } 422 423 // There is now one part, held in Val. Correct it to match ValueVT. 424 EVT PartEVT = Val.getValueType(); 425 426 if (PartEVT == ValueVT) 427 return Val; 428 429 if (PartEVT.isVector()) { 430 // If the element type of the source/dest vectors are the same, but the 431 // parts vector has more elements than the value vector, then we have a 432 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 433 // elements we want. 434 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 435 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 436 "Cannot narrow, it would be a lossy transformation"); 437 return DAG.getNode( 438 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 439 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 440 } 441 442 // Vector/Vector bitcast. 443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 445 446 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 447 "Cannot handle this kind of promotion"); 448 // Promoted vector extract 449 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 450 451 } 452 453 // Trivial bitcast if the types are the same size and the destination 454 // vector type is legal. 455 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 456 TLI.isTypeLegal(ValueVT)) 457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 458 459 if (ValueVT.getVectorNumElements() != 1) { 460 // Certain ABIs require that vectors are passed as integers. For vectors 461 // are the same size, this is an obvious bitcast. 462 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 464 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 465 // Bitcast Val back the original type and extract the corresponding 466 // vector we want. 467 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 468 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 469 ValueVT.getVectorElementType(), Elts); 470 Val = DAG.getBitcast(WiderVecType, Val); 471 return DAG.getNode( 472 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 473 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 474 } 475 476 diagnosePossiblyInvalidConstraint( 477 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 478 return DAG.getUNDEF(ValueVT); 479 } 480 481 // Handle cases such as i8 -> <1 x i1> 482 EVT ValueSVT = ValueVT.getVectorElementType(); 483 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 484 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 485 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 486 487 return DAG.getBuildVector(ValueVT, DL, Val); 488 } 489 490 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 491 SDValue Val, SDValue *Parts, unsigned NumParts, 492 MVT PartVT, const Value *V, 493 Optional<CallingConv::ID> CallConv); 494 495 /// getCopyToParts - Create a series of nodes that contain the specified value 496 /// split into legal parts. If the parts contain more bits than Val, then, for 497 /// integers, ExtendKind can be used to specify how to generate the extra bits. 498 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 499 SDValue *Parts, unsigned NumParts, MVT PartVT, 500 const Value *V, 501 Optional<CallingConv::ID> CallConv = None, 502 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 503 EVT ValueVT = Val.getValueType(); 504 505 // Handle the vector case separately. 506 if (ValueVT.isVector()) 507 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 508 CallConv); 509 510 unsigned PartBits = PartVT.getSizeInBits(); 511 unsigned OrigNumParts = NumParts; 512 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 513 "Copying to an illegal type!"); 514 515 if (NumParts == 0) 516 return; 517 518 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 519 EVT PartEVT = PartVT; 520 if (PartEVT == ValueVT) { 521 assert(NumParts == 1 && "No-op copy with multiple parts!"); 522 Parts[0] = Val; 523 return; 524 } 525 526 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 527 // If the parts cover more bits than the value has, promote the value. 528 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 529 assert(NumParts == 1 && "Do not know what to promote to!"); 530 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 531 } else { 532 if (ValueVT.isFloatingPoint()) { 533 // FP values need to be bitcast, then extended if they are being put 534 // into a larger container. 535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 536 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 537 } 538 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 539 ValueVT.isInteger() && 540 "Unknown mismatch!"); 541 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 542 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 543 if (PartVT == MVT::x86mmx) 544 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 545 } 546 } else if (PartBits == ValueVT.getSizeInBits()) { 547 // Different types of the same size. 548 assert(NumParts == 1 && PartEVT != ValueVT); 549 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 550 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 551 // If the parts cover less bits than value has, truncate the value. 552 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 553 ValueVT.isInteger() && 554 "Unknown mismatch!"); 555 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 556 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 557 if (PartVT == MVT::x86mmx) 558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 559 } 560 561 // The value may have changed - recompute ValueVT. 562 ValueVT = Val.getValueType(); 563 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 564 "Failed to tile the value with PartVT!"); 565 566 if (NumParts == 1) { 567 if (PartEVT != ValueVT) { 568 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 569 "scalar-to-vector conversion failed"); 570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 571 } 572 573 Parts[0] = Val; 574 return; 575 } 576 577 // Expand the value into multiple parts. 578 if (NumParts & (NumParts - 1)) { 579 // The number of parts is not a power of 2. Split off and copy the tail. 580 assert(PartVT.isInteger() && ValueVT.isInteger() && 581 "Do not know what to expand to!"); 582 unsigned RoundParts = 1 << Log2_32(NumParts); 583 unsigned RoundBits = RoundParts * PartBits; 584 unsigned OddParts = NumParts - RoundParts; 585 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 586 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 587 588 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 589 CallConv); 590 591 if (DAG.getDataLayout().isBigEndian()) 592 // The odd parts were reversed by getCopyToParts - unreverse them. 593 std::reverse(Parts + RoundParts, Parts + NumParts); 594 595 NumParts = RoundParts; 596 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 597 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 598 } 599 600 // The number of parts is a power of 2. Repeatedly bisect the value using 601 // EXTRACT_ELEMENT. 602 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 603 EVT::getIntegerVT(*DAG.getContext(), 604 ValueVT.getSizeInBits()), 605 Val); 606 607 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 608 for (unsigned i = 0; i < NumParts; i += StepSize) { 609 unsigned ThisBits = StepSize * PartBits / 2; 610 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 611 SDValue &Part0 = Parts[i]; 612 SDValue &Part1 = Parts[i+StepSize/2]; 613 614 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 615 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 616 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 617 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 618 619 if (ThisBits == PartBits && ThisVT != PartVT) { 620 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 621 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 622 } 623 } 624 } 625 626 if (DAG.getDataLayout().isBigEndian()) 627 std::reverse(Parts, Parts + OrigNumParts); 628 } 629 630 static SDValue widenVectorToPartType(SelectionDAG &DAG, 631 SDValue Val, const SDLoc &DL, EVT PartVT) { 632 if (!PartVT.isVector()) 633 return SDValue(); 634 635 EVT ValueVT = Val.getValueType(); 636 unsigned PartNumElts = PartVT.getVectorNumElements(); 637 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 638 if (PartNumElts > ValueNumElts && 639 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 640 EVT ElementVT = PartVT.getVectorElementType(); 641 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 642 // undef elements. 643 SmallVector<SDValue, 16> Ops; 644 DAG.ExtractVectorElements(Val, Ops); 645 SDValue EltUndef = DAG.getUNDEF(ElementVT); 646 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 647 Ops.push_back(EltUndef); 648 649 // FIXME: Use CONCAT for 2x -> 4x. 650 return DAG.getBuildVector(PartVT, DL, Ops); 651 } 652 653 return SDValue(); 654 } 655 656 /// getCopyToPartsVector - Create a series of nodes that contain the specified 657 /// value split into legal parts. 658 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 659 SDValue Val, SDValue *Parts, unsigned NumParts, 660 MVT PartVT, const Value *V, 661 Optional<CallingConv::ID> CallConv) { 662 EVT ValueVT = Val.getValueType(); 663 assert(ValueVT.isVector() && "Not a vector"); 664 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 665 const bool IsABIRegCopy = CallConv.hasValue(); 666 667 if (NumParts == 1) { 668 EVT PartEVT = PartVT; 669 if (PartEVT == ValueVT) { 670 // Nothing to do. 671 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 672 // Bitconvert vector->vector case. 673 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 674 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 675 Val = Widened; 676 } else if (PartVT.isVector() && 677 PartEVT.getVectorElementType().bitsGE( 678 ValueVT.getVectorElementType()) && 679 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 680 681 // Promoted vector extract 682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 683 } else { 684 if (ValueVT.getVectorNumElements() == 1) { 685 Val = DAG.getNode( 686 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 687 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 688 } else { 689 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 690 "lossy conversion of vector to scalar type"); 691 EVT IntermediateType = 692 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 693 Val = DAG.getBitcast(IntermediateType, Val); 694 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 695 } 696 } 697 698 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 699 Parts[0] = Val; 700 return; 701 } 702 703 // Handle a multi-element vector. 704 EVT IntermediateVT; 705 MVT RegisterVT; 706 unsigned NumIntermediates; 707 unsigned NumRegs; 708 if (IsABIRegCopy) { 709 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 710 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 711 NumIntermediates, RegisterVT); 712 } else { 713 NumRegs = 714 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 715 NumIntermediates, RegisterVT); 716 } 717 718 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 719 NumParts = NumRegs; // Silence a compiler warning. 720 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 721 722 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 723 IntermediateVT.getVectorNumElements() : 1; 724 725 // Convert the vector to the appropiate type if necessary. 726 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 727 728 EVT BuiltVectorTy = EVT::getVectorVT( 729 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 730 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 731 if (ValueVT != BuiltVectorTy) { 732 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 733 Val = Widened; 734 735 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 736 } 737 738 // Split the vector into intermediate operands. 739 SmallVector<SDValue, 8> Ops(NumIntermediates); 740 for (unsigned i = 0; i != NumIntermediates; ++i) { 741 if (IntermediateVT.isVector()) { 742 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 743 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 744 } else { 745 Ops[i] = DAG.getNode( 746 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 747 DAG.getConstant(i, DL, IdxVT)); 748 } 749 } 750 751 // Split the intermediate operands into legal parts. 752 if (NumParts == NumIntermediates) { 753 // If the register was not expanded, promote or copy the value, 754 // as appropriate. 755 for (unsigned i = 0; i != NumParts; ++i) 756 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 757 } else if (NumParts > 0) { 758 // If the intermediate type was expanded, split each the value into 759 // legal parts. 760 assert(NumIntermediates != 0 && "division by zero"); 761 assert(NumParts % NumIntermediates == 0 && 762 "Must expand into a divisible number of parts!"); 763 unsigned Factor = NumParts / NumIntermediates; 764 for (unsigned i = 0; i != NumIntermediates; ++i) 765 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 766 CallConv); 767 } 768 } 769 770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 771 EVT valuevt, Optional<CallingConv::ID> CC) 772 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 773 RegCount(1, regs.size()), CallConv(CC) {} 774 775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 776 const DataLayout &DL, unsigned Reg, Type *Ty, 777 Optional<CallingConv::ID> CC) { 778 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 779 780 CallConv = CC; 781 782 for (EVT ValueVT : ValueVTs) { 783 unsigned NumRegs = 784 isABIMangled() 785 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 786 : TLI.getNumRegisters(Context, ValueVT); 787 MVT RegisterVT = 788 isABIMangled() 789 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 790 : TLI.getRegisterType(Context, ValueVT); 791 for (unsigned i = 0; i != NumRegs; ++i) 792 Regs.push_back(Reg + i); 793 RegVTs.push_back(RegisterVT); 794 RegCount.push_back(NumRegs); 795 Reg += NumRegs; 796 } 797 } 798 799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 800 FunctionLoweringInfo &FuncInfo, 801 const SDLoc &dl, SDValue &Chain, 802 SDValue *Flag, const Value *V) const { 803 // A Value with type {} or [0 x %t] needs no registers. 804 if (ValueVTs.empty()) 805 return SDValue(); 806 807 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 808 809 // Assemble the legal parts into the final values. 810 SmallVector<SDValue, 4> Values(ValueVTs.size()); 811 SmallVector<SDValue, 8> Parts; 812 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 813 // Copy the legal parts from the registers. 814 EVT ValueVT = ValueVTs[Value]; 815 unsigned NumRegs = RegCount[Value]; 816 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 817 *DAG.getContext(), 818 CallConv.getValue(), RegVTs[Value]) 819 : RegVTs[Value]; 820 821 Parts.resize(NumRegs); 822 for (unsigned i = 0; i != NumRegs; ++i) { 823 SDValue P; 824 if (!Flag) { 825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 826 } else { 827 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 828 *Flag = P.getValue(2); 829 } 830 831 Chain = P.getValue(1); 832 Parts[i] = P; 833 834 // If the source register was virtual and if we know something about it, 835 // add an assert node. 836 if (!Register::isVirtualRegister(Regs[Part + i]) || 837 !RegisterVT.isInteger()) 838 continue; 839 840 const FunctionLoweringInfo::LiveOutInfo *LOI = 841 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 842 if (!LOI) 843 continue; 844 845 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 846 unsigned NumSignBits = LOI->NumSignBits; 847 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 848 849 if (NumZeroBits == RegSize) { 850 // The current value is a zero. 851 // Explicitly express that as it would be easier for 852 // optimizations to kick in. 853 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 854 continue; 855 } 856 857 // FIXME: We capture more information than the dag can represent. For 858 // now, just use the tightest assertzext/assertsext possible. 859 bool isSExt; 860 EVT FromVT(MVT::Other); 861 if (NumZeroBits) { 862 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 863 isSExt = false; 864 } else if (NumSignBits > 1) { 865 FromVT = 866 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 867 isSExt = true; 868 } else { 869 continue; 870 } 871 // Add an assertion node. 872 assert(FromVT != MVT::Other); 873 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 874 RegisterVT, P, DAG.getValueType(FromVT)); 875 } 876 877 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 878 RegisterVT, ValueVT, V, CallConv); 879 Part += NumRegs; 880 Parts.clear(); 881 } 882 883 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 884 } 885 886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 887 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 888 const Value *V, 889 ISD::NodeType PreferredExtendType) const { 890 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 891 ISD::NodeType ExtendKind = PreferredExtendType; 892 893 // Get the list of the values's legal parts. 894 unsigned NumRegs = Regs.size(); 895 SmallVector<SDValue, 8> Parts(NumRegs); 896 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 897 unsigned NumParts = RegCount[Value]; 898 899 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 900 *DAG.getContext(), 901 CallConv.getValue(), RegVTs[Value]) 902 : RegVTs[Value]; 903 904 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 905 ExtendKind = ISD::ZERO_EXTEND; 906 907 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 908 NumParts, RegisterVT, V, CallConv, ExtendKind); 909 Part += NumParts; 910 } 911 912 // Copy the parts into the registers. 913 SmallVector<SDValue, 8> Chains(NumRegs); 914 for (unsigned i = 0; i != NumRegs; ++i) { 915 SDValue Part; 916 if (!Flag) { 917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 918 } else { 919 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 920 *Flag = Part.getValue(1); 921 } 922 923 Chains[i] = Part.getValue(0); 924 } 925 926 if (NumRegs == 1 || Flag) 927 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 928 // flagged to it. That is the CopyToReg nodes and the user are considered 929 // a single scheduling unit. If we create a TokenFactor and return it as 930 // chain, then the TokenFactor is both a predecessor (operand) of the 931 // user as well as a successor (the TF operands are flagged to the user). 932 // c1, f1 = CopyToReg 933 // c2, f2 = CopyToReg 934 // c3 = TokenFactor c1, c2 935 // ... 936 // = op c3, ..., f2 937 Chain = Chains[NumRegs-1]; 938 else 939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 940 } 941 942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 943 unsigned MatchingIdx, const SDLoc &dl, 944 SelectionDAG &DAG, 945 std::vector<SDValue> &Ops) const { 946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 947 948 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 949 if (HasMatching) 950 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 951 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) { 952 // Put the register class of the virtual registers in the flag word. That 953 // way, later passes can recompute register class constraints for inline 954 // assembly as well as normal instructions. 955 // Don't do this for tied operands that can use the regclass information 956 // from the def. 957 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 958 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 959 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 960 } 961 962 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 963 Ops.push_back(Res); 964 965 if (Code == InlineAsm::Kind_Clobber) { 966 // Clobbers should always have a 1:1 mapping with registers, and may 967 // reference registers that have illegal (e.g. vector) types. Hence, we 968 // shouldn't try to apply any sort of splitting logic to them. 969 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 970 "No 1:1 mapping from clobbers to regs?"); 971 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 972 (void)SP; 973 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 974 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 975 assert( 976 (Regs[I] != SP || 977 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 978 "If we clobbered the stack pointer, MFI should know about it."); 979 } 980 return; 981 } 982 983 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 984 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 985 MVT RegisterVT = RegVTs[Value]; 986 for (unsigned i = 0; i != NumRegs; ++i) { 987 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 988 unsigned TheReg = Regs[Reg++]; 989 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 990 } 991 } 992 } 993 994 SmallVector<std::pair<unsigned, unsigned>, 4> 995 RegsForValue::getRegsAndSizes() const { 996 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 997 unsigned I = 0; 998 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 999 unsigned RegCount = std::get<0>(CountAndVT); 1000 MVT RegisterVT = std::get<1>(CountAndVT); 1001 unsigned RegisterSize = RegisterVT.getSizeInBits(); 1002 for (unsigned E = I + RegCount; I != E; ++I) 1003 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 1004 } 1005 return OutVec; 1006 } 1007 1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1009 const TargetLibraryInfo *li) { 1010 AA = aa; 1011 GFI = gfi; 1012 LibInfo = li; 1013 DL = &DAG.getDataLayout(); 1014 Context = DAG.getContext(); 1015 LPadToCallSiteMap.clear(); 1016 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout()); 1017 } 1018 1019 void SelectionDAGBuilder::clear() { 1020 NodeMap.clear(); 1021 UnusedArgNodeMap.clear(); 1022 PendingLoads.clear(); 1023 PendingExports.clear(); 1024 CurInst = nullptr; 1025 HasTailCall = false; 1026 SDNodeOrder = LowestSDNodeOrder; 1027 StatepointLowering.clear(); 1028 } 1029 1030 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1031 DanglingDebugInfoMap.clear(); 1032 } 1033 1034 SDValue SelectionDAGBuilder::getRoot() { 1035 if (PendingLoads.empty()) 1036 return DAG.getRoot(); 1037 1038 if (PendingLoads.size() == 1) { 1039 SDValue Root = PendingLoads[0]; 1040 DAG.setRoot(Root); 1041 PendingLoads.clear(); 1042 return Root; 1043 } 1044 1045 // Otherwise, we have to make a token factor node. 1046 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1047 PendingLoads.clear(); 1048 DAG.setRoot(Root); 1049 return Root; 1050 } 1051 1052 SDValue SelectionDAGBuilder::getControlRoot() { 1053 SDValue Root = DAG.getRoot(); 1054 1055 if (PendingExports.empty()) 1056 return Root; 1057 1058 // Turn all of the CopyToReg chains into one factored node. 1059 if (Root.getOpcode() != ISD::EntryToken) { 1060 unsigned i = 0, e = PendingExports.size(); 1061 for (; i != e; ++i) { 1062 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1063 if (PendingExports[i].getNode()->getOperand(0) == Root) 1064 break; // Don't add the root if we already indirectly depend on it. 1065 } 1066 1067 if (i == e) 1068 PendingExports.push_back(Root); 1069 } 1070 1071 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1072 PendingExports); 1073 PendingExports.clear(); 1074 DAG.setRoot(Root); 1075 return Root; 1076 } 1077 1078 void SelectionDAGBuilder::visit(const Instruction &I) { 1079 // Set up outgoing PHI node register values before emitting the terminator. 1080 if (I.isTerminator()) { 1081 HandlePHINodesInSuccessorBlocks(I.getParent()); 1082 } 1083 1084 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1085 if (!isa<DbgInfoIntrinsic>(I)) 1086 ++SDNodeOrder; 1087 1088 CurInst = &I; 1089 1090 visit(I.getOpcode(), I); 1091 1092 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1093 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1094 // maps to this instruction. 1095 // TODO: We could handle all flags (nsw, etc) here. 1096 // TODO: If an IR instruction maps to >1 node, only the final node will have 1097 // flags set. 1098 if (SDNode *Node = getNodeForIRValue(&I)) { 1099 SDNodeFlags IncomingFlags; 1100 IncomingFlags.copyFMF(*FPMO); 1101 if (!Node->getFlags().isDefined()) 1102 Node->setFlags(IncomingFlags); 1103 else 1104 Node->intersectFlagsWith(IncomingFlags); 1105 } 1106 } 1107 1108 if (!I.isTerminator() && !HasTailCall && 1109 !isStatepoint(&I)) // statepoints handle their exports internally 1110 CopyToExportRegsIfNeeded(&I); 1111 1112 CurInst = nullptr; 1113 } 1114 1115 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1116 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1117 } 1118 1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1120 // Note: this doesn't use InstVisitor, because it has to work with 1121 // ConstantExpr's in addition to instructions. 1122 switch (Opcode) { 1123 default: llvm_unreachable("Unknown instruction type encountered!"); 1124 // Build the switch statement using the Instruction.def file. 1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1126 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1127 #include "llvm/IR/Instruction.def" 1128 } 1129 } 1130 1131 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1132 const DIExpression *Expr) { 1133 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1134 const DbgValueInst *DI = DDI.getDI(); 1135 DIVariable *DanglingVariable = DI->getVariable(); 1136 DIExpression *DanglingExpr = DI->getExpression(); 1137 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1138 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1139 return true; 1140 } 1141 return false; 1142 }; 1143 1144 for (auto &DDIMI : DanglingDebugInfoMap) { 1145 DanglingDebugInfoVector &DDIV = DDIMI.second; 1146 1147 // If debug info is to be dropped, run it through final checks to see 1148 // whether it can be salvaged. 1149 for (auto &DDI : DDIV) 1150 if (isMatchingDbgValue(DDI)) 1151 salvageUnresolvedDbgValue(DDI); 1152 1153 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1154 } 1155 } 1156 1157 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1158 // generate the debug data structures now that we've seen its definition. 1159 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1160 SDValue Val) { 1161 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1162 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1163 return; 1164 1165 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1166 for (auto &DDI : DDIV) { 1167 const DbgValueInst *DI = DDI.getDI(); 1168 assert(DI && "Ill-formed DanglingDebugInfo"); 1169 DebugLoc dl = DDI.getdl(); 1170 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1171 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1172 DILocalVariable *Variable = DI->getVariable(); 1173 DIExpression *Expr = DI->getExpression(); 1174 assert(Variable->isValidLocationForIntrinsic(dl) && 1175 "Expected inlined-at fields to agree"); 1176 SDDbgValue *SDV; 1177 if (Val.getNode()) { 1178 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1179 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1180 // we couldn't resolve it directly when examining the DbgValue intrinsic 1181 // in the first place we should not be more successful here). Unless we 1182 // have some test case that prove this to be correct we should avoid 1183 // calling EmitFuncArgumentDbgValue here. 1184 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1185 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1186 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1187 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1188 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1189 // inserted after the definition of Val when emitting the instructions 1190 // after ISel. An alternative could be to teach 1191 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1192 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1193 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1194 << ValSDNodeOrder << "\n"); 1195 SDV = getDbgValue(Val, Variable, Expr, dl, 1196 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1197 DAG.AddDbgValue(SDV, Val.getNode(), false); 1198 } else 1199 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1200 << "in EmitFuncArgumentDbgValue\n"); 1201 } else { 1202 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1203 auto Undef = 1204 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1205 auto SDV = 1206 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1207 DAG.AddDbgValue(SDV, nullptr, false); 1208 } 1209 } 1210 DDIV.clear(); 1211 } 1212 1213 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1214 Value *V = DDI.getDI()->getValue(); 1215 DILocalVariable *Var = DDI.getDI()->getVariable(); 1216 DIExpression *Expr = DDI.getDI()->getExpression(); 1217 DebugLoc DL = DDI.getdl(); 1218 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1219 unsigned SDOrder = DDI.getSDNodeOrder(); 1220 1221 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1222 // that DW_OP_stack_value is desired. 1223 assert(isa<DbgValueInst>(DDI.getDI())); 1224 bool StackValue = true; 1225 1226 // Can this Value can be encoded without any further work? 1227 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1228 return; 1229 1230 // Attempt to salvage back through as many instructions as possible. Bail if 1231 // a non-instruction is seen, such as a constant expression or global 1232 // variable. FIXME: Further work could recover those too. 1233 while (isa<Instruction>(V)) { 1234 Instruction &VAsInst = *cast<Instruction>(V); 1235 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1236 1237 // If we cannot salvage any further, and haven't yet found a suitable debug 1238 // expression, bail out. 1239 if (!NewExpr) 1240 break; 1241 1242 // New value and expr now represent this debuginfo. 1243 V = VAsInst.getOperand(0); 1244 Expr = NewExpr; 1245 1246 // Some kind of simplification occurred: check whether the operand of the 1247 // salvaged debug expression can be encoded in this DAG. 1248 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1249 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1250 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1251 return; 1252 } 1253 } 1254 1255 // This was the final opportunity to salvage this debug information, and it 1256 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1257 // any earlier variable location. 1258 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1259 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1260 DAG.AddDbgValue(SDV, nullptr, false); 1261 1262 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1263 << "\n"); 1264 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1265 << "\n"); 1266 } 1267 1268 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1269 DIExpression *Expr, DebugLoc dl, 1270 DebugLoc InstDL, unsigned Order) { 1271 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1272 SDDbgValue *SDV; 1273 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1274 isa<ConstantPointerNull>(V)) { 1275 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1276 DAG.AddDbgValue(SDV, nullptr, false); 1277 return true; 1278 } 1279 1280 // If the Value is a frame index, we can create a FrameIndex debug value 1281 // without relying on the DAG at all. 1282 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1283 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1284 if (SI != FuncInfo.StaticAllocaMap.end()) { 1285 auto SDV = 1286 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1287 /*IsIndirect*/ false, dl, SDNodeOrder); 1288 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1289 // is still available even if the SDNode gets optimized out. 1290 DAG.AddDbgValue(SDV, nullptr, false); 1291 return true; 1292 } 1293 } 1294 1295 // Do not use getValue() in here; we don't want to generate code at 1296 // this point if it hasn't been done yet. 1297 SDValue N = NodeMap[V]; 1298 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1299 N = UnusedArgNodeMap[V]; 1300 if (N.getNode()) { 1301 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1302 return true; 1303 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1304 DAG.AddDbgValue(SDV, N.getNode(), false); 1305 return true; 1306 } 1307 1308 // Special rules apply for the first dbg.values of parameter variables in a 1309 // function. Identify them by the fact they reference Argument Values, that 1310 // they're parameters, and they are parameters of the current function. We 1311 // need to let them dangle until they get an SDNode. 1312 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1313 !InstDL.getInlinedAt(); 1314 if (!IsParamOfFunc) { 1315 // The value is not used in this block yet (or it would have an SDNode). 1316 // We still want the value to appear for the user if possible -- if it has 1317 // an associated VReg, we can refer to that instead. 1318 auto VMI = FuncInfo.ValueMap.find(V); 1319 if (VMI != FuncInfo.ValueMap.end()) { 1320 unsigned Reg = VMI->second; 1321 // If this is a PHI node, it may be split up into several MI PHI nodes 1322 // (in FunctionLoweringInfo::set). 1323 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1324 V->getType(), None); 1325 if (RFV.occupiesMultipleRegs()) { 1326 unsigned Offset = 0; 1327 unsigned BitsToDescribe = 0; 1328 if (auto VarSize = Var->getSizeInBits()) 1329 BitsToDescribe = *VarSize; 1330 if (auto Fragment = Expr->getFragmentInfo()) 1331 BitsToDescribe = Fragment->SizeInBits; 1332 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1333 unsigned RegisterSize = RegAndSize.second; 1334 // Bail out if all bits are described already. 1335 if (Offset >= BitsToDescribe) 1336 break; 1337 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1338 ? BitsToDescribe - Offset 1339 : RegisterSize; 1340 auto FragmentExpr = DIExpression::createFragmentExpression( 1341 Expr, Offset, FragmentSize); 1342 if (!FragmentExpr) 1343 continue; 1344 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1345 false, dl, SDNodeOrder); 1346 DAG.AddDbgValue(SDV, nullptr, false); 1347 Offset += RegisterSize; 1348 } 1349 } else { 1350 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1351 DAG.AddDbgValue(SDV, nullptr, false); 1352 } 1353 return true; 1354 } 1355 } 1356 1357 return false; 1358 } 1359 1360 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1361 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1362 for (auto &Pair : DanglingDebugInfoMap) 1363 for (auto &DDI : Pair.second) 1364 salvageUnresolvedDbgValue(DDI); 1365 clearDanglingDebugInfo(); 1366 } 1367 1368 /// getCopyFromRegs - If there was virtual register allocated for the value V 1369 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1370 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1371 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1372 SDValue Result; 1373 1374 if (It != FuncInfo.ValueMap.end()) { 1375 unsigned InReg = It->second; 1376 1377 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1378 DAG.getDataLayout(), InReg, Ty, 1379 None); // This is not an ABI copy. 1380 SDValue Chain = DAG.getEntryNode(); 1381 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1382 V); 1383 resolveDanglingDebugInfo(V, Result); 1384 } 1385 1386 return Result; 1387 } 1388 1389 /// getValue - Return an SDValue for the given Value. 1390 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1391 // If we already have an SDValue for this value, use it. It's important 1392 // to do this first, so that we don't create a CopyFromReg if we already 1393 // have a regular SDValue. 1394 SDValue &N = NodeMap[V]; 1395 if (N.getNode()) return N; 1396 1397 // If there's a virtual register allocated and initialized for this 1398 // value, use it. 1399 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1400 return copyFromReg; 1401 1402 // Otherwise create a new SDValue and remember it. 1403 SDValue Val = getValueImpl(V); 1404 NodeMap[V] = Val; 1405 resolveDanglingDebugInfo(V, Val); 1406 return Val; 1407 } 1408 1409 // Return true if SDValue exists for the given Value 1410 bool SelectionDAGBuilder::findValue(const Value *V) const { 1411 return (NodeMap.find(V) != NodeMap.end()) || 1412 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1413 } 1414 1415 /// getNonRegisterValue - Return an SDValue for the given Value, but 1416 /// don't look in FuncInfo.ValueMap for a virtual register. 1417 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1418 // If we already have an SDValue for this value, use it. 1419 SDValue &N = NodeMap[V]; 1420 if (N.getNode()) { 1421 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1422 // Remove the debug location from the node as the node is about to be used 1423 // in a location which may differ from the original debug location. This 1424 // is relevant to Constant and ConstantFP nodes because they can appear 1425 // as constant expressions inside PHI nodes. 1426 N->setDebugLoc(DebugLoc()); 1427 } 1428 return N; 1429 } 1430 1431 // Otherwise create a new SDValue and remember it. 1432 SDValue Val = getValueImpl(V); 1433 NodeMap[V] = Val; 1434 resolveDanglingDebugInfo(V, Val); 1435 return Val; 1436 } 1437 1438 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1439 /// Create an SDValue for the given value. 1440 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1441 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1442 1443 if (const Constant *C = dyn_cast<Constant>(V)) { 1444 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1445 1446 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1447 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1448 1449 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1450 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1451 1452 if (isa<ConstantPointerNull>(C)) { 1453 unsigned AS = V->getType()->getPointerAddressSpace(); 1454 return DAG.getConstant(0, getCurSDLoc(), 1455 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1456 } 1457 1458 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1459 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1460 1461 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1462 return DAG.getUNDEF(VT); 1463 1464 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1465 visit(CE->getOpcode(), *CE); 1466 SDValue N1 = NodeMap[V]; 1467 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1468 return N1; 1469 } 1470 1471 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1472 SmallVector<SDValue, 4> Constants; 1473 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1474 OI != OE; ++OI) { 1475 SDNode *Val = getValue(*OI).getNode(); 1476 // If the operand is an empty aggregate, there are no values. 1477 if (!Val) continue; 1478 // Add each leaf value from the operand to the Constants list 1479 // to form a flattened list of all the values. 1480 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1481 Constants.push_back(SDValue(Val, i)); 1482 } 1483 1484 return DAG.getMergeValues(Constants, getCurSDLoc()); 1485 } 1486 1487 if (const ConstantDataSequential *CDS = 1488 dyn_cast<ConstantDataSequential>(C)) { 1489 SmallVector<SDValue, 4> Ops; 1490 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1491 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1492 // Add each leaf value from the operand to the Constants list 1493 // to form a flattened list of all the values. 1494 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1495 Ops.push_back(SDValue(Val, i)); 1496 } 1497 1498 if (isa<ArrayType>(CDS->getType())) 1499 return DAG.getMergeValues(Ops, getCurSDLoc()); 1500 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1501 } 1502 1503 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1504 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1505 "Unknown struct or array constant!"); 1506 1507 SmallVector<EVT, 4> ValueVTs; 1508 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1509 unsigned NumElts = ValueVTs.size(); 1510 if (NumElts == 0) 1511 return SDValue(); // empty struct 1512 SmallVector<SDValue, 4> Constants(NumElts); 1513 for (unsigned i = 0; i != NumElts; ++i) { 1514 EVT EltVT = ValueVTs[i]; 1515 if (isa<UndefValue>(C)) 1516 Constants[i] = DAG.getUNDEF(EltVT); 1517 else if (EltVT.isFloatingPoint()) 1518 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1519 else 1520 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1521 } 1522 1523 return DAG.getMergeValues(Constants, getCurSDLoc()); 1524 } 1525 1526 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1527 return DAG.getBlockAddress(BA, VT); 1528 1529 VectorType *VecTy = cast<VectorType>(V->getType()); 1530 unsigned NumElements = VecTy->getNumElements(); 1531 1532 // Now that we know the number and type of the elements, get that number of 1533 // elements into the Ops array based on what kind of constant it is. 1534 SmallVector<SDValue, 16> Ops; 1535 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1536 for (unsigned i = 0; i != NumElements; ++i) 1537 Ops.push_back(getValue(CV->getOperand(i))); 1538 } else { 1539 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1540 EVT EltVT = 1541 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1542 1543 SDValue Op; 1544 if (EltVT.isFloatingPoint()) 1545 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1546 else 1547 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1548 Ops.assign(NumElements, Op); 1549 } 1550 1551 // Create a BUILD_VECTOR node. 1552 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1553 } 1554 1555 // If this is a static alloca, generate it as the frameindex instead of 1556 // computation. 1557 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1558 DenseMap<const AllocaInst*, int>::iterator SI = 1559 FuncInfo.StaticAllocaMap.find(AI); 1560 if (SI != FuncInfo.StaticAllocaMap.end()) 1561 return DAG.getFrameIndex(SI->second, 1562 TLI.getFrameIndexTy(DAG.getDataLayout())); 1563 } 1564 1565 // If this is an instruction which fast-isel has deferred, select it now. 1566 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1567 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1568 1569 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1570 Inst->getType(), getABIRegCopyCC(V)); 1571 SDValue Chain = DAG.getEntryNode(); 1572 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1573 } 1574 1575 llvm_unreachable("Can't get register for value!"); 1576 } 1577 1578 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1579 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1580 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1581 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1582 bool IsSEH = isAsynchronousEHPersonality(Pers); 1583 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1584 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1585 if (!IsSEH) 1586 CatchPadMBB->setIsEHScopeEntry(); 1587 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1588 if (IsMSVCCXX || IsCoreCLR) 1589 CatchPadMBB->setIsEHFuncletEntry(); 1590 // Wasm does not need catchpads anymore 1591 if (!IsWasmCXX) 1592 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1593 getControlRoot())); 1594 } 1595 1596 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1597 // Update machine-CFG edge. 1598 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1599 FuncInfo.MBB->addSuccessor(TargetMBB); 1600 1601 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1602 bool IsSEH = isAsynchronousEHPersonality(Pers); 1603 if (IsSEH) { 1604 // If this is not a fall-through branch or optimizations are switched off, 1605 // emit the branch. 1606 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1607 TM.getOptLevel() == CodeGenOpt::None) 1608 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1609 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1610 return; 1611 } 1612 1613 // Figure out the funclet membership for the catchret's successor. 1614 // This will be used by the FuncletLayout pass to determine how to order the 1615 // BB's. 1616 // A 'catchret' returns to the outer scope's color. 1617 Value *ParentPad = I.getCatchSwitchParentPad(); 1618 const BasicBlock *SuccessorColor; 1619 if (isa<ConstantTokenNone>(ParentPad)) 1620 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1621 else 1622 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1623 assert(SuccessorColor && "No parent funclet for catchret!"); 1624 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1625 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1626 1627 // Create the terminator node. 1628 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1629 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1630 DAG.getBasicBlock(SuccessorColorMBB)); 1631 DAG.setRoot(Ret); 1632 } 1633 1634 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1635 // Don't emit any special code for the cleanuppad instruction. It just marks 1636 // the start of an EH scope/funclet. 1637 FuncInfo.MBB->setIsEHScopeEntry(); 1638 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1639 if (Pers != EHPersonality::Wasm_CXX) { 1640 FuncInfo.MBB->setIsEHFuncletEntry(); 1641 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1642 } 1643 } 1644 1645 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1646 // the control flow always stops at the single catch pad, as it does for a 1647 // cleanup pad. In case the exception caught is not of the types the catch pad 1648 // catches, it will be rethrown by a rethrow. 1649 static void findWasmUnwindDestinations( 1650 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1651 BranchProbability Prob, 1652 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1653 &UnwindDests) { 1654 while (EHPadBB) { 1655 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1656 if (isa<CleanupPadInst>(Pad)) { 1657 // Stop on cleanup pads. 1658 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1659 UnwindDests.back().first->setIsEHScopeEntry(); 1660 break; 1661 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1662 // Add the catchpad handlers to the possible destinations. We don't 1663 // continue to the unwind destination of the catchswitch for wasm. 1664 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1665 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1666 UnwindDests.back().first->setIsEHScopeEntry(); 1667 } 1668 break; 1669 } else { 1670 continue; 1671 } 1672 } 1673 } 1674 1675 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1676 /// many places it could ultimately go. In the IR, we have a single unwind 1677 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1678 /// This function skips over imaginary basic blocks that hold catchswitch 1679 /// instructions, and finds all the "real" machine 1680 /// basic block destinations. As those destinations may not be successors of 1681 /// EHPadBB, here we also calculate the edge probability to those destinations. 1682 /// The passed-in Prob is the edge probability to EHPadBB. 1683 static void findUnwindDestinations( 1684 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1685 BranchProbability Prob, 1686 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1687 &UnwindDests) { 1688 EHPersonality Personality = 1689 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1690 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1691 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1692 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1693 bool IsSEH = isAsynchronousEHPersonality(Personality); 1694 1695 if (IsWasmCXX) { 1696 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1697 assert(UnwindDests.size() <= 1 && 1698 "There should be at most one unwind destination for wasm"); 1699 return; 1700 } 1701 1702 while (EHPadBB) { 1703 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1704 BasicBlock *NewEHPadBB = nullptr; 1705 if (isa<LandingPadInst>(Pad)) { 1706 // Stop on landingpads. They are not funclets. 1707 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1708 break; 1709 } else if (isa<CleanupPadInst>(Pad)) { 1710 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1711 // personalities. 1712 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1713 UnwindDests.back().first->setIsEHScopeEntry(); 1714 UnwindDests.back().first->setIsEHFuncletEntry(); 1715 break; 1716 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1717 // Add the catchpad handlers to the possible destinations. 1718 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1719 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1720 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1721 if (IsMSVCCXX || IsCoreCLR) 1722 UnwindDests.back().first->setIsEHFuncletEntry(); 1723 if (!IsSEH) 1724 UnwindDests.back().first->setIsEHScopeEntry(); 1725 } 1726 NewEHPadBB = CatchSwitch->getUnwindDest(); 1727 } else { 1728 continue; 1729 } 1730 1731 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1732 if (BPI && NewEHPadBB) 1733 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1734 EHPadBB = NewEHPadBB; 1735 } 1736 } 1737 1738 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1739 // Update successor info. 1740 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1741 auto UnwindDest = I.getUnwindDest(); 1742 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1743 BranchProbability UnwindDestProb = 1744 (BPI && UnwindDest) 1745 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1746 : BranchProbability::getZero(); 1747 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1748 for (auto &UnwindDest : UnwindDests) { 1749 UnwindDest.first->setIsEHPad(); 1750 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1751 } 1752 FuncInfo.MBB->normalizeSuccProbs(); 1753 1754 // Create the terminator node. 1755 SDValue Ret = 1756 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1757 DAG.setRoot(Ret); 1758 } 1759 1760 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1761 report_fatal_error("visitCatchSwitch not yet implemented!"); 1762 } 1763 1764 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1765 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1766 auto &DL = DAG.getDataLayout(); 1767 SDValue Chain = getControlRoot(); 1768 SmallVector<ISD::OutputArg, 8> Outs; 1769 SmallVector<SDValue, 8> OutVals; 1770 1771 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1772 // lower 1773 // 1774 // %val = call <ty> @llvm.experimental.deoptimize() 1775 // ret <ty> %val 1776 // 1777 // differently. 1778 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1779 LowerDeoptimizingReturn(); 1780 return; 1781 } 1782 1783 if (!FuncInfo.CanLowerReturn) { 1784 unsigned DemoteReg = FuncInfo.DemoteRegister; 1785 const Function *F = I.getParent()->getParent(); 1786 1787 // Emit a store of the return value through the virtual register. 1788 // Leave Outs empty so that LowerReturn won't try to load return 1789 // registers the usual way. 1790 SmallVector<EVT, 1> PtrValueVTs; 1791 ComputeValueVTs(TLI, DL, 1792 F->getReturnType()->getPointerTo( 1793 DAG.getDataLayout().getAllocaAddrSpace()), 1794 PtrValueVTs); 1795 1796 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1797 DemoteReg, PtrValueVTs[0]); 1798 SDValue RetOp = getValue(I.getOperand(0)); 1799 1800 SmallVector<EVT, 4> ValueVTs, MemVTs; 1801 SmallVector<uint64_t, 4> Offsets; 1802 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs, 1803 &Offsets); 1804 unsigned NumValues = ValueVTs.size(); 1805 1806 SmallVector<SDValue, 4> Chains(NumValues); 1807 for (unsigned i = 0; i != NumValues; ++i) { 1808 // An aggregate return value cannot wrap around the address space, so 1809 // offsets to its parts don't wrap either. 1810 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1811 1812 SDValue Val = RetOp.getValue(RetOp.getResNo() + i); 1813 if (MemVTs[i] != ValueVTs[i]) 1814 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]); 1815 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val, 1816 // FIXME: better loc info would be nice. 1817 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1818 } 1819 1820 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1821 MVT::Other, Chains); 1822 } else if (I.getNumOperands() != 0) { 1823 SmallVector<EVT, 4> ValueVTs; 1824 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1825 unsigned NumValues = ValueVTs.size(); 1826 if (NumValues) { 1827 SDValue RetOp = getValue(I.getOperand(0)); 1828 1829 const Function *F = I.getParent()->getParent(); 1830 1831 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters( 1832 I.getOperand(0)->getType(), F->getCallingConv(), 1833 /*IsVarArg*/ false); 1834 1835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1836 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1837 Attribute::SExt)) 1838 ExtendKind = ISD::SIGN_EXTEND; 1839 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1840 Attribute::ZExt)) 1841 ExtendKind = ISD::ZERO_EXTEND; 1842 1843 LLVMContext &Context = F->getContext(); 1844 bool RetInReg = F->getAttributes().hasAttribute( 1845 AttributeList::ReturnIndex, Attribute::InReg); 1846 1847 for (unsigned j = 0; j != NumValues; ++j) { 1848 EVT VT = ValueVTs[j]; 1849 1850 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1851 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1852 1853 CallingConv::ID CC = F->getCallingConv(); 1854 1855 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1856 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1857 SmallVector<SDValue, 4> Parts(NumParts); 1858 getCopyToParts(DAG, getCurSDLoc(), 1859 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1860 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1861 1862 // 'inreg' on function refers to return value 1863 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1864 if (RetInReg) 1865 Flags.setInReg(); 1866 1867 if (I.getOperand(0)->getType()->isPointerTy()) { 1868 Flags.setPointer(); 1869 Flags.setPointerAddrSpace( 1870 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace()); 1871 } 1872 1873 if (NeedsRegBlock) { 1874 Flags.setInConsecutiveRegs(); 1875 if (j == NumValues - 1) 1876 Flags.setInConsecutiveRegsLast(); 1877 } 1878 1879 // Propagate extension type if any 1880 if (ExtendKind == ISD::SIGN_EXTEND) 1881 Flags.setSExt(); 1882 else if (ExtendKind == ISD::ZERO_EXTEND) 1883 Flags.setZExt(); 1884 1885 for (unsigned i = 0; i < NumParts; ++i) { 1886 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1887 VT, /*isfixed=*/true, 0, 0)); 1888 OutVals.push_back(Parts[i]); 1889 } 1890 } 1891 } 1892 } 1893 1894 // Push in swifterror virtual register as the last element of Outs. This makes 1895 // sure swifterror virtual register will be returned in the swifterror 1896 // physical register. 1897 const Function *F = I.getParent()->getParent(); 1898 if (TLI.supportSwiftError() && 1899 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1900 assert(SwiftError.getFunctionArg() && "Need a swift error argument"); 1901 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1902 Flags.setSwiftError(); 1903 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1904 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1905 true /*isfixed*/, 1 /*origidx*/, 1906 0 /*partOffs*/)); 1907 // Create SDNode for the swifterror virtual register. 1908 OutVals.push_back( 1909 DAG.getRegister(SwiftError.getOrCreateVRegUseAt( 1910 &I, FuncInfo.MBB, SwiftError.getFunctionArg()), 1911 EVT(TLI.getPointerTy(DL)))); 1912 } 1913 1914 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1915 CallingConv::ID CallConv = 1916 DAG.getMachineFunction().getFunction().getCallingConv(); 1917 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1918 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1919 1920 // Verify that the target's LowerReturn behaved as expected. 1921 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1922 "LowerReturn didn't return a valid chain!"); 1923 1924 // Update the DAG with the new chain value resulting from return lowering. 1925 DAG.setRoot(Chain); 1926 } 1927 1928 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1929 /// created for it, emit nodes to copy the value into the virtual 1930 /// registers. 1931 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1932 // Skip empty types 1933 if (V->getType()->isEmptyTy()) 1934 return; 1935 1936 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1937 if (VMI != FuncInfo.ValueMap.end()) { 1938 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1939 CopyValueToVirtualRegister(V, VMI->second); 1940 } 1941 } 1942 1943 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1944 /// the current basic block, add it to ValueMap now so that we'll get a 1945 /// CopyTo/FromReg. 1946 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1947 // No need to export constants. 1948 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1949 1950 // Already exported? 1951 if (FuncInfo.isExportedInst(V)) return; 1952 1953 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1954 CopyValueToVirtualRegister(V, Reg); 1955 } 1956 1957 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1958 const BasicBlock *FromBB) { 1959 // The operands of the setcc have to be in this block. We don't know 1960 // how to export them from some other block. 1961 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1962 // Can export from current BB. 1963 if (VI->getParent() == FromBB) 1964 return true; 1965 1966 // Is already exported, noop. 1967 return FuncInfo.isExportedInst(V); 1968 } 1969 1970 // If this is an argument, we can export it if the BB is the entry block or 1971 // if it is already exported. 1972 if (isa<Argument>(V)) { 1973 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1974 return true; 1975 1976 // Otherwise, can only export this if it is already exported. 1977 return FuncInfo.isExportedInst(V); 1978 } 1979 1980 // Otherwise, constants can always be exported. 1981 return true; 1982 } 1983 1984 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1985 BranchProbability 1986 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1987 const MachineBasicBlock *Dst) const { 1988 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1989 const BasicBlock *SrcBB = Src->getBasicBlock(); 1990 const BasicBlock *DstBB = Dst->getBasicBlock(); 1991 if (!BPI) { 1992 // If BPI is not available, set the default probability as 1 / N, where N is 1993 // the number of successors. 1994 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1995 return BranchProbability(1, SuccSize); 1996 } 1997 return BPI->getEdgeProbability(SrcBB, DstBB); 1998 } 1999 2000 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 2001 MachineBasicBlock *Dst, 2002 BranchProbability Prob) { 2003 if (!FuncInfo.BPI) 2004 Src->addSuccessorWithoutProb(Dst); 2005 else { 2006 if (Prob.isUnknown()) 2007 Prob = getEdgeProbability(Src, Dst); 2008 Src->addSuccessor(Dst, Prob); 2009 } 2010 } 2011 2012 static bool InBlock(const Value *V, const BasicBlock *BB) { 2013 if (const Instruction *I = dyn_cast<Instruction>(V)) 2014 return I->getParent() == BB; 2015 return true; 2016 } 2017 2018 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 2019 /// This function emits a branch and is used at the leaves of an OR or an 2020 /// AND operator tree. 2021 void 2022 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 2023 MachineBasicBlock *TBB, 2024 MachineBasicBlock *FBB, 2025 MachineBasicBlock *CurBB, 2026 MachineBasicBlock *SwitchBB, 2027 BranchProbability TProb, 2028 BranchProbability FProb, 2029 bool InvertCond) { 2030 const BasicBlock *BB = CurBB->getBasicBlock(); 2031 2032 // If the leaf of the tree is a comparison, merge the condition into 2033 // the caseblock. 2034 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2035 // The operands of the cmp have to be in this block. We don't know 2036 // how to export them from some other block. If this is the first block 2037 // of the sequence, no exporting is needed. 2038 if (CurBB == SwitchBB || 2039 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2040 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2041 ISD::CondCode Condition; 2042 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2043 ICmpInst::Predicate Pred = 2044 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2045 Condition = getICmpCondCode(Pred); 2046 } else { 2047 const FCmpInst *FC = cast<FCmpInst>(Cond); 2048 FCmpInst::Predicate Pred = 2049 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2050 Condition = getFCmpCondCode(Pred); 2051 if (TM.Options.NoNaNsFPMath) 2052 Condition = getFCmpCodeWithoutNaN(Condition); 2053 } 2054 2055 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2056 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2057 SL->SwitchCases.push_back(CB); 2058 return; 2059 } 2060 } 2061 2062 // Create a CaseBlock record representing this branch. 2063 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2064 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2065 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2066 SL->SwitchCases.push_back(CB); 2067 } 2068 2069 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2070 MachineBasicBlock *TBB, 2071 MachineBasicBlock *FBB, 2072 MachineBasicBlock *CurBB, 2073 MachineBasicBlock *SwitchBB, 2074 Instruction::BinaryOps Opc, 2075 BranchProbability TProb, 2076 BranchProbability FProb, 2077 bool InvertCond) { 2078 // Skip over not part of the tree and remember to invert op and operands at 2079 // next level. 2080 Value *NotCond; 2081 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2082 InBlock(NotCond, CurBB->getBasicBlock())) { 2083 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2084 !InvertCond); 2085 return; 2086 } 2087 2088 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2089 // Compute the effective opcode for Cond, taking into account whether it needs 2090 // to be inverted, e.g. 2091 // and (not (or A, B)), C 2092 // gets lowered as 2093 // and (and (not A, not B), C) 2094 unsigned BOpc = 0; 2095 if (BOp) { 2096 BOpc = BOp->getOpcode(); 2097 if (InvertCond) { 2098 if (BOpc == Instruction::And) 2099 BOpc = Instruction::Or; 2100 else if (BOpc == Instruction::Or) 2101 BOpc = Instruction::And; 2102 } 2103 } 2104 2105 // If this node is not part of the or/and tree, emit it as a branch. 2106 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2107 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2108 BOp->getParent() != CurBB->getBasicBlock() || 2109 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2110 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2111 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2112 TProb, FProb, InvertCond); 2113 return; 2114 } 2115 2116 // Create TmpBB after CurBB. 2117 MachineFunction::iterator BBI(CurBB); 2118 MachineFunction &MF = DAG.getMachineFunction(); 2119 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2120 CurBB->getParent()->insert(++BBI, TmpBB); 2121 2122 if (Opc == Instruction::Or) { 2123 // Codegen X | Y as: 2124 // BB1: 2125 // jmp_if_X TBB 2126 // jmp TmpBB 2127 // TmpBB: 2128 // jmp_if_Y TBB 2129 // jmp FBB 2130 // 2131 2132 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2133 // The requirement is that 2134 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2135 // = TrueProb for original BB. 2136 // Assuming the original probabilities are A and B, one choice is to set 2137 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2138 // A/(1+B) and 2B/(1+B). This choice assumes that 2139 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2140 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2141 // TmpBB, but the math is more complicated. 2142 2143 auto NewTrueProb = TProb / 2; 2144 auto NewFalseProb = TProb / 2 + FProb; 2145 // Emit the LHS condition. 2146 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2147 NewTrueProb, NewFalseProb, InvertCond); 2148 2149 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2150 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2151 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2152 // Emit the RHS condition into TmpBB. 2153 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2154 Probs[0], Probs[1], InvertCond); 2155 } else { 2156 assert(Opc == Instruction::And && "Unknown merge op!"); 2157 // Codegen X & Y as: 2158 // BB1: 2159 // jmp_if_X TmpBB 2160 // jmp FBB 2161 // TmpBB: 2162 // jmp_if_Y TBB 2163 // jmp FBB 2164 // 2165 // This requires creation of TmpBB after CurBB. 2166 2167 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2168 // The requirement is that 2169 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2170 // = FalseProb for original BB. 2171 // Assuming the original probabilities are A and B, one choice is to set 2172 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2173 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2174 // TrueProb for BB1 * FalseProb for TmpBB. 2175 2176 auto NewTrueProb = TProb + FProb / 2; 2177 auto NewFalseProb = FProb / 2; 2178 // Emit the LHS condition. 2179 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2180 NewTrueProb, NewFalseProb, InvertCond); 2181 2182 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2183 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2184 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2185 // Emit the RHS condition into TmpBB. 2186 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2187 Probs[0], Probs[1], InvertCond); 2188 } 2189 } 2190 2191 /// If the set of cases should be emitted as a series of branches, return true. 2192 /// If we should emit this as a bunch of and/or'd together conditions, return 2193 /// false. 2194 bool 2195 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2196 if (Cases.size() != 2) return true; 2197 2198 // If this is two comparisons of the same values or'd or and'd together, they 2199 // will get folded into a single comparison, so don't emit two blocks. 2200 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2201 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2202 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2203 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2204 return false; 2205 } 2206 2207 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2208 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2209 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2210 Cases[0].CC == Cases[1].CC && 2211 isa<Constant>(Cases[0].CmpRHS) && 2212 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2213 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2214 return false; 2215 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2216 return false; 2217 } 2218 2219 return true; 2220 } 2221 2222 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2223 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2224 2225 // Update machine-CFG edges. 2226 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2227 2228 if (I.isUnconditional()) { 2229 // Update machine-CFG edges. 2230 BrMBB->addSuccessor(Succ0MBB); 2231 2232 // If this is not a fall-through branch or optimizations are switched off, 2233 // emit the branch. 2234 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2235 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2236 MVT::Other, getControlRoot(), 2237 DAG.getBasicBlock(Succ0MBB))); 2238 2239 return; 2240 } 2241 2242 // If this condition is one of the special cases we handle, do special stuff 2243 // now. 2244 const Value *CondVal = I.getCondition(); 2245 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2246 2247 // If this is a series of conditions that are or'd or and'd together, emit 2248 // this as a sequence of branches instead of setcc's with and/or operations. 2249 // As long as jumps are not expensive, this should improve performance. 2250 // For example, instead of something like: 2251 // cmp A, B 2252 // C = seteq 2253 // cmp D, E 2254 // F = setle 2255 // or C, F 2256 // jnz foo 2257 // Emit: 2258 // cmp A, B 2259 // je foo 2260 // cmp D, E 2261 // jle foo 2262 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2263 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2264 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2265 !I.hasMetadata(LLVMContext::MD_unpredictable) && 2266 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2267 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2268 Opcode, 2269 getEdgeProbability(BrMBB, Succ0MBB), 2270 getEdgeProbability(BrMBB, Succ1MBB), 2271 /*InvertCond=*/false); 2272 // If the compares in later blocks need to use values not currently 2273 // exported from this block, export them now. This block should always 2274 // be the first entry. 2275 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2276 2277 // Allow some cases to be rejected. 2278 if (ShouldEmitAsBranches(SL->SwitchCases)) { 2279 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) { 2280 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS); 2281 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS); 2282 } 2283 2284 // Emit the branch for this block. 2285 visitSwitchCase(SL->SwitchCases[0], BrMBB); 2286 SL->SwitchCases.erase(SL->SwitchCases.begin()); 2287 return; 2288 } 2289 2290 // Okay, we decided not to do this, remove any inserted MBB's and clear 2291 // SwitchCases. 2292 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) 2293 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB); 2294 2295 SL->SwitchCases.clear(); 2296 } 2297 } 2298 2299 // Create a CaseBlock record representing this branch. 2300 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2301 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2302 2303 // Use visitSwitchCase to actually insert the fast branch sequence for this 2304 // cond branch. 2305 visitSwitchCase(CB, BrMBB); 2306 } 2307 2308 /// visitSwitchCase - Emits the necessary code to represent a single node in 2309 /// the binary search tree resulting from lowering a switch instruction. 2310 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2311 MachineBasicBlock *SwitchBB) { 2312 SDValue Cond; 2313 SDValue CondLHS = getValue(CB.CmpLHS); 2314 SDLoc dl = CB.DL; 2315 2316 if (CB.CC == ISD::SETTRUE) { 2317 // Branch or fall through to TrueBB. 2318 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2319 SwitchBB->normalizeSuccProbs(); 2320 if (CB.TrueBB != NextBlock(SwitchBB)) { 2321 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(), 2322 DAG.getBasicBlock(CB.TrueBB))); 2323 } 2324 return; 2325 } 2326 2327 auto &TLI = DAG.getTargetLoweringInfo(); 2328 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType()); 2329 2330 // Build the setcc now. 2331 if (!CB.CmpMHS) { 2332 // Fold "(X == true)" to X and "(X == false)" to !X to 2333 // handle common cases produced by branch lowering. 2334 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2335 CB.CC == ISD::SETEQ) 2336 Cond = CondLHS; 2337 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2338 CB.CC == ISD::SETEQ) { 2339 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2340 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2341 } else { 2342 SDValue CondRHS = getValue(CB.CmpRHS); 2343 2344 // If a pointer's DAG type is larger than its memory type then the DAG 2345 // values are zero-extended. This breaks signed comparisons so truncate 2346 // back to the underlying type before doing the compare. 2347 if (CondLHS.getValueType() != MemVT) { 2348 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT); 2349 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT); 2350 } 2351 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC); 2352 } 2353 } else { 2354 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2355 2356 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2357 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2358 2359 SDValue CmpOp = getValue(CB.CmpMHS); 2360 EVT VT = CmpOp.getValueType(); 2361 2362 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2363 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2364 ISD::SETLE); 2365 } else { 2366 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2367 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2368 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2369 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2370 } 2371 } 2372 2373 // Update successor info 2374 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2375 // TrueBB and FalseBB are always different unless the incoming IR is 2376 // degenerate. This only happens when running llc on weird IR. 2377 if (CB.TrueBB != CB.FalseBB) 2378 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2379 SwitchBB->normalizeSuccProbs(); 2380 2381 // If the lhs block is the next block, invert the condition so that we can 2382 // fall through to the lhs instead of the rhs block. 2383 if (CB.TrueBB == NextBlock(SwitchBB)) { 2384 std::swap(CB.TrueBB, CB.FalseBB); 2385 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2386 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2387 } 2388 2389 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2390 MVT::Other, getControlRoot(), Cond, 2391 DAG.getBasicBlock(CB.TrueBB)); 2392 2393 // Insert the false branch. Do this even if it's a fall through branch, 2394 // this makes it easier to do DAG optimizations which require inverting 2395 // the branch condition. 2396 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2397 DAG.getBasicBlock(CB.FalseBB)); 2398 2399 DAG.setRoot(BrCond); 2400 } 2401 2402 /// visitJumpTable - Emit JumpTable node in the current MBB 2403 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) { 2404 // Emit the code for the jump table 2405 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2406 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2407 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2408 JT.Reg, PTy); 2409 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2410 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2411 MVT::Other, Index.getValue(1), 2412 Table, Index); 2413 DAG.setRoot(BrJumpTable); 2414 } 2415 2416 /// visitJumpTableHeader - This function emits necessary code to produce index 2417 /// in the JumpTable from switch case. 2418 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT, 2419 JumpTableHeader &JTH, 2420 MachineBasicBlock *SwitchBB) { 2421 SDLoc dl = getCurSDLoc(); 2422 2423 // Subtract the lowest switch case value from the value being switched on. 2424 SDValue SwitchOp = getValue(JTH.SValue); 2425 EVT VT = SwitchOp.getValueType(); 2426 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2427 DAG.getConstant(JTH.First, dl, VT)); 2428 2429 // The SDNode we just created, which holds the value being switched on minus 2430 // the smallest case value, needs to be copied to a virtual register so it 2431 // can be used as an index into the jump table in a subsequent basic block. 2432 // This value may be smaller or larger than the target's pointer type, and 2433 // therefore require extension or truncating. 2434 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2435 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2436 2437 unsigned JumpTableReg = 2438 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2439 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2440 JumpTableReg, SwitchOp); 2441 JT.Reg = JumpTableReg; 2442 2443 if (!JTH.OmitRangeCheck) { 2444 // Emit the range check for the jump table, and branch to the default block 2445 // for the switch statement if the value being switched on exceeds the 2446 // largest case in the switch. 2447 SDValue CMP = DAG.getSetCC( 2448 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2449 Sub.getValueType()), 2450 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2451 2452 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2453 MVT::Other, CopyTo, CMP, 2454 DAG.getBasicBlock(JT.Default)); 2455 2456 // Avoid emitting unnecessary branches to the next block. 2457 if (JT.MBB != NextBlock(SwitchBB)) 2458 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2459 DAG.getBasicBlock(JT.MBB)); 2460 2461 DAG.setRoot(BrCond); 2462 } else { 2463 // Avoid emitting unnecessary branches to the next block. 2464 if (JT.MBB != NextBlock(SwitchBB)) 2465 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2466 DAG.getBasicBlock(JT.MBB))); 2467 else 2468 DAG.setRoot(CopyTo); 2469 } 2470 } 2471 2472 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2473 /// variable if there exists one. 2474 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2475 SDValue &Chain) { 2476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2477 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2478 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2479 MachineFunction &MF = DAG.getMachineFunction(); 2480 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2481 MachineSDNode *Node = 2482 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2483 if (Global) { 2484 MachinePointerInfo MPInfo(Global); 2485 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2486 MachineMemOperand::MODereferenceable; 2487 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2488 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2489 DAG.setNodeMemRefs(Node, {MemRef}); 2490 } 2491 if (PtrTy != PtrMemTy) 2492 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy); 2493 return SDValue(Node, 0); 2494 } 2495 2496 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2497 /// tail spliced into a stack protector check success bb. 2498 /// 2499 /// For a high level explanation of how this fits into the stack protector 2500 /// generation see the comment on the declaration of class 2501 /// StackProtectorDescriptor. 2502 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2503 MachineBasicBlock *ParentBB) { 2504 2505 // First create the loads to the guard/stack slot for the comparison. 2506 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2507 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2508 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout()); 2509 2510 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2511 int FI = MFI.getStackProtectorIndex(); 2512 2513 SDValue Guard; 2514 SDLoc dl = getCurSDLoc(); 2515 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2516 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2517 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2518 2519 // Generate code to load the content of the guard slot. 2520 SDValue GuardVal = DAG.getLoad( 2521 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr, 2522 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2523 MachineMemOperand::MOVolatile); 2524 2525 if (TLI.useStackGuardXorFP()) 2526 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2527 2528 // Retrieve guard check function, nullptr if instrumentation is inlined. 2529 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2530 // The target provides a guard check function to validate the guard value. 2531 // Generate a call to that function with the content of the guard slot as 2532 // argument. 2533 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2534 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2535 2536 TargetLowering::ArgListTy Args; 2537 TargetLowering::ArgListEntry Entry; 2538 Entry.Node = GuardVal; 2539 Entry.Ty = FnTy->getParamType(0); 2540 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2541 Entry.IsInReg = true; 2542 Args.push_back(Entry); 2543 2544 TargetLowering::CallLoweringInfo CLI(DAG); 2545 CLI.setDebugLoc(getCurSDLoc()) 2546 .setChain(DAG.getEntryNode()) 2547 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2548 getValue(GuardCheckFn), std::move(Args)); 2549 2550 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2551 DAG.setRoot(Result.second); 2552 return; 2553 } 2554 2555 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2556 // Otherwise, emit a volatile load to retrieve the stack guard value. 2557 SDValue Chain = DAG.getEntryNode(); 2558 if (TLI.useLoadStackGuardNode()) { 2559 Guard = getLoadStackGuard(DAG, dl, Chain); 2560 } else { 2561 const Value *IRGuard = TLI.getSDagStackGuard(M); 2562 SDValue GuardPtr = getValue(IRGuard); 2563 2564 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr, 2565 MachinePointerInfo(IRGuard, 0), Align, 2566 MachineMemOperand::MOVolatile); 2567 } 2568 2569 // Perform the comparison via a subtract/getsetcc. 2570 EVT VT = Guard.getValueType(); 2571 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2572 2573 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2574 *DAG.getContext(), 2575 Sub.getValueType()), 2576 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2577 2578 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2579 // branch to failure MBB. 2580 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2581 MVT::Other, GuardVal.getOperand(0), 2582 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2583 // Otherwise branch to success MBB. 2584 SDValue Br = DAG.getNode(ISD::BR, dl, 2585 MVT::Other, BrCond, 2586 DAG.getBasicBlock(SPD.getSuccessMBB())); 2587 2588 DAG.setRoot(Br); 2589 } 2590 2591 /// Codegen the failure basic block for a stack protector check. 2592 /// 2593 /// A failure stack protector machine basic block consists simply of a call to 2594 /// __stack_chk_fail(). 2595 /// 2596 /// For a high level explanation of how this fits into the stack protector 2597 /// generation see the comment on the declaration of class 2598 /// StackProtectorDescriptor. 2599 void 2600 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2602 TargetLowering::MakeLibCallOptions CallOptions; 2603 CallOptions.setDiscardResult(true); 2604 SDValue Chain = 2605 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2606 None, CallOptions, getCurSDLoc()).second; 2607 // On PS4, the "return address" must still be within the calling function, 2608 // even if it's at the very end, so emit an explicit TRAP here. 2609 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2610 if (TM.getTargetTriple().isPS4CPU()) 2611 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2612 2613 DAG.setRoot(Chain); 2614 } 2615 2616 /// visitBitTestHeader - This function emits necessary code to produce value 2617 /// suitable for "bit tests" 2618 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2619 MachineBasicBlock *SwitchBB) { 2620 SDLoc dl = getCurSDLoc(); 2621 2622 // Subtract the minimum value. 2623 SDValue SwitchOp = getValue(B.SValue); 2624 EVT VT = SwitchOp.getValueType(); 2625 SDValue RangeSub = 2626 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT)); 2627 2628 // Determine the type of the test operands. 2629 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2630 bool UsePtrType = false; 2631 if (!TLI.isTypeLegal(VT)) { 2632 UsePtrType = true; 2633 } else { 2634 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2635 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2636 // Switch table case range are encoded into series of masks. 2637 // Just use pointer type, it's guaranteed to fit. 2638 UsePtrType = true; 2639 break; 2640 } 2641 } 2642 SDValue Sub = RangeSub; 2643 if (UsePtrType) { 2644 VT = TLI.getPointerTy(DAG.getDataLayout()); 2645 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2646 } 2647 2648 B.RegVT = VT.getSimpleVT(); 2649 B.Reg = FuncInfo.CreateReg(B.RegVT); 2650 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2651 2652 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2653 2654 if (!B.OmitRangeCheck) 2655 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2656 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2657 SwitchBB->normalizeSuccProbs(); 2658 2659 SDValue Root = CopyTo; 2660 if (!B.OmitRangeCheck) { 2661 // Conditional branch to the default block. 2662 SDValue RangeCmp = DAG.getSetCC(dl, 2663 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2664 RangeSub.getValueType()), 2665 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()), 2666 ISD::SETUGT); 2667 2668 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp, 2669 DAG.getBasicBlock(B.Default)); 2670 } 2671 2672 // Avoid emitting unnecessary branches to the next block. 2673 if (MBB != NextBlock(SwitchBB)) 2674 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB)); 2675 2676 DAG.setRoot(Root); 2677 } 2678 2679 /// visitBitTestCase - this function produces one "bit test" 2680 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2681 MachineBasicBlock* NextMBB, 2682 BranchProbability BranchProbToNext, 2683 unsigned Reg, 2684 BitTestCase &B, 2685 MachineBasicBlock *SwitchBB) { 2686 SDLoc dl = getCurSDLoc(); 2687 MVT VT = BB.RegVT; 2688 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2689 SDValue Cmp; 2690 unsigned PopCount = countPopulation(B.Mask); 2691 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2692 if (PopCount == 1) { 2693 // Testing for a single bit; just compare the shift count with what it 2694 // would need to be to shift a 1 bit in that position. 2695 Cmp = DAG.getSetCC( 2696 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2697 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2698 ISD::SETEQ); 2699 } else if (PopCount == BB.Range) { 2700 // There is only one zero bit in the range, test for it directly. 2701 Cmp = DAG.getSetCC( 2702 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2703 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2704 ISD::SETNE); 2705 } else { 2706 // Make desired shift 2707 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2708 DAG.getConstant(1, dl, VT), ShiftOp); 2709 2710 // Emit bit tests and jumps 2711 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2712 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2713 Cmp = DAG.getSetCC( 2714 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2715 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2716 } 2717 2718 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2719 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2720 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2721 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2722 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2723 // one as they are relative probabilities (and thus work more like weights), 2724 // and hence we need to normalize them to let the sum of them become one. 2725 SwitchBB->normalizeSuccProbs(); 2726 2727 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2728 MVT::Other, getControlRoot(), 2729 Cmp, DAG.getBasicBlock(B.TargetBB)); 2730 2731 // Avoid emitting unnecessary branches to the next block. 2732 if (NextMBB != NextBlock(SwitchBB)) 2733 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2734 DAG.getBasicBlock(NextMBB)); 2735 2736 DAG.setRoot(BrAnd); 2737 } 2738 2739 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2740 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2741 2742 // Retrieve successors. Look through artificial IR level blocks like 2743 // catchswitch for successors. 2744 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2745 const BasicBlock *EHPadBB = I.getSuccessor(1); 2746 2747 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2748 // have to do anything here to lower funclet bundles. 2749 assert(!I.hasOperandBundlesOtherThan( 2750 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2751 "Cannot lower invokes with arbitrary operand bundles yet!"); 2752 2753 const Value *Callee(I.getCalledValue()); 2754 const Function *Fn = dyn_cast<Function>(Callee); 2755 if (isa<InlineAsm>(Callee)) 2756 visitInlineAsm(&I); 2757 else if (Fn && Fn->isIntrinsic()) { 2758 switch (Fn->getIntrinsicID()) { 2759 default: 2760 llvm_unreachable("Cannot invoke this intrinsic"); 2761 case Intrinsic::donothing: 2762 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2763 break; 2764 case Intrinsic::experimental_patchpoint_void: 2765 case Intrinsic::experimental_patchpoint_i64: 2766 visitPatchpoint(&I, EHPadBB); 2767 break; 2768 case Intrinsic::experimental_gc_statepoint: 2769 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2770 break; 2771 case Intrinsic::wasm_rethrow_in_catch: { 2772 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2773 // special because it can be invoked, so we manually lower it to a DAG 2774 // node here. 2775 SmallVector<SDValue, 8> Ops; 2776 Ops.push_back(getRoot()); // inchain 2777 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2778 Ops.push_back( 2779 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2780 TLI.getPointerTy(DAG.getDataLayout()))); 2781 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2782 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2783 break; 2784 } 2785 } 2786 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2787 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2788 // Eventually we will support lowering the @llvm.experimental.deoptimize 2789 // intrinsic, and right now there are no plans to support other intrinsics 2790 // with deopt state. 2791 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2792 } else { 2793 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2794 } 2795 2796 // If the value of the invoke is used outside of its defining block, make it 2797 // available as a virtual register. 2798 // We already took care of the exported value for the statepoint instruction 2799 // during call to the LowerStatepoint. 2800 if (!isStatepoint(I)) { 2801 CopyToExportRegsIfNeeded(&I); 2802 } 2803 2804 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2805 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2806 BranchProbability EHPadBBProb = 2807 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2808 : BranchProbability::getZero(); 2809 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2810 2811 // Update successor info. 2812 addSuccessorWithProb(InvokeMBB, Return); 2813 for (auto &UnwindDest : UnwindDests) { 2814 UnwindDest.first->setIsEHPad(); 2815 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2816 } 2817 InvokeMBB->normalizeSuccProbs(); 2818 2819 // Drop into normal successor. 2820 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2821 DAG.getBasicBlock(Return))); 2822 } 2823 2824 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2825 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2826 2827 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2828 // have to do anything here to lower funclet bundles. 2829 assert(!I.hasOperandBundlesOtherThan( 2830 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2831 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2832 2833 assert(isa<InlineAsm>(I.getCalledValue()) && 2834 "Only know how to handle inlineasm callbr"); 2835 visitInlineAsm(&I); 2836 2837 // Retrieve successors. 2838 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2839 2840 // Update successor info. 2841 addSuccessorWithProb(CallBrMBB, Return); 2842 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2843 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2844 addSuccessorWithProb(CallBrMBB, Target); 2845 } 2846 CallBrMBB->normalizeSuccProbs(); 2847 2848 // Drop into default successor. 2849 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2850 MVT::Other, getControlRoot(), 2851 DAG.getBasicBlock(Return))); 2852 } 2853 2854 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2855 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2856 } 2857 2858 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2859 assert(FuncInfo.MBB->isEHPad() && 2860 "Call to landingpad not in landing pad!"); 2861 2862 // If there aren't registers to copy the values into (e.g., during SjLj 2863 // exceptions), then don't bother to create these DAG nodes. 2864 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2865 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2866 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2867 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2868 return; 2869 2870 // If landingpad's return type is token type, we don't create DAG nodes 2871 // for its exception pointer and selector value. The extraction of exception 2872 // pointer or selector value from token type landingpads is not currently 2873 // supported. 2874 if (LP.getType()->isTokenTy()) 2875 return; 2876 2877 SmallVector<EVT, 2> ValueVTs; 2878 SDLoc dl = getCurSDLoc(); 2879 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2880 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2881 2882 // Get the two live-in registers as SDValues. The physregs have already been 2883 // copied into virtual registers. 2884 SDValue Ops[2]; 2885 if (FuncInfo.ExceptionPointerVirtReg) { 2886 Ops[0] = DAG.getZExtOrTrunc( 2887 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2888 FuncInfo.ExceptionPointerVirtReg, 2889 TLI.getPointerTy(DAG.getDataLayout())), 2890 dl, ValueVTs[0]); 2891 } else { 2892 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2893 } 2894 Ops[1] = DAG.getZExtOrTrunc( 2895 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2896 FuncInfo.ExceptionSelectorVirtReg, 2897 TLI.getPointerTy(DAG.getDataLayout())), 2898 dl, ValueVTs[1]); 2899 2900 // Merge into one. 2901 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2902 DAG.getVTList(ValueVTs), Ops); 2903 setValue(&LP, Res); 2904 } 2905 2906 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2907 MachineBasicBlock *Last) { 2908 // Update JTCases. 2909 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i) 2910 if (SL->JTCases[i].first.HeaderBB == First) 2911 SL->JTCases[i].first.HeaderBB = Last; 2912 2913 // Update BitTestCases. 2914 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i) 2915 if (SL->BitTestCases[i].Parent == First) 2916 SL->BitTestCases[i].Parent = Last; 2917 } 2918 2919 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2920 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2921 2922 // Update machine-CFG edges with unique successors. 2923 SmallSet<BasicBlock*, 32> Done; 2924 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2925 BasicBlock *BB = I.getSuccessor(i); 2926 bool Inserted = Done.insert(BB).second; 2927 if (!Inserted) 2928 continue; 2929 2930 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2931 addSuccessorWithProb(IndirectBrMBB, Succ); 2932 } 2933 IndirectBrMBB->normalizeSuccProbs(); 2934 2935 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2936 MVT::Other, getControlRoot(), 2937 getValue(I.getAddress()))); 2938 } 2939 2940 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2941 if (!DAG.getTarget().Options.TrapUnreachable) 2942 return; 2943 2944 // We may be able to ignore unreachable behind a noreturn call. 2945 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2946 const BasicBlock &BB = *I.getParent(); 2947 if (&I != &BB.front()) { 2948 BasicBlock::const_iterator PredI = 2949 std::prev(BasicBlock::const_iterator(&I)); 2950 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2951 if (Call->doesNotReturn()) 2952 return; 2953 } 2954 } 2955 } 2956 2957 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2958 } 2959 2960 void SelectionDAGBuilder::visitFSub(const User &I) { 2961 // -0.0 - X --> fneg 2962 Type *Ty = I.getType(); 2963 if (isa<Constant>(I.getOperand(0)) && 2964 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2965 SDValue Op2 = getValue(I.getOperand(1)); 2966 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2967 Op2.getValueType(), Op2)); 2968 return; 2969 } 2970 2971 visitBinary(I, ISD::FSUB); 2972 } 2973 2974 /// Checks if the given instruction performs a vector reduction, in which case 2975 /// we have the freedom to alter the elements in the result as long as the 2976 /// reduction of them stays unchanged. 2977 static bool isVectorReductionOp(const User *I) { 2978 const Instruction *Inst = dyn_cast<Instruction>(I); 2979 if (!Inst || !Inst->getType()->isVectorTy()) 2980 return false; 2981 2982 auto OpCode = Inst->getOpcode(); 2983 switch (OpCode) { 2984 case Instruction::Add: 2985 case Instruction::Mul: 2986 case Instruction::And: 2987 case Instruction::Or: 2988 case Instruction::Xor: 2989 break; 2990 case Instruction::FAdd: 2991 case Instruction::FMul: 2992 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2993 if (FPOp->getFastMathFlags().isFast()) 2994 break; 2995 LLVM_FALLTHROUGH; 2996 default: 2997 return false; 2998 } 2999 3000 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 3001 // Ensure the reduction size is a power of 2. 3002 if (!isPowerOf2_32(ElemNum)) 3003 return false; 3004 3005 unsigned ElemNumToReduce = ElemNum; 3006 3007 // Do DFS search on the def-use chain from the given instruction. We only 3008 // allow four kinds of operations during the search until we reach the 3009 // instruction that extracts the first element from the vector: 3010 // 3011 // 1. The reduction operation of the same opcode as the given instruction. 3012 // 3013 // 2. PHI node. 3014 // 3015 // 3. ShuffleVector instruction together with a reduction operation that 3016 // does a partial reduction. 3017 // 3018 // 4. ExtractElement that extracts the first element from the vector, and we 3019 // stop searching the def-use chain here. 3020 // 3021 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 3022 // from 1-3 to the stack to continue the DFS. The given instruction is not 3023 // a reduction operation if we meet any other instructions other than those 3024 // listed above. 3025 3026 SmallVector<const User *, 16> UsersToVisit{Inst}; 3027 SmallPtrSet<const User *, 16> Visited; 3028 bool ReduxExtracted = false; 3029 3030 while (!UsersToVisit.empty()) { 3031 auto User = UsersToVisit.back(); 3032 UsersToVisit.pop_back(); 3033 if (!Visited.insert(User).second) 3034 continue; 3035 3036 for (const auto &U : User->users()) { 3037 auto Inst = dyn_cast<Instruction>(U); 3038 if (!Inst) 3039 return false; 3040 3041 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3042 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3043 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3044 return false; 3045 UsersToVisit.push_back(U); 3046 } else if (const ShuffleVectorInst *ShufInst = 3047 dyn_cast<ShuffleVectorInst>(U)) { 3048 // Detect the following pattern: A ShuffleVector instruction together 3049 // with a reduction that do partial reduction on the first and second 3050 // ElemNumToReduce / 2 elements, and store the result in 3051 // ElemNumToReduce / 2 elements in another vector. 3052 3053 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3054 if (ResultElements < ElemNum) 3055 return false; 3056 3057 if (ElemNumToReduce == 1) 3058 return false; 3059 if (!isa<UndefValue>(U->getOperand(1))) 3060 return false; 3061 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3062 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3063 return false; 3064 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3065 if (ShufInst->getMaskValue(i) != -1) 3066 return false; 3067 3068 // There is only one user of this ShuffleVector instruction, which 3069 // must be a reduction operation. 3070 if (!U->hasOneUse()) 3071 return false; 3072 3073 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3074 if (!U2 || U2->getOpcode() != OpCode) 3075 return false; 3076 3077 // Check operands of the reduction operation. 3078 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3079 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3080 UsersToVisit.push_back(U2); 3081 ElemNumToReduce /= 2; 3082 } else 3083 return false; 3084 } else if (isa<ExtractElementInst>(U)) { 3085 // At this moment we should have reduced all elements in the vector. 3086 if (ElemNumToReduce != 1) 3087 return false; 3088 3089 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3090 if (!Val || !Val->isZero()) 3091 return false; 3092 3093 ReduxExtracted = true; 3094 } else 3095 return false; 3096 } 3097 } 3098 return ReduxExtracted; 3099 } 3100 3101 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3102 SDNodeFlags Flags; 3103 3104 SDValue Op = getValue(I.getOperand(0)); 3105 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3106 Op, Flags); 3107 setValue(&I, UnNodeValue); 3108 } 3109 3110 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3111 SDNodeFlags Flags; 3112 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3113 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3114 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3115 } 3116 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3117 Flags.setExact(ExactOp->isExact()); 3118 } 3119 if (isVectorReductionOp(&I)) { 3120 Flags.setVectorReduction(true); 3121 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3122 } 3123 3124 SDValue Op1 = getValue(I.getOperand(0)); 3125 SDValue Op2 = getValue(I.getOperand(1)); 3126 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3127 Op1, Op2, Flags); 3128 setValue(&I, BinNodeValue); 3129 } 3130 3131 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3132 SDValue Op1 = getValue(I.getOperand(0)); 3133 SDValue Op2 = getValue(I.getOperand(1)); 3134 3135 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3136 Op1.getValueType(), DAG.getDataLayout()); 3137 3138 // Coerce the shift amount to the right type if we can. 3139 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3140 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3141 unsigned Op2Size = Op2.getValueSizeInBits(); 3142 SDLoc DL = getCurSDLoc(); 3143 3144 // If the operand is smaller than the shift count type, promote it. 3145 if (ShiftSize > Op2Size) 3146 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3147 3148 // If the operand is larger than the shift count type but the shift 3149 // count type has enough bits to represent any shift value, truncate 3150 // it now. This is a common case and it exposes the truncate to 3151 // optimization early. 3152 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3153 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3154 // Otherwise we'll need to temporarily settle for some other convenient 3155 // type. Type legalization will make adjustments once the shiftee is split. 3156 else 3157 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3158 } 3159 3160 bool nuw = false; 3161 bool nsw = false; 3162 bool exact = false; 3163 3164 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3165 3166 if (const OverflowingBinaryOperator *OFBinOp = 3167 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3168 nuw = OFBinOp->hasNoUnsignedWrap(); 3169 nsw = OFBinOp->hasNoSignedWrap(); 3170 } 3171 if (const PossiblyExactOperator *ExactOp = 3172 dyn_cast<const PossiblyExactOperator>(&I)) 3173 exact = ExactOp->isExact(); 3174 } 3175 SDNodeFlags Flags; 3176 Flags.setExact(exact); 3177 Flags.setNoSignedWrap(nsw); 3178 Flags.setNoUnsignedWrap(nuw); 3179 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3180 Flags); 3181 setValue(&I, Res); 3182 } 3183 3184 void SelectionDAGBuilder::visitSDiv(const User &I) { 3185 SDValue Op1 = getValue(I.getOperand(0)); 3186 SDValue Op2 = getValue(I.getOperand(1)); 3187 3188 SDNodeFlags Flags; 3189 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3190 cast<PossiblyExactOperator>(&I)->isExact()); 3191 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3192 Op2, Flags)); 3193 } 3194 3195 void SelectionDAGBuilder::visitICmp(const User &I) { 3196 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3197 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3198 predicate = IC->getPredicate(); 3199 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3200 predicate = ICmpInst::Predicate(IC->getPredicate()); 3201 SDValue Op1 = getValue(I.getOperand(0)); 3202 SDValue Op2 = getValue(I.getOperand(1)); 3203 ISD::CondCode Opcode = getICmpCondCode(predicate); 3204 3205 auto &TLI = DAG.getTargetLoweringInfo(); 3206 EVT MemVT = 3207 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3208 3209 // If a pointer's DAG type is larger than its memory type then the DAG values 3210 // are zero-extended. This breaks signed comparisons so truncate back to the 3211 // underlying type before doing the compare. 3212 if (Op1.getValueType() != MemVT) { 3213 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT); 3214 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT); 3215 } 3216 3217 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3218 I.getType()); 3219 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3220 } 3221 3222 void SelectionDAGBuilder::visitFCmp(const User &I) { 3223 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3224 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3225 predicate = FC->getPredicate(); 3226 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3227 predicate = FCmpInst::Predicate(FC->getPredicate()); 3228 SDValue Op1 = getValue(I.getOperand(0)); 3229 SDValue Op2 = getValue(I.getOperand(1)); 3230 3231 ISD::CondCode Condition = getFCmpCondCode(predicate); 3232 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3233 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3234 Condition = getFCmpCodeWithoutNaN(Condition); 3235 3236 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3237 I.getType()); 3238 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3239 } 3240 3241 // Check if the condition of the select has one use or two users that are both 3242 // selects with the same condition. 3243 static bool hasOnlySelectUsers(const Value *Cond) { 3244 return llvm::all_of(Cond->users(), [](const Value *V) { 3245 return isa<SelectInst>(V); 3246 }); 3247 } 3248 3249 void SelectionDAGBuilder::visitSelect(const User &I) { 3250 SmallVector<EVT, 4> ValueVTs; 3251 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3252 ValueVTs); 3253 unsigned NumValues = ValueVTs.size(); 3254 if (NumValues == 0) return; 3255 3256 SmallVector<SDValue, 4> Values(NumValues); 3257 SDValue Cond = getValue(I.getOperand(0)); 3258 SDValue LHSVal = getValue(I.getOperand(1)); 3259 SDValue RHSVal = getValue(I.getOperand(2)); 3260 auto BaseOps = {Cond}; 3261 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3262 ISD::VSELECT : ISD::SELECT; 3263 3264 bool IsUnaryAbs = false; 3265 3266 // Min/max matching is only viable if all output VTs are the same. 3267 if (is_splat(ValueVTs)) { 3268 EVT VT = ValueVTs[0]; 3269 LLVMContext &Ctx = *DAG.getContext(); 3270 auto &TLI = DAG.getTargetLoweringInfo(); 3271 3272 // We care about the legality of the operation after it has been type 3273 // legalized. 3274 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal) 3275 VT = TLI.getTypeToTransformTo(Ctx, VT); 3276 3277 // If the vselect is legal, assume we want to leave this as a vector setcc + 3278 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3279 // min/max is legal on the scalar type. 3280 bool UseScalarMinMax = VT.isVector() && 3281 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3282 3283 Value *LHS, *RHS; 3284 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3285 ISD::NodeType Opc = ISD::DELETED_NODE; 3286 switch (SPR.Flavor) { 3287 case SPF_UMAX: Opc = ISD::UMAX; break; 3288 case SPF_UMIN: Opc = ISD::UMIN; break; 3289 case SPF_SMAX: Opc = ISD::SMAX; break; 3290 case SPF_SMIN: Opc = ISD::SMIN; break; 3291 case SPF_FMINNUM: 3292 switch (SPR.NaNBehavior) { 3293 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3294 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3295 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3296 case SPNB_RETURNS_ANY: { 3297 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3298 Opc = ISD::FMINNUM; 3299 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3300 Opc = ISD::FMINIMUM; 3301 else if (UseScalarMinMax) 3302 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3303 ISD::FMINNUM : ISD::FMINIMUM; 3304 break; 3305 } 3306 } 3307 break; 3308 case SPF_FMAXNUM: 3309 switch (SPR.NaNBehavior) { 3310 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3311 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3312 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3313 case SPNB_RETURNS_ANY: 3314 3315 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3316 Opc = ISD::FMAXNUM; 3317 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3318 Opc = ISD::FMAXIMUM; 3319 else if (UseScalarMinMax) 3320 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3321 ISD::FMAXNUM : ISD::FMAXIMUM; 3322 break; 3323 } 3324 break; 3325 case SPF_ABS: 3326 IsUnaryAbs = true; 3327 Opc = ISD::ABS; 3328 break; 3329 case SPF_NABS: 3330 // TODO: we need to produce sub(0, abs(X)). 3331 default: break; 3332 } 3333 3334 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3335 (TLI.isOperationLegalOrCustom(Opc, VT) || 3336 (UseScalarMinMax && 3337 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3338 // If the underlying comparison instruction is used by any other 3339 // instruction, the consumed instructions won't be destroyed, so it is 3340 // not profitable to convert to a min/max. 3341 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3342 OpCode = Opc; 3343 LHSVal = getValue(LHS); 3344 RHSVal = getValue(RHS); 3345 BaseOps = {}; 3346 } 3347 3348 if (IsUnaryAbs) { 3349 OpCode = Opc; 3350 LHSVal = getValue(LHS); 3351 BaseOps = {}; 3352 } 3353 } 3354 3355 if (IsUnaryAbs) { 3356 for (unsigned i = 0; i != NumValues; ++i) { 3357 Values[i] = 3358 DAG.getNode(OpCode, getCurSDLoc(), 3359 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3360 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3361 } 3362 } else { 3363 for (unsigned i = 0; i != NumValues; ++i) { 3364 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3365 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3366 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3367 Values[i] = DAG.getNode( 3368 OpCode, getCurSDLoc(), 3369 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3370 } 3371 } 3372 3373 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3374 DAG.getVTList(ValueVTs), Values)); 3375 } 3376 3377 void SelectionDAGBuilder::visitTrunc(const User &I) { 3378 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3379 SDValue N = getValue(I.getOperand(0)); 3380 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3381 I.getType()); 3382 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3383 } 3384 3385 void SelectionDAGBuilder::visitZExt(const User &I) { 3386 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3387 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3388 SDValue N = getValue(I.getOperand(0)); 3389 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3390 I.getType()); 3391 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3392 } 3393 3394 void SelectionDAGBuilder::visitSExt(const User &I) { 3395 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3396 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3397 SDValue N = getValue(I.getOperand(0)); 3398 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3399 I.getType()); 3400 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3401 } 3402 3403 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3404 // FPTrunc is never a no-op cast, no need to check 3405 SDValue N = getValue(I.getOperand(0)); 3406 SDLoc dl = getCurSDLoc(); 3407 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3408 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3409 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3410 DAG.getTargetConstant( 3411 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3412 } 3413 3414 void SelectionDAGBuilder::visitFPExt(const User &I) { 3415 // FPExt is never a no-op cast, no need to check 3416 SDValue N = getValue(I.getOperand(0)); 3417 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3418 I.getType()); 3419 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3420 } 3421 3422 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3423 // FPToUI is never a no-op cast, no need to check 3424 SDValue N = getValue(I.getOperand(0)); 3425 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3426 I.getType()); 3427 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3428 } 3429 3430 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3431 // FPToSI is never a no-op cast, no need to check 3432 SDValue N = getValue(I.getOperand(0)); 3433 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3434 I.getType()); 3435 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3436 } 3437 3438 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3439 // UIToFP is never a no-op cast, no need to check 3440 SDValue N = getValue(I.getOperand(0)); 3441 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3442 I.getType()); 3443 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3444 } 3445 3446 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3447 // SIToFP is never a no-op cast, no need to check 3448 SDValue N = getValue(I.getOperand(0)); 3449 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3450 I.getType()); 3451 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3452 } 3453 3454 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3455 // What to do depends on the size of the integer and the size of the pointer. 3456 // We can either truncate, zero extend, or no-op, accordingly. 3457 SDValue N = getValue(I.getOperand(0)); 3458 auto &TLI = DAG.getTargetLoweringInfo(); 3459 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3460 I.getType()); 3461 EVT PtrMemVT = 3462 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType()); 3463 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3464 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT); 3465 setValue(&I, N); 3466 } 3467 3468 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3469 // What to do depends on the size of the integer and the size of the pointer. 3470 // We can either truncate, zero extend, or no-op, accordingly. 3471 SDValue N = getValue(I.getOperand(0)); 3472 auto &TLI = DAG.getTargetLoweringInfo(); 3473 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3474 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 3475 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT); 3476 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT); 3477 setValue(&I, N); 3478 } 3479 3480 void SelectionDAGBuilder::visitBitCast(const User &I) { 3481 SDValue N = getValue(I.getOperand(0)); 3482 SDLoc dl = getCurSDLoc(); 3483 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3484 I.getType()); 3485 3486 // BitCast assures us that source and destination are the same size so this is 3487 // either a BITCAST or a no-op. 3488 if (DestVT != N.getValueType()) 3489 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3490 DestVT, N)); // convert types. 3491 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3492 // might fold any kind of constant expression to an integer constant and that 3493 // is not what we are looking for. Only recognize a bitcast of a genuine 3494 // constant integer as an opaque constant. 3495 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3496 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3497 /*isOpaque*/true)); 3498 else 3499 setValue(&I, N); // noop cast. 3500 } 3501 3502 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3503 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3504 const Value *SV = I.getOperand(0); 3505 SDValue N = getValue(SV); 3506 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3507 3508 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3509 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3510 3511 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3512 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3513 3514 setValue(&I, N); 3515 } 3516 3517 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3518 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3519 SDValue InVec = getValue(I.getOperand(0)); 3520 SDValue InVal = getValue(I.getOperand(1)); 3521 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3522 TLI.getVectorIdxTy(DAG.getDataLayout())); 3523 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3524 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3525 InVec, InVal, InIdx)); 3526 } 3527 3528 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3529 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3530 SDValue InVec = getValue(I.getOperand(0)); 3531 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3532 TLI.getVectorIdxTy(DAG.getDataLayout())); 3533 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3534 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3535 InVec, InIdx)); 3536 } 3537 3538 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3539 SDValue Src1 = getValue(I.getOperand(0)); 3540 SDValue Src2 = getValue(I.getOperand(1)); 3541 Constant *MaskV = cast<Constant>(I.getOperand(2)); 3542 SDLoc DL = getCurSDLoc(); 3543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3544 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3545 EVT SrcVT = Src1.getValueType(); 3546 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3547 3548 if (MaskV->isNullValue() && VT.isScalableVector()) { 3549 // Canonical splat form of first element of first input vector. 3550 SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3551 SrcVT.getScalarType(), Src1, 3552 DAG.getConstant(0, DL, 3553 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3554 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt)); 3555 return; 3556 } 3557 3558 // For now, we only handle splats for scalable vectors. 3559 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation 3560 // for targets that support a SPLAT_VECTOR for non-scalable vector types. 3561 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle"); 3562 3563 SmallVector<int, 8> Mask; 3564 ShuffleVectorInst::getShuffleMask(MaskV, Mask); 3565 unsigned MaskNumElts = Mask.size(); 3566 3567 if (SrcNumElts == MaskNumElts) { 3568 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3569 return; 3570 } 3571 3572 // Normalize the shuffle vector since mask and vector length don't match. 3573 if (SrcNumElts < MaskNumElts) { 3574 // Mask is longer than the source vectors. We can use concatenate vector to 3575 // make the mask and vectors lengths match. 3576 3577 if (MaskNumElts % SrcNumElts == 0) { 3578 // Mask length is a multiple of the source vector length. 3579 // Check if the shuffle is some kind of concatenation of the input 3580 // vectors. 3581 unsigned NumConcat = MaskNumElts / SrcNumElts; 3582 bool IsConcat = true; 3583 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3584 for (unsigned i = 0; i != MaskNumElts; ++i) { 3585 int Idx = Mask[i]; 3586 if (Idx < 0) 3587 continue; 3588 // Ensure the indices in each SrcVT sized piece are sequential and that 3589 // the same source is used for the whole piece. 3590 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3591 (ConcatSrcs[i / SrcNumElts] >= 0 && 3592 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3593 IsConcat = false; 3594 break; 3595 } 3596 // Remember which source this index came from. 3597 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3598 } 3599 3600 // The shuffle is concatenating multiple vectors together. Just emit 3601 // a CONCAT_VECTORS operation. 3602 if (IsConcat) { 3603 SmallVector<SDValue, 8> ConcatOps; 3604 for (auto Src : ConcatSrcs) { 3605 if (Src < 0) 3606 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3607 else if (Src == 0) 3608 ConcatOps.push_back(Src1); 3609 else 3610 ConcatOps.push_back(Src2); 3611 } 3612 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3613 return; 3614 } 3615 } 3616 3617 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3618 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3619 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3620 PaddedMaskNumElts); 3621 3622 // Pad both vectors with undefs to make them the same length as the mask. 3623 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3624 3625 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3626 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3627 MOps1[0] = Src1; 3628 MOps2[0] = Src2; 3629 3630 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3631 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3632 3633 // Readjust mask for new input vector length. 3634 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3635 for (unsigned i = 0; i != MaskNumElts; ++i) { 3636 int Idx = Mask[i]; 3637 if (Idx >= (int)SrcNumElts) 3638 Idx -= SrcNumElts - PaddedMaskNumElts; 3639 MappedOps[i] = Idx; 3640 } 3641 3642 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3643 3644 // If the concatenated vector was padded, extract a subvector with the 3645 // correct number of elements. 3646 if (MaskNumElts != PaddedMaskNumElts) 3647 Result = DAG.getNode( 3648 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3649 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3650 3651 setValue(&I, Result); 3652 return; 3653 } 3654 3655 if (SrcNumElts > MaskNumElts) { 3656 // Analyze the access pattern of the vector to see if we can extract 3657 // two subvectors and do the shuffle. 3658 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3659 bool CanExtract = true; 3660 for (int Idx : Mask) { 3661 unsigned Input = 0; 3662 if (Idx < 0) 3663 continue; 3664 3665 if (Idx >= (int)SrcNumElts) { 3666 Input = 1; 3667 Idx -= SrcNumElts; 3668 } 3669 3670 // If all the indices come from the same MaskNumElts sized portion of 3671 // the sources we can use extract. Also make sure the extract wouldn't 3672 // extract past the end of the source. 3673 int NewStartIdx = alignDown(Idx, MaskNumElts); 3674 if (NewStartIdx + MaskNumElts > SrcNumElts || 3675 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3676 CanExtract = false; 3677 // Make sure we always update StartIdx as we use it to track if all 3678 // elements are undef. 3679 StartIdx[Input] = NewStartIdx; 3680 } 3681 3682 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3683 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3684 return; 3685 } 3686 if (CanExtract) { 3687 // Extract appropriate subvector and generate a vector shuffle 3688 for (unsigned Input = 0; Input < 2; ++Input) { 3689 SDValue &Src = Input == 0 ? Src1 : Src2; 3690 if (StartIdx[Input] < 0) 3691 Src = DAG.getUNDEF(VT); 3692 else { 3693 Src = DAG.getNode( 3694 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3695 DAG.getConstant(StartIdx[Input], DL, 3696 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3697 } 3698 } 3699 3700 // Calculate new mask. 3701 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3702 for (int &Idx : MappedOps) { 3703 if (Idx >= (int)SrcNumElts) 3704 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3705 else if (Idx >= 0) 3706 Idx -= StartIdx[0]; 3707 } 3708 3709 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3710 return; 3711 } 3712 } 3713 3714 // We can't use either concat vectors or extract subvectors so fall back to 3715 // replacing the shuffle with extract and build vector. 3716 // to insert and build vector. 3717 EVT EltVT = VT.getVectorElementType(); 3718 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3719 SmallVector<SDValue,8> Ops; 3720 for (int Idx : Mask) { 3721 SDValue Res; 3722 3723 if (Idx < 0) { 3724 Res = DAG.getUNDEF(EltVT); 3725 } else { 3726 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3727 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3728 3729 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3730 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3731 } 3732 3733 Ops.push_back(Res); 3734 } 3735 3736 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3737 } 3738 3739 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3740 ArrayRef<unsigned> Indices; 3741 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3742 Indices = IV->getIndices(); 3743 else 3744 Indices = cast<ConstantExpr>(&I)->getIndices(); 3745 3746 const Value *Op0 = I.getOperand(0); 3747 const Value *Op1 = I.getOperand(1); 3748 Type *AggTy = I.getType(); 3749 Type *ValTy = Op1->getType(); 3750 bool IntoUndef = isa<UndefValue>(Op0); 3751 bool FromUndef = isa<UndefValue>(Op1); 3752 3753 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3754 3755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3756 SmallVector<EVT, 4> AggValueVTs; 3757 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3758 SmallVector<EVT, 4> ValValueVTs; 3759 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3760 3761 unsigned NumAggValues = AggValueVTs.size(); 3762 unsigned NumValValues = ValValueVTs.size(); 3763 SmallVector<SDValue, 4> Values(NumAggValues); 3764 3765 // Ignore an insertvalue that produces an empty object 3766 if (!NumAggValues) { 3767 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3768 return; 3769 } 3770 3771 SDValue Agg = getValue(Op0); 3772 unsigned i = 0; 3773 // Copy the beginning value(s) from the original aggregate. 3774 for (; i != LinearIndex; ++i) 3775 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3776 SDValue(Agg.getNode(), Agg.getResNo() + i); 3777 // Copy values from the inserted value(s). 3778 if (NumValValues) { 3779 SDValue Val = getValue(Op1); 3780 for (; i != LinearIndex + NumValValues; ++i) 3781 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3782 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3783 } 3784 // Copy remaining value(s) from the original aggregate. 3785 for (; i != NumAggValues; ++i) 3786 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3787 SDValue(Agg.getNode(), Agg.getResNo() + i); 3788 3789 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3790 DAG.getVTList(AggValueVTs), Values)); 3791 } 3792 3793 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3794 ArrayRef<unsigned> Indices; 3795 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3796 Indices = EV->getIndices(); 3797 else 3798 Indices = cast<ConstantExpr>(&I)->getIndices(); 3799 3800 const Value *Op0 = I.getOperand(0); 3801 Type *AggTy = Op0->getType(); 3802 Type *ValTy = I.getType(); 3803 bool OutOfUndef = isa<UndefValue>(Op0); 3804 3805 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3806 3807 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3808 SmallVector<EVT, 4> ValValueVTs; 3809 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3810 3811 unsigned NumValValues = ValValueVTs.size(); 3812 3813 // Ignore a extractvalue that produces an empty object 3814 if (!NumValValues) { 3815 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3816 return; 3817 } 3818 3819 SmallVector<SDValue, 4> Values(NumValValues); 3820 3821 SDValue Agg = getValue(Op0); 3822 // Copy out the selected value(s). 3823 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3824 Values[i - LinearIndex] = 3825 OutOfUndef ? 3826 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3827 SDValue(Agg.getNode(), Agg.getResNo() + i); 3828 3829 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3830 DAG.getVTList(ValValueVTs), Values)); 3831 } 3832 3833 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3834 Value *Op0 = I.getOperand(0); 3835 // Note that the pointer operand may be a vector of pointers. Take the scalar 3836 // element which holds a pointer. 3837 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3838 SDValue N = getValue(Op0); 3839 SDLoc dl = getCurSDLoc(); 3840 auto &TLI = DAG.getTargetLoweringInfo(); 3841 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS); 3842 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS); 3843 3844 // Normalize Vector GEP - all scalar operands should be converted to the 3845 // splat vector. 3846 unsigned VectorWidth = I.getType()->isVectorTy() ? 3847 I.getType()->getVectorNumElements() : 0; 3848 3849 if (VectorWidth && !N.getValueType().isVector()) { 3850 LLVMContext &Context = *DAG.getContext(); 3851 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3852 N = DAG.getSplatBuildVector(VT, dl, N); 3853 } 3854 3855 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3856 GTI != E; ++GTI) { 3857 const Value *Idx = GTI.getOperand(); 3858 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3859 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3860 if (Field) { 3861 // N = N + Offset 3862 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3863 3864 // In an inbounds GEP with an offset that is nonnegative even when 3865 // interpreted as signed, assume there is no unsigned overflow. 3866 SDNodeFlags Flags; 3867 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3868 Flags.setNoUnsignedWrap(true); 3869 3870 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3871 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3872 } 3873 } else { 3874 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3875 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3876 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3877 3878 // If this is a scalar constant or a splat vector of constants, 3879 // handle it quickly. 3880 const auto *C = dyn_cast<Constant>(Idx); 3881 if (C && isa<VectorType>(C->getType())) 3882 C = C->getSplatValue(); 3883 3884 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) { 3885 if (CI->isZero()) 3886 continue; 3887 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3888 LLVMContext &Context = *DAG.getContext(); 3889 SDValue OffsVal = VectorWidth ? 3890 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3891 DAG.getConstant(Offs, dl, IdxTy); 3892 3893 // In an inbounds GEP with an offset that is nonnegative even when 3894 // interpreted as signed, assume there is no unsigned overflow. 3895 SDNodeFlags Flags; 3896 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3897 Flags.setNoUnsignedWrap(true); 3898 3899 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType()); 3900 3901 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3902 continue; 3903 } 3904 3905 // N = N + Idx * ElementSize; 3906 SDValue IdxN = getValue(Idx); 3907 3908 if (!IdxN.getValueType().isVector() && VectorWidth) { 3909 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3910 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3911 } 3912 3913 // If the index is smaller or larger than intptr_t, truncate or extend 3914 // it. 3915 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3916 3917 // If this is a multiply by a power of two, turn it into a shl 3918 // immediately. This is a very common case. 3919 if (ElementSize != 1) { 3920 if (ElementSize.isPowerOf2()) { 3921 unsigned Amt = ElementSize.logBase2(); 3922 IdxN = DAG.getNode(ISD::SHL, dl, 3923 N.getValueType(), IdxN, 3924 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3925 } else { 3926 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl, 3927 IdxN.getValueType()); 3928 IdxN = DAG.getNode(ISD::MUL, dl, 3929 N.getValueType(), IdxN, Scale); 3930 } 3931 } 3932 3933 N = DAG.getNode(ISD::ADD, dl, 3934 N.getValueType(), N, IdxN); 3935 } 3936 } 3937 3938 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds()) 3939 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy); 3940 3941 setValue(&I, N); 3942 } 3943 3944 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3945 // If this is a fixed sized alloca in the entry block of the function, 3946 // allocate it statically on the stack. 3947 if (FuncInfo.StaticAllocaMap.count(&I)) 3948 return; // getValue will auto-populate this. 3949 3950 SDLoc dl = getCurSDLoc(); 3951 Type *Ty = I.getAllocatedType(); 3952 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3953 auto &DL = DAG.getDataLayout(); 3954 uint64_t TySize = DL.getTypeAllocSize(Ty); 3955 unsigned Align = 3956 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3957 3958 SDValue AllocSize = getValue(I.getArraySize()); 3959 3960 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3961 if (AllocSize.getValueType() != IntPtr) 3962 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3963 3964 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3965 AllocSize, 3966 DAG.getConstant(TySize, dl, IntPtr)); 3967 3968 // Handle alignment. If the requested alignment is less than or equal to 3969 // the stack alignment, ignore it. If the size is greater than or equal to 3970 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3971 unsigned StackAlign = 3972 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3973 if (Align <= StackAlign) 3974 Align = 0; 3975 3976 // Round the size of the allocation up to the stack alignment size 3977 // by add SA-1 to the size. This doesn't overflow because we're computing 3978 // an address inside an alloca. 3979 SDNodeFlags Flags; 3980 Flags.setNoUnsignedWrap(true); 3981 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3982 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3983 3984 // Mask out the low bits for alignment purposes. 3985 AllocSize = 3986 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3987 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3988 3989 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3990 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3991 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3992 setValue(&I, DSA); 3993 DAG.setRoot(DSA.getValue(1)); 3994 3995 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3996 } 3997 3998 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3999 if (I.isAtomic()) 4000 return visitAtomicLoad(I); 4001 4002 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4003 const Value *SV = I.getOperand(0); 4004 if (TLI.supportSwiftError()) { 4005 // Swifterror values can come from either a function parameter with 4006 // swifterror attribute or an alloca with swifterror attribute. 4007 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 4008 if (Arg->hasSwiftErrorAttr()) 4009 return visitLoadFromSwiftError(I); 4010 } 4011 4012 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 4013 if (Alloca->isSwiftError()) 4014 return visitLoadFromSwiftError(I); 4015 } 4016 } 4017 4018 SDValue Ptr = getValue(SV); 4019 4020 Type *Ty = I.getType(); 4021 4022 bool isVolatile = I.isVolatile(); 4023 bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal); 4024 bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load); 4025 bool isDereferenceable = 4026 isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout()); 4027 unsigned Alignment = I.getAlignment(); 4028 4029 AAMDNodes AAInfo; 4030 I.getAAMetadata(AAInfo); 4031 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4032 4033 SmallVector<EVT, 4> ValueVTs, MemVTs; 4034 SmallVector<uint64_t, 4> Offsets; 4035 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets); 4036 unsigned NumValues = ValueVTs.size(); 4037 if (NumValues == 0) 4038 return; 4039 4040 SDValue Root; 4041 bool ConstantMemory = false; 4042 if (isVolatile || NumValues > MaxParallelChains) 4043 // Serialize volatile loads with other side effects. 4044 Root = getRoot(); 4045 else if (AA && 4046 AA->pointsToConstantMemory(MemoryLocation( 4047 SV, 4048 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4049 AAInfo))) { 4050 // Do not serialize (non-volatile) loads of constant memory with anything. 4051 Root = DAG.getEntryNode(); 4052 ConstantMemory = true; 4053 } else { 4054 // Do not serialize non-volatile loads against each other. 4055 Root = DAG.getRoot(); 4056 } 4057 4058 SDLoc dl = getCurSDLoc(); 4059 4060 if (isVolatile) 4061 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 4062 4063 // An aggregate load cannot wrap around the address space, so offsets to its 4064 // parts don't wrap either. 4065 SDNodeFlags Flags; 4066 Flags.setNoUnsignedWrap(true); 4067 4068 SmallVector<SDValue, 4> Values(NumValues); 4069 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4070 EVT PtrVT = Ptr.getValueType(); 4071 unsigned ChainI = 0; 4072 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4073 // Serializing loads here may result in excessive register pressure, and 4074 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4075 // could recover a bit by hoisting nodes upward in the chain by recognizing 4076 // they are side-effect free or do not alias. The optimizer should really 4077 // avoid this case by converting large object/array copies to llvm.memcpy 4078 // (MaxParallelChains should always remain as failsafe). 4079 if (ChainI == MaxParallelChains) { 4080 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4081 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4082 makeArrayRef(Chains.data(), ChainI)); 4083 Root = Chain; 4084 ChainI = 0; 4085 } 4086 SDValue A = DAG.getNode(ISD::ADD, dl, 4087 PtrVT, Ptr, 4088 DAG.getConstant(Offsets[i], dl, PtrVT), 4089 Flags); 4090 auto MMOFlags = MachineMemOperand::MONone; 4091 if (isVolatile) 4092 MMOFlags |= MachineMemOperand::MOVolatile; 4093 if (isNonTemporal) 4094 MMOFlags |= MachineMemOperand::MONonTemporal; 4095 if (isInvariant) 4096 MMOFlags |= MachineMemOperand::MOInvariant; 4097 if (isDereferenceable) 4098 MMOFlags |= MachineMemOperand::MODereferenceable; 4099 MMOFlags |= TLI.getMMOFlags(I); 4100 4101 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, 4102 MachinePointerInfo(SV, Offsets[i]), Alignment, 4103 MMOFlags, AAInfo, Ranges); 4104 Chains[ChainI] = L.getValue(1); 4105 4106 if (MemVTs[i] != ValueVTs[i]) 4107 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]); 4108 4109 Values[i] = L; 4110 } 4111 4112 if (!ConstantMemory) { 4113 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4114 makeArrayRef(Chains.data(), ChainI)); 4115 if (isVolatile) 4116 DAG.setRoot(Chain); 4117 else 4118 PendingLoads.push_back(Chain); 4119 } 4120 4121 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4122 DAG.getVTList(ValueVTs), Values)); 4123 } 4124 4125 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4126 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4127 "call visitStoreToSwiftError when backend supports swifterror"); 4128 4129 SmallVector<EVT, 4> ValueVTs; 4130 SmallVector<uint64_t, 4> Offsets; 4131 const Value *SrcV = I.getOperand(0); 4132 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4133 SrcV->getType(), ValueVTs, &Offsets); 4134 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4135 "expect a single EVT for swifterror"); 4136 4137 SDValue Src = getValue(SrcV); 4138 // Create a virtual register, then update the virtual register. 4139 Register VReg = 4140 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand()); 4141 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4142 // Chain can be getRoot or getControlRoot. 4143 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4144 SDValue(Src.getNode(), Src.getResNo())); 4145 DAG.setRoot(CopyNode); 4146 } 4147 4148 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4149 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4150 "call visitLoadFromSwiftError when backend supports swifterror"); 4151 4152 assert(!I.isVolatile() && 4153 !I.hasMetadata(LLVMContext::MD_nontemporal) && 4154 !I.hasMetadata(LLVMContext::MD_invariant_load) && 4155 "Support volatile, non temporal, invariant for load_from_swift_error"); 4156 4157 const Value *SV = I.getOperand(0); 4158 Type *Ty = I.getType(); 4159 AAMDNodes AAInfo; 4160 I.getAAMetadata(AAInfo); 4161 assert( 4162 (!AA || 4163 !AA->pointsToConstantMemory(MemoryLocation( 4164 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4165 AAInfo))) && 4166 "load_from_swift_error should not be constant memory"); 4167 4168 SmallVector<EVT, 4> ValueVTs; 4169 SmallVector<uint64_t, 4> Offsets; 4170 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4171 ValueVTs, &Offsets); 4172 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4173 "expect a single EVT for swifterror"); 4174 4175 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4176 SDValue L = DAG.getCopyFromReg( 4177 getRoot(), getCurSDLoc(), 4178 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]); 4179 4180 setValue(&I, L); 4181 } 4182 4183 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4184 if (I.isAtomic()) 4185 return visitAtomicStore(I); 4186 4187 const Value *SrcV = I.getOperand(0); 4188 const Value *PtrV = I.getOperand(1); 4189 4190 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4191 if (TLI.supportSwiftError()) { 4192 // Swifterror values can come from either a function parameter with 4193 // swifterror attribute or an alloca with swifterror attribute. 4194 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4195 if (Arg->hasSwiftErrorAttr()) 4196 return visitStoreToSwiftError(I); 4197 } 4198 4199 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4200 if (Alloca->isSwiftError()) 4201 return visitStoreToSwiftError(I); 4202 } 4203 } 4204 4205 SmallVector<EVT, 4> ValueVTs, MemVTs; 4206 SmallVector<uint64_t, 4> Offsets; 4207 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4208 SrcV->getType(), ValueVTs, &MemVTs, &Offsets); 4209 unsigned NumValues = ValueVTs.size(); 4210 if (NumValues == 0) 4211 return; 4212 4213 // Get the lowered operands. Note that we do this after 4214 // checking if NumResults is zero, because with zero results 4215 // the operands won't have values in the map. 4216 SDValue Src = getValue(SrcV); 4217 SDValue Ptr = getValue(PtrV); 4218 4219 SDValue Root = getRoot(); 4220 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4221 SDLoc dl = getCurSDLoc(); 4222 EVT PtrVT = Ptr.getValueType(); 4223 unsigned Alignment = I.getAlignment(); 4224 AAMDNodes AAInfo; 4225 I.getAAMetadata(AAInfo); 4226 4227 auto MMOFlags = MachineMemOperand::MONone; 4228 if (I.isVolatile()) 4229 MMOFlags |= MachineMemOperand::MOVolatile; 4230 if (I.hasMetadata(LLVMContext::MD_nontemporal)) 4231 MMOFlags |= MachineMemOperand::MONonTemporal; 4232 MMOFlags |= TLI.getMMOFlags(I); 4233 4234 // An aggregate load cannot wrap around the address space, so offsets to its 4235 // parts don't wrap either. 4236 SDNodeFlags Flags; 4237 Flags.setNoUnsignedWrap(true); 4238 4239 unsigned ChainI = 0; 4240 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4241 // See visitLoad comments. 4242 if (ChainI == MaxParallelChains) { 4243 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4244 makeArrayRef(Chains.data(), ChainI)); 4245 Root = Chain; 4246 ChainI = 0; 4247 } 4248 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4249 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4250 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i); 4251 if (MemVTs[i] != ValueVTs[i]) 4252 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]); 4253 SDValue St = 4254 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]), 4255 Alignment, MMOFlags, AAInfo); 4256 Chains[ChainI] = St; 4257 } 4258 4259 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4260 makeArrayRef(Chains.data(), ChainI)); 4261 DAG.setRoot(StoreNode); 4262 } 4263 4264 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4265 bool IsCompressing) { 4266 SDLoc sdl = getCurSDLoc(); 4267 4268 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4269 unsigned& Alignment) { 4270 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4271 Src0 = I.getArgOperand(0); 4272 Ptr = I.getArgOperand(1); 4273 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4274 Mask = I.getArgOperand(3); 4275 }; 4276 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4277 unsigned& Alignment) { 4278 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4279 Src0 = I.getArgOperand(0); 4280 Ptr = I.getArgOperand(1); 4281 Mask = I.getArgOperand(2); 4282 Alignment = 0; 4283 }; 4284 4285 Value *PtrOperand, *MaskOperand, *Src0Operand; 4286 unsigned Alignment; 4287 if (IsCompressing) 4288 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4289 else 4290 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4291 4292 SDValue Ptr = getValue(PtrOperand); 4293 SDValue Src0 = getValue(Src0Operand); 4294 SDValue Mask = getValue(MaskOperand); 4295 4296 EVT VT = Src0.getValueType(); 4297 if (!Alignment) 4298 Alignment = DAG.getEVTAlignment(VT); 4299 4300 AAMDNodes AAInfo; 4301 I.getAAMetadata(AAInfo); 4302 4303 MachineMemOperand *MMO = 4304 DAG.getMachineFunction(). 4305 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4306 MachineMemOperand::MOStore, VT.getStoreSize(), 4307 Alignment, AAInfo); 4308 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4309 MMO, false /* Truncating */, 4310 IsCompressing); 4311 DAG.setRoot(StoreNode); 4312 setValue(&I, StoreNode); 4313 } 4314 4315 // Get a uniform base for the Gather/Scatter intrinsic. 4316 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4317 // We try to represent it as a base pointer + vector of indices. 4318 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4319 // The first operand of the GEP may be a single pointer or a vector of pointers 4320 // Example: 4321 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4322 // or 4323 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4324 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4325 // 4326 // When the first GEP operand is a single pointer - it is the uniform base we 4327 // are looking for. If first operand of the GEP is a splat vector - we 4328 // extract the splat value and use it as a uniform base. 4329 // In all other cases the function returns 'false'. 4330 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index, 4331 ISD::MemIndexType &IndexType, SDValue &Scale, 4332 SelectionDAGBuilder *SDB) { 4333 SelectionDAG& DAG = SDB->DAG; 4334 LLVMContext &Context = *DAG.getContext(); 4335 4336 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4337 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4338 if (!GEP) 4339 return false; 4340 4341 const Value *GEPPtr = GEP->getPointerOperand(); 4342 if (!GEPPtr->getType()->isVectorTy()) 4343 Ptr = GEPPtr; 4344 else if (!(Ptr = getSplatValue(GEPPtr))) 4345 return false; 4346 4347 unsigned FinalIndex = GEP->getNumOperands() - 1; 4348 Value *IndexVal = GEP->getOperand(FinalIndex); 4349 4350 // Ensure all the other indices are 0. 4351 for (unsigned i = 1; i < FinalIndex; ++i) { 4352 auto *C = dyn_cast<Constant>(GEP->getOperand(i)); 4353 if (!C) 4354 return false; 4355 if (isa<VectorType>(C->getType())) 4356 C = C->getSplatValue(); 4357 auto *CI = dyn_cast_or_null<ConstantInt>(C); 4358 if (!CI || !CI->isZero()) 4359 return false; 4360 } 4361 4362 // The operands of the GEP may be defined in another basic block. 4363 // In this case we'll not find nodes for the operands. 4364 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4365 return false; 4366 4367 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4368 const DataLayout &DL = DAG.getDataLayout(); 4369 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4370 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4371 Base = SDB->getValue(Ptr); 4372 Index = SDB->getValue(IndexVal); 4373 IndexType = ISD::SIGNED_SCALED; 4374 4375 if (!Index.getValueType().isVector()) { 4376 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4377 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4378 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4379 } 4380 return true; 4381 } 4382 4383 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4384 SDLoc sdl = getCurSDLoc(); 4385 4386 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4387 const Value *Ptr = I.getArgOperand(1); 4388 SDValue Src0 = getValue(I.getArgOperand(0)); 4389 SDValue Mask = getValue(I.getArgOperand(3)); 4390 EVT VT = Src0.getValueType(); 4391 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4392 if (!Alignment) 4393 Alignment = DAG.getEVTAlignment(VT); 4394 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4395 4396 AAMDNodes AAInfo; 4397 I.getAAMetadata(AAInfo); 4398 4399 SDValue Base; 4400 SDValue Index; 4401 ISD::MemIndexType IndexType; 4402 SDValue Scale; 4403 const Value *BasePtr = Ptr; 4404 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4405 this); 4406 4407 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4408 MachineMemOperand *MMO = DAG.getMachineFunction(). 4409 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4410 MachineMemOperand::MOStore, VT.getStoreSize(), 4411 Alignment, AAInfo); 4412 if (!UniformBase) { 4413 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4414 Index = getValue(Ptr); 4415 IndexType = ISD::SIGNED_SCALED; 4416 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4417 } 4418 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4419 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4420 Ops, MMO, IndexType); 4421 DAG.setRoot(Scatter); 4422 setValue(&I, Scatter); 4423 } 4424 4425 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4426 SDLoc sdl = getCurSDLoc(); 4427 4428 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4429 unsigned& Alignment) { 4430 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4431 Ptr = I.getArgOperand(0); 4432 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4433 Mask = I.getArgOperand(2); 4434 Src0 = I.getArgOperand(3); 4435 }; 4436 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4437 unsigned& Alignment) { 4438 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4439 Ptr = I.getArgOperand(0); 4440 Alignment = 0; 4441 Mask = I.getArgOperand(1); 4442 Src0 = I.getArgOperand(2); 4443 }; 4444 4445 Value *PtrOperand, *MaskOperand, *Src0Operand; 4446 unsigned Alignment; 4447 if (IsExpanding) 4448 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4449 else 4450 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4451 4452 SDValue Ptr = getValue(PtrOperand); 4453 SDValue Src0 = getValue(Src0Operand); 4454 SDValue Mask = getValue(MaskOperand); 4455 4456 EVT VT = Src0.getValueType(); 4457 if (!Alignment) 4458 Alignment = DAG.getEVTAlignment(VT); 4459 4460 AAMDNodes AAInfo; 4461 I.getAAMetadata(AAInfo); 4462 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4463 4464 // Do not serialize masked loads of constant memory with anything. 4465 MemoryLocation ML; 4466 if (VT.isScalableVector()) 4467 ML = MemoryLocation(PtrOperand); 4468 else 4469 ML = MemoryLocation(PtrOperand, LocationSize::precise( 4470 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4471 AAInfo); 4472 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML); 4473 4474 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4475 4476 MachineMemOperand *MMO = 4477 DAG.getMachineFunction(). 4478 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4479 MachineMemOperand::MOLoad, VT.getStoreSize(), 4480 Alignment, AAInfo, Ranges); 4481 4482 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4483 ISD::NON_EXTLOAD, IsExpanding); 4484 if (AddToChain) 4485 PendingLoads.push_back(Load.getValue(1)); 4486 setValue(&I, Load); 4487 } 4488 4489 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4490 SDLoc sdl = getCurSDLoc(); 4491 4492 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4493 const Value *Ptr = I.getArgOperand(0); 4494 SDValue Src0 = getValue(I.getArgOperand(3)); 4495 SDValue Mask = getValue(I.getArgOperand(2)); 4496 4497 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4498 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4499 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4500 if (!Alignment) 4501 Alignment = DAG.getEVTAlignment(VT); 4502 4503 AAMDNodes AAInfo; 4504 I.getAAMetadata(AAInfo); 4505 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4506 4507 SDValue Root = DAG.getRoot(); 4508 SDValue Base; 4509 SDValue Index; 4510 ISD::MemIndexType IndexType; 4511 SDValue Scale; 4512 const Value *BasePtr = Ptr; 4513 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale, 4514 this); 4515 bool ConstantMemory = false; 4516 if (UniformBase && AA && 4517 AA->pointsToConstantMemory( 4518 MemoryLocation(BasePtr, 4519 LocationSize::precise( 4520 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4521 AAInfo))) { 4522 // Do not serialize (non-volatile) loads of constant memory with anything. 4523 Root = DAG.getEntryNode(); 4524 ConstantMemory = true; 4525 } 4526 4527 MachineMemOperand *MMO = 4528 DAG.getMachineFunction(). 4529 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4530 MachineMemOperand::MOLoad, VT.getStoreSize(), 4531 Alignment, AAInfo, Ranges); 4532 4533 if (!UniformBase) { 4534 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4535 Index = getValue(Ptr); 4536 IndexType = ISD::SIGNED_SCALED; 4537 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4538 } 4539 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4540 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4541 Ops, MMO, IndexType); 4542 4543 SDValue OutChain = Gather.getValue(1); 4544 if (!ConstantMemory) 4545 PendingLoads.push_back(OutChain); 4546 setValue(&I, Gather); 4547 } 4548 4549 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4550 SDLoc dl = getCurSDLoc(); 4551 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4552 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4553 SyncScope::ID SSID = I.getSyncScopeID(); 4554 4555 SDValue InChain = getRoot(); 4556 4557 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4558 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4559 4560 auto Alignment = DAG.getEVTAlignment(MemVT); 4561 4562 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4563 if (I.isVolatile()) 4564 Flags |= MachineMemOperand::MOVolatile; 4565 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4566 4567 MachineFunction &MF = DAG.getMachineFunction(); 4568 MachineMemOperand *MMO = 4569 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4570 Flags, MemVT.getStoreSize(), Alignment, 4571 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4572 FailureOrdering); 4573 4574 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4575 dl, MemVT, VTs, InChain, 4576 getValue(I.getPointerOperand()), 4577 getValue(I.getCompareOperand()), 4578 getValue(I.getNewValOperand()), MMO); 4579 4580 SDValue OutChain = L.getValue(2); 4581 4582 setValue(&I, L); 4583 DAG.setRoot(OutChain); 4584 } 4585 4586 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4587 SDLoc dl = getCurSDLoc(); 4588 ISD::NodeType NT; 4589 switch (I.getOperation()) { 4590 default: llvm_unreachable("Unknown atomicrmw operation"); 4591 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4592 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4593 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4594 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4595 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4596 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4597 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4598 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4599 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4600 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4601 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4602 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4603 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4604 } 4605 AtomicOrdering Ordering = I.getOrdering(); 4606 SyncScope::ID SSID = I.getSyncScopeID(); 4607 4608 SDValue InChain = getRoot(); 4609 4610 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4611 auto Alignment = DAG.getEVTAlignment(MemVT); 4612 4613 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4614 if (I.isVolatile()) 4615 Flags |= MachineMemOperand::MOVolatile; 4616 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4617 4618 MachineFunction &MF = DAG.getMachineFunction(); 4619 MachineMemOperand *MMO = 4620 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4621 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4622 nullptr, SSID, Ordering); 4623 4624 SDValue L = 4625 DAG.getAtomic(NT, dl, MemVT, InChain, 4626 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4627 MMO); 4628 4629 SDValue OutChain = L.getValue(1); 4630 4631 setValue(&I, L); 4632 DAG.setRoot(OutChain); 4633 } 4634 4635 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4636 SDLoc dl = getCurSDLoc(); 4637 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4638 SDValue Ops[3]; 4639 Ops[0] = getRoot(); 4640 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4641 TLI.getFenceOperandTy(DAG.getDataLayout())); 4642 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4643 TLI.getFenceOperandTy(DAG.getDataLayout())); 4644 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4645 } 4646 4647 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4648 SDLoc dl = getCurSDLoc(); 4649 AtomicOrdering Order = I.getOrdering(); 4650 SyncScope::ID SSID = I.getSyncScopeID(); 4651 4652 SDValue InChain = getRoot(); 4653 4654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4655 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4656 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType()); 4657 4658 if (!TLI.supportsUnalignedAtomics() && 4659 I.getAlignment() < MemVT.getSizeInBits() / 8) 4660 report_fatal_error("Cannot generate unaligned atomic load"); 4661 4662 auto Flags = MachineMemOperand::MOLoad; 4663 if (I.isVolatile()) 4664 Flags |= MachineMemOperand::MOVolatile; 4665 if (I.hasMetadata(LLVMContext::MD_invariant_load)) 4666 Flags |= MachineMemOperand::MOInvariant; 4667 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(), 4668 DAG.getDataLayout())) 4669 Flags |= MachineMemOperand::MODereferenceable; 4670 4671 Flags |= TLI.getMMOFlags(I); 4672 4673 MachineMemOperand *MMO = 4674 DAG.getMachineFunction(). 4675 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4676 Flags, MemVT.getStoreSize(), 4677 I.getAlignment() ? I.getAlignment() : 4678 DAG.getEVTAlignment(MemVT), 4679 AAMDNodes(), nullptr, SSID, Order); 4680 4681 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4682 4683 SDValue Ptr = getValue(I.getPointerOperand()); 4684 4685 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) { 4686 // TODO: Once this is better exercised by tests, it should be merged with 4687 // the normal path for loads to prevent future divergence. 4688 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO); 4689 if (MemVT != VT) 4690 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4691 4692 setValue(&I, L); 4693 SDValue OutChain = L.getValue(1); 4694 if (!I.isUnordered()) 4695 DAG.setRoot(OutChain); 4696 else 4697 PendingLoads.push_back(OutChain); 4698 return; 4699 } 4700 4701 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain, 4702 Ptr, MMO); 4703 4704 SDValue OutChain = L.getValue(1); 4705 if (MemVT != VT) 4706 L = DAG.getPtrExtOrTrunc(L, dl, VT); 4707 4708 setValue(&I, L); 4709 DAG.setRoot(OutChain); 4710 } 4711 4712 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4713 SDLoc dl = getCurSDLoc(); 4714 4715 AtomicOrdering Ordering = I.getOrdering(); 4716 SyncScope::ID SSID = I.getSyncScopeID(); 4717 4718 SDValue InChain = getRoot(); 4719 4720 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4721 EVT MemVT = 4722 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4723 4724 if (I.getAlignment() < MemVT.getSizeInBits() / 8) 4725 report_fatal_error("Cannot generate unaligned atomic store"); 4726 4727 auto Flags = MachineMemOperand::MOStore; 4728 if (I.isVolatile()) 4729 Flags |= MachineMemOperand::MOVolatile; 4730 Flags |= TLI.getMMOFlags(I); 4731 4732 MachineFunction &MF = DAG.getMachineFunction(); 4733 MachineMemOperand *MMO = 4734 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4735 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4736 nullptr, SSID, Ordering); 4737 4738 SDValue Val = getValue(I.getValueOperand()); 4739 if (Val.getValueType() != MemVT) 4740 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT); 4741 SDValue Ptr = getValue(I.getPointerOperand()); 4742 4743 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) { 4744 // TODO: Once this is better exercised by tests, it should be merged with 4745 // the normal path for stores to prevent future divergence. 4746 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO); 4747 DAG.setRoot(S); 4748 return; 4749 } 4750 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, 4751 Ptr, Val, MMO); 4752 4753 4754 DAG.setRoot(OutChain); 4755 } 4756 4757 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4758 /// node. 4759 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4760 unsigned Intrinsic) { 4761 // Ignore the callsite's attributes. A specific call site may be marked with 4762 // readnone, but the lowering code will expect the chain based on the 4763 // definition. 4764 const Function *F = I.getCalledFunction(); 4765 bool HasChain = !F->doesNotAccessMemory(); 4766 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4767 4768 // Build the operand list. 4769 SmallVector<SDValue, 8> Ops; 4770 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4771 if (OnlyLoad) { 4772 // We don't need to serialize loads against other loads. 4773 Ops.push_back(DAG.getRoot()); 4774 } else { 4775 Ops.push_back(getRoot()); 4776 } 4777 } 4778 4779 // Info is set by getTgtMemInstrinsic 4780 TargetLowering::IntrinsicInfo Info; 4781 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4782 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4783 DAG.getMachineFunction(), 4784 Intrinsic); 4785 4786 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4787 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4788 Info.opc == ISD::INTRINSIC_W_CHAIN) 4789 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4790 TLI.getPointerTy(DAG.getDataLayout()))); 4791 4792 // Add all operands of the call to the operand list. 4793 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4794 const Value *Arg = I.getArgOperand(i); 4795 if (!I.paramHasAttr(i, Attribute::ImmArg)) { 4796 Ops.push_back(getValue(Arg)); 4797 continue; 4798 } 4799 4800 // Use TargetConstant instead of a regular constant for immarg. 4801 EVT VT = TLI.getValueType(*DL, Arg->getType(), true); 4802 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) { 4803 assert(CI->getBitWidth() <= 64 && 4804 "large intrinsic immediates not handled"); 4805 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT)); 4806 } else { 4807 Ops.push_back( 4808 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT)); 4809 } 4810 } 4811 4812 SmallVector<EVT, 4> ValueVTs; 4813 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4814 4815 if (HasChain) 4816 ValueVTs.push_back(MVT::Other); 4817 4818 SDVTList VTs = DAG.getVTList(ValueVTs); 4819 4820 // Create the node. 4821 SDValue Result; 4822 if (IsTgtIntrinsic) { 4823 // This is target intrinsic that touches memory 4824 AAMDNodes AAInfo; 4825 I.getAAMetadata(AAInfo); 4826 Result = DAG.getMemIntrinsicNode( 4827 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT, 4828 MachinePointerInfo(Info.ptrVal, Info.offset), 4829 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo); 4830 } else if (!HasChain) { 4831 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4832 } else if (!I.getType()->isVoidTy()) { 4833 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4834 } else { 4835 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4836 } 4837 4838 if (HasChain) { 4839 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4840 if (OnlyLoad) 4841 PendingLoads.push_back(Chain); 4842 else 4843 DAG.setRoot(Chain); 4844 } 4845 4846 if (!I.getType()->isVoidTy()) { 4847 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4848 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4849 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4850 } else 4851 Result = lowerRangeToAssertZExt(DAG, I, Result); 4852 4853 setValue(&I, Result); 4854 } 4855 } 4856 4857 /// GetSignificand - Get the significand and build it into a floating-point 4858 /// number with exponent of 1: 4859 /// 4860 /// Op = (Op & 0x007fffff) | 0x3f800000; 4861 /// 4862 /// where Op is the hexadecimal representation of floating point value. 4863 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4864 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4865 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4866 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4867 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4868 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4869 } 4870 4871 /// GetExponent - Get the exponent: 4872 /// 4873 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4874 /// 4875 /// where Op is the hexadecimal representation of floating point value. 4876 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4877 const TargetLowering &TLI, const SDLoc &dl) { 4878 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4879 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4880 SDValue t1 = DAG.getNode( 4881 ISD::SRL, dl, MVT::i32, t0, 4882 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4883 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4884 DAG.getConstant(127, dl, MVT::i32)); 4885 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4886 } 4887 4888 /// getF32Constant - Get 32-bit floating point constant. 4889 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4890 const SDLoc &dl) { 4891 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4892 MVT::f32); 4893 } 4894 4895 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4896 SelectionDAG &DAG) { 4897 // TODO: What fast-math-flags should be set on the floating-point nodes? 4898 4899 // IntegerPartOfX = ((int32_t)(t0); 4900 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4901 4902 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4903 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4904 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4905 4906 // IntegerPartOfX <<= 23; 4907 IntegerPartOfX = DAG.getNode( 4908 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4909 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4910 DAG.getDataLayout()))); 4911 4912 SDValue TwoToFractionalPartOfX; 4913 if (LimitFloatPrecision <= 6) { 4914 // For floating-point precision of 6: 4915 // 4916 // TwoToFractionalPartOfX = 4917 // 0.997535578f + 4918 // (0.735607626f + 0.252464424f * x) * x; 4919 // 4920 // error 0.0144103317, which is 6 bits 4921 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4922 getF32Constant(DAG, 0x3e814304, dl)); 4923 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4924 getF32Constant(DAG, 0x3f3c50c8, dl)); 4925 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4926 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4927 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4928 } else if (LimitFloatPrecision <= 12) { 4929 // For floating-point precision of 12: 4930 // 4931 // TwoToFractionalPartOfX = 4932 // 0.999892986f + 4933 // (0.696457318f + 4934 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4935 // 4936 // error 0.000107046256, which is 13 to 14 bits 4937 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4938 getF32Constant(DAG, 0x3da235e3, dl)); 4939 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4940 getF32Constant(DAG, 0x3e65b8f3, dl)); 4941 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4942 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4943 getF32Constant(DAG, 0x3f324b07, dl)); 4944 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4945 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4946 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4947 } else { // LimitFloatPrecision <= 18 4948 // For floating-point precision of 18: 4949 // 4950 // TwoToFractionalPartOfX = 4951 // 0.999999982f + 4952 // (0.693148872f + 4953 // (0.240227044f + 4954 // (0.554906021e-1f + 4955 // (0.961591928e-2f + 4956 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4957 // error 2.47208000*10^(-7), which is better than 18 bits 4958 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4959 getF32Constant(DAG, 0x3924b03e, dl)); 4960 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4961 getF32Constant(DAG, 0x3ab24b87, dl)); 4962 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4963 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4964 getF32Constant(DAG, 0x3c1d8c17, dl)); 4965 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4966 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4967 getF32Constant(DAG, 0x3d634a1d, dl)); 4968 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4969 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4970 getF32Constant(DAG, 0x3e75fe14, dl)); 4971 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4972 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4973 getF32Constant(DAG, 0x3f317234, dl)); 4974 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4975 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4976 getF32Constant(DAG, 0x3f800000, dl)); 4977 } 4978 4979 // Add the exponent into the result in integer domain. 4980 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4981 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4982 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4983 } 4984 4985 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4986 /// limited-precision mode. 4987 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4988 const TargetLowering &TLI) { 4989 if (Op.getValueType() == MVT::f32 && 4990 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4991 4992 // Put the exponent in the right bit position for later addition to the 4993 // final result: 4994 // 4995 // t0 = Op * log2(e) 4996 4997 // TODO: What fast-math-flags should be set here? 4998 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4999 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32)); 5000 return getLimitedPrecisionExp2(t0, dl, DAG); 5001 } 5002 5003 // No special expansion. 5004 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 5005 } 5006 5007 /// expandLog - Lower a log intrinsic. Handles the special sequences for 5008 /// limited-precision mode. 5009 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5010 const TargetLowering &TLI) { 5011 // TODO: What fast-math-flags should be set on the floating-point nodes? 5012 5013 if (Op.getValueType() == MVT::f32 && 5014 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5015 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5016 5017 // Scale the exponent by log(2). 5018 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5019 SDValue LogOfExponent = 5020 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5021 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32)); 5022 5023 // Get the significand and build it into a floating-point number with 5024 // exponent of 1. 5025 SDValue X = GetSignificand(DAG, Op1, dl); 5026 5027 SDValue LogOfMantissa; 5028 if (LimitFloatPrecision <= 6) { 5029 // For floating-point precision of 6: 5030 // 5031 // LogofMantissa = 5032 // -1.1609546f + 5033 // (1.4034025f - 0.23903021f * x) * x; 5034 // 5035 // error 0.0034276066, which is better than 8 bits 5036 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5037 getF32Constant(DAG, 0xbe74c456, dl)); 5038 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5039 getF32Constant(DAG, 0x3fb3a2b1, dl)); 5040 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5041 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5042 getF32Constant(DAG, 0x3f949a29, dl)); 5043 } else if (LimitFloatPrecision <= 12) { 5044 // For floating-point precision of 12: 5045 // 5046 // LogOfMantissa = 5047 // -1.7417939f + 5048 // (2.8212026f + 5049 // (-1.4699568f + 5050 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 5051 // 5052 // error 0.000061011436, which is 14 bits 5053 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5054 getF32Constant(DAG, 0xbd67b6d6, dl)); 5055 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5056 getF32Constant(DAG, 0x3ee4f4b8, dl)); 5057 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5058 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5059 getF32Constant(DAG, 0x3fbc278b, dl)); 5060 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5061 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5062 getF32Constant(DAG, 0x40348e95, dl)); 5063 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5064 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5065 getF32Constant(DAG, 0x3fdef31a, dl)); 5066 } else { // LimitFloatPrecision <= 18 5067 // For floating-point precision of 18: 5068 // 5069 // LogOfMantissa = 5070 // -2.1072184f + 5071 // (4.2372794f + 5072 // (-3.7029485f + 5073 // (2.2781945f + 5074 // (-0.87823314f + 5075 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 5076 // 5077 // error 0.0000023660568, which is better than 18 bits 5078 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5079 getF32Constant(DAG, 0xbc91e5ac, dl)); 5080 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5081 getF32Constant(DAG, 0x3e4350aa, dl)); 5082 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5083 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5084 getF32Constant(DAG, 0x3f60d3e3, dl)); 5085 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5086 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5087 getF32Constant(DAG, 0x4011cdf0, dl)); 5088 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5089 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5090 getF32Constant(DAG, 0x406cfd1c, dl)); 5091 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5092 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5093 getF32Constant(DAG, 0x408797cb, dl)); 5094 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5095 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5096 getF32Constant(DAG, 0x4006dcab, dl)); 5097 } 5098 5099 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 5100 } 5101 5102 // No special expansion. 5103 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 5104 } 5105 5106 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 5107 /// limited-precision mode. 5108 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5109 const TargetLowering &TLI) { 5110 // TODO: What fast-math-flags should be set on the floating-point nodes? 5111 5112 if (Op.getValueType() == MVT::f32 && 5113 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5114 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5115 5116 // Get the exponent. 5117 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 5118 5119 // Get the significand and build it into a floating-point number with 5120 // exponent of 1. 5121 SDValue X = GetSignificand(DAG, Op1, dl); 5122 5123 // Different possible minimax approximations of significand in 5124 // floating-point for various degrees of accuracy over [1,2]. 5125 SDValue Log2ofMantissa; 5126 if (LimitFloatPrecision <= 6) { 5127 // For floating-point precision of 6: 5128 // 5129 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 5130 // 5131 // error 0.0049451742, which is more than 7 bits 5132 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5133 getF32Constant(DAG, 0xbeb08fe0, dl)); 5134 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5135 getF32Constant(DAG, 0x40019463, dl)); 5136 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5137 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5138 getF32Constant(DAG, 0x3fd6633d, dl)); 5139 } else if (LimitFloatPrecision <= 12) { 5140 // For floating-point precision of 12: 5141 // 5142 // Log2ofMantissa = 5143 // -2.51285454f + 5144 // (4.07009056f + 5145 // (-2.12067489f + 5146 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5147 // 5148 // error 0.0000876136000, which is better than 13 bits 5149 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5150 getF32Constant(DAG, 0xbda7262e, dl)); 5151 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5152 getF32Constant(DAG, 0x3f25280b, dl)); 5153 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5154 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5155 getF32Constant(DAG, 0x4007b923, dl)); 5156 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5157 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5158 getF32Constant(DAG, 0x40823e2f, dl)); 5159 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5160 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5161 getF32Constant(DAG, 0x4020d29c, dl)); 5162 } else { // LimitFloatPrecision <= 18 5163 // For floating-point precision of 18: 5164 // 5165 // Log2ofMantissa = 5166 // -3.0400495f + 5167 // (6.1129976f + 5168 // (-5.3420409f + 5169 // (3.2865683f + 5170 // (-1.2669343f + 5171 // (0.27515199f - 5172 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5173 // 5174 // error 0.0000018516, which is better than 18 bits 5175 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5176 getF32Constant(DAG, 0xbcd2769e, dl)); 5177 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5178 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5179 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5180 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5181 getF32Constant(DAG, 0x3fa22ae7, dl)); 5182 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5183 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5184 getF32Constant(DAG, 0x40525723, dl)); 5185 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5186 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5187 getF32Constant(DAG, 0x40aaf200, dl)); 5188 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5189 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5190 getF32Constant(DAG, 0x40c39dad, dl)); 5191 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5192 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5193 getF32Constant(DAG, 0x4042902c, dl)); 5194 } 5195 5196 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5197 } 5198 5199 // No special expansion. 5200 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5201 } 5202 5203 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5204 /// limited-precision mode. 5205 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5206 const TargetLowering &TLI) { 5207 // TODO: What fast-math-flags should be set on the floating-point nodes? 5208 5209 if (Op.getValueType() == MVT::f32 && 5210 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5211 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5212 5213 // Scale the exponent by log10(2) [0.30102999f]. 5214 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5215 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5216 getF32Constant(DAG, 0x3e9a209a, dl)); 5217 5218 // Get the significand and build it into a floating-point number with 5219 // exponent of 1. 5220 SDValue X = GetSignificand(DAG, Op1, dl); 5221 5222 SDValue Log10ofMantissa; 5223 if (LimitFloatPrecision <= 6) { 5224 // For floating-point precision of 6: 5225 // 5226 // Log10ofMantissa = 5227 // -0.50419619f + 5228 // (0.60948995f - 0.10380950f * x) * x; 5229 // 5230 // error 0.0014886165, which is 6 bits 5231 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5232 getF32Constant(DAG, 0xbdd49a13, dl)); 5233 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5234 getF32Constant(DAG, 0x3f1c0789, dl)); 5235 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5236 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5237 getF32Constant(DAG, 0x3f011300, dl)); 5238 } else if (LimitFloatPrecision <= 12) { 5239 // For floating-point precision of 12: 5240 // 5241 // Log10ofMantissa = 5242 // -0.64831180f + 5243 // (0.91751397f + 5244 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5245 // 5246 // error 0.00019228036, which is better than 12 bits 5247 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5248 getF32Constant(DAG, 0x3d431f31, dl)); 5249 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5250 getF32Constant(DAG, 0x3ea21fb2, dl)); 5251 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5252 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5253 getF32Constant(DAG, 0x3f6ae232, dl)); 5254 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5255 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5256 getF32Constant(DAG, 0x3f25f7c3, dl)); 5257 } else { // LimitFloatPrecision <= 18 5258 // For floating-point precision of 18: 5259 // 5260 // Log10ofMantissa = 5261 // -0.84299375f + 5262 // (1.5327582f + 5263 // (-1.0688956f + 5264 // (0.49102474f + 5265 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5266 // 5267 // error 0.0000037995730, which is better than 18 bits 5268 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5269 getF32Constant(DAG, 0x3c5d51ce, dl)); 5270 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5271 getF32Constant(DAG, 0x3e00685a, dl)); 5272 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5273 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5274 getF32Constant(DAG, 0x3efb6798, dl)); 5275 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5276 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5277 getF32Constant(DAG, 0x3f88d192, dl)); 5278 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5279 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5280 getF32Constant(DAG, 0x3fc4316c, dl)); 5281 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5282 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5283 getF32Constant(DAG, 0x3f57ce70, dl)); 5284 } 5285 5286 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5287 } 5288 5289 // No special expansion. 5290 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5291 } 5292 5293 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5294 /// limited-precision mode. 5295 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5296 const TargetLowering &TLI) { 5297 if (Op.getValueType() == MVT::f32 && 5298 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5299 return getLimitedPrecisionExp2(Op, dl, DAG); 5300 5301 // No special expansion. 5302 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5303 } 5304 5305 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5306 /// limited-precision mode with x == 10.0f. 5307 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5308 SelectionDAG &DAG, const TargetLowering &TLI) { 5309 bool IsExp10 = false; 5310 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5311 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5312 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5313 APFloat Ten(10.0f); 5314 IsExp10 = LHSC->isExactlyValue(Ten); 5315 } 5316 } 5317 5318 // TODO: What fast-math-flags should be set on the FMUL node? 5319 if (IsExp10) { 5320 // Put the exponent in the right bit position for later addition to the 5321 // final result: 5322 // 5323 // #define LOG2OF10 3.3219281f 5324 // t0 = Op * LOG2OF10; 5325 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5326 getF32Constant(DAG, 0x40549a78, dl)); 5327 return getLimitedPrecisionExp2(t0, dl, DAG); 5328 } 5329 5330 // No special expansion. 5331 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5332 } 5333 5334 /// ExpandPowI - Expand a llvm.powi intrinsic. 5335 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5336 SelectionDAG &DAG) { 5337 // If RHS is a constant, we can expand this out to a multiplication tree, 5338 // otherwise we end up lowering to a call to __powidf2 (for example). When 5339 // optimizing for size, we only want to do this if the expansion would produce 5340 // a small number of multiplies, otherwise we do the full expansion. 5341 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5342 // Get the exponent as a positive value. 5343 unsigned Val = RHSC->getSExtValue(); 5344 if ((int)Val < 0) Val = -Val; 5345 5346 // powi(x, 0) -> 1.0 5347 if (Val == 0) 5348 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5349 5350 const Function &F = DAG.getMachineFunction().getFunction(); 5351 if (!F.hasOptSize() || 5352 // If optimizing for size, don't insert too many multiplies. 5353 // This inserts up to 5 multiplies. 5354 countPopulation(Val) + Log2_32(Val) < 7) { 5355 // We use the simple binary decomposition method to generate the multiply 5356 // sequence. There are more optimal ways to do this (for example, 5357 // powi(x,15) generates one more multiply than it should), but this has 5358 // the benefit of being both really simple and much better than a libcall. 5359 SDValue Res; // Logically starts equal to 1.0 5360 SDValue CurSquare = LHS; 5361 // TODO: Intrinsics should have fast-math-flags that propagate to these 5362 // nodes. 5363 while (Val) { 5364 if (Val & 1) { 5365 if (Res.getNode()) 5366 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5367 else 5368 Res = CurSquare; // 1.0*CurSquare. 5369 } 5370 5371 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5372 CurSquare, CurSquare); 5373 Val >>= 1; 5374 } 5375 5376 // If the original was negative, invert the result, producing 1/(x*x*x). 5377 if (RHSC->getSExtValue() < 0) 5378 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5379 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5380 return Res; 5381 } 5382 } 5383 5384 // Otherwise, expand to a libcall. 5385 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5386 } 5387 5388 // getUnderlyingArgRegs - Find underlying registers used for a truncated, 5389 // bitcasted, or split argument. Returns a list of <Register, size in bits> 5390 static void 5391 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs, 5392 const SDValue &N) { 5393 switch (N.getOpcode()) { 5394 case ISD::CopyFromReg: { 5395 SDValue Op = N.getOperand(1); 5396 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(), 5397 Op.getValueType().getSizeInBits()); 5398 return; 5399 } 5400 case ISD::BITCAST: 5401 case ISD::AssertZext: 5402 case ISD::AssertSext: 5403 case ISD::TRUNCATE: 5404 getUnderlyingArgRegs(Regs, N.getOperand(0)); 5405 return; 5406 case ISD::BUILD_PAIR: 5407 case ISD::BUILD_VECTOR: 5408 case ISD::CONCAT_VECTORS: 5409 for (SDValue Op : N->op_values()) 5410 getUnderlyingArgRegs(Regs, Op); 5411 return; 5412 default: 5413 return; 5414 } 5415 } 5416 5417 /// If the DbgValueInst is a dbg_value of a function argument, create the 5418 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5419 /// instruction selection, they will be inserted to the entry BB. 5420 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5421 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5422 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5423 const Argument *Arg = dyn_cast<Argument>(V); 5424 if (!Arg) 5425 return false; 5426 5427 if (!IsDbgDeclare) { 5428 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5429 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5430 // the entry block. 5431 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5432 if (!IsInEntryBlock) 5433 return false; 5434 5435 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5436 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5437 // variable that also is a param. 5438 // 5439 // Although, if we are at the top of the entry block already, we can still 5440 // emit using ArgDbgValue. This might catch some situations when the 5441 // dbg.value refers to an argument that isn't used in the entry block, so 5442 // any CopyToReg node would be optimized out and the only way to express 5443 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5444 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5445 // we should only emit as ArgDbgValue if the Variable is an argument to the 5446 // current function, and the dbg.value intrinsic is found in the entry 5447 // block. 5448 bool VariableIsFunctionInputArg = Variable->isParameter() && 5449 !DL->getInlinedAt(); 5450 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5451 if (!IsInPrologue && !VariableIsFunctionInputArg) 5452 return false; 5453 5454 // Here we assume that a function argument on IR level only can be used to 5455 // describe one input parameter on source level. If we for example have 5456 // source code like this 5457 // 5458 // struct A { long x, y; }; 5459 // void foo(struct A a, long b) { 5460 // ... 5461 // b = a.x; 5462 // ... 5463 // } 5464 // 5465 // and IR like this 5466 // 5467 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5468 // entry: 5469 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5470 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5471 // call void @llvm.dbg.value(metadata i32 %b, "b", 5472 // ... 5473 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5474 // ... 5475 // 5476 // then the last dbg.value is describing a parameter "b" using a value that 5477 // is an argument. But since we already has used %a1 to describe a parameter 5478 // we should not handle that last dbg.value here (that would result in an 5479 // incorrect hoisting of the DBG_VALUE to the function entry). 5480 // Notice that we allow one dbg.value per IR level argument, to accomodate 5481 // for the situation with fragments above. 5482 if (VariableIsFunctionInputArg) { 5483 unsigned ArgNo = Arg->getArgNo(); 5484 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5485 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5486 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5487 return false; 5488 FuncInfo.DescribedArgs.set(ArgNo); 5489 } 5490 } 5491 5492 MachineFunction &MF = DAG.getMachineFunction(); 5493 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5494 5495 bool IsIndirect = false; 5496 Optional<MachineOperand> Op; 5497 // Some arguments' frame index is recorded during argument lowering. 5498 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5499 if (FI != std::numeric_limits<int>::max()) 5500 Op = MachineOperand::CreateFI(FI); 5501 5502 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes; 5503 if (!Op && N.getNode()) { 5504 getUnderlyingArgRegs(ArgRegsAndSizes, N); 5505 Register Reg; 5506 if (ArgRegsAndSizes.size() == 1) 5507 Reg = ArgRegsAndSizes.front().first; 5508 5509 if (Reg && Reg.isVirtual()) { 5510 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5511 Register PR = RegInfo.getLiveInPhysReg(Reg); 5512 if (PR) 5513 Reg = PR; 5514 } 5515 if (Reg) { 5516 Op = MachineOperand::CreateReg(Reg, false); 5517 IsIndirect = IsDbgDeclare; 5518 } 5519 } 5520 5521 if (!Op && N.getNode()) { 5522 // Check if frame index is available. 5523 SDValue LCandidate = peekThroughBitcasts(N); 5524 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5525 if (FrameIndexSDNode *FINode = 5526 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5527 Op = MachineOperand::CreateFI(FINode->getIndex()); 5528 } 5529 5530 if (!Op) { 5531 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg 5532 auto splitMultiRegDbgValue 5533 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) { 5534 unsigned Offset = 0; 5535 for (auto RegAndSize : SplitRegs) { 5536 auto FragmentExpr = DIExpression::createFragmentExpression( 5537 Expr, Offset, RegAndSize.second); 5538 if (!FragmentExpr) 5539 continue; 5540 assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?"); 5541 FuncInfo.ArgDbgValues.push_back( 5542 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5543 RegAndSize.first, Variable, *FragmentExpr)); 5544 Offset += RegAndSize.second; 5545 } 5546 }; 5547 5548 // Check if ValueMap has reg number. 5549 DenseMap<const Value *, unsigned>::const_iterator 5550 VMI = FuncInfo.ValueMap.find(V); 5551 if (VMI != FuncInfo.ValueMap.end()) { 5552 const auto &TLI = DAG.getTargetLoweringInfo(); 5553 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5554 V->getType(), getABIRegCopyCC(V)); 5555 if (RFV.occupiesMultipleRegs()) { 5556 splitMultiRegDbgValue(RFV.getRegsAndSizes()); 5557 return true; 5558 } 5559 5560 Op = MachineOperand::CreateReg(VMI->second, false); 5561 IsIndirect = IsDbgDeclare; 5562 } else if (ArgRegsAndSizes.size() > 1) { 5563 // This was split due to the calling convention, and no virtual register 5564 // mapping exists for the value. 5565 splitMultiRegDbgValue(ArgRegsAndSizes); 5566 return true; 5567 } 5568 } 5569 5570 if (!Op) 5571 return false; 5572 5573 assert(Variable->isValidLocationForIntrinsic(DL) && 5574 "Expected inlined-at fields to agree"); 5575 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5576 if (IsIndirect) 5577 Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref}); 5578 FuncInfo.ArgDbgValues.push_back( 5579 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false, 5580 *Op, Variable, Expr)); 5581 5582 return true; 5583 } 5584 5585 /// Return the appropriate SDDbgValue based on N. 5586 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5587 DILocalVariable *Variable, 5588 DIExpression *Expr, 5589 const DebugLoc &dl, 5590 unsigned DbgSDNodeOrder) { 5591 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5592 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5593 // stack slot locations. 5594 // 5595 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5596 // debug values here after optimization: 5597 // 5598 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5599 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5600 // 5601 // Both describe the direct values of their associated variables. 5602 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5603 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5604 } 5605 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5606 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5607 } 5608 5609 // VisualStudio defines setjmp as _setjmp 5610 #if defined(_MSC_VER) && defined(setjmp) && \ 5611 !defined(setjmp_undefined_for_msvc) 5612 # pragma push_macro("setjmp") 5613 # undef setjmp 5614 # define setjmp_undefined_for_msvc 5615 #endif 5616 5617 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5618 switch (Intrinsic) { 5619 case Intrinsic::smul_fix: 5620 return ISD::SMULFIX; 5621 case Intrinsic::umul_fix: 5622 return ISD::UMULFIX; 5623 default: 5624 llvm_unreachable("Unhandled fixed point intrinsic"); 5625 } 5626 } 5627 5628 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I, 5629 const char *FunctionName) { 5630 assert(FunctionName && "FunctionName must not be nullptr"); 5631 SDValue Callee = DAG.getExternalSymbol( 5632 FunctionName, 5633 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 5634 LowerCallTo(&I, Callee, I.isTailCall()); 5635 } 5636 5637 /// Lower the call to the specified intrinsic function. 5638 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, 5639 unsigned Intrinsic) { 5640 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5641 SDLoc sdl = getCurSDLoc(); 5642 DebugLoc dl = getCurDebugLoc(); 5643 SDValue Res; 5644 5645 switch (Intrinsic) { 5646 default: 5647 // By default, turn this into a target intrinsic node. 5648 visitTargetIntrinsic(I, Intrinsic); 5649 return; 5650 case Intrinsic::vastart: visitVAStart(I); return; 5651 case Intrinsic::vaend: visitVAEnd(I); return; 5652 case Intrinsic::vacopy: visitVACopy(I); return; 5653 case Intrinsic::returnaddress: 5654 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5655 TLI.getPointerTy(DAG.getDataLayout()), 5656 getValue(I.getArgOperand(0)))); 5657 return; 5658 case Intrinsic::addressofreturnaddress: 5659 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5660 TLI.getPointerTy(DAG.getDataLayout()))); 5661 return; 5662 case Intrinsic::sponentry: 5663 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5664 TLI.getFrameIndexTy(DAG.getDataLayout()))); 5665 return; 5666 case Intrinsic::frameaddress: 5667 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5668 TLI.getFrameIndexTy(DAG.getDataLayout()), 5669 getValue(I.getArgOperand(0)))); 5670 return; 5671 case Intrinsic::read_register: { 5672 Value *Reg = I.getArgOperand(0); 5673 SDValue Chain = getRoot(); 5674 SDValue RegName = 5675 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5676 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5677 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5678 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5679 setValue(&I, Res); 5680 DAG.setRoot(Res.getValue(1)); 5681 return; 5682 } 5683 case Intrinsic::write_register: { 5684 Value *Reg = I.getArgOperand(0); 5685 Value *RegValue = I.getArgOperand(1); 5686 SDValue Chain = getRoot(); 5687 SDValue RegName = 5688 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5689 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5690 RegName, getValue(RegValue))); 5691 return; 5692 } 5693 case Intrinsic::setjmp: 5694 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]); 5695 return; 5696 case Intrinsic::longjmp: 5697 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]); 5698 return; 5699 case Intrinsic::memcpy: { 5700 const auto &MCI = cast<MemCpyInst>(I); 5701 SDValue Op1 = getValue(I.getArgOperand(0)); 5702 SDValue Op2 = getValue(I.getArgOperand(1)); 5703 SDValue Op3 = getValue(I.getArgOperand(2)); 5704 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5705 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5706 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5707 unsigned Align = MinAlign(DstAlign, SrcAlign); 5708 bool isVol = MCI.isVolatile(); 5709 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5710 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5711 // node. 5712 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5713 false, isTC, 5714 MachinePointerInfo(I.getArgOperand(0)), 5715 MachinePointerInfo(I.getArgOperand(1))); 5716 updateDAGForMaybeTailCall(MC); 5717 return; 5718 } 5719 case Intrinsic::memset: { 5720 const auto &MSI = cast<MemSetInst>(I); 5721 SDValue Op1 = getValue(I.getArgOperand(0)); 5722 SDValue Op2 = getValue(I.getArgOperand(1)); 5723 SDValue Op3 = getValue(I.getArgOperand(2)); 5724 // @llvm.memset defines 0 and 1 to both mean no alignment. 5725 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5726 bool isVol = MSI.isVolatile(); 5727 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5728 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5729 isTC, MachinePointerInfo(I.getArgOperand(0))); 5730 updateDAGForMaybeTailCall(MS); 5731 return; 5732 } 5733 case Intrinsic::memmove: { 5734 const auto &MMI = cast<MemMoveInst>(I); 5735 SDValue Op1 = getValue(I.getArgOperand(0)); 5736 SDValue Op2 = getValue(I.getArgOperand(1)); 5737 SDValue Op3 = getValue(I.getArgOperand(2)); 5738 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5739 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5740 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5741 unsigned Align = MinAlign(DstAlign, SrcAlign); 5742 bool isVol = MMI.isVolatile(); 5743 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5744 // FIXME: Support passing different dest/src alignments to the memmove DAG 5745 // node. 5746 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5747 isTC, MachinePointerInfo(I.getArgOperand(0)), 5748 MachinePointerInfo(I.getArgOperand(1))); 5749 updateDAGForMaybeTailCall(MM); 5750 return; 5751 } 5752 case Intrinsic::memcpy_element_unordered_atomic: { 5753 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5754 SDValue Dst = getValue(MI.getRawDest()); 5755 SDValue Src = getValue(MI.getRawSource()); 5756 SDValue Length = getValue(MI.getLength()); 5757 5758 unsigned DstAlign = MI.getDestAlignment(); 5759 unsigned SrcAlign = MI.getSourceAlignment(); 5760 Type *LengthTy = MI.getLength()->getType(); 5761 unsigned ElemSz = MI.getElementSizeInBytes(); 5762 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5763 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5764 SrcAlign, Length, LengthTy, ElemSz, isTC, 5765 MachinePointerInfo(MI.getRawDest()), 5766 MachinePointerInfo(MI.getRawSource())); 5767 updateDAGForMaybeTailCall(MC); 5768 return; 5769 } 5770 case Intrinsic::memmove_element_unordered_atomic: { 5771 auto &MI = cast<AtomicMemMoveInst>(I); 5772 SDValue Dst = getValue(MI.getRawDest()); 5773 SDValue Src = getValue(MI.getRawSource()); 5774 SDValue Length = getValue(MI.getLength()); 5775 5776 unsigned DstAlign = MI.getDestAlignment(); 5777 unsigned SrcAlign = MI.getSourceAlignment(); 5778 Type *LengthTy = MI.getLength()->getType(); 5779 unsigned ElemSz = MI.getElementSizeInBytes(); 5780 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5781 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5782 SrcAlign, Length, LengthTy, ElemSz, isTC, 5783 MachinePointerInfo(MI.getRawDest()), 5784 MachinePointerInfo(MI.getRawSource())); 5785 updateDAGForMaybeTailCall(MC); 5786 return; 5787 } 5788 case Intrinsic::memset_element_unordered_atomic: { 5789 auto &MI = cast<AtomicMemSetInst>(I); 5790 SDValue Dst = getValue(MI.getRawDest()); 5791 SDValue Val = getValue(MI.getValue()); 5792 SDValue Length = getValue(MI.getLength()); 5793 5794 unsigned DstAlign = MI.getDestAlignment(); 5795 Type *LengthTy = MI.getLength()->getType(); 5796 unsigned ElemSz = MI.getElementSizeInBytes(); 5797 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5798 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5799 LengthTy, ElemSz, isTC, 5800 MachinePointerInfo(MI.getRawDest())); 5801 updateDAGForMaybeTailCall(MC); 5802 return; 5803 } 5804 case Intrinsic::dbg_addr: 5805 case Intrinsic::dbg_declare: { 5806 const auto &DI = cast<DbgVariableIntrinsic>(I); 5807 DILocalVariable *Variable = DI.getVariable(); 5808 DIExpression *Expression = DI.getExpression(); 5809 dropDanglingDebugInfo(Variable, Expression); 5810 assert(Variable && "Missing variable"); 5811 5812 // Check if address has undef value. 5813 const Value *Address = DI.getVariableLocation(); 5814 if (!Address || isa<UndefValue>(Address) || 5815 (Address->use_empty() && !isa<Argument>(Address))) { 5816 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5817 return; 5818 } 5819 5820 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5821 5822 // Check if this variable can be described by a frame index, typically 5823 // either as a static alloca or a byval parameter. 5824 int FI = std::numeric_limits<int>::max(); 5825 if (const auto *AI = 5826 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5827 if (AI->isStaticAlloca()) { 5828 auto I = FuncInfo.StaticAllocaMap.find(AI); 5829 if (I != FuncInfo.StaticAllocaMap.end()) 5830 FI = I->second; 5831 } 5832 } else if (const auto *Arg = dyn_cast<Argument>( 5833 Address->stripInBoundsConstantOffsets())) { 5834 FI = FuncInfo.getArgumentFrameIndex(Arg); 5835 } 5836 5837 // llvm.dbg.addr is control dependent and always generates indirect 5838 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5839 // the MachineFunction variable table. 5840 if (FI != std::numeric_limits<int>::max()) { 5841 if (Intrinsic == Intrinsic::dbg_addr) { 5842 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5843 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5844 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5845 } 5846 return; 5847 } 5848 5849 SDValue &N = NodeMap[Address]; 5850 if (!N.getNode() && isa<Argument>(Address)) 5851 // Check unused arguments map. 5852 N = UnusedArgNodeMap[Address]; 5853 SDDbgValue *SDV; 5854 if (N.getNode()) { 5855 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5856 Address = BCI->getOperand(0); 5857 // Parameters are handled specially. 5858 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5859 if (isParameter && FINode) { 5860 // Byval parameter. We have a frame index at this point. 5861 SDV = 5862 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5863 /*IsIndirect*/ true, dl, SDNodeOrder); 5864 } else if (isa<Argument>(Address)) { 5865 // Address is an argument, so try to emit its dbg value using 5866 // virtual register info from the FuncInfo.ValueMap. 5867 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5868 return; 5869 } else { 5870 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5871 true, dl, SDNodeOrder); 5872 } 5873 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5874 } else { 5875 // If Address is an argument then try to emit its dbg value using 5876 // virtual register info from the FuncInfo.ValueMap. 5877 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5878 N)) { 5879 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5880 } 5881 } 5882 return; 5883 } 5884 case Intrinsic::dbg_label: { 5885 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5886 DILabel *Label = DI.getLabel(); 5887 assert(Label && "Missing label"); 5888 5889 SDDbgLabel *SDV; 5890 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5891 DAG.AddDbgLabel(SDV); 5892 return; 5893 } 5894 case Intrinsic::dbg_value: { 5895 const DbgValueInst &DI = cast<DbgValueInst>(I); 5896 assert(DI.getVariable() && "Missing variable"); 5897 5898 DILocalVariable *Variable = DI.getVariable(); 5899 DIExpression *Expression = DI.getExpression(); 5900 dropDanglingDebugInfo(Variable, Expression); 5901 const Value *V = DI.getValue(); 5902 if (!V) 5903 return; 5904 5905 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5906 SDNodeOrder)) 5907 return; 5908 5909 // TODO: Dangling debug info will eventually either be resolved or produce 5910 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5911 // between the original dbg.value location and its resolved DBG_VALUE, which 5912 // we should ideally fill with an extra Undef DBG_VALUE. 5913 5914 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5915 return; 5916 } 5917 5918 case Intrinsic::eh_typeid_for: { 5919 // Find the type id for the given typeinfo. 5920 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5921 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5922 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5923 setValue(&I, Res); 5924 return; 5925 } 5926 5927 case Intrinsic::eh_return_i32: 5928 case Intrinsic::eh_return_i64: 5929 DAG.getMachineFunction().setCallsEHReturn(true); 5930 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5931 MVT::Other, 5932 getControlRoot(), 5933 getValue(I.getArgOperand(0)), 5934 getValue(I.getArgOperand(1)))); 5935 return; 5936 case Intrinsic::eh_unwind_init: 5937 DAG.getMachineFunction().setCallsUnwindInit(true); 5938 return; 5939 case Intrinsic::eh_dwarf_cfa: 5940 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5941 TLI.getPointerTy(DAG.getDataLayout()), 5942 getValue(I.getArgOperand(0)))); 5943 return; 5944 case Intrinsic::eh_sjlj_callsite: { 5945 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5946 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5947 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5948 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5949 5950 MMI.setCurrentCallSite(CI->getZExtValue()); 5951 return; 5952 } 5953 case Intrinsic::eh_sjlj_functioncontext: { 5954 // Get and store the index of the function context. 5955 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5956 AllocaInst *FnCtx = 5957 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5958 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5959 MFI.setFunctionContextIndex(FI); 5960 return; 5961 } 5962 case Intrinsic::eh_sjlj_setjmp: { 5963 SDValue Ops[2]; 5964 Ops[0] = getRoot(); 5965 Ops[1] = getValue(I.getArgOperand(0)); 5966 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5967 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5968 setValue(&I, Op.getValue(0)); 5969 DAG.setRoot(Op.getValue(1)); 5970 return; 5971 } 5972 case Intrinsic::eh_sjlj_longjmp: 5973 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5974 getRoot(), getValue(I.getArgOperand(0)))); 5975 return; 5976 case Intrinsic::eh_sjlj_setup_dispatch: 5977 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5978 getRoot())); 5979 return; 5980 case Intrinsic::masked_gather: 5981 visitMaskedGather(I); 5982 return; 5983 case Intrinsic::masked_load: 5984 visitMaskedLoad(I); 5985 return; 5986 case Intrinsic::masked_scatter: 5987 visitMaskedScatter(I); 5988 return; 5989 case Intrinsic::masked_store: 5990 visitMaskedStore(I); 5991 return; 5992 case Intrinsic::masked_expandload: 5993 visitMaskedLoad(I, true /* IsExpanding */); 5994 return; 5995 case Intrinsic::masked_compressstore: 5996 visitMaskedStore(I, true /* IsCompressing */); 5997 return; 5998 case Intrinsic::powi: 5999 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 6000 getValue(I.getArgOperand(1)), DAG)); 6001 return; 6002 case Intrinsic::log: 6003 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6004 return; 6005 case Intrinsic::log2: 6006 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6007 return; 6008 case Intrinsic::log10: 6009 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6010 return; 6011 case Intrinsic::exp: 6012 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6013 return; 6014 case Intrinsic::exp2: 6015 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 6016 return; 6017 case Intrinsic::pow: 6018 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 6019 getValue(I.getArgOperand(1)), DAG, TLI)); 6020 return; 6021 case Intrinsic::sqrt: 6022 case Intrinsic::fabs: 6023 case Intrinsic::sin: 6024 case Intrinsic::cos: 6025 case Intrinsic::floor: 6026 case Intrinsic::ceil: 6027 case Intrinsic::trunc: 6028 case Intrinsic::rint: 6029 case Intrinsic::nearbyint: 6030 case Intrinsic::round: 6031 case Intrinsic::canonicalize: { 6032 unsigned Opcode; 6033 switch (Intrinsic) { 6034 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6035 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 6036 case Intrinsic::fabs: Opcode = ISD::FABS; break; 6037 case Intrinsic::sin: Opcode = ISD::FSIN; break; 6038 case Intrinsic::cos: Opcode = ISD::FCOS; break; 6039 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 6040 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 6041 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 6042 case Intrinsic::rint: Opcode = ISD::FRINT; break; 6043 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 6044 case Intrinsic::round: Opcode = ISD::FROUND; break; 6045 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 6046 } 6047 6048 setValue(&I, DAG.getNode(Opcode, sdl, 6049 getValue(I.getArgOperand(0)).getValueType(), 6050 getValue(I.getArgOperand(0)))); 6051 return; 6052 } 6053 case Intrinsic::lround: 6054 case Intrinsic::llround: 6055 case Intrinsic::lrint: 6056 case Intrinsic::llrint: { 6057 unsigned Opcode; 6058 switch (Intrinsic) { 6059 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6060 case Intrinsic::lround: Opcode = ISD::LROUND; break; 6061 case Intrinsic::llround: Opcode = ISD::LLROUND; break; 6062 case Intrinsic::lrint: Opcode = ISD::LRINT; break; 6063 case Intrinsic::llrint: Opcode = ISD::LLRINT; break; 6064 } 6065 6066 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6067 setValue(&I, DAG.getNode(Opcode, sdl, RetVT, 6068 getValue(I.getArgOperand(0)))); 6069 return; 6070 } 6071 case Intrinsic::minnum: 6072 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl, 6073 getValue(I.getArgOperand(0)).getValueType(), 6074 getValue(I.getArgOperand(0)), 6075 getValue(I.getArgOperand(1)))); 6076 return; 6077 case Intrinsic::maxnum: 6078 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl, 6079 getValue(I.getArgOperand(0)).getValueType(), 6080 getValue(I.getArgOperand(0)), 6081 getValue(I.getArgOperand(1)))); 6082 return; 6083 case Intrinsic::minimum: 6084 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 6085 getValue(I.getArgOperand(0)).getValueType(), 6086 getValue(I.getArgOperand(0)), 6087 getValue(I.getArgOperand(1)))); 6088 return; 6089 case Intrinsic::maximum: 6090 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 6091 getValue(I.getArgOperand(0)).getValueType(), 6092 getValue(I.getArgOperand(0)), 6093 getValue(I.getArgOperand(1)))); 6094 return; 6095 case Intrinsic::copysign: 6096 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 6097 getValue(I.getArgOperand(0)).getValueType(), 6098 getValue(I.getArgOperand(0)), 6099 getValue(I.getArgOperand(1)))); 6100 return; 6101 case Intrinsic::fma: 6102 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6103 getValue(I.getArgOperand(0)).getValueType(), 6104 getValue(I.getArgOperand(0)), 6105 getValue(I.getArgOperand(1)), 6106 getValue(I.getArgOperand(2)))); 6107 return; 6108 case Intrinsic::experimental_constrained_fadd: 6109 case Intrinsic::experimental_constrained_fsub: 6110 case Intrinsic::experimental_constrained_fmul: 6111 case Intrinsic::experimental_constrained_fdiv: 6112 case Intrinsic::experimental_constrained_frem: 6113 case Intrinsic::experimental_constrained_fma: 6114 case Intrinsic::experimental_constrained_fptosi: 6115 case Intrinsic::experimental_constrained_fptoui: 6116 case Intrinsic::experimental_constrained_fptrunc: 6117 case Intrinsic::experimental_constrained_fpext: 6118 case Intrinsic::experimental_constrained_sqrt: 6119 case Intrinsic::experimental_constrained_pow: 6120 case Intrinsic::experimental_constrained_powi: 6121 case Intrinsic::experimental_constrained_sin: 6122 case Intrinsic::experimental_constrained_cos: 6123 case Intrinsic::experimental_constrained_exp: 6124 case Intrinsic::experimental_constrained_exp2: 6125 case Intrinsic::experimental_constrained_log: 6126 case Intrinsic::experimental_constrained_log10: 6127 case Intrinsic::experimental_constrained_log2: 6128 case Intrinsic::experimental_constrained_lrint: 6129 case Intrinsic::experimental_constrained_llrint: 6130 case Intrinsic::experimental_constrained_rint: 6131 case Intrinsic::experimental_constrained_nearbyint: 6132 case Intrinsic::experimental_constrained_maxnum: 6133 case Intrinsic::experimental_constrained_minnum: 6134 case Intrinsic::experimental_constrained_ceil: 6135 case Intrinsic::experimental_constrained_floor: 6136 case Intrinsic::experimental_constrained_lround: 6137 case Intrinsic::experimental_constrained_llround: 6138 case Intrinsic::experimental_constrained_round: 6139 case Intrinsic::experimental_constrained_trunc: 6140 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6141 return; 6142 case Intrinsic::fmuladd: { 6143 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6144 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6145 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 6146 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6147 getValue(I.getArgOperand(0)).getValueType(), 6148 getValue(I.getArgOperand(0)), 6149 getValue(I.getArgOperand(1)), 6150 getValue(I.getArgOperand(2)))); 6151 } else { 6152 // TODO: Intrinsic calls should have fast-math-flags. 6153 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6154 getValue(I.getArgOperand(0)).getValueType(), 6155 getValue(I.getArgOperand(0)), 6156 getValue(I.getArgOperand(1))); 6157 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6158 getValue(I.getArgOperand(0)).getValueType(), 6159 Mul, 6160 getValue(I.getArgOperand(2))); 6161 setValue(&I, Add); 6162 } 6163 return; 6164 } 6165 case Intrinsic::convert_to_fp16: 6166 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6167 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6168 getValue(I.getArgOperand(0)), 6169 DAG.getTargetConstant(0, sdl, 6170 MVT::i32)))); 6171 return; 6172 case Intrinsic::convert_from_fp16: 6173 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6174 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6175 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6176 getValue(I.getArgOperand(0))))); 6177 return; 6178 case Intrinsic::pcmarker: { 6179 SDValue Tmp = getValue(I.getArgOperand(0)); 6180 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6181 return; 6182 } 6183 case Intrinsic::readcyclecounter: { 6184 SDValue Op = getRoot(); 6185 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6186 DAG.getVTList(MVT::i64, MVT::Other), Op); 6187 setValue(&I, Res); 6188 DAG.setRoot(Res.getValue(1)); 6189 return; 6190 } 6191 case Intrinsic::bitreverse: 6192 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6193 getValue(I.getArgOperand(0)).getValueType(), 6194 getValue(I.getArgOperand(0)))); 6195 return; 6196 case Intrinsic::bswap: 6197 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6198 getValue(I.getArgOperand(0)).getValueType(), 6199 getValue(I.getArgOperand(0)))); 6200 return; 6201 case Intrinsic::cttz: { 6202 SDValue Arg = getValue(I.getArgOperand(0)); 6203 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6204 EVT Ty = Arg.getValueType(); 6205 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6206 sdl, Ty, Arg)); 6207 return; 6208 } 6209 case Intrinsic::ctlz: { 6210 SDValue Arg = getValue(I.getArgOperand(0)); 6211 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6212 EVT Ty = Arg.getValueType(); 6213 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6214 sdl, Ty, Arg)); 6215 return; 6216 } 6217 case Intrinsic::ctpop: { 6218 SDValue Arg = getValue(I.getArgOperand(0)); 6219 EVT Ty = Arg.getValueType(); 6220 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6221 return; 6222 } 6223 case Intrinsic::fshl: 6224 case Intrinsic::fshr: { 6225 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6226 SDValue X = getValue(I.getArgOperand(0)); 6227 SDValue Y = getValue(I.getArgOperand(1)); 6228 SDValue Z = getValue(I.getArgOperand(2)); 6229 EVT VT = X.getValueType(); 6230 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6231 SDValue Zero = DAG.getConstant(0, sdl, VT); 6232 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6233 6234 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6235 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6236 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6237 return; 6238 } 6239 6240 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6241 // avoid the select that is necessary in the general case to filter out 6242 // the 0-shift possibility that leads to UB. 6243 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6244 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6245 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6246 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6247 return; 6248 } 6249 6250 // Some targets only rotate one way. Try the opposite direction. 6251 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6252 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6253 // Negate the shift amount because it is safe to ignore the high bits. 6254 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6255 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6256 return; 6257 } 6258 6259 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6260 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6261 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6262 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6263 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6264 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6265 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6266 return; 6267 } 6268 6269 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6270 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6271 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6272 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6273 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6274 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6275 6276 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6277 // and that is undefined. We must compare and select to avoid UB. 6278 EVT CCVT = MVT::i1; 6279 if (VT.isVector()) 6280 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6281 6282 // For fshl, 0-shift returns the 1st arg (X). 6283 // For fshr, 0-shift returns the 2nd arg (Y). 6284 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6285 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6286 return; 6287 } 6288 case Intrinsic::sadd_sat: { 6289 SDValue Op1 = getValue(I.getArgOperand(0)); 6290 SDValue Op2 = getValue(I.getArgOperand(1)); 6291 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6292 return; 6293 } 6294 case Intrinsic::uadd_sat: { 6295 SDValue Op1 = getValue(I.getArgOperand(0)); 6296 SDValue Op2 = getValue(I.getArgOperand(1)); 6297 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6298 return; 6299 } 6300 case Intrinsic::ssub_sat: { 6301 SDValue Op1 = getValue(I.getArgOperand(0)); 6302 SDValue Op2 = getValue(I.getArgOperand(1)); 6303 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6304 return; 6305 } 6306 case Intrinsic::usub_sat: { 6307 SDValue Op1 = getValue(I.getArgOperand(0)); 6308 SDValue Op2 = getValue(I.getArgOperand(1)); 6309 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6310 return; 6311 } 6312 case Intrinsic::smul_fix: 6313 case Intrinsic::umul_fix: { 6314 SDValue Op1 = getValue(I.getArgOperand(0)); 6315 SDValue Op2 = getValue(I.getArgOperand(1)); 6316 SDValue Op3 = getValue(I.getArgOperand(2)); 6317 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6318 Op1.getValueType(), Op1, Op2, Op3)); 6319 return; 6320 } 6321 case Intrinsic::smul_fix_sat: { 6322 SDValue Op1 = getValue(I.getArgOperand(0)); 6323 SDValue Op2 = getValue(I.getArgOperand(1)); 6324 SDValue Op3 = getValue(I.getArgOperand(2)); 6325 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6326 Op3)); 6327 return; 6328 } 6329 case Intrinsic::umul_fix_sat: { 6330 SDValue Op1 = getValue(I.getArgOperand(0)); 6331 SDValue Op2 = getValue(I.getArgOperand(1)); 6332 SDValue Op3 = getValue(I.getArgOperand(2)); 6333 setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2, 6334 Op3)); 6335 return; 6336 } 6337 case Intrinsic::stacksave: { 6338 SDValue Op = getRoot(); 6339 Res = DAG.getNode( 6340 ISD::STACKSAVE, sdl, 6341 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6342 setValue(&I, Res); 6343 DAG.setRoot(Res.getValue(1)); 6344 return; 6345 } 6346 case Intrinsic::stackrestore: 6347 Res = getValue(I.getArgOperand(0)); 6348 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6349 return; 6350 case Intrinsic::get_dynamic_area_offset: { 6351 SDValue Op = getRoot(); 6352 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6353 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6354 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6355 // target. 6356 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits()) 6357 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6358 " intrinsic!"); 6359 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6360 Op); 6361 DAG.setRoot(Op); 6362 setValue(&I, Res); 6363 return; 6364 } 6365 case Intrinsic::stackguard: { 6366 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6367 MachineFunction &MF = DAG.getMachineFunction(); 6368 const Module &M = *MF.getFunction().getParent(); 6369 SDValue Chain = getRoot(); 6370 if (TLI.useLoadStackGuardNode()) { 6371 Res = getLoadStackGuard(DAG, sdl, Chain); 6372 } else { 6373 const Value *Global = TLI.getSDagStackGuard(M); 6374 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6375 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6376 MachinePointerInfo(Global, 0), Align, 6377 MachineMemOperand::MOVolatile); 6378 } 6379 if (TLI.useStackGuardXorFP()) 6380 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6381 DAG.setRoot(Chain); 6382 setValue(&I, Res); 6383 return; 6384 } 6385 case Intrinsic::stackprotector: { 6386 // Emit code into the DAG to store the stack guard onto the stack. 6387 MachineFunction &MF = DAG.getMachineFunction(); 6388 MachineFrameInfo &MFI = MF.getFrameInfo(); 6389 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6390 SDValue Src, Chain = getRoot(); 6391 6392 if (TLI.useLoadStackGuardNode()) 6393 Src = getLoadStackGuard(DAG, sdl, Chain); 6394 else 6395 Src = getValue(I.getArgOperand(0)); // The guard's value. 6396 6397 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6398 6399 int FI = FuncInfo.StaticAllocaMap[Slot]; 6400 MFI.setStackProtectorIndex(FI); 6401 6402 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6403 6404 // Store the stack protector onto the stack. 6405 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6406 DAG.getMachineFunction(), FI), 6407 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6408 setValue(&I, Res); 6409 DAG.setRoot(Res); 6410 return; 6411 } 6412 case Intrinsic::objectsize: 6413 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 6414 6415 case Intrinsic::is_constant: 6416 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 6417 6418 case Intrinsic::annotation: 6419 case Intrinsic::ptr_annotation: 6420 case Intrinsic::launder_invariant_group: 6421 case Intrinsic::strip_invariant_group: 6422 // Drop the intrinsic, but forward the value 6423 setValue(&I, getValue(I.getOperand(0))); 6424 return; 6425 case Intrinsic::assume: 6426 case Intrinsic::var_annotation: 6427 case Intrinsic::sideeffect: 6428 // Discard annotate attributes, assumptions, and artificial side-effects. 6429 return; 6430 6431 case Intrinsic::codeview_annotation: { 6432 // Emit a label associated with this metadata. 6433 MachineFunction &MF = DAG.getMachineFunction(); 6434 MCSymbol *Label = 6435 MF.getMMI().getContext().createTempSymbol("annotation", true); 6436 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6437 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6438 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6439 DAG.setRoot(Res); 6440 return; 6441 } 6442 6443 case Intrinsic::init_trampoline: { 6444 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6445 6446 SDValue Ops[6]; 6447 Ops[0] = getRoot(); 6448 Ops[1] = getValue(I.getArgOperand(0)); 6449 Ops[2] = getValue(I.getArgOperand(1)); 6450 Ops[3] = getValue(I.getArgOperand(2)); 6451 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6452 Ops[5] = DAG.getSrcValue(F); 6453 6454 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6455 6456 DAG.setRoot(Res); 6457 return; 6458 } 6459 case Intrinsic::adjust_trampoline: 6460 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6461 TLI.getPointerTy(DAG.getDataLayout()), 6462 getValue(I.getArgOperand(0)))); 6463 return; 6464 case Intrinsic::gcroot: { 6465 assert(DAG.getMachineFunction().getFunction().hasGC() && 6466 "only valid in functions with gc specified, enforced by Verifier"); 6467 assert(GFI && "implied by previous"); 6468 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6469 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6470 6471 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6472 GFI->addStackRoot(FI->getIndex(), TypeMap); 6473 return; 6474 } 6475 case Intrinsic::gcread: 6476 case Intrinsic::gcwrite: 6477 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6478 case Intrinsic::flt_rounds: 6479 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6480 return; 6481 6482 case Intrinsic::expect: 6483 // Just replace __builtin_expect(exp, c) with EXP. 6484 setValue(&I, getValue(I.getArgOperand(0))); 6485 return; 6486 6487 case Intrinsic::debugtrap: 6488 case Intrinsic::trap: { 6489 StringRef TrapFuncName = 6490 I.getAttributes() 6491 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6492 .getValueAsString(); 6493 if (TrapFuncName.empty()) { 6494 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6495 ISD::TRAP : ISD::DEBUGTRAP; 6496 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6497 return; 6498 } 6499 TargetLowering::ArgListTy Args; 6500 6501 TargetLowering::CallLoweringInfo CLI(DAG); 6502 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6503 CallingConv::C, I.getType(), 6504 DAG.getExternalSymbol(TrapFuncName.data(), 6505 TLI.getPointerTy(DAG.getDataLayout())), 6506 std::move(Args)); 6507 6508 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6509 DAG.setRoot(Result.second); 6510 return; 6511 } 6512 6513 case Intrinsic::uadd_with_overflow: 6514 case Intrinsic::sadd_with_overflow: 6515 case Intrinsic::usub_with_overflow: 6516 case Intrinsic::ssub_with_overflow: 6517 case Intrinsic::umul_with_overflow: 6518 case Intrinsic::smul_with_overflow: { 6519 ISD::NodeType Op; 6520 switch (Intrinsic) { 6521 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6522 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6523 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6524 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6525 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6526 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6527 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6528 } 6529 SDValue Op1 = getValue(I.getArgOperand(0)); 6530 SDValue Op2 = getValue(I.getArgOperand(1)); 6531 6532 EVT ResultVT = Op1.getValueType(); 6533 EVT OverflowVT = MVT::i1; 6534 if (ResultVT.isVector()) 6535 OverflowVT = EVT::getVectorVT( 6536 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6537 6538 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6539 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6540 return; 6541 } 6542 case Intrinsic::prefetch: { 6543 SDValue Ops[5]; 6544 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6545 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6546 Ops[0] = DAG.getRoot(); 6547 Ops[1] = getValue(I.getArgOperand(0)); 6548 Ops[2] = getValue(I.getArgOperand(1)); 6549 Ops[3] = getValue(I.getArgOperand(2)); 6550 Ops[4] = getValue(I.getArgOperand(3)); 6551 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6552 DAG.getVTList(MVT::Other), Ops, 6553 EVT::getIntegerVT(*Context, 8), 6554 MachinePointerInfo(I.getArgOperand(0)), 6555 0, /* align */ 6556 Flags); 6557 6558 // Chain the prefetch in parallell with any pending loads, to stay out of 6559 // the way of later optimizations. 6560 PendingLoads.push_back(Result); 6561 Result = getRoot(); 6562 DAG.setRoot(Result); 6563 return; 6564 } 6565 case Intrinsic::lifetime_start: 6566 case Intrinsic::lifetime_end: { 6567 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6568 // Stack coloring is not enabled in O0, discard region information. 6569 if (TM.getOptLevel() == CodeGenOpt::None) 6570 return; 6571 6572 const int64_t ObjectSize = 6573 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6574 Value *const ObjectPtr = I.getArgOperand(1); 6575 SmallVector<const Value *, 4> Allocas; 6576 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6577 6578 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(), 6579 E = Allocas.end(); Object != E; ++Object) { 6580 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6581 6582 // Could not find an Alloca. 6583 if (!LifetimeObject) 6584 continue; 6585 6586 // First check that the Alloca is static, otherwise it won't have a 6587 // valid frame index. 6588 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6589 if (SI == FuncInfo.StaticAllocaMap.end()) 6590 return; 6591 6592 const int FrameIndex = SI->second; 6593 int64_t Offset; 6594 if (GetPointerBaseWithConstantOffset( 6595 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6596 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6597 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6598 Offset); 6599 DAG.setRoot(Res); 6600 } 6601 return; 6602 } 6603 case Intrinsic::invariant_start: 6604 // Discard region information. 6605 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6606 return; 6607 case Intrinsic::invariant_end: 6608 // Discard region information. 6609 return; 6610 case Intrinsic::clear_cache: 6611 /// FunctionName may be null. 6612 if (const char *FunctionName = TLI.getClearCacheBuiltinName()) 6613 lowerCallToExternalSymbol(I, FunctionName); 6614 return; 6615 case Intrinsic::donothing: 6616 // ignore 6617 return; 6618 case Intrinsic::experimental_stackmap: 6619 visitStackmap(I); 6620 return; 6621 case Intrinsic::experimental_patchpoint_void: 6622 case Intrinsic::experimental_patchpoint_i64: 6623 visitPatchpoint(&I); 6624 return; 6625 case Intrinsic::experimental_gc_statepoint: 6626 LowerStatepoint(ImmutableStatepoint(&I)); 6627 return; 6628 case Intrinsic::experimental_gc_result: 6629 visitGCResult(cast<GCResultInst>(I)); 6630 return; 6631 case Intrinsic::experimental_gc_relocate: 6632 visitGCRelocate(cast<GCRelocateInst>(I)); 6633 return; 6634 case Intrinsic::instrprof_increment: 6635 llvm_unreachable("instrprof failed to lower an increment"); 6636 case Intrinsic::instrprof_value_profile: 6637 llvm_unreachable("instrprof failed to lower a value profiling call"); 6638 case Intrinsic::localescape: { 6639 MachineFunction &MF = DAG.getMachineFunction(); 6640 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6641 6642 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6643 // is the same on all targets. 6644 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6645 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6646 if (isa<ConstantPointerNull>(Arg)) 6647 continue; // Skip null pointers. They represent a hole in index space. 6648 AllocaInst *Slot = cast<AllocaInst>(Arg); 6649 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6650 "can only escape static allocas"); 6651 int FI = FuncInfo.StaticAllocaMap[Slot]; 6652 MCSymbol *FrameAllocSym = 6653 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6654 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6656 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6657 .addSym(FrameAllocSym) 6658 .addFrameIndex(FI); 6659 } 6660 6661 return; 6662 } 6663 6664 case Intrinsic::localrecover: { 6665 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6666 MachineFunction &MF = DAG.getMachineFunction(); 6667 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6668 6669 // Get the symbol that defines the frame offset. 6670 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6671 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6672 unsigned IdxVal = 6673 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6674 MCSymbol *FrameAllocSym = 6675 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6676 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6677 6678 // Create a MCSymbol for the label to avoid any target lowering 6679 // that would make this PC relative. 6680 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6681 SDValue OffsetVal = 6682 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6683 6684 // Add the offset to the FP. 6685 Value *FP = I.getArgOperand(1); 6686 SDValue FPVal = getValue(FP); 6687 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6688 setValue(&I, Add); 6689 6690 return; 6691 } 6692 6693 case Intrinsic::eh_exceptionpointer: 6694 case Intrinsic::eh_exceptioncode: { 6695 // Get the exception pointer vreg, copy from it, and resize it to fit. 6696 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6697 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6698 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6699 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6700 SDValue N = 6701 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6702 if (Intrinsic == Intrinsic::eh_exceptioncode) 6703 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6704 setValue(&I, N); 6705 return; 6706 } 6707 case Intrinsic::xray_customevent: { 6708 // Here we want to make sure that the intrinsic behaves as if it has a 6709 // specific calling convention, and only for x86_64. 6710 // FIXME: Support other platforms later. 6711 const auto &Triple = DAG.getTarget().getTargetTriple(); 6712 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6713 return; 6714 6715 SDLoc DL = getCurSDLoc(); 6716 SmallVector<SDValue, 8> Ops; 6717 6718 // We want to say that we always want the arguments in registers. 6719 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6720 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6721 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6722 SDValue Chain = getRoot(); 6723 Ops.push_back(LogEntryVal); 6724 Ops.push_back(StrSizeVal); 6725 Ops.push_back(Chain); 6726 6727 // We need to enforce the calling convention for the callsite, so that 6728 // argument ordering is enforced correctly, and that register allocation can 6729 // see that some registers may be assumed clobbered and have to preserve 6730 // them across calls to the intrinsic. 6731 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6732 DL, NodeTys, Ops); 6733 SDValue patchableNode = SDValue(MN, 0); 6734 DAG.setRoot(patchableNode); 6735 setValue(&I, patchableNode); 6736 return; 6737 } 6738 case Intrinsic::xray_typedevent: { 6739 // Here we want to make sure that the intrinsic behaves as if it has a 6740 // specific calling convention, and only for x86_64. 6741 // FIXME: Support other platforms later. 6742 const auto &Triple = DAG.getTarget().getTargetTriple(); 6743 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6744 return; 6745 6746 SDLoc DL = getCurSDLoc(); 6747 SmallVector<SDValue, 8> Ops; 6748 6749 // We want to say that we always want the arguments in registers. 6750 // It's unclear to me how manipulating the selection DAG here forces callers 6751 // to provide arguments in registers instead of on the stack. 6752 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6753 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6754 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6755 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6756 SDValue Chain = getRoot(); 6757 Ops.push_back(LogTypeId); 6758 Ops.push_back(LogEntryVal); 6759 Ops.push_back(StrSizeVal); 6760 Ops.push_back(Chain); 6761 6762 // We need to enforce the calling convention for the callsite, so that 6763 // argument ordering is enforced correctly, and that register allocation can 6764 // see that some registers may be assumed clobbered and have to preserve 6765 // them across calls to the intrinsic. 6766 MachineSDNode *MN = DAG.getMachineNode( 6767 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6768 SDValue patchableNode = SDValue(MN, 0); 6769 DAG.setRoot(patchableNode); 6770 setValue(&I, patchableNode); 6771 return; 6772 } 6773 case Intrinsic::experimental_deoptimize: 6774 LowerDeoptimizeCall(&I); 6775 return; 6776 6777 case Intrinsic::experimental_vector_reduce_v2_fadd: 6778 case Intrinsic::experimental_vector_reduce_v2_fmul: 6779 case Intrinsic::experimental_vector_reduce_add: 6780 case Intrinsic::experimental_vector_reduce_mul: 6781 case Intrinsic::experimental_vector_reduce_and: 6782 case Intrinsic::experimental_vector_reduce_or: 6783 case Intrinsic::experimental_vector_reduce_xor: 6784 case Intrinsic::experimental_vector_reduce_smax: 6785 case Intrinsic::experimental_vector_reduce_smin: 6786 case Intrinsic::experimental_vector_reduce_umax: 6787 case Intrinsic::experimental_vector_reduce_umin: 6788 case Intrinsic::experimental_vector_reduce_fmax: 6789 case Intrinsic::experimental_vector_reduce_fmin: 6790 visitVectorReduce(I, Intrinsic); 6791 return; 6792 6793 case Intrinsic::icall_branch_funnel: { 6794 SmallVector<SDValue, 16> Ops; 6795 Ops.push_back(getValue(I.getArgOperand(0))); 6796 6797 int64_t Offset; 6798 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6799 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6800 if (!Base) 6801 report_fatal_error( 6802 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6803 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6804 6805 struct BranchFunnelTarget { 6806 int64_t Offset; 6807 SDValue Target; 6808 }; 6809 SmallVector<BranchFunnelTarget, 8> Targets; 6810 6811 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6812 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6813 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6814 if (ElemBase != Base) 6815 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6816 "to the same GlobalValue"); 6817 6818 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6819 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6820 if (!GA) 6821 report_fatal_error( 6822 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6823 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6824 GA->getGlobal(), getCurSDLoc(), 6825 Val.getValueType(), GA->getOffset())}); 6826 } 6827 llvm::sort(Targets, 6828 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6829 return T1.Offset < T2.Offset; 6830 }); 6831 6832 for (auto &T : Targets) { 6833 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6834 Ops.push_back(T.Target); 6835 } 6836 6837 Ops.push_back(DAG.getRoot()); // Chain 6838 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6839 getCurSDLoc(), MVT::Other, Ops), 6840 0); 6841 DAG.setRoot(N); 6842 setValue(&I, N); 6843 HasTailCall = true; 6844 return; 6845 } 6846 6847 case Intrinsic::wasm_landingpad_index: 6848 // Information this intrinsic contained has been transferred to 6849 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6850 // delete it now. 6851 return; 6852 6853 case Intrinsic::aarch64_settag: 6854 case Intrinsic::aarch64_settag_zero: { 6855 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6856 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero; 6857 SDValue Val = TSI.EmitTargetCodeForSetTag( 6858 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)), 6859 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)), 6860 ZeroMemory); 6861 DAG.setRoot(Val); 6862 setValue(&I, Val); 6863 return; 6864 } 6865 case Intrinsic::ptrmask: { 6866 SDValue Ptr = getValue(I.getOperand(0)); 6867 SDValue Const = getValue(I.getOperand(1)); 6868 6869 EVT DestVT = 6870 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6871 6872 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr, 6873 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT))); 6874 return; 6875 } 6876 } 6877 } 6878 6879 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6880 const ConstrainedFPIntrinsic &FPI) { 6881 SDLoc sdl = getCurSDLoc(); 6882 unsigned Opcode; 6883 switch (FPI.getIntrinsicID()) { 6884 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6885 case Intrinsic::experimental_constrained_fadd: 6886 Opcode = ISD::STRICT_FADD; 6887 break; 6888 case Intrinsic::experimental_constrained_fsub: 6889 Opcode = ISD::STRICT_FSUB; 6890 break; 6891 case Intrinsic::experimental_constrained_fmul: 6892 Opcode = ISD::STRICT_FMUL; 6893 break; 6894 case Intrinsic::experimental_constrained_fdiv: 6895 Opcode = ISD::STRICT_FDIV; 6896 break; 6897 case Intrinsic::experimental_constrained_frem: 6898 Opcode = ISD::STRICT_FREM; 6899 break; 6900 case Intrinsic::experimental_constrained_fma: 6901 Opcode = ISD::STRICT_FMA; 6902 break; 6903 case Intrinsic::experimental_constrained_fptosi: 6904 Opcode = ISD::STRICT_FP_TO_SINT; 6905 break; 6906 case Intrinsic::experimental_constrained_fptoui: 6907 Opcode = ISD::STRICT_FP_TO_UINT; 6908 break; 6909 case Intrinsic::experimental_constrained_fptrunc: 6910 Opcode = ISD::STRICT_FP_ROUND; 6911 break; 6912 case Intrinsic::experimental_constrained_fpext: 6913 Opcode = ISD::STRICT_FP_EXTEND; 6914 break; 6915 case Intrinsic::experimental_constrained_sqrt: 6916 Opcode = ISD::STRICT_FSQRT; 6917 break; 6918 case Intrinsic::experimental_constrained_pow: 6919 Opcode = ISD::STRICT_FPOW; 6920 break; 6921 case Intrinsic::experimental_constrained_powi: 6922 Opcode = ISD::STRICT_FPOWI; 6923 break; 6924 case Intrinsic::experimental_constrained_sin: 6925 Opcode = ISD::STRICT_FSIN; 6926 break; 6927 case Intrinsic::experimental_constrained_cos: 6928 Opcode = ISD::STRICT_FCOS; 6929 break; 6930 case Intrinsic::experimental_constrained_exp: 6931 Opcode = ISD::STRICT_FEXP; 6932 break; 6933 case Intrinsic::experimental_constrained_exp2: 6934 Opcode = ISD::STRICT_FEXP2; 6935 break; 6936 case Intrinsic::experimental_constrained_log: 6937 Opcode = ISD::STRICT_FLOG; 6938 break; 6939 case Intrinsic::experimental_constrained_log10: 6940 Opcode = ISD::STRICT_FLOG10; 6941 break; 6942 case Intrinsic::experimental_constrained_log2: 6943 Opcode = ISD::STRICT_FLOG2; 6944 break; 6945 case Intrinsic::experimental_constrained_lrint: 6946 Opcode = ISD::STRICT_LRINT; 6947 break; 6948 case Intrinsic::experimental_constrained_llrint: 6949 Opcode = ISD::STRICT_LLRINT; 6950 break; 6951 case Intrinsic::experimental_constrained_rint: 6952 Opcode = ISD::STRICT_FRINT; 6953 break; 6954 case Intrinsic::experimental_constrained_nearbyint: 6955 Opcode = ISD::STRICT_FNEARBYINT; 6956 break; 6957 case Intrinsic::experimental_constrained_maxnum: 6958 Opcode = ISD::STRICT_FMAXNUM; 6959 break; 6960 case Intrinsic::experimental_constrained_minnum: 6961 Opcode = ISD::STRICT_FMINNUM; 6962 break; 6963 case Intrinsic::experimental_constrained_ceil: 6964 Opcode = ISD::STRICT_FCEIL; 6965 break; 6966 case Intrinsic::experimental_constrained_floor: 6967 Opcode = ISD::STRICT_FFLOOR; 6968 break; 6969 case Intrinsic::experimental_constrained_lround: 6970 Opcode = ISD::STRICT_LROUND; 6971 break; 6972 case Intrinsic::experimental_constrained_llround: 6973 Opcode = ISD::STRICT_LLROUND; 6974 break; 6975 case Intrinsic::experimental_constrained_round: 6976 Opcode = ISD::STRICT_FROUND; 6977 break; 6978 case Intrinsic::experimental_constrained_trunc: 6979 Opcode = ISD::STRICT_FTRUNC; 6980 break; 6981 } 6982 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6983 SDValue Chain = getRoot(); 6984 SmallVector<EVT, 4> ValueVTs; 6985 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6986 ValueVTs.push_back(MVT::Other); // Out chain 6987 6988 SDVTList VTs = DAG.getVTList(ValueVTs); 6989 SDValue Result; 6990 if (Opcode == ISD::STRICT_FP_ROUND) 6991 Result = DAG.getNode(Opcode, sdl, VTs, 6992 { Chain, getValue(FPI.getArgOperand(0)), 6993 DAG.getTargetConstant(0, sdl, 6994 TLI.getPointerTy(DAG.getDataLayout())) }); 6995 else if (FPI.isUnaryOp()) 6996 Result = DAG.getNode(Opcode, sdl, VTs, 6997 { Chain, getValue(FPI.getArgOperand(0)) }); 6998 else if (FPI.isTernaryOp()) 6999 Result = DAG.getNode(Opcode, sdl, VTs, 7000 { Chain, getValue(FPI.getArgOperand(0)), 7001 getValue(FPI.getArgOperand(1)), 7002 getValue(FPI.getArgOperand(2)) }); 7003 else 7004 Result = DAG.getNode(Opcode, sdl, VTs, 7005 { Chain, getValue(FPI.getArgOperand(0)), 7006 getValue(FPI.getArgOperand(1)) }); 7007 7008 if (FPI.getExceptionBehavior() != 7009 ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) { 7010 SDNodeFlags Flags; 7011 Flags.setFPExcept(true); 7012 Result->setFlags(Flags); 7013 } 7014 7015 assert(Result.getNode()->getNumValues() == 2); 7016 SDValue OutChain = Result.getValue(1); 7017 DAG.setRoot(OutChain); 7018 SDValue FPResult = Result.getValue(0); 7019 setValue(&FPI, FPResult); 7020 } 7021 7022 std::pair<SDValue, SDValue> 7023 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 7024 const BasicBlock *EHPadBB) { 7025 MachineFunction &MF = DAG.getMachineFunction(); 7026 MachineModuleInfo &MMI = MF.getMMI(); 7027 MCSymbol *BeginLabel = nullptr; 7028 7029 if (EHPadBB) { 7030 // Insert a label before the invoke call to mark the try range. This can be 7031 // used to detect deletion of the invoke via the MachineModuleInfo. 7032 BeginLabel = MMI.getContext().createTempSymbol(); 7033 7034 // For SjLj, keep track of which landing pads go with which invokes 7035 // so as to maintain the ordering of pads in the LSDA. 7036 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 7037 if (CallSiteIndex) { 7038 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 7039 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 7040 7041 // Now that the call site is handled, stop tracking it. 7042 MMI.setCurrentCallSite(0); 7043 } 7044 7045 // Both PendingLoads and PendingExports must be flushed here; 7046 // this call might not return. 7047 (void)getRoot(); 7048 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 7049 7050 CLI.setChain(getRoot()); 7051 } 7052 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7053 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 7054 7055 assert((CLI.IsTailCall || Result.second.getNode()) && 7056 "Non-null chain expected with non-tail call!"); 7057 assert((Result.second.getNode() || !Result.first.getNode()) && 7058 "Null value expected with tail call!"); 7059 7060 if (!Result.second.getNode()) { 7061 // As a special case, a null chain means that a tail call has been emitted 7062 // and the DAG root is already updated. 7063 HasTailCall = true; 7064 7065 // Since there's no actual continuation from this block, nothing can be 7066 // relying on us setting vregs for them. 7067 PendingExports.clear(); 7068 } else { 7069 DAG.setRoot(Result.second); 7070 } 7071 7072 if (EHPadBB) { 7073 // Insert a label at the end of the invoke call to mark the try range. This 7074 // can be used to detect deletion of the invoke via the MachineModuleInfo. 7075 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 7076 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 7077 7078 // Inform MachineModuleInfo of range. 7079 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 7080 // There is a platform (e.g. wasm) that uses funclet style IR but does not 7081 // actually use outlined funclets and their LSDA info style. 7082 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 7083 assert(CLI.CS); 7084 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 7085 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 7086 BeginLabel, EndLabel); 7087 } else if (!isScopedEHPersonality(Pers)) { 7088 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 7089 } 7090 } 7091 7092 return Result; 7093 } 7094 7095 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 7096 bool isTailCall, 7097 const BasicBlock *EHPadBB) { 7098 auto &DL = DAG.getDataLayout(); 7099 FunctionType *FTy = CS.getFunctionType(); 7100 Type *RetTy = CS.getType(); 7101 7102 TargetLowering::ArgListTy Args; 7103 Args.reserve(CS.arg_size()); 7104 7105 const Value *SwiftErrorVal = nullptr; 7106 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7107 7108 // We can't tail call inside a function with a swifterror argument. Lowering 7109 // does not support this yet. It would have to move into the swifterror 7110 // register before the call. 7111 auto *Caller = CS.getInstruction()->getParent()->getParent(); 7112 if (TLI.supportSwiftError() && 7113 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 7114 isTailCall = false; 7115 7116 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 7117 i != e; ++i) { 7118 TargetLowering::ArgListEntry Entry; 7119 const Value *V = *i; 7120 7121 // Skip empty types 7122 if (V->getType()->isEmptyTy()) 7123 continue; 7124 7125 SDValue ArgNode = getValue(V); 7126 Entry.Node = ArgNode; Entry.Ty = V->getType(); 7127 7128 Entry.setAttributes(&CS, i - CS.arg_begin()); 7129 7130 // Use swifterror virtual register as input to the call. 7131 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 7132 SwiftErrorVal = V; 7133 // We find the virtual register for the actual swifterror argument. 7134 // Instead of using the Value, we use the virtual register instead. 7135 Entry.Node = DAG.getRegister( 7136 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V), 7137 EVT(TLI.getPointerTy(DL))); 7138 } 7139 7140 Args.push_back(Entry); 7141 7142 // If we have an explicit sret argument that is an Instruction, (i.e., it 7143 // might point to function-local memory), we can't meaningfully tail-call. 7144 if (Entry.IsSRet && isa<Instruction>(V)) 7145 isTailCall = false; 7146 } 7147 7148 // Check if target-independent constraints permit a tail call here. 7149 // Target-dependent constraints are checked within TLI->LowerCallTo. 7150 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 7151 isTailCall = false; 7152 7153 // Disable tail calls if there is an swifterror argument. Targets have not 7154 // been updated to support tail calls. 7155 if (TLI.supportSwiftError() && SwiftErrorVal) 7156 isTailCall = false; 7157 7158 TargetLowering::CallLoweringInfo CLI(DAG); 7159 CLI.setDebugLoc(getCurSDLoc()) 7160 .setChain(getRoot()) 7161 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 7162 .setTailCall(isTailCall) 7163 .setConvergent(CS.isConvergent()); 7164 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7165 7166 if (Result.first.getNode()) { 7167 const Instruction *Inst = CS.getInstruction(); 7168 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 7169 setValue(Inst, Result.first); 7170 } 7171 7172 // The last element of CLI.InVals has the SDValue for swifterror return. 7173 // Here we copy it to a virtual register and update SwiftErrorMap for 7174 // book-keeping. 7175 if (SwiftErrorVal && TLI.supportSwiftError()) { 7176 // Get the last element of InVals. 7177 SDValue Src = CLI.InVals.back(); 7178 Register VReg = SwiftError.getOrCreateVRegDefAt( 7179 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal); 7180 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 7181 DAG.setRoot(CopyNode); 7182 } 7183 } 7184 7185 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 7186 SelectionDAGBuilder &Builder) { 7187 // Check to see if this load can be trivially constant folded, e.g. if the 7188 // input is from a string literal. 7189 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 7190 // Cast pointer to the type we really want to load. 7191 Type *LoadTy = 7192 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7193 if (LoadVT.isVector()) 7194 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7195 7196 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7197 PointerType::getUnqual(LoadTy)); 7198 7199 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7200 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7201 return Builder.getValue(LoadCst); 7202 } 7203 7204 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7205 // still constant memory, the input chain can be the entry node. 7206 SDValue Root; 7207 bool ConstantMemory = false; 7208 7209 // Do not serialize (non-volatile) loads of constant memory with anything. 7210 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7211 Root = Builder.DAG.getEntryNode(); 7212 ConstantMemory = true; 7213 } else { 7214 // Do not serialize non-volatile loads against each other. 7215 Root = Builder.DAG.getRoot(); 7216 } 7217 7218 SDValue Ptr = Builder.getValue(PtrVal); 7219 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7220 Ptr, MachinePointerInfo(PtrVal), 7221 /* Alignment = */ 1); 7222 7223 if (!ConstantMemory) 7224 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7225 return LoadVal; 7226 } 7227 7228 /// Record the value for an instruction that produces an integer result, 7229 /// converting the type where necessary. 7230 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7231 SDValue Value, 7232 bool IsSigned) { 7233 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7234 I.getType(), true); 7235 if (IsSigned) 7236 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7237 else 7238 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7239 setValue(&I, Value); 7240 } 7241 7242 /// See if we can lower a memcmp call into an optimized form. If so, return 7243 /// true and lower it. Otherwise return false, and it will be lowered like a 7244 /// normal call. 7245 /// The caller already checked that \p I calls the appropriate LibFunc with a 7246 /// correct prototype. 7247 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7248 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7249 const Value *Size = I.getArgOperand(2); 7250 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7251 if (CSize && CSize->getZExtValue() == 0) { 7252 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7253 I.getType(), true); 7254 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7255 return true; 7256 } 7257 7258 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7259 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7260 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7261 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7262 if (Res.first.getNode()) { 7263 processIntegerCallValue(I, Res.first, true); 7264 PendingLoads.push_back(Res.second); 7265 return true; 7266 } 7267 7268 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7269 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7270 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7271 return false; 7272 7273 // If the target has a fast compare for the given size, it will return a 7274 // preferred load type for that size. Require that the load VT is legal and 7275 // that the target supports unaligned loads of that type. Otherwise, return 7276 // INVALID. 7277 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7278 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7279 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7280 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7281 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7282 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7283 // TODO: Check alignment of src and dest ptrs. 7284 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7285 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7286 if (!TLI.isTypeLegal(LVT) || 7287 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7288 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7289 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7290 } 7291 7292 return LVT; 7293 }; 7294 7295 // This turns into unaligned loads. We only do this if the target natively 7296 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7297 // we'll only produce a small number of byte loads. 7298 MVT LoadVT; 7299 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7300 switch (NumBitsToCompare) { 7301 default: 7302 return false; 7303 case 16: 7304 LoadVT = MVT::i16; 7305 break; 7306 case 32: 7307 LoadVT = MVT::i32; 7308 break; 7309 case 64: 7310 case 128: 7311 case 256: 7312 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7313 break; 7314 } 7315 7316 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7317 return false; 7318 7319 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7320 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7321 7322 // Bitcast to a wide integer type if the loads are vectors. 7323 if (LoadVT.isVector()) { 7324 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7325 LoadL = DAG.getBitcast(CmpVT, LoadL); 7326 LoadR = DAG.getBitcast(CmpVT, LoadR); 7327 } 7328 7329 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7330 processIntegerCallValue(I, Cmp, false); 7331 return true; 7332 } 7333 7334 /// See if we can lower a memchr call into an optimized form. If so, return 7335 /// true and lower it. Otherwise return false, and it will be lowered like a 7336 /// normal call. 7337 /// The caller already checked that \p I calls the appropriate LibFunc with a 7338 /// correct prototype. 7339 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7340 const Value *Src = I.getArgOperand(0); 7341 const Value *Char = I.getArgOperand(1); 7342 const Value *Length = I.getArgOperand(2); 7343 7344 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7345 std::pair<SDValue, SDValue> Res = 7346 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7347 getValue(Src), getValue(Char), getValue(Length), 7348 MachinePointerInfo(Src)); 7349 if (Res.first.getNode()) { 7350 setValue(&I, Res.first); 7351 PendingLoads.push_back(Res.second); 7352 return true; 7353 } 7354 7355 return false; 7356 } 7357 7358 /// See if we can lower a mempcpy call into an optimized form. If so, return 7359 /// true and lower it. Otherwise return false, and it will be lowered like a 7360 /// normal call. 7361 /// The caller already checked that \p I calls the appropriate LibFunc with a 7362 /// correct prototype. 7363 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7364 SDValue Dst = getValue(I.getArgOperand(0)); 7365 SDValue Src = getValue(I.getArgOperand(1)); 7366 SDValue Size = getValue(I.getArgOperand(2)); 7367 7368 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7369 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7370 unsigned Align = std::min(DstAlign, SrcAlign); 7371 if (Align == 0) // Alignment of one or both could not be inferred. 7372 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7373 7374 bool isVol = false; 7375 SDLoc sdl = getCurSDLoc(); 7376 7377 // In the mempcpy context we need to pass in a false value for isTailCall 7378 // because the return pointer needs to be adjusted by the size of 7379 // the copied memory. 7380 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7381 false, /*isTailCall=*/false, 7382 MachinePointerInfo(I.getArgOperand(0)), 7383 MachinePointerInfo(I.getArgOperand(1))); 7384 assert(MC.getNode() != nullptr && 7385 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7386 DAG.setRoot(MC); 7387 7388 // Check if Size needs to be truncated or extended. 7389 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7390 7391 // Adjust return pointer to point just past the last dst byte. 7392 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7393 Dst, Size); 7394 setValue(&I, DstPlusSize); 7395 return true; 7396 } 7397 7398 /// See if we can lower a strcpy call into an optimized form. If so, return 7399 /// true and lower it, otherwise return false and it will be lowered like a 7400 /// normal call. 7401 /// The caller already checked that \p I calls the appropriate LibFunc with a 7402 /// correct prototype. 7403 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7404 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7405 7406 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7407 std::pair<SDValue, SDValue> Res = 7408 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7409 getValue(Arg0), getValue(Arg1), 7410 MachinePointerInfo(Arg0), 7411 MachinePointerInfo(Arg1), isStpcpy); 7412 if (Res.first.getNode()) { 7413 setValue(&I, Res.first); 7414 DAG.setRoot(Res.second); 7415 return true; 7416 } 7417 7418 return false; 7419 } 7420 7421 /// See if we can lower a strcmp call into an optimized form. If so, return 7422 /// true and lower it, otherwise return false and it will be lowered like a 7423 /// normal call. 7424 /// The caller already checked that \p I calls the appropriate LibFunc with a 7425 /// correct prototype. 7426 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7427 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7428 7429 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7430 std::pair<SDValue, SDValue> Res = 7431 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7432 getValue(Arg0), getValue(Arg1), 7433 MachinePointerInfo(Arg0), 7434 MachinePointerInfo(Arg1)); 7435 if (Res.first.getNode()) { 7436 processIntegerCallValue(I, Res.first, true); 7437 PendingLoads.push_back(Res.second); 7438 return true; 7439 } 7440 7441 return false; 7442 } 7443 7444 /// See if we can lower a strlen call into an optimized form. If so, return 7445 /// true and lower it, otherwise return false and it will be lowered like a 7446 /// normal call. 7447 /// The caller already checked that \p I calls the appropriate LibFunc with a 7448 /// correct prototype. 7449 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7450 const Value *Arg0 = I.getArgOperand(0); 7451 7452 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7453 std::pair<SDValue, SDValue> Res = 7454 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7455 getValue(Arg0), MachinePointerInfo(Arg0)); 7456 if (Res.first.getNode()) { 7457 processIntegerCallValue(I, Res.first, false); 7458 PendingLoads.push_back(Res.second); 7459 return true; 7460 } 7461 7462 return false; 7463 } 7464 7465 /// See if we can lower a strnlen call into an optimized form. If so, return 7466 /// true and lower it, otherwise return false and it will be lowered like a 7467 /// normal call. 7468 /// The caller already checked that \p I calls the appropriate LibFunc with a 7469 /// correct prototype. 7470 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7471 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7472 7473 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7474 std::pair<SDValue, SDValue> Res = 7475 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7476 getValue(Arg0), getValue(Arg1), 7477 MachinePointerInfo(Arg0)); 7478 if (Res.first.getNode()) { 7479 processIntegerCallValue(I, Res.first, false); 7480 PendingLoads.push_back(Res.second); 7481 return true; 7482 } 7483 7484 return false; 7485 } 7486 7487 /// See if we can lower a unary floating-point operation into an SDNode with 7488 /// the specified Opcode. If so, return true and lower it, otherwise return 7489 /// false and it will be lowered like a normal call. 7490 /// The caller already checked that \p I calls the appropriate LibFunc with a 7491 /// correct prototype. 7492 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7493 unsigned Opcode) { 7494 // We already checked this call's prototype; verify it doesn't modify errno. 7495 if (!I.onlyReadsMemory()) 7496 return false; 7497 7498 SDValue Tmp = getValue(I.getArgOperand(0)); 7499 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7500 return true; 7501 } 7502 7503 /// See if we can lower a binary floating-point operation into an SDNode with 7504 /// the specified Opcode. If so, return true and lower it. Otherwise return 7505 /// false, and it will be lowered like a normal call. 7506 /// The caller already checked that \p I calls the appropriate LibFunc with a 7507 /// correct prototype. 7508 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7509 unsigned Opcode) { 7510 // We already checked this call's prototype; verify it doesn't modify errno. 7511 if (!I.onlyReadsMemory()) 7512 return false; 7513 7514 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7515 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7516 EVT VT = Tmp0.getValueType(); 7517 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7518 return true; 7519 } 7520 7521 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7522 // Handle inline assembly differently. 7523 if (isa<InlineAsm>(I.getCalledValue())) { 7524 visitInlineAsm(&I); 7525 return; 7526 } 7527 7528 if (Function *F = I.getCalledFunction()) { 7529 if (F->isDeclaration()) { 7530 // Is this an LLVM intrinsic or a target-specific intrinsic? 7531 unsigned IID = F->getIntrinsicID(); 7532 if (!IID) 7533 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7534 IID = II->getIntrinsicID(F); 7535 7536 if (IID) { 7537 visitIntrinsicCall(I, IID); 7538 return; 7539 } 7540 } 7541 7542 // Check for well-known libc/libm calls. If the function is internal, it 7543 // can't be a library call. Don't do the check if marked as nobuiltin for 7544 // some reason or the call site requires strict floating point semantics. 7545 LibFunc Func; 7546 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7547 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7548 LibInfo->hasOptimizedCodeGen(Func)) { 7549 switch (Func) { 7550 default: break; 7551 case LibFunc_copysign: 7552 case LibFunc_copysignf: 7553 case LibFunc_copysignl: 7554 // We already checked this call's prototype; verify it doesn't modify 7555 // errno. 7556 if (I.onlyReadsMemory()) { 7557 SDValue LHS = getValue(I.getArgOperand(0)); 7558 SDValue RHS = getValue(I.getArgOperand(1)); 7559 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7560 LHS.getValueType(), LHS, RHS)); 7561 return; 7562 } 7563 break; 7564 case LibFunc_fabs: 7565 case LibFunc_fabsf: 7566 case LibFunc_fabsl: 7567 if (visitUnaryFloatCall(I, ISD::FABS)) 7568 return; 7569 break; 7570 case LibFunc_fmin: 7571 case LibFunc_fminf: 7572 case LibFunc_fminl: 7573 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7574 return; 7575 break; 7576 case LibFunc_fmax: 7577 case LibFunc_fmaxf: 7578 case LibFunc_fmaxl: 7579 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7580 return; 7581 break; 7582 case LibFunc_sin: 7583 case LibFunc_sinf: 7584 case LibFunc_sinl: 7585 if (visitUnaryFloatCall(I, ISD::FSIN)) 7586 return; 7587 break; 7588 case LibFunc_cos: 7589 case LibFunc_cosf: 7590 case LibFunc_cosl: 7591 if (visitUnaryFloatCall(I, ISD::FCOS)) 7592 return; 7593 break; 7594 case LibFunc_sqrt: 7595 case LibFunc_sqrtf: 7596 case LibFunc_sqrtl: 7597 case LibFunc_sqrt_finite: 7598 case LibFunc_sqrtf_finite: 7599 case LibFunc_sqrtl_finite: 7600 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7601 return; 7602 break; 7603 case LibFunc_floor: 7604 case LibFunc_floorf: 7605 case LibFunc_floorl: 7606 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7607 return; 7608 break; 7609 case LibFunc_nearbyint: 7610 case LibFunc_nearbyintf: 7611 case LibFunc_nearbyintl: 7612 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7613 return; 7614 break; 7615 case LibFunc_ceil: 7616 case LibFunc_ceilf: 7617 case LibFunc_ceill: 7618 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7619 return; 7620 break; 7621 case LibFunc_rint: 7622 case LibFunc_rintf: 7623 case LibFunc_rintl: 7624 if (visitUnaryFloatCall(I, ISD::FRINT)) 7625 return; 7626 break; 7627 case LibFunc_round: 7628 case LibFunc_roundf: 7629 case LibFunc_roundl: 7630 if (visitUnaryFloatCall(I, ISD::FROUND)) 7631 return; 7632 break; 7633 case LibFunc_trunc: 7634 case LibFunc_truncf: 7635 case LibFunc_truncl: 7636 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7637 return; 7638 break; 7639 case LibFunc_log2: 7640 case LibFunc_log2f: 7641 case LibFunc_log2l: 7642 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7643 return; 7644 break; 7645 case LibFunc_exp2: 7646 case LibFunc_exp2f: 7647 case LibFunc_exp2l: 7648 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7649 return; 7650 break; 7651 case LibFunc_memcmp: 7652 if (visitMemCmpCall(I)) 7653 return; 7654 break; 7655 case LibFunc_mempcpy: 7656 if (visitMemPCpyCall(I)) 7657 return; 7658 break; 7659 case LibFunc_memchr: 7660 if (visitMemChrCall(I)) 7661 return; 7662 break; 7663 case LibFunc_strcpy: 7664 if (visitStrCpyCall(I, false)) 7665 return; 7666 break; 7667 case LibFunc_stpcpy: 7668 if (visitStrCpyCall(I, true)) 7669 return; 7670 break; 7671 case LibFunc_strcmp: 7672 if (visitStrCmpCall(I)) 7673 return; 7674 break; 7675 case LibFunc_strlen: 7676 if (visitStrLenCall(I)) 7677 return; 7678 break; 7679 case LibFunc_strnlen: 7680 if (visitStrNLenCall(I)) 7681 return; 7682 break; 7683 } 7684 } 7685 } 7686 7687 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7688 // have to do anything here to lower funclet bundles. 7689 assert(!I.hasOperandBundlesOtherThan( 7690 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7691 "Cannot lower calls with arbitrary operand bundles!"); 7692 7693 SDValue Callee = getValue(I.getCalledValue()); 7694 7695 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7696 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7697 else 7698 // Check if we can potentially perform a tail call. More detailed checking 7699 // is be done within LowerCallTo, after more information about the call is 7700 // known. 7701 LowerCallTo(&I, Callee, I.isTailCall()); 7702 } 7703 7704 namespace { 7705 7706 /// AsmOperandInfo - This contains information for each constraint that we are 7707 /// lowering. 7708 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7709 public: 7710 /// CallOperand - If this is the result output operand or a clobber 7711 /// this is null, otherwise it is the incoming operand to the CallInst. 7712 /// This gets modified as the asm is processed. 7713 SDValue CallOperand; 7714 7715 /// AssignedRegs - If this is a register or register class operand, this 7716 /// contains the set of register corresponding to the operand. 7717 RegsForValue AssignedRegs; 7718 7719 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7720 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7721 } 7722 7723 /// Whether or not this operand accesses memory 7724 bool hasMemory(const TargetLowering &TLI) const { 7725 // Indirect operand accesses access memory. 7726 if (isIndirect) 7727 return true; 7728 7729 for (const auto &Code : Codes) 7730 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7731 return true; 7732 7733 return false; 7734 } 7735 7736 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7737 /// corresponds to. If there is no Value* for this operand, it returns 7738 /// MVT::Other. 7739 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7740 const DataLayout &DL) const { 7741 if (!CallOperandVal) return MVT::Other; 7742 7743 if (isa<BasicBlock>(CallOperandVal)) 7744 return TLI.getPointerTy(DL); 7745 7746 llvm::Type *OpTy = CallOperandVal->getType(); 7747 7748 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7749 // If this is an indirect operand, the operand is a pointer to the 7750 // accessed type. 7751 if (isIndirect) { 7752 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7753 if (!PtrTy) 7754 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7755 OpTy = PtrTy->getElementType(); 7756 } 7757 7758 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7759 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7760 if (STy->getNumElements() == 1) 7761 OpTy = STy->getElementType(0); 7762 7763 // If OpTy is not a single value, it may be a struct/union that we 7764 // can tile with integers. 7765 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7766 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7767 switch (BitSize) { 7768 default: break; 7769 case 1: 7770 case 8: 7771 case 16: 7772 case 32: 7773 case 64: 7774 case 128: 7775 OpTy = IntegerType::get(Context, BitSize); 7776 break; 7777 } 7778 } 7779 7780 return TLI.getValueType(DL, OpTy, true); 7781 } 7782 }; 7783 7784 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7785 7786 } // end anonymous namespace 7787 7788 /// Make sure that the output operand \p OpInfo and its corresponding input 7789 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7790 /// out). 7791 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7792 SDISelAsmOperandInfo &MatchingOpInfo, 7793 SelectionDAG &DAG) { 7794 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7795 return; 7796 7797 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7798 const auto &TLI = DAG.getTargetLoweringInfo(); 7799 7800 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7801 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7802 OpInfo.ConstraintVT); 7803 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7804 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7805 MatchingOpInfo.ConstraintVT); 7806 if ((OpInfo.ConstraintVT.isInteger() != 7807 MatchingOpInfo.ConstraintVT.isInteger()) || 7808 (MatchRC.second != InputRC.second)) { 7809 // FIXME: error out in a more elegant fashion 7810 report_fatal_error("Unsupported asm: input constraint" 7811 " with a matching output constraint of" 7812 " incompatible type!"); 7813 } 7814 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7815 } 7816 7817 /// Get a direct memory input to behave well as an indirect operand. 7818 /// This may introduce stores, hence the need for a \p Chain. 7819 /// \return The (possibly updated) chain. 7820 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7821 SDISelAsmOperandInfo &OpInfo, 7822 SelectionDAG &DAG) { 7823 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7824 7825 // If we don't have an indirect input, put it in the constpool if we can, 7826 // otherwise spill it to a stack slot. 7827 // TODO: This isn't quite right. We need to handle these according to 7828 // the addressing mode that the constraint wants. Also, this may take 7829 // an additional register for the computation and we don't want that 7830 // either. 7831 7832 // If the operand is a float, integer, or vector constant, spill to a 7833 // constant pool entry to get its address. 7834 const Value *OpVal = OpInfo.CallOperandVal; 7835 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7836 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7837 OpInfo.CallOperand = DAG.getConstantPool( 7838 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7839 return Chain; 7840 } 7841 7842 // Otherwise, create a stack slot and emit a store to it before the asm. 7843 Type *Ty = OpVal->getType(); 7844 auto &DL = DAG.getDataLayout(); 7845 uint64_t TySize = DL.getTypeAllocSize(Ty); 7846 unsigned Align = DL.getPrefTypeAlignment(Ty); 7847 MachineFunction &MF = DAG.getMachineFunction(); 7848 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7849 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7850 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7851 MachinePointerInfo::getFixedStack(MF, SSFI), 7852 TLI.getMemValueType(DL, Ty)); 7853 OpInfo.CallOperand = StackSlot; 7854 7855 return Chain; 7856 } 7857 7858 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7859 /// specified operand. We prefer to assign virtual registers, to allow the 7860 /// register allocator to handle the assignment process. However, if the asm 7861 /// uses features that we can't model on machineinstrs, we have SDISel do the 7862 /// allocation. This produces generally horrible, but correct, code. 7863 /// 7864 /// OpInfo describes the operand 7865 /// RefOpInfo describes the matching operand if any, the operand otherwise 7866 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7867 SDISelAsmOperandInfo &OpInfo, 7868 SDISelAsmOperandInfo &RefOpInfo) { 7869 LLVMContext &Context = *DAG.getContext(); 7870 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7871 7872 MachineFunction &MF = DAG.getMachineFunction(); 7873 SmallVector<unsigned, 4> Regs; 7874 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7875 7876 // No work to do for memory operations. 7877 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7878 return; 7879 7880 // If this is a constraint for a single physreg, or a constraint for a 7881 // register class, find it. 7882 unsigned AssignedReg; 7883 const TargetRegisterClass *RC; 7884 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7885 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7886 // RC is unset only on failure. Return immediately. 7887 if (!RC) 7888 return; 7889 7890 // Get the actual register value type. This is important, because the user 7891 // may have asked for (e.g.) the AX register in i32 type. We need to 7892 // remember that AX is actually i16 to get the right extension. 7893 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7894 7895 if (OpInfo.ConstraintVT != MVT::Other) { 7896 // If this is an FP operand in an integer register (or visa versa), or more 7897 // generally if the operand value disagrees with the register class we plan 7898 // to stick it in, fix the operand type. 7899 // 7900 // If this is an input value, the bitcast to the new type is done now. 7901 // Bitcast for output value is done at the end of visitInlineAsm(). 7902 if ((OpInfo.Type == InlineAsm::isOutput || 7903 OpInfo.Type == InlineAsm::isInput) && 7904 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7905 // Try to convert to the first EVT that the reg class contains. If the 7906 // types are identical size, use a bitcast to convert (e.g. two differing 7907 // vector types). Note: output bitcast is done at the end of 7908 // visitInlineAsm(). 7909 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7910 // Exclude indirect inputs while they are unsupported because the code 7911 // to perform the load is missing and thus OpInfo.CallOperand still 7912 // refers to the input address rather than the pointed-to value. 7913 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7914 OpInfo.CallOperand = 7915 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7916 OpInfo.ConstraintVT = RegVT; 7917 // If the operand is an FP value and we want it in integer registers, 7918 // use the corresponding integer type. This turns an f64 value into 7919 // i64, which can be passed with two i32 values on a 32-bit machine. 7920 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7921 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7922 if (OpInfo.Type == InlineAsm::isInput) 7923 OpInfo.CallOperand = 7924 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7925 OpInfo.ConstraintVT = VT; 7926 } 7927 } 7928 } 7929 7930 // No need to allocate a matching input constraint since the constraint it's 7931 // matching to has already been allocated. 7932 if (OpInfo.isMatchingInputConstraint()) 7933 return; 7934 7935 EVT ValueVT = OpInfo.ConstraintVT; 7936 if (OpInfo.ConstraintVT == MVT::Other) 7937 ValueVT = RegVT; 7938 7939 // Initialize NumRegs. 7940 unsigned NumRegs = 1; 7941 if (OpInfo.ConstraintVT != MVT::Other) 7942 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7943 7944 // If this is a constraint for a specific physical register, like {r17}, 7945 // assign it now. 7946 7947 // If this associated to a specific register, initialize iterator to correct 7948 // place. If virtual, make sure we have enough registers 7949 7950 // Initialize iterator if necessary 7951 TargetRegisterClass::iterator I = RC->begin(); 7952 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7953 7954 // Do not check for single registers. 7955 if (AssignedReg) { 7956 for (; *I != AssignedReg; ++I) 7957 assert(I != RC->end() && "AssignedReg should be member of RC"); 7958 } 7959 7960 for (; NumRegs; --NumRegs, ++I) { 7961 assert(I != RC->end() && "Ran out of registers to allocate!"); 7962 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC); 7963 Regs.push_back(R); 7964 } 7965 7966 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7967 } 7968 7969 static unsigned 7970 findMatchingInlineAsmOperand(unsigned OperandNo, 7971 const std::vector<SDValue> &AsmNodeOperands) { 7972 // Scan until we find the definition we already emitted of this operand. 7973 unsigned CurOp = InlineAsm::Op_FirstOperand; 7974 for (; OperandNo; --OperandNo) { 7975 // Advance to the next operand. 7976 unsigned OpFlag = 7977 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7978 assert((InlineAsm::isRegDefKind(OpFlag) || 7979 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7980 InlineAsm::isMemKind(OpFlag)) && 7981 "Skipped past definitions?"); 7982 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7983 } 7984 return CurOp; 7985 } 7986 7987 namespace { 7988 7989 class ExtraFlags { 7990 unsigned Flags = 0; 7991 7992 public: 7993 explicit ExtraFlags(ImmutableCallSite CS) { 7994 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7995 if (IA->hasSideEffects()) 7996 Flags |= InlineAsm::Extra_HasSideEffects; 7997 if (IA->isAlignStack()) 7998 Flags |= InlineAsm::Extra_IsAlignStack; 7999 if (CS.isConvergent()) 8000 Flags |= InlineAsm::Extra_IsConvergent; 8001 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 8002 } 8003 8004 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 8005 // Ideally, we would only check against memory constraints. However, the 8006 // meaning of an Other constraint can be target-specific and we can't easily 8007 // reason about it. Therefore, be conservative and set MayLoad/MayStore 8008 // for Other constraints as well. 8009 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8010 OpInfo.ConstraintType == TargetLowering::C_Other) { 8011 if (OpInfo.Type == InlineAsm::isInput) 8012 Flags |= InlineAsm::Extra_MayLoad; 8013 else if (OpInfo.Type == InlineAsm::isOutput) 8014 Flags |= InlineAsm::Extra_MayStore; 8015 else if (OpInfo.Type == InlineAsm::isClobber) 8016 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 8017 } 8018 } 8019 8020 unsigned get() const { return Flags; } 8021 }; 8022 8023 } // end anonymous namespace 8024 8025 /// visitInlineAsm - Handle a call to an InlineAsm object. 8026 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 8027 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 8028 8029 /// ConstraintOperands - Information about all of the constraints. 8030 SDISelAsmOperandInfoVector ConstraintOperands; 8031 8032 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8033 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 8034 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 8035 8036 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 8037 // AsmDialect, MayLoad, MayStore). 8038 bool HasSideEffect = IA->hasSideEffects(); 8039 ExtraFlags ExtraInfo(CS); 8040 8041 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 8042 unsigned ResNo = 0; // ResNo - The result number of the next output. 8043 for (auto &T : TargetConstraints) { 8044 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 8045 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 8046 8047 // Compute the value type for each operand. 8048 if (OpInfo.Type == InlineAsm::isInput || 8049 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 8050 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 8051 8052 // Process the call argument. BasicBlocks are labels, currently appearing 8053 // only in asm's. 8054 const Instruction *I = CS.getInstruction(); 8055 if (isa<CallBrInst>(I) && 8056 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 8057 cast<CallBrInst>(I)->getNumIndirectDests())) { 8058 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 8059 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 8060 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 8061 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 8062 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 8063 } else { 8064 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 8065 } 8066 8067 OpInfo.ConstraintVT = 8068 OpInfo 8069 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 8070 .getSimpleVT(); 8071 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 8072 // The return value of the call is this value. As such, there is no 8073 // corresponding argument. 8074 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8075 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 8076 OpInfo.ConstraintVT = TLI.getSimpleValueType( 8077 DAG.getDataLayout(), STy->getElementType(ResNo)); 8078 } else { 8079 assert(ResNo == 0 && "Asm only has one result!"); 8080 OpInfo.ConstraintVT = 8081 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 8082 } 8083 ++ResNo; 8084 } else { 8085 OpInfo.ConstraintVT = MVT::Other; 8086 } 8087 8088 if (!HasSideEffect) 8089 HasSideEffect = OpInfo.hasMemory(TLI); 8090 8091 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 8092 // FIXME: Could we compute this on OpInfo rather than T? 8093 8094 // Compute the constraint code and ConstraintType to use. 8095 TLI.ComputeConstraintToUse(T, SDValue()); 8096 8097 if (T.ConstraintType == TargetLowering::C_Immediate && 8098 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand)) 8099 // We've delayed emitting a diagnostic like the "n" constraint because 8100 // inlining could cause an integer showing up. 8101 return emitInlineAsmError( 8102 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an " 8103 "integer constant expression"); 8104 8105 ExtraInfo.update(T); 8106 } 8107 8108 8109 // We won't need to flush pending loads if this asm doesn't touch 8110 // memory and is nonvolatile. 8111 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 8112 8113 bool IsCallBr = isa<CallBrInst>(CS.getInstruction()); 8114 if (IsCallBr) { 8115 // If this is a callbr we need to flush pending exports since inlineasm_br 8116 // is a terminator. We need to do this before nodes are glued to 8117 // the inlineasm_br node. 8118 Chain = getControlRoot(); 8119 } 8120 8121 // Second pass over the constraints: compute which constraint option to use. 8122 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8123 // If this is an output operand with a matching input operand, look up the 8124 // matching input. If their types mismatch, e.g. one is an integer, the 8125 // other is floating point, or their sizes are different, flag it as an 8126 // error. 8127 if (OpInfo.hasMatchingInput()) { 8128 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 8129 patchMatchingInput(OpInfo, Input, DAG); 8130 } 8131 8132 // Compute the constraint code and ConstraintType to use. 8133 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 8134 8135 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8136 OpInfo.Type == InlineAsm::isClobber) 8137 continue; 8138 8139 // If this is a memory input, and if the operand is not indirect, do what we 8140 // need to provide an address for the memory input. 8141 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 8142 !OpInfo.isIndirect) { 8143 assert((OpInfo.isMultipleAlternative || 8144 (OpInfo.Type == InlineAsm::isInput)) && 8145 "Can only indirectify direct input operands!"); 8146 8147 // Memory operands really want the address of the value. 8148 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 8149 8150 // There is no longer a Value* corresponding to this operand. 8151 OpInfo.CallOperandVal = nullptr; 8152 8153 // It is now an indirect operand. 8154 OpInfo.isIndirect = true; 8155 } 8156 8157 } 8158 8159 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 8160 std::vector<SDValue> AsmNodeOperands; 8161 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 8162 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 8163 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 8164 8165 // If we have a !srcloc metadata node associated with it, we want to attach 8166 // this to the ultimately generated inline asm machineinstr. To do this, we 8167 // pass in the third operand as this (potentially null) inline asm MDNode. 8168 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 8169 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 8170 8171 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 8172 // bits as operand 3. 8173 AsmNodeOperands.push_back(DAG.getTargetConstant( 8174 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8175 8176 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 8177 // this, assign virtual and physical registers for inputs and otput. 8178 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8179 // Assign Registers. 8180 SDISelAsmOperandInfo &RefOpInfo = 8181 OpInfo.isMatchingInputConstraint() 8182 ? ConstraintOperands[OpInfo.getMatchedOperand()] 8183 : OpInfo; 8184 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 8185 8186 switch (OpInfo.Type) { 8187 case InlineAsm::isOutput: 8188 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 8189 ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8190 OpInfo.ConstraintType == TargetLowering::C_Other) && 8191 OpInfo.isIndirect)) { 8192 unsigned ConstraintID = 8193 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8194 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8195 "Failed to convert memory constraint code to constraint id."); 8196 8197 // Add information to the INLINEASM node to know about this output. 8198 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8199 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 8200 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 8201 MVT::i32)); 8202 AsmNodeOperands.push_back(OpInfo.CallOperand); 8203 break; 8204 } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8205 OpInfo.ConstraintType == TargetLowering::C_Other) && 8206 !OpInfo.isIndirect) || 8207 OpInfo.ConstraintType == TargetLowering::C_Register || 8208 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8209 // Otherwise, this outputs to a register (directly for C_Register / 8210 // C_RegisterClass, and a target-defined fashion for 8211 // C_Immediate/C_Other). Find a register that we can use. 8212 if (OpInfo.AssignedRegs.Regs.empty()) { 8213 emitInlineAsmError( 8214 CS, "couldn't allocate output register for constraint '" + 8215 Twine(OpInfo.ConstraintCode) + "'"); 8216 return; 8217 } 8218 8219 // Add information to the INLINEASM node to know that this register is 8220 // set. 8221 OpInfo.AssignedRegs.AddInlineAsmOperands( 8222 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8223 : InlineAsm::Kind_RegDef, 8224 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8225 } 8226 break; 8227 8228 case InlineAsm::isInput: { 8229 SDValue InOperandVal = OpInfo.CallOperand; 8230 8231 if (OpInfo.isMatchingInputConstraint()) { 8232 // If this is required to match an output register we have already set, 8233 // just use its register. 8234 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8235 AsmNodeOperands); 8236 unsigned OpFlag = 8237 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8238 if (InlineAsm::isRegDefKind(OpFlag) || 8239 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8240 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8241 if (OpInfo.isIndirect) { 8242 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8243 emitInlineAsmError(CS, "inline asm not supported yet:" 8244 " don't know how to handle tied " 8245 "indirect register inputs"); 8246 return; 8247 } 8248 8249 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8250 SmallVector<unsigned, 4> Regs; 8251 8252 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8253 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8254 MachineRegisterInfo &RegInfo = 8255 DAG.getMachineFunction().getRegInfo(); 8256 for (unsigned i = 0; i != NumRegs; ++i) 8257 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8258 } else { 8259 emitInlineAsmError(CS, "inline asm error: This value type register " 8260 "class is not natively supported!"); 8261 return; 8262 } 8263 8264 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8265 8266 SDLoc dl = getCurSDLoc(); 8267 // Use the produced MatchedRegs object to 8268 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8269 CS.getInstruction()); 8270 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8271 true, OpInfo.getMatchedOperand(), dl, 8272 DAG, AsmNodeOperands); 8273 break; 8274 } 8275 8276 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8277 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8278 "Unexpected number of operands"); 8279 // Add information to the INLINEASM node to know about this input. 8280 // See InlineAsm.h isUseOperandTiedToDef. 8281 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8282 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8283 OpInfo.getMatchedOperand()); 8284 AsmNodeOperands.push_back(DAG.getTargetConstant( 8285 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8286 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8287 break; 8288 } 8289 8290 // Treat indirect 'X' constraint as memory. 8291 if ((OpInfo.ConstraintType == TargetLowering::C_Immediate || 8292 OpInfo.ConstraintType == TargetLowering::C_Other) && 8293 OpInfo.isIndirect) 8294 OpInfo.ConstraintType = TargetLowering::C_Memory; 8295 8296 if (OpInfo.ConstraintType == TargetLowering::C_Immediate || 8297 OpInfo.ConstraintType == TargetLowering::C_Other) { 8298 std::vector<SDValue> Ops; 8299 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8300 Ops, DAG); 8301 if (Ops.empty()) { 8302 if (OpInfo.ConstraintType == TargetLowering::C_Immediate) 8303 if (isa<ConstantSDNode>(InOperandVal)) { 8304 emitInlineAsmError(CS, "value out of range for constraint '" + 8305 Twine(OpInfo.ConstraintCode) + "'"); 8306 return; 8307 } 8308 8309 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8310 Twine(OpInfo.ConstraintCode) + "'"); 8311 return; 8312 } 8313 8314 // Add information to the INLINEASM node to know about this input. 8315 unsigned ResOpType = 8316 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8317 AsmNodeOperands.push_back(DAG.getTargetConstant( 8318 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8319 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8320 break; 8321 } 8322 8323 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8324 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8325 assert(InOperandVal.getValueType() == 8326 TLI.getPointerTy(DAG.getDataLayout()) && 8327 "Memory operands expect pointer values"); 8328 8329 unsigned ConstraintID = 8330 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8331 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8332 "Failed to convert memory constraint code to constraint id."); 8333 8334 // Add information to the INLINEASM node to know about this input. 8335 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8336 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8337 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8338 getCurSDLoc(), 8339 MVT::i32)); 8340 AsmNodeOperands.push_back(InOperandVal); 8341 break; 8342 } 8343 8344 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8345 OpInfo.ConstraintType == TargetLowering::C_Register || 8346 OpInfo.ConstraintType == TargetLowering::C_Immediate) && 8347 "Unknown constraint type!"); 8348 8349 // TODO: Support this. 8350 if (OpInfo.isIndirect) { 8351 emitInlineAsmError( 8352 CS, "Don't know how to handle indirect register inputs yet " 8353 "for constraint '" + 8354 Twine(OpInfo.ConstraintCode) + "'"); 8355 return; 8356 } 8357 8358 // Copy the input into the appropriate registers. 8359 if (OpInfo.AssignedRegs.Regs.empty()) { 8360 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8361 Twine(OpInfo.ConstraintCode) + "'"); 8362 return; 8363 } 8364 8365 SDLoc dl = getCurSDLoc(); 8366 8367 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8368 Chain, &Flag, CS.getInstruction()); 8369 8370 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8371 dl, DAG, AsmNodeOperands); 8372 break; 8373 } 8374 case InlineAsm::isClobber: 8375 // Add the clobbered value to the operand list, so that the register 8376 // allocator is aware that the physreg got clobbered. 8377 if (!OpInfo.AssignedRegs.Regs.empty()) 8378 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8379 false, 0, getCurSDLoc(), DAG, 8380 AsmNodeOperands); 8381 break; 8382 } 8383 } 8384 8385 // Finish up input operands. Set the input chain and add the flag last. 8386 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8387 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8388 8389 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM; 8390 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8391 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8392 Flag = Chain.getValue(1); 8393 8394 // Do additional work to generate outputs. 8395 8396 SmallVector<EVT, 1> ResultVTs; 8397 SmallVector<SDValue, 1> ResultValues; 8398 SmallVector<SDValue, 8> OutChains; 8399 8400 llvm::Type *CSResultType = CS.getType(); 8401 ArrayRef<Type *> ResultTypes; 8402 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8403 ResultTypes = StructResult->elements(); 8404 else if (!CSResultType->isVoidTy()) 8405 ResultTypes = makeArrayRef(CSResultType); 8406 8407 auto CurResultType = ResultTypes.begin(); 8408 auto handleRegAssign = [&](SDValue V) { 8409 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8410 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8411 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8412 ++CurResultType; 8413 // If the type of the inline asm call site return value is different but has 8414 // same size as the type of the asm output bitcast it. One example of this 8415 // is for vectors with different width / number of elements. This can 8416 // happen for register classes that can contain multiple different value 8417 // types. The preg or vreg allocated may not have the same VT as was 8418 // expected. 8419 // 8420 // This can also happen for a return value that disagrees with the register 8421 // class it is put in, eg. a double in a general-purpose register on a 8422 // 32-bit machine. 8423 if (ResultVT != V.getValueType() && 8424 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8425 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8426 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8427 V.getValueType().isInteger()) { 8428 // If a result value was tied to an input value, the computed result 8429 // may have a wider width than the expected result. Extract the 8430 // relevant portion. 8431 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8432 } 8433 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8434 ResultVTs.push_back(ResultVT); 8435 ResultValues.push_back(V); 8436 }; 8437 8438 // Deal with output operands. 8439 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8440 if (OpInfo.Type == InlineAsm::isOutput) { 8441 SDValue Val; 8442 // Skip trivial output operands. 8443 if (OpInfo.AssignedRegs.Regs.empty()) 8444 continue; 8445 8446 switch (OpInfo.ConstraintType) { 8447 case TargetLowering::C_Register: 8448 case TargetLowering::C_RegisterClass: 8449 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8450 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8451 break; 8452 case TargetLowering::C_Immediate: 8453 case TargetLowering::C_Other: 8454 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8455 OpInfo, DAG); 8456 break; 8457 case TargetLowering::C_Memory: 8458 break; // Already handled. 8459 case TargetLowering::C_Unknown: 8460 assert(false && "Unexpected unknown constraint"); 8461 } 8462 8463 // Indirect output manifest as stores. Record output chains. 8464 if (OpInfo.isIndirect) { 8465 const Value *Ptr = OpInfo.CallOperandVal; 8466 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8467 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8468 MachinePointerInfo(Ptr)); 8469 OutChains.push_back(Store); 8470 } else { 8471 // generate CopyFromRegs to associated registers. 8472 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8473 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8474 for (const SDValue &V : Val->op_values()) 8475 handleRegAssign(V); 8476 } else 8477 handleRegAssign(Val); 8478 } 8479 } 8480 } 8481 8482 // Set results. 8483 if (!ResultValues.empty()) { 8484 assert(CurResultType == ResultTypes.end() && 8485 "Mismatch in number of ResultTypes"); 8486 assert(ResultValues.size() == ResultTypes.size() && 8487 "Mismatch in number of output operands in asm result"); 8488 8489 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8490 DAG.getVTList(ResultVTs), ResultValues); 8491 setValue(CS.getInstruction(), V); 8492 } 8493 8494 // Collect store chains. 8495 if (!OutChains.empty()) 8496 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8497 8498 // Only Update Root if inline assembly has a memory effect. 8499 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr) 8500 DAG.setRoot(Chain); 8501 } 8502 8503 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8504 const Twine &Message) { 8505 LLVMContext &Ctx = *DAG.getContext(); 8506 Ctx.emitError(CS.getInstruction(), Message); 8507 8508 // Make sure we leave the DAG in a valid state 8509 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8510 SmallVector<EVT, 1> ValueVTs; 8511 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8512 8513 if (ValueVTs.empty()) 8514 return; 8515 8516 SmallVector<SDValue, 1> Ops; 8517 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8518 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8519 8520 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8521 } 8522 8523 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8524 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8525 MVT::Other, getRoot(), 8526 getValue(I.getArgOperand(0)), 8527 DAG.getSrcValue(I.getArgOperand(0)))); 8528 } 8529 8530 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8531 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8532 const DataLayout &DL = DAG.getDataLayout(); 8533 SDValue V = DAG.getVAArg( 8534 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(), 8535 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)), 8536 DL.getABITypeAlignment(I.getType())); 8537 DAG.setRoot(V.getValue(1)); 8538 8539 if (I.getType()->isPointerTy()) 8540 V = DAG.getPtrExtOrTrunc( 8541 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType())); 8542 setValue(&I, V); 8543 } 8544 8545 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8546 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8547 MVT::Other, getRoot(), 8548 getValue(I.getArgOperand(0)), 8549 DAG.getSrcValue(I.getArgOperand(0)))); 8550 } 8551 8552 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8553 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8554 MVT::Other, getRoot(), 8555 getValue(I.getArgOperand(0)), 8556 getValue(I.getArgOperand(1)), 8557 DAG.getSrcValue(I.getArgOperand(0)), 8558 DAG.getSrcValue(I.getArgOperand(1)))); 8559 } 8560 8561 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8562 const Instruction &I, 8563 SDValue Op) { 8564 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8565 if (!Range) 8566 return Op; 8567 8568 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8569 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8570 return Op; 8571 8572 APInt Lo = CR.getUnsignedMin(); 8573 if (!Lo.isMinValue()) 8574 return Op; 8575 8576 APInt Hi = CR.getUnsignedMax(); 8577 unsigned Bits = std::max(Hi.getActiveBits(), 8578 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8579 8580 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8581 8582 SDLoc SL = getCurSDLoc(); 8583 8584 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8585 DAG.getValueType(SmallVT)); 8586 unsigned NumVals = Op.getNode()->getNumValues(); 8587 if (NumVals == 1) 8588 return ZExt; 8589 8590 SmallVector<SDValue, 4> Ops; 8591 8592 Ops.push_back(ZExt); 8593 for (unsigned I = 1; I != NumVals; ++I) 8594 Ops.push_back(Op.getValue(I)); 8595 8596 return DAG.getMergeValues(Ops, SL); 8597 } 8598 8599 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8600 /// the call being lowered. 8601 /// 8602 /// This is a helper for lowering intrinsics that follow a target calling 8603 /// convention or require stack pointer adjustment. Only a subset of the 8604 /// intrinsic's operands need to participate in the calling convention. 8605 void SelectionDAGBuilder::populateCallLoweringInfo( 8606 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8607 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8608 bool IsPatchPoint) { 8609 TargetLowering::ArgListTy Args; 8610 Args.reserve(NumArgs); 8611 8612 // Populate the argument list. 8613 // Attributes for args start at offset 1, after the return attribute. 8614 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8615 ArgI != ArgE; ++ArgI) { 8616 const Value *V = Call->getOperand(ArgI); 8617 8618 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8619 8620 TargetLowering::ArgListEntry Entry; 8621 Entry.Node = getValue(V); 8622 Entry.Ty = V->getType(); 8623 Entry.setAttributes(Call, ArgI); 8624 Args.push_back(Entry); 8625 } 8626 8627 CLI.setDebugLoc(getCurSDLoc()) 8628 .setChain(getRoot()) 8629 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8630 .setDiscardResult(Call->use_empty()) 8631 .setIsPatchPoint(IsPatchPoint); 8632 } 8633 8634 /// Add a stack map intrinsic call's live variable operands to a stackmap 8635 /// or patchpoint target node's operand list. 8636 /// 8637 /// Constants are converted to TargetConstants purely as an optimization to 8638 /// avoid constant materialization and register allocation. 8639 /// 8640 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8641 /// generate addess computation nodes, and so FinalizeISel can convert the 8642 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8643 /// address materialization and register allocation, but may also be required 8644 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8645 /// alloca in the entry block, then the runtime may assume that the alloca's 8646 /// StackMap location can be read immediately after compilation and that the 8647 /// location is valid at any point during execution (this is similar to the 8648 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8649 /// only available in a register, then the runtime would need to trap when 8650 /// execution reaches the StackMap in order to read the alloca's location. 8651 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8652 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8653 SelectionDAGBuilder &Builder) { 8654 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8655 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8656 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8657 Ops.push_back( 8658 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8659 Ops.push_back( 8660 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8661 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8662 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8663 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8664 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8665 } else 8666 Ops.push_back(OpVal); 8667 } 8668 } 8669 8670 /// Lower llvm.experimental.stackmap directly to its target opcode. 8671 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8672 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8673 // [live variables...]) 8674 8675 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8676 8677 SDValue Chain, InFlag, Callee, NullPtr; 8678 SmallVector<SDValue, 32> Ops; 8679 8680 SDLoc DL = getCurSDLoc(); 8681 Callee = getValue(CI.getCalledValue()); 8682 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8683 8684 // The stackmap intrinsic only records the live variables (the arguemnts 8685 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8686 // intrinsic, this won't be lowered to a function call. This means we don't 8687 // have to worry about calling conventions and target specific lowering code. 8688 // Instead we perform the call lowering right here. 8689 // 8690 // chain, flag = CALLSEQ_START(chain, 0, 0) 8691 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8692 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8693 // 8694 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8695 InFlag = Chain.getValue(1); 8696 8697 // Add the <id> and <numBytes> constants. 8698 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8699 Ops.push_back(DAG.getTargetConstant( 8700 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8701 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8702 Ops.push_back(DAG.getTargetConstant( 8703 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8704 MVT::i32)); 8705 8706 // Push live variables for the stack map. 8707 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8708 8709 // We are not pushing any register mask info here on the operands list, 8710 // because the stackmap doesn't clobber anything. 8711 8712 // Push the chain and the glue flag. 8713 Ops.push_back(Chain); 8714 Ops.push_back(InFlag); 8715 8716 // Create the STACKMAP node. 8717 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8718 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8719 Chain = SDValue(SM, 0); 8720 InFlag = Chain.getValue(1); 8721 8722 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8723 8724 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8725 8726 // Set the root to the target-lowered call chain. 8727 DAG.setRoot(Chain); 8728 8729 // Inform the Frame Information that we have a stackmap in this function. 8730 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8731 } 8732 8733 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8734 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8735 const BasicBlock *EHPadBB) { 8736 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8737 // i32 <numBytes>, 8738 // i8* <target>, 8739 // i32 <numArgs>, 8740 // [Args...], 8741 // [live variables...]) 8742 8743 CallingConv::ID CC = CS.getCallingConv(); 8744 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8745 bool HasDef = !CS->getType()->isVoidTy(); 8746 SDLoc dl = getCurSDLoc(); 8747 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8748 8749 // Handle immediate and symbolic callees. 8750 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8751 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8752 /*isTarget=*/true); 8753 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8754 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8755 SDLoc(SymbolicCallee), 8756 SymbolicCallee->getValueType(0)); 8757 8758 // Get the real number of arguments participating in the call <numArgs> 8759 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8760 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8761 8762 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8763 // Intrinsics include all meta-operands up to but not including CC. 8764 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8765 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8766 "Not enough arguments provided to the patchpoint intrinsic"); 8767 8768 // For AnyRegCC the arguments are lowered later on manually. 8769 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8770 Type *ReturnTy = 8771 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8772 8773 TargetLowering::CallLoweringInfo CLI(DAG); 8774 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8775 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8776 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8777 8778 SDNode *CallEnd = Result.second.getNode(); 8779 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8780 CallEnd = CallEnd->getOperand(0).getNode(); 8781 8782 /// Get a call instruction from the call sequence chain. 8783 /// Tail calls are not allowed. 8784 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8785 "Expected a callseq node."); 8786 SDNode *Call = CallEnd->getOperand(0).getNode(); 8787 bool HasGlue = Call->getGluedNode(); 8788 8789 // Replace the target specific call node with the patchable intrinsic. 8790 SmallVector<SDValue, 8> Ops; 8791 8792 // Add the <id> and <numBytes> constants. 8793 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8794 Ops.push_back(DAG.getTargetConstant( 8795 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8796 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8797 Ops.push_back(DAG.getTargetConstant( 8798 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8799 MVT::i32)); 8800 8801 // Add the callee. 8802 Ops.push_back(Callee); 8803 8804 // Adjust <numArgs> to account for any arguments that have been passed on the 8805 // stack instead. 8806 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8807 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8808 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8809 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8810 8811 // Add the calling convention 8812 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8813 8814 // Add the arguments we omitted previously. The register allocator should 8815 // place these in any free register. 8816 if (IsAnyRegCC) 8817 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8818 Ops.push_back(getValue(CS.getArgument(i))); 8819 8820 // Push the arguments from the call instruction up to the register mask. 8821 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8822 Ops.append(Call->op_begin() + 2, e); 8823 8824 // Push live variables for the stack map. 8825 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8826 8827 // Push the register mask info. 8828 if (HasGlue) 8829 Ops.push_back(*(Call->op_end()-2)); 8830 else 8831 Ops.push_back(*(Call->op_end()-1)); 8832 8833 // Push the chain (this is originally the first operand of the call, but 8834 // becomes now the last or second to last operand). 8835 Ops.push_back(*(Call->op_begin())); 8836 8837 // Push the glue flag (last operand). 8838 if (HasGlue) 8839 Ops.push_back(*(Call->op_end()-1)); 8840 8841 SDVTList NodeTys; 8842 if (IsAnyRegCC && HasDef) { 8843 // Create the return types based on the intrinsic definition 8844 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8845 SmallVector<EVT, 3> ValueVTs; 8846 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8847 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8848 8849 // There is always a chain and a glue type at the end 8850 ValueVTs.push_back(MVT::Other); 8851 ValueVTs.push_back(MVT::Glue); 8852 NodeTys = DAG.getVTList(ValueVTs); 8853 } else 8854 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8855 8856 // Replace the target specific call node with a PATCHPOINT node. 8857 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8858 dl, NodeTys, Ops); 8859 8860 // Update the NodeMap. 8861 if (HasDef) { 8862 if (IsAnyRegCC) 8863 setValue(CS.getInstruction(), SDValue(MN, 0)); 8864 else 8865 setValue(CS.getInstruction(), Result.first); 8866 } 8867 8868 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8869 // call sequence. Furthermore the location of the chain and glue can change 8870 // when the AnyReg calling convention is used and the intrinsic returns a 8871 // value. 8872 if (IsAnyRegCC && HasDef) { 8873 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8874 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8875 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8876 } else 8877 DAG.ReplaceAllUsesWith(Call, MN); 8878 DAG.DeleteNode(Call); 8879 8880 // Inform the Frame Information that we have a patchpoint in this function. 8881 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8882 } 8883 8884 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8885 unsigned Intrinsic) { 8886 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8887 SDValue Op1 = getValue(I.getArgOperand(0)); 8888 SDValue Op2; 8889 if (I.getNumArgOperands() > 1) 8890 Op2 = getValue(I.getArgOperand(1)); 8891 SDLoc dl = getCurSDLoc(); 8892 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8893 SDValue Res; 8894 FastMathFlags FMF; 8895 if (isa<FPMathOperator>(I)) 8896 FMF = I.getFastMathFlags(); 8897 8898 switch (Intrinsic) { 8899 case Intrinsic::experimental_vector_reduce_v2_fadd: 8900 if (FMF.allowReassoc()) 8901 Res = DAG.getNode(ISD::FADD, dl, VT, Op1, 8902 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2)); 8903 else 8904 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8905 break; 8906 case Intrinsic::experimental_vector_reduce_v2_fmul: 8907 if (FMF.allowReassoc()) 8908 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1, 8909 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2)); 8910 else 8911 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8912 break; 8913 case Intrinsic::experimental_vector_reduce_add: 8914 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8915 break; 8916 case Intrinsic::experimental_vector_reduce_mul: 8917 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8918 break; 8919 case Intrinsic::experimental_vector_reduce_and: 8920 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8921 break; 8922 case Intrinsic::experimental_vector_reduce_or: 8923 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8924 break; 8925 case Intrinsic::experimental_vector_reduce_xor: 8926 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8927 break; 8928 case Intrinsic::experimental_vector_reduce_smax: 8929 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8930 break; 8931 case Intrinsic::experimental_vector_reduce_smin: 8932 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8933 break; 8934 case Intrinsic::experimental_vector_reduce_umax: 8935 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8936 break; 8937 case Intrinsic::experimental_vector_reduce_umin: 8938 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8939 break; 8940 case Intrinsic::experimental_vector_reduce_fmax: 8941 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8942 break; 8943 case Intrinsic::experimental_vector_reduce_fmin: 8944 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8945 break; 8946 default: 8947 llvm_unreachable("Unhandled vector reduce intrinsic"); 8948 } 8949 setValue(&I, Res); 8950 } 8951 8952 /// Returns an AttributeList representing the attributes applied to the return 8953 /// value of the given call. 8954 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8955 SmallVector<Attribute::AttrKind, 2> Attrs; 8956 if (CLI.RetSExt) 8957 Attrs.push_back(Attribute::SExt); 8958 if (CLI.RetZExt) 8959 Attrs.push_back(Attribute::ZExt); 8960 if (CLI.IsInReg) 8961 Attrs.push_back(Attribute::InReg); 8962 8963 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8964 Attrs); 8965 } 8966 8967 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8968 /// implementation, which just calls LowerCall. 8969 /// FIXME: When all targets are 8970 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8971 std::pair<SDValue, SDValue> 8972 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8973 // Handle the incoming return values from the call. 8974 CLI.Ins.clear(); 8975 Type *OrigRetTy = CLI.RetTy; 8976 SmallVector<EVT, 4> RetTys; 8977 SmallVector<uint64_t, 4> Offsets; 8978 auto &DL = CLI.DAG.getDataLayout(); 8979 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8980 8981 if (CLI.IsPostTypeLegalization) { 8982 // If we are lowering a libcall after legalization, split the return type. 8983 SmallVector<EVT, 4> OldRetTys; 8984 SmallVector<uint64_t, 4> OldOffsets; 8985 RetTys.swap(OldRetTys); 8986 Offsets.swap(OldOffsets); 8987 8988 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8989 EVT RetVT = OldRetTys[i]; 8990 uint64_t Offset = OldOffsets[i]; 8991 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8992 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8993 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8994 RetTys.append(NumRegs, RegisterVT); 8995 for (unsigned j = 0; j != NumRegs; ++j) 8996 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8997 } 8998 } 8999 9000 SmallVector<ISD::OutputArg, 4> Outs; 9001 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 9002 9003 bool CanLowerReturn = 9004 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 9005 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 9006 9007 SDValue DemoteStackSlot; 9008 int DemoteStackIdx = -100; 9009 if (!CanLowerReturn) { 9010 // FIXME: equivalent assert? 9011 // assert(!CS.hasInAllocaArgument() && 9012 // "sret demotion is incompatible with inalloca"); 9013 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 9014 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 9015 MachineFunction &MF = CLI.DAG.getMachineFunction(); 9016 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 9017 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 9018 DL.getAllocaAddrSpace()); 9019 9020 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 9021 ArgListEntry Entry; 9022 Entry.Node = DemoteStackSlot; 9023 Entry.Ty = StackSlotPtrType; 9024 Entry.IsSExt = false; 9025 Entry.IsZExt = false; 9026 Entry.IsInReg = false; 9027 Entry.IsSRet = true; 9028 Entry.IsNest = false; 9029 Entry.IsByVal = false; 9030 Entry.IsReturned = false; 9031 Entry.IsSwiftSelf = false; 9032 Entry.IsSwiftError = false; 9033 Entry.Alignment = Align; 9034 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 9035 CLI.NumFixedArgs += 1; 9036 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 9037 9038 // sret demotion isn't compatible with tail-calls, since the sret argument 9039 // points into the callers stack frame. 9040 CLI.IsTailCall = false; 9041 } else { 9042 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9043 CLI.RetTy, CLI.CallConv, CLI.IsVarArg); 9044 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9045 ISD::ArgFlagsTy Flags; 9046 if (NeedsRegBlock) { 9047 Flags.setInConsecutiveRegs(); 9048 if (I == RetTys.size() - 1) 9049 Flags.setInConsecutiveRegsLast(); 9050 } 9051 EVT VT = RetTys[I]; 9052 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9053 CLI.CallConv, VT); 9054 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9055 CLI.CallConv, VT); 9056 for (unsigned i = 0; i != NumRegs; ++i) { 9057 ISD::InputArg MyFlags; 9058 MyFlags.Flags = Flags; 9059 MyFlags.VT = RegisterVT; 9060 MyFlags.ArgVT = VT; 9061 MyFlags.Used = CLI.IsReturnValueUsed; 9062 if (CLI.RetTy->isPointerTy()) { 9063 MyFlags.Flags.setPointer(); 9064 MyFlags.Flags.setPointerAddrSpace( 9065 cast<PointerType>(CLI.RetTy)->getAddressSpace()); 9066 } 9067 if (CLI.RetSExt) 9068 MyFlags.Flags.setSExt(); 9069 if (CLI.RetZExt) 9070 MyFlags.Flags.setZExt(); 9071 if (CLI.IsInReg) 9072 MyFlags.Flags.setInReg(); 9073 CLI.Ins.push_back(MyFlags); 9074 } 9075 } 9076 } 9077 9078 // We push in swifterror return as the last element of CLI.Ins. 9079 ArgListTy &Args = CLI.getArgs(); 9080 if (supportSwiftError()) { 9081 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9082 if (Args[i].IsSwiftError) { 9083 ISD::InputArg MyFlags; 9084 MyFlags.VT = getPointerTy(DL); 9085 MyFlags.ArgVT = EVT(getPointerTy(DL)); 9086 MyFlags.Flags.setSwiftError(); 9087 CLI.Ins.push_back(MyFlags); 9088 } 9089 } 9090 } 9091 9092 // Handle all of the outgoing arguments. 9093 CLI.Outs.clear(); 9094 CLI.OutVals.clear(); 9095 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 9096 SmallVector<EVT, 4> ValueVTs; 9097 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 9098 // FIXME: Split arguments if CLI.IsPostTypeLegalization 9099 Type *FinalType = Args[i].Ty; 9100 if (Args[i].IsByVal) 9101 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 9102 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 9103 FinalType, CLI.CallConv, CLI.IsVarArg); 9104 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 9105 ++Value) { 9106 EVT VT = ValueVTs[Value]; 9107 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 9108 SDValue Op = SDValue(Args[i].Node.getNode(), 9109 Args[i].Node.getResNo() + Value); 9110 ISD::ArgFlagsTy Flags; 9111 9112 // Certain targets (such as MIPS), may have a different ABI alignment 9113 // for a type depending on the context. Give the target a chance to 9114 // specify the alignment it wants. 9115 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL)); 9116 9117 if (Args[i].Ty->isPointerTy()) { 9118 Flags.setPointer(); 9119 Flags.setPointerAddrSpace( 9120 cast<PointerType>(Args[i].Ty)->getAddressSpace()); 9121 } 9122 if (Args[i].IsZExt) 9123 Flags.setZExt(); 9124 if (Args[i].IsSExt) 9125 Flags.setSExt(); 9126 if (Args[i].IsInReg) { 9127 // If we are using vectorcall calling convention, a structure that is 9128 // passed InReg - is surely an HVA 9129 if (CLI.CallConv == CallingConv::X86_VectorCall && 9130 isa<StructType>(FinalType)) { 9131 // The first value of a structure is marked 9132 if (0 == Value) 9133 Flags.setHvaStart(); 9134 Flags.setHva(); 9135 } 9136 // Set InReg Flag 9137 Flags.setInReg(); 9138 } 9139 if (Args[i].IsSRet) 9140 Flags.setSRet(); 9141 if (Args[i].IsSwiftSelf) 9142 Flags.setSwiftSelf(); 9143 if (Args[i].IsSwiftError) 9144 Flags.setSwiftError(); 9145 if (Args[i].IsByVal) 9146 Flags.setByVal(); 9147 if (Args[i].IsInAlloca) { 9148 Flags.setInAlloca(); 9149 // Set the byval flag for CCAssignFn callbacks that don't know about 9150 // inalloca. This way we can know how many bytes we should've allocated 9151 // and how many bytes a callee cleanup function will pop. If we port 9152 // inalloca to more targets, we'll have to add custom inalloca handling 9153 // in the various CC lowering callbacks. 9154 Flags.setByVal(); 9155 } 9156 if (Args[i].IsByVal || Args[i].IsInAlloca) { 9157 PointerType *Ty = cast<PointerType>(Args[i].Ty); 9158 Type *ElementTy = Ty->getElementType(); 9159 9160 unsigned FrameSize = DL.getTypeAllocSize( 9161 Args[i].ByValType ? Args[i].ByValType : ElementTy); 9162 Flags.setByValSize(FrameSize); 9163 9164 // info is not there but there are cases it cannot get right. 9165 unsigned FrameAlign; 9166 if (Args[i].Alignment) 9167 FrameAlign = Args[i].Alignment; 9168 else 9169 FrameAlign = getByValTypeAlignment(ElementTy, DL); 9170 Flags.setByValAlign(Align(FrameAlign)); 9171 } 9172 if (Args[i].IsNest) 9173 Flags.setNest(); 9174 if (NeedsRegBlock) 9175 Flags.setInConsecutiveRegs(); 9176 Flags.setOrigAlign(OriginalAlignment); 9177 9178 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9179 CLI.CallConv, VT); 9180 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9181 CLI.CallConv, VT); 9182 SmallVector<SDValue, 4> Parts(NumParts); 9183 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 9184 9185 if (Args[i].IsSExt) 9186 ExtendKind = ISD::SIGN_EXTEND; 9187 else if (Args[i].IsZExt) 9188 ExtendKind = ISD::ZERO_EXTEND; 9189 9190 // Conservatively only handle 'returned' on non-vectors that can be lowered, 9191 // for now. 9192 if (Args[i].IsReturned && !Op.getValueType().isVector() && 9193 CanLowerReturn) { 9194 assert((CLI.RetTy == Args[i].Ty || 9195 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() && 9196 CLI.RetTy->getPointerAddressSpace() == 9197 Args[i].Ty->getPointerAddressSpace())) && 9198 RetTys.size() == NumValues && "unexpected use of 'returned'"); 9199 // Before passing 'returned' to the target lowering code, ensure that 9200 // either the register MVT and the actual EVT are the same size or that 9201 // the return value and argument are extended in the same way; in these 9202 // cases it's safe to pass the argument register value unchanged as the 9203 // return register value (although it's at the target's option whether 9204 // to do so) 9205 // TODO: allow code generation to take advantage of partially preserved 9206 // registers rather than clobbering the entire register when the 9207 // parameter extension method is not compatible with the return 9208 // extension method 9209 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 9210 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 9211 CLI.RetZExt == Args[i].IsZExt)) 9212 Flags.setReturned(); 9213 } 9214 9215 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 9216 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 9217 9218 for (unsigned j = 0; j != NumParts; ++j) { 9219 // if it isn't first piece, alignment must be 1 9220 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 9221 i < CLI.NumFixedArgs, 9222 i, j*Parts[j].getValueType().getStoreSize()); 9223 if (NumParts > 1 && j == 0) 9224 MyFlags.Flags.setSplit(); 9225 else if (j != 0) { 9226 MyFlags.Flags.setOrigAlign(Align::None()); 9227 if (j == NumParts - 1) 9228 MyFlags.Flags.setSplitEnd(); 9229 } 9230 9231 CLI.Outs.push_back(MyFlags); 9232 CLI.OutVals.push_back(Parts[j]); 9233 } 9234 9235 if (NeedsRegBlock && Value == NumValues - 1) 9236 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 9237 } 9238 } 9239 9240 SmallVector<SDValue, 4> InVals; 9241 CLI.Chain = LowerCall(CLI, InVals); 9242 9243 // Update CLI.InVals to use outside of this function. 9244 CLI.InVals = InVals; 9245 9246 // Verify that the target's LowerCall behaved as expected. 9247 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 9248 "LowerCall didn't return a valid chain!"); 9249 assert((!CLI.IsTailCall || InVals.empty()) && 9250 "LowerCall emitted a return value for a tail call!"); 9251 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9252 "LowerCall didn't emit the correct number of values!"); 9253 9254 // For a tail call, the return value is merely live-out and there aren't 9255 // any nodes in the DAG representing it. Return a special value to 9256 // indicate that a tail call has been emitted and no more Instructions 9257 // should be processed in the current block. 9258 if (CLI.IsTailCall) { 9259 CLI.DAG.setRoot(CLI.Chain); 9260 return std::make_pair(SDValue(), SDValue()); 9261 } 9262 9263 #ifndef NDEBUG 9264 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9265 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9266 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9267 "LowerCall emitted a value with the wrong type!"); 9268 } 9269 #endif 9270 9271 SmallVector<SDValue, 4> ReturnValues; 9272 if (!CanLowerReturn) { 9273 // The instruction result is the result of loading from the 9274 // hidden sret parameter. 9275 SmallVector<EVT, 1> PVTs; 9276 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9277 9278 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9279 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9280 EVT PtrVT = PVTs[0]; 9281 9282 unsigned NumValues = RetTys.size(); 9283 ReturnValues.resize(NumValues); 9284 SmallVector<SDValue, 4> Chains(NumValues); 9285 9286 // An aggregate return value cannot wrap around the address space, so 9287 // offsets to its parts don't wrap either. 9288 SDNodeFlags Flags; 9289 Flags.setNoUnsignedWrap(true); 9290 9291 for (unsigned i = 0; i < NumValues; ++i) { 9292 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9293 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9294 PtrVT), Flags); 9295 SDValue L = CLI.DAG.getLoad( 9296 RetTys[i], CLI.DL, CLI.Chain, Add, 9297 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9298 DemoteStackIdx, Offsets[i]), 9299 /* Alignment = */ 1); 9300 ReturnValues[i] = L; 9301 Chains[i] = L.getValue(1); 9302 } 9303 9304 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9305 } else { 9306 // Collect the legal value parts into potentially illegal values 9307 // that correspond to the original function's return values. 9308 Optional<ISD::NodeType> AssertOp; 9309 if (CLI.RetSExt) 9310 AssertOp = ISD::AssertSext; 9311 else if (CLI.RetZExt) 9312 AssertOp = ISD::AssertZext; 9313 unsigned CurReg = 0; 9314 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9315 EVT VT = RetTys[I]; 9316 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9317 CLI.CallConv, VT); 9318 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9319 CLI.CallConv, VT); 9320 9321 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9322 NumRegs, RegisterVT, VT, nullptr, 9323 CLI.CallConv, AssertOp)); 9324 CurReg += NumRegs; 9325 } 9326 9327 // For a function returning void, there is no return value. We can't create 9328 // such a node, so we just return a null return value in that case. In 9329 // that case, nothing will actually look at the value. 9330 if (ReturnValues.empty()) 9331 return std::make_pair(SDValue(), CLI.Chain); 9332 } 9333 9334 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9335 CLI.DAG.getVTList(RetTys), ReturnValues); 9336 return std::make_pair(Res, CLI.Chain); 9337 } 9338 9339 void TargetLowering::LowerOperationWrapper(SDNode *N, 9340 SmallVectorImpl<SDValue> &Results, 9341 SelectionDAG &DAG) const { 9342 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9343 Results.push_back(Res); 9344 } 9345 9346 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9347 llvm_unreachable("LowerOperation not implemented for this target!"); 9348 } 9349 9350 void 9351 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9352 SDValue Op = getNonRegisterValue(V); 9353 assert((Op.getOpcode() != ISD::CopyFromReg || 9354 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9355 "Copy from a reg to the same reg!"); 9356 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg"); 9357 9358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9359 // If this is an InlineAsm we have to match the registers required, not the 9360 // notional registers required by the type. 9361 9362 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9363 None); // This is not an ABI copy. 9364 SDValue Chain = DAG.getEntryNode(); 9365 9366 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9367 FuncInfo.PreferredExtendType.end()) 9368 ? ISD::ANY_EXTEND 9369 : FuncInfo.PreferredExtendType[V]; 9370 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9371 PendingExports.push_back(Chain); 9372 } 9373 9374 #include "llvm/CodeGen/SelectionDAGISel.h" 9375 9376 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9377 /// entry block, return true. This includes arguments used by switches, since 9378 /// the switch may expand into multiple basic blocks. 9379 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9380 // With FastISel active, we may be splitting blocks, so force creation 9381 // of virtual registers for all non-dead arguments. 9382 if (FastISel) 9383 return A->use_empty(); 9384 9385 const BasicBlock &Entry = A->getParent()->front(); 9386 for (const User *U : A->users()) 9387 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9388 return false; // Use not in entry block. 9389 9390 return true; 9391 } 9392 9393 using ArgCopyElisionMapTy = 9394 DenseMap<const Argument *, 9395 std::pair<const AllocaInst *, const StoreInst *>>; 9396 9397 /// Scan the entry block of the function in FuncInfo for arguments that look 9398 /// like copies into a local alloca. Record any copied arguments in 9399 /// ArgCopyElisionCandidates. 9400 static void 9401 findArgumentCopyElisionCandidates(const DataLayout &DL, 9402 FunctionLoweringInfo *FuncInfo, 9403 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9404 // Record the state of every static alloca used in the entry block. Argument 9405 // allocas are all used in the entry block, so we need approximately as many 9406 // entries as we have arguments. 9407 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9408 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9409 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9410 StaticAllocas.reserve(NumArgs * 2); 9411 9412 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9413 if (!V) 9414 return nullptr; 9415 V = V->stripPointerCasts(); 9416 const auto *AI = dyn_cast<AllocaInst>(V); 9417 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9418 return nullptr; 9419 auto Iter = StaticAllocas.insert({AI, Unknown}); 9420 return &Iter.first->second; 9421 }; 9422 9423 // Look for stores of arguments to static allocas. Look through bitcasts and 9424 // GEPs to handle type coercions, as long as the alloca is fully initialized 9425 // by the store. Any non-store use of an alloca escapes it and any subsequent 9426 // unanalyzed store might write it. 9427 // FIXME: Handle structs initialized with multiple stores. 9428 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9429 // Look for stores, and handle non-store uses conservatively. 9430 const auto *SI = dyn_cast<StoreInst>(&I); 9431 if (!SI) { 9432 // We will look through cast uses, so ignore them completely. 9433 if (I.isCast()) 9434 continue; 9435 // Ignore debug info intrinsics, they don't escape or store to allocas. 9436 if (isa<DbgInfoIntrinsic>(I)) 9437 continue; 9438 // This is an unknown instruction. Assume it escapes or writes to all 9439 // static alloca operands. 9440 for (const Use &U : I.operands()) { 9441 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9442 *Info = StaticAllocaInfo::Clobbered; 9443 } 9444 continue; 9445 } 9446 9447 // If the stored value is a static alloca, mark it as escaped. 9448 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9449 *Info = StaticAllocaInfo::Clobbered; 9450 9451 // Check if the destination is a static alloca. 9452 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9453 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9454 if (!Info) 9455 continue; 9456 const AllocaInst *AI = cast<AllocaInst>(Dst); 9457 9458 // Skip allocas that have been initialized or clobbered. 9459 if (*Info != StaticAllocaInfo::Unknown) 9460 continue; 9461 9462 // Check if the stored value is an argument, and that this store fully 9463 // initializes the alloca. Don't elide copies from the same argument twice. 9464 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9465 const auto *Arg = dyn_cast<Argument>(Val); 9466 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9467 Arg->getType()->isEmptyTy() || 9468 DL.getTypeStoreSize(Arg->getType()) != 9469 DL.getTypeAllocSize(AI->getAllocatedType()) || 9470 ArgCopyElisionCandidates.count(Arg)) { 9471 *Info = StaticAllocaInfo::Clobbered; 9472 continue; 9473 } 9474 9475 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9476 << '\n'); 9477 9478 // Mark this alloca and store for argument copy elision. 9479 *Info = StaticAllocaInfo::Elidable; 9480 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9481 9482 // Stop scanning if we've seen all arguments. This will happen early in -O0 9483 // builds, which is useful, because -O0 builds have large entry blocks and 9484 // many allocas. 9485 if (ArgCopyElisionCandidates.size() == NumArgs) 9486 break; 9487 } 9488 } 9489 9490 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9491 /// ArgVal is a load from a suitable fixed stack object. 9492 static void tryToElideArgumentCopy( 9493 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9494 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9495 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9496 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9497 SDValue ArgVal, bool &ArgHasUses) { 9498 // Check if this is a load from a fixed stack object. 9499 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9500 if (!LNode) 9501 return; 9502 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9503 if (!FINode) 9504 return; 9505 9506 // Check that the fixed stack object is the right size and alignment. 9507 // Look at the alignment that the user wrote on the alloca instead of looking 9508 // at the stack object. 9509 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9510 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9511 const AllocaInst *AI = ArgCopyIter->second.first; 9512 int FixedIndex = FINode->getIndex(); 9513 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9514 int OldIndex = AllocaIndex; 9515 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9516 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9517 LLVM_DEBUG( 9518 dbgs() << " argument copy elision failed due to bad fixed stack " 9519 "object size\n"); 9520 return; 9521 } 9522 unsigned RequiredAlignment = AI->getAlignment(); 9523 if (!RequiredAlignment) { 9524 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9525 AI->getAllocatedType()); 9526 } 9527 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9528 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9529 "greater than stack argument alignment (" 9530 << RequiredAlignment << " vs " 9531 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9532 return; 9533 } 9534 9535 // Perform the elision. Delete the old stack object and replace its only use 9536 // in the variable info map. Mark the stack object as mutable. 9537 LLVM_DEBUG({ 9538 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9539 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9540 << '\n'; 9541 }); 9542 MFI.RemoveStackObject(OldIndex); 9543 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9544 AllocaIndex = FixedIndex; 9545 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9546 Chains.push_back(ArgVal.getValue(1)); 9547 9548 // Avoid emitting code for the store implementing the copy. 9549 const StoreInst *SI = ArgCopyIter->second.second; 9550 ElidedArgCopyInstrs.insert(SI); 9551 9552 // Check for uses of the argument again so that we can avoid exporting ArgVal 9553 // if it is't used by anything other than the store. 9554 for (const Value *U : Arg.users()) { 9555 if (U != SI) { 9556 ArgHasUses = true; 9557 break; 9558 } 9559 } 9560 } 9561 9562 void SelectionDAGISel::LowerArguments(const Function &F) { 9563 SelectionDAG &DAG = SDB->DAG; 9564 SDLoc dl = SDB->getCurSDLoc(); 9565 const DataLayout &DL = DAG.getDataLayout(); 9566 SmallVector<ISD::InputArg, 16> Ins; 9567 9568 if (!FuncInfo->CanLowerReturn) { 9569 // Put in an sret pointer parameter before all the other parameters. 9570 SmallVector<EVT, 1> ValueVTs; 9571 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9572 F.getReturnType()->getPointerTo( 9573 DAG.getDataLayout().getAllocaAddrSpace()), 9574 ValueVTs); 9575 9576 // NOTE: Assuming that a pointer will never break down to more than one VT 9577 // or one register. 9578 ISD::ArgFlagsTy Flags; 9579 Flags.setSRet(); 9580 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9581 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9582 ISD::InputArg::NoArgIndex, 0); 9583 Ins.push_back(RetArg); 9584 } 9585 9586 // Look for stores of arguments to static allocas. Mark such arguments with a 9587 // flag to ask the target to give us the memory location of that argument if 9588 // available. 9589 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9590 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9591 9592 // Set up the incoming argument description vector. 9593 for (const Argument &Arg : F.args()) { 9594 unsigned ArgNo = Arg.getArgNo(); 9595 SmallVector<EVT, 4> ValueVTs; 9596 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9597 bool isArgValueUsed = !Arg.use_empty(); 9598 unsigned PartBase = 0; 9599 Type *FinalType = Arg.getType(); 9600 if (Arg.hasAttribute(Attribute::ByVal)) 9601 FinalType = Arg.getParamByValType(); 9602 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9603 FinalType, F.getCallingConv(), F.isVarArg()); 9604 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9605 Value != NumValues; ++Value) { 9606 EVT VT = ValueVTs[Value]; 9607 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9608 ISD::ArgFlagsTy Flags; 9609 9610 // Certain targets (such as MIPS), may have a different ABI alignment 9611 // for a type depending on the context. Give the target a chance to 9612 // specify the alignment it wants. 9613 const Align OriginalAlignment( 9614 TLI->getABIAlignmentForCallingConv(ArgTy, DL)); 9615 9616 if (Arg.getType()->isPointerTy()) { 9617 Flags.setPointer(); 9618 Flags.setPointerAddrSpace( 9619 cast<PointerType>(Arg.getType())->getAddressSpace()); 9620 } 9621 if (Arg.hasAttribute(Attribute::ZExt)) 9622 Flags.setZExt(); 9623 if (Arg.hasAttribute(Attribute::SExt)) 9624 Flags.setSExt(); 9625 if (Arg.hasAttribute(Attribute::InReg)) { 9626 // If we are using vectorcall calling convention, a structure that is 9627 // passed InReg - is surely an HVA 9628 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9629 isa<StructType>(Arg.getType())) { 9630 // The first value of a structure is marked 9631 if (0 == Value) 9632 Flags.setHvaStart(); 9633 Flags.setHva(); 9634 } 9635 // Set InReg Flag 9636 Flags.setInReg(); 9637 } 9638 if (Arg.hasAttribute(Attribute::StructRet)) 9639 Flags.setSRet(); 9640 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9641 Flags.setSwiftSelf(); 9642 if (Arg.hasAttribute(Attribute::SwiftError)) 9643 Flags.setSwiftError(); 9644 if (Arg.hasAttribute(Attribute::ByVal)) 9645 Flags.setByVal(); 9646 if (Arg.hasAttribute(Attribute::InAlloca)) { 9647 Flags.setInAlloca(); 9648 // Set the byval flag for CCAssignFn callbacks that don't know about 9649 // inalloca. This way we can know how many bytes we should've allocated 9650 // and how many bytes a callee cleanup function will pop. If we port 9651 // inalloca to more targets, we'll have to add custom inalloca handling 9652 // in the various CC lowering callbacks. 9653 Flags.setByVal(); 9654 } 9655 if (F.getCallingConv() == CallingConv::X86_INTR) { 9656 // IA Interrupt passes frame (1st parameter) by value in the stack. 9657 if (ArgNo == 0) 9658 Flags.setByVal(); 9659 } 9660 if (Flags.isByVal() || Flags.isInAlloca()) { 9661 Type *ElementTy = Arg.getParamByValType(); 9662 9663 // For ByVal, size and alignment should be passed from FE. BE will 9664 // guess if this info is not there but there are cases it cannot get 9665 // right. 9666 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType()); 9667 Flags.setByValSize(FrameSize); 9668 9669 unsigned FrameAlign; 9670 if (Arg.getParamAlignment()) 9671 FrameAlign = Arg.getParamAlignment(); 9672 else 9673 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9674 Flags.setByValAlign(Align(FrameAlign)); 9675 } 9676 if (Arg.hasAttribute(Attribute::Nest)) 9677 Flags.setNest(); 9678 if (NeedsRegBlock) 9679 Flags.setInConsecutiveRegs(); 9680 Flags.setOrigAlign(OriginalAlignment); 9681 if (ArgCopyElisionCandidates.count(&Arg)) 9682 Flags.setCopyElisionCandidate(); 9683 if (Arg.hasAttribute(Attribute::Returned)) 9684 Flags.setReturned(); 9685 9686 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9687 *CurDAG->getContext(), F.getCallingConv(), VT); 9688 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9689 *CurDAG->getContext(), F.getCallingConv(), VT); 9690 for (unsigned i = 0; i != NumRegs; ++i) { 9691 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9692 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9693 if (NumRegs > 1 && i == 0) 9694 MyFlags.Flags.setSplit(); 9695 // if it isn't first piece, alignment must be 1 9696 else if (i > 0) { 9697 MyFlags.Flags.setOrigAlign(Align::None()); 9698 if (i == NumRegs - 1) 9699 MyFlags.Flags.setSplitEnd(); 9700 } 9701 Ins.push_back(MyFlags); 9702 } 9703 if (NeedsRegBlock && Value == NumValues - 1) 9704 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9705 PartBase += VT.getStoreSize(); 9706 } 9707 } 9708 9709 // Call the target to set up the argument values. 9710 SmallVector<SDValue, 8> InVals; 9711 SDValue NewRoot = TLI->LowerFormalArguments( 9712 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9713 9714 // Verify that the target's LowerFormalArguments behaved as expected. 9715 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9716 "LowerFormalArguments didn't return a valid chain!"); 9717 assert(InVals.size() == Ins.size() && 9718 "LowerFormalArguments didn't emit the correct number of values!"); 9719 LLVM_DEBUG({ 9720 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9721 assert(InVals[i].getNode() && 9722 "LowerFormalArguments emitted a null value!"); 9723 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9724 "LowerFormalArguments emitted a value with the wrong type!"); 9725 } 9726 }); 9727 9728 // Update the DAG with the new chain value resulting from argument lowering. 9729 DAG.setRoot(NewRoot); 9730 9731 // Set up the argument values. 9732 unsigned i = 0; 9733 if (!FuncInfo->CanLowerReturn) { 9734 // Create a virtual register for the sret pointer, and put in a copy 9735 // from the sret argument into it. 9736 SmallVector<EVT, 1> ValueVTs; 9737 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9738 F.getReturnType()->getPointerTo( 9739 DAG.getDataLayout().getAllocaAddrSpace()), 9740 ValueVTs); 9741 MVT VT = ValueVTs[0].getSimpleVT(); 9742 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9743 Optional<ISD::NodeType> AssertOp = None; 9744 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9745 nullptr, F.getCallingConv(), AssertOp); 9746 9747 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9748 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9749 Register SRetReg = 9750 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9751 FuncInfo->DemoteRegister = SRetReg; 9752 NewRoot = 9753 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9754 DAG.setRoot(NewRoot); 9755 9756 // i indexes lowered arguments. Bump it past the hidden sret argument. 9757 ++i; 9758 } 9759 9760 SmallVector<SDValue, 4> Chains; 9761 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9762 for (const Argument &Arg : F.args()) { 9763 SmallVector<SDValue, 4> ArgValues; 9764 SmallVector<EVT, 4> ValueVTs; 9765 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9766 unsigned NumValues = ValueVTs.size(); 9767 if (NumValues == 0) 9768 continue; 9769 9770 bool ArgHasUses = !Arg.use_empty(); 9771 9772 // Elide the copying store if the target loaded this argument from a 9773 // suitable fixed stack object. 9774 if (Ins[i].Flags.isCopyElisionCandidate()) { 9775 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9776 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9777 InVals[i], ArgHasUses); 9778 } 9779 9780 // If this argument is unused then remember its value. It is used to generate 9781 // debugging information. 9782 bool isSwiftErrorArg = 9783 TLI->supportSwiftError() && 9784 Arg.hasAttribute(Attribute::SwiftError); 9785 if (!ArgHasUses && !isSwiftErrorArg) { 9786 SDB->setUnusedArgValue(&Arg, InVals[i]); 9787 9788 // Also remember any frame index for use in FastISel. 9789 if (FrameIndexSDNode *FI = 9790 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9791 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9792 } 9793 9794 for (unsigned Val = 0; Val != NumValues; ++Val) { 9795 EVT VT = ValueVTs[Val]; 9796 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9797 F.getCallingConv(), VT); 9798 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9799 *CurDAG->getContext(), F.getCallingConv(), VT); 9800 9801 // Even an apparant 'unused' swifterror argument needs to be returned. So 9802 // we do generate a copy for it that can be used on return from the 9803 // function. 9804 if (ArgHasUses || isSwiftErrorArg) { 9805 Optional<ISD::NodeType> AssertOp; 9806 if (Arg.hasAttribute(Attribute::SExt)) 9807 AssertOp = ISD::AssertSext; 9808 else if (Arg.hasAttribute(Attribute::ZExt)) 9809 AssertOp = ISD::AssertZext; 9810 9811 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9812 PartVT, VT, nullptr, 9813 F.getCallingConv(), AssertOp)); 9814 } 9815 9816 i += NumParts; 9817 } 9818 9819 // We don't need to do anything else for unused arguments. 9820 if (ArgValues.empty()) 9821 continue; 9822 9823 // Note down frame index. 9824 if (FrameIndexSDNode *FI = 9825 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9826 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9827 9828 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9829 SDB->getCurSDLoc()); 9830 9831 SDB->setValue(&Arg, Res); 9832 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9833 // We want to associate the argument with the frame index, among 9834 // involved operands, that correspond to the lowest address. The 9835 // getCopyFromParts function, called earlier, is swapping the order of 9836 // the operands to BUILD_PAIR depending on endianness. The result of 9837 // that swapping is that the least significant bits of the argument will 9838 // be in the first operand of the BUILD_PAIR node, and the most 9839 // significant bits will be in the second operand. 9840 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9841 if (LoadSDNode *LNode = 9842 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9843 if (FrameIndexSDNode *FI = 9844 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9845 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9846 } 9847 9848 // Analyses past this point are naive and don't expect an assertion. 9849 if (Res.getOpcode() == ISD::AssertZext) 9850 Res = Res.getOperand(0); 9851 9852 // Update the SwiftErrorVRegDefMap. 9853 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9854 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9855 if (Register::isVirtualRegister(Reg)) 9856 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(), 9857 Reg); 9858 } 9859 9860 // If this argument is live outside of the entry block, insert a copy from 9861 // wherever we got it to the vreg that other BB's will reference it as. 9862 if (Res.getOpcode() == ISD::CopyFromReg) { 9863 // If we can, though, try to skip creating an unnecessary vreg. 9864 // FIXME: This isn't very clean... it would be nice to make this more 9865 // general. 9866 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9867 if (Register::isVirtualRegister(Reg)) { 9868 FuncInfo->ValueMap[&Arg] = Reg; 9869 continue; 9870 } 9871 } 9872 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9873 FuncInfo->InitializeRegForValue(&Arg); 9874 SDB->CopyToExportRegsIfNeeded(&Arg); 9875 } 9876 } 9877 9878 if (!Chains.empty()) { 9879 Chains.push_back(NewRoot); 9880 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9881 } 9882 9883 DAG.setRoot(NewRoot); 9884 9885 assert(i == InVals.size() && "Argument register count mismatch!"); 9886 9887 // If any argument copy elisions occurred and we have debug info, update the 9888 // stale frame indices used in the dbg.declare variable info table. 9889 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9890 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9891 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9892 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9893 if (I != ArgCopyElisionFrameIndexMap.end()) 9894 VI.Slot = I->second; 9895 } 9896 } 9897 9898 // Finally, if the target has anything special to do, allow it to do so. 9899 EmitFunctionEntryCode(); 9900 } 9901 9902 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9903 /// ensure constants are generated when needed. Remember the virtual registers 9904 /// that need to be added to the Machine PHI nodes as input. We cannot just 9905 /// directly add them, because expansion might result in multiple MBB's for one 9906 /// BB. As such, the start of the BB might correspond to a different MBB than 9907 /// the end. 9908 void 9909 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9910 const Instruction *TI = LLVMBB->getTerminator(); 9911 9912 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9913 9914 // Check PHI nodes in successors that expect a value to be available from this 9915 // block. 9916 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9917 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9918 if (!isa<PHINode>(SuccBB->begin())) continue; 9919 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9920 9921 // If this terminator has multiple identical successors (common for 9922 // switches), only handle each succ once. 9923 if (!SuccsHandled.insert(SuccMBB).second) 9924 continue; 9925 9926 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9927 9928 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9929 // nodes and Machine PHI nodes, but the incoming operands have not been 9930 // emitted yet. 9931 for (const PHINode &PN : SuccBB->phis()) { 9932 // Ignore dead phi's. 9933 if (PN.use_empty()) 9934 continue; 9935 9936 // Skip empty types 9937 if (PN.getType()->isEmptyTy()) 9938 continue; 9939 9940 unsigned Reg; 9941 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9942 9943 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9944 unsigned &RegOut = ConstantsOut[C]; 9945 if (RegOut == 0) { 9946 RegOut = FuncInfo.CreateRegs(C); 9947 CopyValueToVirtualRegister(C, RegOut); 9948 } 9949 Reg = RegOut; 9950 } else { 9951 DenseMap<const Value *, unsigned>::iterator I = 9952 FuncInfo.ValueMap.find(PHIOp); 9953 if (I != FuncInfo.ValueMap.end()) 9954 Reg = I->second; 9955 else { 9956 assert(isa<AllocaInst>(PHIOp) && 9957 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9958 "Didn't codegen value into a register!??"); 9959 Reg = FuncInfo.CreateRegs(PHIOp); 9960 CopyValueToVirtualRegister(PHIOp, Reg); 9961 } 9962 } 9963 9964 // Remember that this register needs to added to the machine PHI node as 9965 // the input for this MBB. 9966 SmallVector<EVT, 4> ValueVTs; 9967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9968 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9969 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9970 EVT VT = ValueVTs[vti]; 9971 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9972 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9973 FuncInfo.PHINodesToUpdate.push_back( 9974 std::make_pair(&*MBBI++, Reg + i)); 9975 Reg += NumRegisters; 9976 } 9977 } 9978 } 9979 9980 ConstantsOut.clear(); 9981 } 9982 9983 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9984 /// is 0. 9985 MachineBasicBlock * 9986 SelectionDAGBuilder::StackProtectorDescriptor:: 9987 AddSuccessorMBB(const BasicBlock *BB, 9988 MachineBasicBlock *ParentMBB, 9989 bool IsLikely, 9990 MachineBasicBlock *SuccMBB) { 9991 // If SuccBB has not been created yet, create it. 9992 if (!SuccMBB) { 9993 MachineFunction *MF = ParentMBB->getParent(); 9994 MachineFunction::iterator BBI(ParentMBB); 9995 SuccMBB = MF->CreateMachineBasicBlock(BB); 9996 MF->insert(++BBI, SuccMBB); 9997 } 9998 // Add it as a successor of ParentMBB. 9999 ParentMBB->addSuccessor( 10000 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 10001 return SuccMBB; 10002 } 10003 10004 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 10005 MachineFunction::iterator I(MBB); 10006 if (++I == FuncInfo.MF->end()) 10007 return nullptr; 10008 return &*I; 10009 } 10010 10011 /// During lowering new call nodes can be created (such as memset, etc.). 10012 /// Those will become new roots of the current DAG, but complications arise 10013 /// when they are tail calls. In such cases, the call lowering will update 10014 /// the root, but the builder still needs to know that a tail call has been 10015 /// lowered in order to avoid generating an additional return. 10016 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 10017 // If the node is null, we do have a tail call. 10018 if (MaybeTC.getNode() != nullptr) 10019 DAG.setRoot(MaybeTC); 10020 else 10021 HasTailCall = true; 10022 } 10023 10024 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10025 MachineBasicBlock *SwitchMBB, 10026 MachineBasicBlock *DefaultMBB) { 10027 MachineFunction *CurMF = FuncInfo.MF; 10028 MachineBasicBlock *NextMBB = nullptr; 10029 MachineFunction::iterator BBI(W.MBB); 10030 if (++BBI != FuncInfo.MF->end()) 10031 NextMBB = &*BBI; 10032 10033 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10034 10035 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10036 10037 if (Size == 2 && W.MBB == SwitchMBB) { 10038 // If any two of the cases has the same destination, and if one value 10039 // is the same as the other, but has one bit unset that the other has set, 10040 // use bit manipulation to do two compares at once. For example: 10041 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10042 // TODO: This could be extended to merge any 2 cases in switches with 3 10043 // cases. 10044 // TODO: Handle cases where W.CaseBB != SwitchBB. 10045 CaseCluster &Small = *W.FirstCluster; 10046 CaseCluster &Big = *W.LastCluster; 10047 10048 if (Small.Low == Small.High && Big.Low == Big.High && 10049 Small.MBB == Big.MBB) { 10050 const APInt &SmallValue = Small.Low->getValue(); 10051 const APInt &BigValue = Big.Low->getValue(); 10052 10053 // Check that there is only one bit different. 10054 APInt CommonBit = BigValue ^ SmallValue; 10055 if (CommonBit.isPowerOf2()) { 10056 SDValue CondLHS = getValue(Cond); 10057 EVT VT = CondLHS.getValueType(); 10058 SDLoc DL = getCurSDLoc(); 10059 10060 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10061 DAG.getConstant(CommonBit, DL, VT)); 10062 SDValue Cond = DAG.getSetCC( 10063 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10064 ISD::SETEQ); 10065 10066 // Update successor info. 10067 // Both Small and Big will jump to Small.BB, so we sum up the 10068 // probabilities. 10069 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10070 if (BPI) 10071 addSuccessorWithProb( 10072 SwitchMBB, DefaultMBB, 10073 // The default destination is the first successor in IR. 10074 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10075 else 10076 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10077 10078 // Insert the true branch. 10079 SDValue BrCond = 10080 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10081 DAG.getBasicBlock(Small.MBB)); 10082 // Insert the false branch. 10083 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10084 DAG.getBasicBlock(DefaultMBB)); 10085 10086 DAG.setRoot(BrCond); 10087 return; 10088 } 10089 } 10090 } 10091 10092 if (TM.getOptLevel() != CodeGenOpt::None) { 10093 // Here, we order cases by probability so the most likely case will be 10094 // checked first. However, two clusters can have the same probability in 10095 // which case their relative ordering is non-deterministic. So we use Low 10096 // as a tie-breaker as clusters are guaranteed to never overlap. 10097 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10098 [](const CaseCluster &a, const CaseCluster &b) { 10099 return a.Prob != b.Prob ? 10100 a.Prob > b.Prob : 10101 a.Low->getValue().slt(b.Low->getValue()); 10102 }); 10103 10104 // Rearrange the case blocks so that the last one falls through if possible 10105 // without changing the order of probabilities. 10106 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10107 --I; 10108 if (I->Prob > W.LastCluster->Prob) 10109 break; 10110 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10111 std::swap(*I, *W.LastCluster); 10112 break; 10113 } 10114 } 10115 } 10116 10117 // Compute total probability. 10118 BranchProbability DefaultProb = W.DefaultProb; 10119 BranchProbability UnhandledProbs = DefaultProb; 10120 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10121 UnhandledProbs += I->Prob; 10122 10123 MachineBasicBlock *CurMBB = W.MBB; 10124 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10125 bool FallthroughUnreachable = false; 10126 MachineBasicBlock *Fallthrough; 10127 if (I == W.LastCluster) { 10128 // For the last cluster, fall through to the default destination. 10129 Fallthrough = DefaultMBB; 10130 FallthroughUnreachable = isa<UnreachableInst>( 10131 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 10132 } else { 10133 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10134 CurMF->insert(BBI, Fallthrough); 10135 // Put Cond in a virtual register to make it available from the new blocks. 10136 ExportFromCurrentBlock(Cond); 10137 } 10138 UnhandledProbs -= I->Prob; 10139 10140 switch (I->Kind) { 10141 case CC_JumpTable: { 10142 // FIXME: Optimize away range check based on pivot comparisons. 10143 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 10144 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 10145 10146 // The jump block hasn't been inserted yet; insert it here. 10147 MachineBasicBlock *JumpMBB = JT->MBB; 10148 CurMF->insert(BBI, JumpMBB); 10149 10150 auto JumpProb = I->Prob; 10151 auto FallthroughProb = UnhandledProbs; 10152 10153 // If the default statement is a target of the jump table, we evenly 10154 // distribute the default probability to successors of CurMBB. Also 10155 // update the probability on the edge from JumpMBB to Fallthrough. 10156 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10157 SE = JumpMBB->succ_end(); 10158 SI != SE; ++SI) { 10159 if (*SI == DefaultMBB) { 10160 JumpProb += DefaultProb / 2; 10161 FallthroughProb -= DefaultProb / 2; 10162 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10163 JumpMBB->normalizeSuccProbs(); 10164 break; 10165 } 10166 } 10167 10168 if (FallthroughUnreachable) { 10169 // Skip the range check if the fallthrough block is unreachable. 10170 JTH->OmitRangeCheck = true; 10171 } 10172 10173 if (!JTH->OmitRangeCheck) 10174 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10175 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10176 CurMBB->normalizeSuccProbs(); 10177 10178 // The jump table header will be inserted in our current block, do the 10179 // range check, and fall through to our fallthrough block. 10180 JTH->HeaderBB = CurMBB; 10181 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10182 10183 // If we're in the right place, emit the jump table header right now. 10184 if (CurMBB == SwitchMBB) { 10185 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10186 JTH->Emitted = true; 10187 } 10188 break; 10189 } 10190 case CC_BitTests: { 10191 // FIXME: Optimize away range check based on pivot comparisons. 10192 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 10193 10194 // The bit test blocks haven't been inserted yet; insert them here. 10195 for (BitTestCase &BTC : BTB->Cases) 10196 CurMF->insert(BBI, BTC.ThisBB); 10197 10198 // Fill in fields of the BitTestBlock. 10199 BTB->Parent = CurMBB; 10200 BTB->Default = Fallthrough; 10201 10202 BTB->DefaultProb = UnhandledProbs; 10203 // If the cases in bit test don't form a contiguous range, we evenly 10204 // distribute the probability on the edge to Fallthrough to two 10205 // successors of CurMBB. 10206 if (!BTB->ContiguousRange) { 10207 BTB->Prob += DefaultProb / 2; 10208 BTB->DefaultProb -= DefaultProb / 2; 10209 } 10210 10211 if (FallthroughUnreachable) { 10212 // Skip the range check if the fallthrough block is unreachable. 10213 BTB->OmitRangeCheck = true; 10214 } 10215 10216 // If we're in the right place, emit the bit test header right now. 10217 if (CurMBB == SwitchMBB) { 10218 visitBitTestHeader(*BTB, SwitchMBB); 10219 BTB->Emitted = true; 10220 } 10221 break; 10222 } 10223 case CC_Range: { 10224 const Value *RHS, *LHS, *MHS; 10225 ISD::CondCode CC; 10226 if (I->Low == I->High) { 10227 // Check Cond == I->Low. 10228 CC = ISD::SETEQ; 10229 LHS = Cond; 10230 RHS=I->Low; 10231 MHS = nullptr; 10232 } else { 10233 // Check I->Low <= Cond <= I->High. 10234 CC = ISD::SETLE; 10235 LHS = I->Low; 10236 MHS = Cond; 10237 RHS = I->High; 10238 } 10239 10240 // If Fallthrough is unreachable, fold away the comparison. 10241 if (FallthroughUnreachable) 10242 CC = ISD::SETTRUE; 10243 10244 // The false probability is the sum of all unhandled cases. 10245 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10246 getCurSDLoc(), I->Prob, UnhandledProbs); 10247 10248 if (CurMBB == SwitchMBB) 10249 visitSwitchCase(CB, SwitchMBB); 10250 else 10251 SL->SwitchCases.push_back(CB); 10252 10253 break; 10254 } 10255 } 10256 CurMBB = Fallthrough; 10257 } 10258 } 10259 10260 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10261 CaseClusterIt First, 10262 CaseClusterIt Last) { 10263 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10264 if (X.Prob != CC.Prob) 10265 return X.Prob > CC.Prob; 10266 10267 // Ties are broken by comparing the case value. 10268 return X.Low->getValue().slt(CC.Low->getValue()); 10269 }); 10270 } 10271 10272 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10273 const SwitchWorkListItem &W, 10274 Value *Cond, 10275 MachineBasicBlock *SwitchMBB) { 10276 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10277 "Clusters not sorted?"); 10278 10279 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10280 10281 // Balance the tree based on branch probabilities to create a near-optimal (in 10282 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10283 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10284 CaseClusterIt LastLeft = W.FirstCluster; 10285 CaseClusterIt FirstRight = W.LastCluster; 10286 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10287 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10288 10289 // Move LastLeft and FirstRight towards each other from opposite directions to 10290 // find a partitioning of the clusters which balances the probability on both 10291 // sides. If LeftProb and RightProb are equal, alternate which side is 10292 // taken to ensure 0-probability nodes are distributed evenly. 10293 unsigned I = 0; 10294 while (LastLeft + 1 < FirstRight) { 10295 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10296 LeftProb += (++LastLeft)->Prob; 10297 else 10298 RightProb += (--FirstRight)->Prob; 10299 I++; 10300 } 10301 10302 while (true) { 10303 // Our binary search tree differs from a typical BST in that ours can have up 10304 // to three values in each leaf. The pivot selection above doesn't take that 10305 // into account, which means the tree might require more nodes and be less 10306 // efficient. We compensate for this here. 10307 10308 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10309 unsigned NumRight = W.LastCluster - FirstRight + 1; 10310 10311 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10312 // If one side has less than 3 clusters, and the other has more than 3, 10313 // consider taking a cluster from the other side. 10314 10315 if (NumLeft < NumRight) { 10316 // Consider moving the first cluster on the right to the left side. 10317 CaseCluster &CC = *FirstRight; 10318 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10319 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10320 if (LeftSideRank <= RightSideRank) { 10321 // Moving the cluster to the left does not demote it. 10322 ++LastLeft; 10323 ++FirstRight; 10324 continue; 10325 } 10326 } else { 10327 assert(NumRight < NumLeft); 10328 // Consider moving the last element on the left to the right side. 10329 CaseCluster &CC = *LastLeft; 10330 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10331 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10332 if (RightSideRank <= LeftSideRank) { 10333 // Moving the cluster to the right does not demot it. 10334 --LastLeft; 10335 --FirstRight; 10336 continue; 10337 } 10338 } 10339 } 10340 break; 10341 } 10342 10343 assert(LastLeft + 1 == FirstRight); 10344 assert(LastLeft >= W.FirstCluster); 10345 assert(FirstRight <= W.LastCluster); 10346 10347 // Use the first element on the right as pivot since we will make less-than 10348 // comparisons against it. 10349 CaseClusterIt PivotCluster = FirstRight; 10350 assert(PivotCluster > W.FirstCluster); 10351 assert(PivotCluster <= W.LastCluster); 10352 10353 CaseClusterIt FirstLeft = W.FirstCluster; 10354 CaseClusterIt LastRight = W.LastCluster; 10355 10356 const ConstantInt *Pivot = PivotCluster->Low; 10357 10358 // New blocks will be inserted immediately after the current one. 10359 MachineFunction::iterator BBI(W.MBB); 10360 ++BBI; 10361 10362 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10363 // we can branch to its destination directly if it's squeezed exactly in 10364 // between the known lower bound and Pivot - 1. 10365 MachineBasicBlock *LeftMBB; 10366 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10367 FirstLeft->Low == W.GE && 10368 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10369 LeftMBB = FirstLeft->MBB; 10370 } else { 10371 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10372 FuncInfo.MF->insert(BBI, LeftMBB); 10373 WorkList.push_back( 10374 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10375 // Put Cond in a virtual register to make it available from the new blocks. 10376 ExportFromCurrentBlock(Cond); 10377 } 10378 10379 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10380 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10381 // directly if RHS.High equals the current upper bound. 10382 MachineBasicBlock *RightMBB; 10383 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10384 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10385 RightMBB = FirstRight->MBB; 10386 } else { 10387 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10388 FuncInfo.MF->insert(BBI, RightMBB); 10389 WorkList.push_back( 10390 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10391 // Put Cond in a virtual register to make it available from the new blocks. 10392 ExportFromCurrentBlock(Cond); 10393 } 10394 10395 // Create the CaseBlock record that will be used to lower the branch. 10396 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10397 getCurSDLoc(), LeftProb, RightProb); 10398 10399 if (W.MBB == SwitchMBB) 10400 visitSwitchCase(CB, SwitchMBB); 10401 else 10402 SL->SwitchCases.push_back(CB); 10403 } 10404 10405 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10406 // from the swith statement. 10407 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10408 BranchProbability PeeledCaseProb) { 10409 if (PeeledCaseProb == BranchProbability::getOne()) 10410 return BranchProbability::getZero(); 10411 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10412 10413 uint32_t Numerator = CaseProb.getNumerator(); 10414 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10415 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10416 } 10417 10418 // Try to peel the top probability case if it exceeds the threshold. 10419 // Return current MachineBasicBlock for the switch statement if the peeling 10420 // does not occur. 10421 // If the peeling is performed, return the newly created MachineBasicBlock 10422 // for the peeled switch statement. Also update Clusters to remove the peeled 10423 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10424 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10425 const SwitchInst &SI, CaseClusterVector &Clusters, 10426 BranchProbability &PeeledCaseProb) { 10427 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10428 // Don't perform if there is only one cluster or optimizing for size. 10429 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10430 TM.getOptLevel() == CodeGenOpt::None || 10431 SwitchMBB->getParent()->getFunction().hasMinSize()) 10432 return SwitchMBB; 10433 10434 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10435 unsigned PeeledCaseIndex = 0; 10436 bool SwitchPeeled = false; 10437 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10438 CaseCluster &CC = Clusters[Index]; 10439 if (CC.Prob < TopCaseProb) 10440 continue; 10441 TopCaseProb = CC.Prob; 10442 PeeledCaseIndex = Index; 10443 SwitchPeeled = true; 10444 } 10445 if (!SwitchPeeled) 10446 return SwitchMBB; 10447 10448 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10449 << TopCaseProb << "\n"); 10450 10451 // Record the MBB for the peeled switch statement. 10452 MachineFunction::iterator BBI(SwitchMBB); 10453 ++BBI; 10454 MachineBasicBlock *PeeledSwitchMBB = 10455 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10456 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10457 10458 ExportFromCurrentBlock(SI.getCondition()); 10459 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10460 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10461 nullptr, nullptr, TopCaseProb.getCompl()}; 10462 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10463 10464 Clusters.erase(PeeledCaseIt); 10465 for (CaseCluster &CC : Clusters) { 10466 LLVM_DEBUG( 10467 dbgs() << "Scale the probablity for one cluster, before scaling: " 10468 << CC.Prob << "\n"); 10469 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10470 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10471 } 10472 PeeledCaseProb = TopCaseProb; 10473 return PeeledSwitchMBB; 10474 } 10475 10476 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10477 // Extract cases from the switch. 10478 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10479 CaseClusterVector Clusters; 10480 Clusters.reserve(SI.getNumCases()); 10481 for (auto I : SI.cases()) { 10482 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10483 const ConstantInt *CaseVal = I.getCaseValue(); 10484 BranchProbability Prob = 10485 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10486 : BranchProbability(1, SI.getNumCases() + 1); 10487 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10488 } 10489 10490 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10491 10492 // Cluster adjacent cases with the same destination. We do this at all 10493 // optimization levels because it's cheap to do and will make codegen faster 10494 // if there are many clusters. 10495 sortAndRangeify(Clusters); 10496 10497 // The branch probablity of the peeled case. 10498 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10499 MachineBasicBlock *PeeledSwitchMBB = 10500 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10501 10502 // If there is only the default destination, jump there directly. 10503 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10504 if (Clusters.empty()) { 10505 assert(PeeledSwitchMBB == SwitchMBB); 10506 SwitchMBB->addSuccessor(DefaultMBB); 10507 if (DefaultMBB != NextBlock(SwitchMBB)) { 10508 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10509 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10510 } 10511 return; 10512 } 10513 10514 SL->findJumpTables(Clusters, &SI, DefaultMBB); 10515 SL->findBitTestClusters(Clusters, &SI); 10516 10517 LLVM_DEBUG({ 10518 dbgs() << "Case clusters: "; 10519 for (const CaseCluster &C : Clusters) { 10520 if (C.Kind == CC_JumpTable) 10521 dbgs() << "JT:"; 10522 if (C.Kind == CC_BitTests) 10523 dbgs() << "BT:"; 10524 10525 C.Low->getValue().print(dbgs(), true); 10526 if (C.Low != C.High) { 10527 dbgs() << '-'; 10528 C.High->getValue().print(dbgs(), true); 10529 } 10530 dbgs() << ' '; 10531 } 10532 dbgs() << '\n'; 10533 }); 10534 10535 assert(!Clusters.empty()); 10536 SwitchWorkList WorkList; 10537 CaseClusterIt First = Clusters.begin(); 10538 CaseClusterIt Last = Clusters.end() - 1; 10539 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10540 // Scale the branchprobability for DefaultMBB if the peel occurs and 10541 // DefaultMBB is not replaced. 10542 if (PeeledCaseProb != BranchProbability::getZero() && 10543 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10544 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10545 WorkList.push_back( 10546 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10547 10548 while (!WorkList.empty()) { 10549 SwitchWorkListItem W = WorkList.back(); 10550 WorkList.pop_back(); 10551 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10552 10553 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10554 !DefaultMBB->getParent()->getFunction().hasMinSize()) { 10555 // For optimized builds, lower large range as a balanced binary tree. 10556 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10557 continue; 10558 } 10559 10560 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10561 } 10562 } 10563