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/TargetFrameLowering.h" 58 #include "llvm/CodeGen/TargetInstrInfo.h" 59 #include "llvm/CodeGen/TargetLowering.h" 60 #include "llvm/CodeGen/TargetOpcodes.h" 61 #include "llvm/CodeGen/TargetRegisterInfo.h" 62 #include "llvm/CodeGen/TargetSubtargetInfo.h" 63 #include "llvm/CodeGen/ValueTypes.h" 64 #include "llvm/CodeGen/WinEHFuncInfo.h" 65 #include "llvm/IR/Argument.h" 66 #include "llvm/IR/Attributes.h" 67 #include "llvm/IR/BasicBlock.h" 68 #include "llvm/IR/CFG.h" 69 #include "llvm/IR/CallSite.h" 70 #include "llvm/IR/CallingConv.h" 71 #include "llvm/IR/Constant.h" 72 #include "llvm/IR/ConstantRange.h" 73 #include "llvm/IR/Constants.h" 74 #include "llvm/IR/DataLayout.h" 75 #include "llvm/IR/DebugInfoMetadata.h" 76 #include "llvm/IR/DebugLoc.h" 77 #include "llvm/IR/DerivedTypes.h" 78 #include "llvm/IR/Function.h" 79 #include "llvm/IR/GetElementPtrTypeIterator.h" 80 #include "llvm/IR/InlineAsm.h" 81 #include "llvm/IR/InstrTypes.h" 82 #include "llvm/IR/Instruction.h" 83 #include "llvm/IR/Instructions.h" 84 #include "llvm/IR/IntrinsicInst.h" 85 #include "llvm/IR/Intrinsics.h" 86 #include "llvm/IR/LLVMContext.h" 87 #include "llvm/IR/Metadata.h" 88 #include "llvm/IR/Module.h" 89 #include "llvm/IR/Operator.h" 90 #include "llvm/IR/PatternMatch.h" 91 #include "llvm/IR/Statepoint.h" 92 #include "llvm/IR/Type.h" 93 #include "llvm/IR/User.h" 94 #include "llvm/IR/Value.h" 95 #include "llvm/MC/MCContext.h" 96 #include "llvm/MC/MCSymbol.h" 97 #include "llvm/Support/AtomicOrdering.h" 98 #include "llvm/Support/BranchProbability.h" 99 #include "llvm/Support/Casting.h" 100 #include "llvm/Support/CodeGen.h" 101 #include "llvm/Support/CommandLine.h" 102 #include "llvm/Support/Compiler.h" 103 #include "llvm/Support/Debug.h" 104 #include "llvm/Support/ErrorHandling.h" 105 #include "llvm/Support/MachineValueType.h" 106 #include "llvm/Support/MathExtras.h" 107 #include "llvm/Support/raw_ostream.h" 108 #include "llvm/Target/TargetIntrinsicInfo.h" 109 #include "llvm/Target/TargetMachine.h" 110 #include "llvm/Target/TargetOptions.h" 111 #include "llvm/Transforms/Utils/Local.h" 112 #include <algorithm> 113 #include <cassert> 114 #include <cstddef> 115 #include <cstdint> 116 #include <cstring> 117 #include <iterator> 118 #include <limits> 119 #include <numeric> 120 #include <tuple> 121 #include <utility> 122 #include <vector> 123 124 using namespace llvm; 125 using namespace PatternMatch; 126 127 #define DEBUG_TYPE "isel" 128 129 /// LimitFloatPrecision - Generate low-precision inline sequences for 130 /// some float libcalls (6, 8 or 12 bits). 131 static unsigned LimitFloatPrecision; 132 133 static cl::opt<unsigned, true> 134 LimitFPPrecision("limit-float-precision", 135 cl::desc("Generate low-precision inline sequences " 136 "for some float libcalls"), 137 cl::location(LimitFloatPrecision), cl::Hidden, 138 cl::init(0)); 139 140 static cl::opt<unsigned> SwitchPeelThreshold( 141 "switch-peel-threshold", cl::Hidden, cl::init(66), 142 cl::desc("Set the case probability threshold for peeling the case from a " 143 "switch statement. A value greater than 100 will void this " 144 "optimization")); 145 146 // Limit the width of DAG chains. This is important in general to prevent 147 // DAG-based analysis from blowing up. For example, alias analysis and 148 // load clustering may not complete in reasonable time. It is difficult to 149 // recognize and avoid this situation within each individual analysis, and 150 // future analyses are likely to have the same behavior. Limiting DAG width is 151 // the safe approach and will be especially important with global DAGs. 152 // 153 // MaxParallelChains default is arbitrarily high to avoid affecting 154 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 155 // sequence over this should have been converted to llvm.memcpy by the 156 // frontend. It is easy to induce this behavior with .ll code such as: 157 // %buffer = alloca [4096 x i8] 158 // %data = load [4096 x i8]* %argPtr 159 // store [4096 x i8] %data, [4096 x i8]* %buffer 160 static const unsigned MaxParallelChains = 64; 161 162 // Return the calling convention if the Value passed requires ABI mangling as it 163 // is a parameter to a function or a return value from a function which is not 164 // an intrinsic. 165 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 166 if (auto *R = dyn_cast<ReturnInst>(V)) 167 return R->getParent()->getParent()->getCallingConv(); 168 169 if (auto *CI = dyn_cast<CallInst>(V)) { 170 const bool IsInlineAsm = CI->isInlineAsm(); 171 const bool IsIndirectFunctionCall = 172 !IsInlineAsm && !CI->getCalledFunction(); 173 174 // It is possible that the call instruction is an inline asm statement or an 175 // indirect function call in which case the return value of 176 // getCalledFunction() would be nullptr. 177 const bool IsInstrinsicCall = 178 !IsInlineAsm && !IsIndirectFunctionCall && 179 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 180 181 if (!IsInlineAsm && !IsInstrinsicCall) 182 return CI->getCallingConv(); 183 } 184 185 return None; 186 } 187 188 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 189 const SDValue *Parts, unsigned NumParts, 190 MVT PartVT, EVT ValueVT, const Value *V, 191 Optional<CallingConv::ID> CC); 192 193 /// getCopyFromParts - Create a value that contains the specified legal parts 194 /// combined into the value they represent. If the parts combine to a type 195 /// larger than ValueVT then AssertOp can be used to specify whether the extra 196 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 197 /// (ISD::AssertSext). 198 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 199 const SDValue *Parts, unsigned NumParts, 200 MVT PartVT, EVT ValueVT, const Value *V, 201 Optional<CallingConv::ID> CC = None, 202 Optional<ISD::NodeType> AssertOp = None) { 203 if (ValueVT.isVector()) 204 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 205 CC); 206 207 assert(NumParts > 0 && "No parts to assemble!"); 208 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 209 SDValue Val = Parts[0]; 210 211 if (NumParts > 1) { 212 // Assemble the value from multiple parts. 213 if (ValueVT.isInteger()) { 214 unsigned PartBits = PartVT.getSizeInBits(); 215 unsigned ValueBits = ValueVT.getSizeInBits(); 216 217 // Assemble the power of 2 part. 218 unsigned RoundParts = NumParts & (NumParts - 1) ? 219 1 << Log2_32(NumParts) : NumParts; 220 unsigned RoundBits = PartBits * RoundParts; 221 EVT RoundVT = RoundBits == ValueBits ? 222 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 223 SDValue Lo, Hi; 224 225 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 226 227 if (RoundParts > 2) { 228 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 229 PartVT, HalfVT, V); 230 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 231 RoundParts / 2, PartVT, HalfVT, V); 232 } else { 233 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 234 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 235 } 236 237 if (DAG.getDataLayout().isBigEndian()) 238 std::swap(Lo, Hi); 239 240 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 241 242 if (RoundParts < NumParts) { 243 // Assemble the trailing non-power-of-2 part. 244 unsigned OddParts = NumParts - RoundParts; 245 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 246 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 247 OddVT, V, CC); 248 249 // Combine the round and odd parts. 250 Lo = Val; 251 if (DAG.getDataLayout().isBigEndian()) 252 std::swap(Lo, Hi); 253 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 254 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 255 Hi = 256 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 257 DAG.getConstant(Lo.getValueSizeInBits(), DL, 258 TLI.getPointerTy(DAG.getDataLayout()))); 259 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 260 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 261 } 262 } else if (PartVT.isFloatingPoint()) { 263 // FP split into multiple FP parts (for ppcf128) 264 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 265 "Unexpected split"); 266 SDValue Lo, Hi; 267 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 268 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 269 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 270 std::swap(Lo, Hi); 271 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 272 } else { 273 // FP split into integer parts (soft fp) 274 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 275 !PartVT.isVector() && "Unexpected split"); 276 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 277 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 278 } 279 } 280 281 // There is now one part, held in Val. Correct it to match ValueVT. 282 // PartEVT is the type of the register class that holds the value. 283 // ValueVT is the type of the inline asm operation. 284 EVT PartEVT = Val.getValueType(); 285 286 if (PartEVT == ValueVT) 287 return Val; 288 289 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 290 ValueVT.bitsLT(PartEVT)) { 291 // For an FP value in an integer part, we need to truncate to the right 292 // width first. 293 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 294 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 295 } 296 297 // Handle types that have the same size. 298 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 299 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 300 301 // Handle types with different sizes. 302 if (PartEVT.isInteger() && ValueVT.isInteger()) { 303 if (ValueVT.bitsLT(PartEVT)) { 304 // For a truncate, see if we have any information to 305 // indicate whether the truncated bits will always be 306 // zero or sign-extension. 307 if (AssertOp.hasValue()) 308 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 309 DAG.getValueType(ValueVT)); 310 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 311 } 312 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 313 } 314 315 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 316 // FP_ROUND's are always exact here. 317 if (ValueVT.bitsLT(Val.getValueType())) 318 return DAG.getNode( 319 ISD::FP_ROUND, DL, ValueVT, Val, 320 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 321 322 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 323 } 324 325 llvm_unreachable("Unknown mismatch!"); 326 } 327 328 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 329 const Twine &ErrMsg) { 330 const Instruction *I = dyn_cast_or_null<Instruction>(V); 331 if (!V) 332 return Ctx.emitError(ErrMsg); 333 334 const char *AsmError = ", possible invalid constraint for vector type"; 335 if (const CallInst *CI = dyn_cast<CallInst>(I)) 336 if (isa<InlineAsm>(CI->getCalledValue())) 337 return Ctx.emitError(I, ErrMsg + AsmError); 338 339 return Ctx.emitError(I, ErrMsg); 340 } 341 342 /// getCopyFromPartsVector - Create a value that contains the specified legal 343 /// parts combined into the value they represent. If the parts combine to a 344 /// type larger than ValueVT then AssertOp can be used to specify whether the 345 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 346 /// ValueVT (ISD::AssertSext). 347 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 348 const SDValue *Parts, unsigned NumParts, 349 MVT PartVT, EVT ValueVT, const Value *V, 350 Optional<CallingConv::ID> CallConv) { 351 assert(ValueVT.isVector() && "Not a vector value"); 352 assert(NumParts > 0 && "No parts to assemble!"); 353 const bool IsABIRegCopy = CallConv.hasValue(); 354 355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 356 SDValue Val = Parts[0]; 357 358 // Handle a multi-element vector. 359 if (NumParts > 1) { 360 EVT IntermediateVT; 361 MVT RegisterVT; 362 unsigned NumIntermediates; 363 unsigned NumRegs; 364 365 if (IsABIRegCopy) { 366 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 367 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 368 NumIntermediates, RegisterVT); 369 } else { 370 NumRegs = 371 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 372 NumIntermediates, RegisterVT); 373 } 374 375 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 376 NumParts = NumRegs; // Silence a compiler warning. 377 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 378 assert(RegisterVT.getSizeInBits() == 379 Parts[0].getSimpleValueType().getSizeInBits() && 380 "Part type sizes don't match!"); 381 382 // Assemble the parts into intermediate operands. 383 SmallVector<SDValue, 8> Ops(NumIntermediates); 384 if (NumIntermediates == NumParts) { 385 // If the register was not expanded, truncate or copy the value, 386 // as appropriate. 387 for (unsigned i = 0; i != NumParts; ++i) 388 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 389 PartVT, IntermediateVT, V); 390 } else if (NumParts > 0) { 391 // If the intermediate type was expanded, build the intermediate 392 // operands from the parts. 393 assert(NumParts % NumIntermediates == 0 && 394 "Must expand into a divisible number of parts!"); 395 unsigned Factor = NumParts / NumIntermediates; 396 for (unsigned i = 0; i != NumIntermediates; ++i) 397 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 398 PartVT, IntermediateVT, V); 399 } 400 401 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 402 // intermediate operands. 403 EVT BuiltVectorTy = 404 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 405 (IntermediateVT.isVector() 406 ? IntermediateVT.getVectorNumElements() * NumParts 407 : NumIntermediates)); 408 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 409 : ISD::BUILD_VECTOR, 410 DL, BuiltVectorTy, Ops); 411 } 412 413 // There is now one part, held in Val. Correct it to match ValueVT. 414 EVT PartEVT = Val.getValueType(); 415 416 if (PartEVT == ValueVT) 417 return Val; 418 419 if (PartEVT.isVector()) { 420 // If the element type of the source/dest vectors are the same, but the 421 // parts vector has more elements than the value vector, then we have a 422 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 423 // elements we want. 424 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 425 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 426 "Cannot narrow, it would be a lossy transformation"); 427 return DAG.getNode( 428 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 429 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 430 } 431 432 // Vector/Vector bitcast. 433 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 434 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 435 436 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 437 "Cannot handle this kind of promotion"); 438 // Promoted vector extract 439 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 440 441 } 442 443 // Trivial bitcast if the types are the same size and the destination 444 // vector type is legal. 445 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 446 TLI.isTypeLegal(ValueVT)) 447 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 448 449 if (ValueVT.getVectorNumElements() != 1) { 450 // Certain ABIs require that vectors are passed as integers. For vectors 451 // are the same size, this is an obvious bitcast. 452 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 453 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 454 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 455 // Bitcast Val back the original type and extract the corresponding 456 // vector we want. 457 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 458 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 459 ValueVT.getVectorElementType(), Elts); 460 Val = DAG.getBitcast(WiderVecType, Val); 461 return DAG.getNode( 462 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 463 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 464 } 465 466 diagnosePossiblyInvalidConstraint( 467 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 468 return DAG.getUNDEF(ValueVT); 469 } 470 471 // Handle cases such as i8 -> <1 x i1> 472 EVT ValueSVT = ValueVT.getVectorElementType(); 473 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 474 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 475 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 476 477 return DAG.getBuildVector(ValueVT, DL, Val); 478 } 479 480 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 481 SDValue Val, SDValue *Parts, unsigned NumParts, 482 MVT PartVT, const Value *V, 483 Optional<CallingConv::ID> CallConv); 484 485 /// getCopyToParts - Create a series of nodes that contain the specified value 486 /// split into legal parts. If the parts contain more bits than Val, then, for 487 /// integers, ExtendKind can be used to specify how to generate the extra bits. 488 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 489 SDValue *Parts, unsigned NumParts, MVT PartVT, 490 const Value *V, 491 Optional<CallingConv::ID> CallConv = None, 492 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 493 EVT ValueVT = Val.getValueType(); 494 495 // Handle the vector case separately. 496 if (ValueVT.isVector()) 497 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 498 CallConv); 499 500 unsigned PartBits = PartVT.getSizeInBits(); 501 unsigned OrigNumParts = NumParts; 502 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 503 "Copying to an illegal type!"); 504 505 if (NumParts == 0) 506 return; 507 508 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 509 EVT PartEVT = PartVT; 510 if (PartEVT == ValueVT) { 511 assert(NumParts == 1 && "No-op copy with multiple parts!"); 512 Parts[0] = Val; 513 return; 514 } 515 516 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 517 // If the parts cover more bits than the value has, promote the value. 518 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 519 assert(NumParts == 1 && "Do not know what to promote to!"); 520 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 521 } else { 522 if (ValueVT.isFloatingPoint()) { 523 // FP values need to be bitcast, then extended if they are being put 524 // into a larger container. 525 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 526 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 527 } 528 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 529 ValueVT.isInteger() && 530 "Unknown mismatch!"); 531 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 532 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 533 if (PartVT == MVT::x86mmx) 534 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 535 } 536 } else if (PartBits == ValueVT.getSizeInBits()) { 537 // Different types of the same size. 538 assert(NumParts == 1 && PartEVT != ValueVT); 539 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 540 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 541 // If the parts cover less bits than value has, truncate the value. 542 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 543 ValueVT.isInteger() && 544 "Unknown mismatch!"); 545 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 546 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 547 if (PartVT == MVT::x86mmx) 548 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 549 } 550 551 // The value may have changed - recompute ValueVT. 552 ValueVT = Val.getValueType(); 553 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 554 "Failed to tile the value with PartVT!"); 555 556 if (NumParts == 1) { 557 if (PartEVT != ValueVT) { 558 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 559 "scalar-to-vector conversion failed"); 560 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 561 } 562 563 Parts[0] = Val; 564 return; 565 } 566 567 // Expand the value into multiple parts. 568 if (NumParts & (NumParts - 1)) { 569 // The number of parts is not a power of 2. Split off and copy the tail. 570 assert(PartVT.isInteger() && ValueVT.isInteger() && 571 "Do not know what to expand to!"); 572 unsigned RoundParts = 1 << Log2_32(NumParts); 573 unsigned RoundBits = RoundParts * PartBits; 574 unsigned OddParts = NumParts - RoundParts; 575 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 576 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false)); 577 578 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 579 CallConv); 580 581 if (DAG.getDataLayout().isBigEndian()) 582 // The odd parts were reversed by getCopyToParts - unreverse them. 583 std::reverse(Parts + RoundParts, Parts + NumParts); 584 585 NumParts = RoundParts; 586 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 587 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 588 } 589 590 // The number of parts is a power of 2. Repeatedly bisect the value using 591 // EXTRACT_ELEMENT. 592 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 593 EVT::getIntegerVT(*DAG.getContext(), 594 ValueVT.getSizeInBits()), 595 Val); 596 597 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 598 for (unsigned i = 0; i < NumParts; i += StepSize) { 599 unsigned ThisBits = StepSize * PartBits / 2; 600 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 601 SDValue &Part0 = Parts[i]; 602 SDValue &Part1 = Parts[i+StepSize/2]; 603 604 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 606 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 607 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 608 609 if (ThisBits == PartBits && ThisVT != PartVT) { 610 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 611 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 612 } 613 } 614 } 615 616 if (DAG.getDataLayout().isBigEndian()) 617 std::reverse(Parts, Parts + OrigNumParts); 618 } 619 620 static SDValue widenVectorToPartType(SelectionDAG &DAG, 621 SDValue Val, const SDLoc &DL, EVT PartVT) { 622 if (!PartVT.isVector()) 623 return SDValue(); 624 625 EVT ValueVT = Val.getValueType(); 626 unsigned PartNumElts = PartVT.getVectorNumElements(); 627 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 628 if (PartNumElts > ValueNumElts && 629 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 630 EVT ElementVT = PartVT.getVectorElementType(); 631 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 632 // undef elements. 633 SmallVector<SDValue, 16> Ops; 634 DAG.ExtractVectorElements(Val, Ops); 635 SDValue EltUndef = DAG.getUNDEF(ElementVT); 636 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 637 Ops.push_back(EltUndef); 638 639 // FIXME: Use CONCAT for 2x -> 4x. 640 return DAG.getBuildVector(PartVT, DL, Ops); 641 } 642 643 return SDValue(); 644 } 645 646 /// getCopyToPartsVector - Create a series of nodes that contain the specified 647 /// value split into legal parts. 648 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 649 SDValue Val, SDValue *Parts, unsigned NumParts, 650 MVT PartVT, const Value *V, 651 Optional<CallingConv::ID> CallConv) { 652 EVT ValueVT = Val.getValueType(); 653 assert(ValueVT.isVector() && "Not a vector"); 654 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 655 const bool IsABIRegCopy = CallConv.hasValue(); 656 657 if (NumParts == 1) { 658 EVT PartEVT = PartVT; 659 if (PartEVT == ValueVT) { 660 // Nothing to do. 661 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 662 // Bitconvert vector->vector case. 663 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 664 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 665 Val = Widened; 666 } else if (PartVT.isVector() && 667 PartEVT.getVectorElementType().bitsGE( 668 ValueVT.getVectorElementType()) && 669 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 670 671 // Promoted vector extract 672 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 673 } else { 674 if (ValueVT.getVectorNumElements() == 1) { 675 Val = DAG.getNode( 676 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 677 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 678 } else { 679 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 680 "lossy conversion of vector to scalar type"); 681 EVT IntermediateType = 682 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 683 Val = DAG.getBitcast(IntermediateType, Val); 684 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 685 } 686 } 687 688 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 689 Parts[0] = Val; 690 return; 691 } 692 693 // Handle a multi-element vector. 694 EVT IntermediateVT; 695 MVT RegisterVT; 696 unsigned NumIntermediates; 697 unsigned NumRegs; 698 if (IsABIRegCopy) { 699 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 700 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 701 NumIntermediates, RegisterVT); 702 } else { 703 NumRegs = 704 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 705 NumIntermediates, RegisterVT); 706 } 707 708 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 709 NumParts = NumRegs; // Silence a compiler warning. 710 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 711 712 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 713 IntermediateVT.getVectorNumElements() : 1; 714 715 // Convert the vector to the appropiate type if necessary. 716 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 717 718 EVT BuiltVectorTy = EVT::getVectorVT( 719 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 720 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 721 if (ValueVT != BuiltVectorTy) { 722 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 723 Val = Widened; 724 725 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 726 } 727 728 // Split the vector into intermediate operands. 729 SmallVector<SDValue, 8> Ops(NumIntermediates); 730 for (unsigned i = 0; i != NumIntermediates; ++i) { 731 if (IntermediateVT.isVector()) { 732 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 733 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 734 } else { 735 Ops[i] = DAG.getNode( 736 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 737 DAG.getConstant(i, DL, IdxVT)); 738 } 739 } 740 741 // Split the intermediate operands into legal parts. 742 if (NumParts == NumIntermediates) { 743 // If the register was not expanded, promote or copy the value, 744 // as appropriate. 745 for (unsigned i = 0; i != NumParts; ++i) 746 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 747 } else if (NumParts > 0) { 748 // If the intermediate type was expanded, split each the value into 749 // legal parts. 750 assert(NumIntermediates != 0 && "division by zero"); 751 assert(NumParts % NumIntermediates == 0 && 752 "Must expand into a divisible number of parts!"); 753 unsigned Factor = NumParts / NumIntermediates; 754 for (unsigned i = 0; i != NumIntermediates; ++i) 755 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 756 CallConv); 757 } 758 } 759 760 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 761 EVT valuevt, Optional<CallingConv::ID> CC) 762 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 763 RegCount(1, regs.size()), CallConv(CC) {} 764 765 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 766 const DataLayout &DL, unsigned Reg, Type *Ty, 767 Optional<CallingConv::ID> CC) { 768 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 769 770 CallConv = CC; 771 772 for (EVT ValueVT : ValueVTs) { 773 unsigned NumRegs = 774 isABIMangled() 775 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 776 : TLI.getNumRegisters(Context, ValueVT); 777 MVT RegisterVT = 778 isABIMangled() 779 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 780 : TLI.getRegisterType(Context, ValueVT); 781 for (unsigned i = 0; i != NumRegs; ++i) 782 Regs.push_back(Reg + i); 783 RegVTs.push_back(RegisterVT); 784 RegCount.push_back(NumRegs); 785 Reg += NumRegs; 786 } 787 } 788 789 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 790 FunctionLoweringInfo &FuncInfo, 791 const SDLoc &dl, SDValue &Chain, 792 SDValue *Flag, const Value *V) const { 793 // A Value with type {} or [0 x %t] needs no registers. 794 if (ValueVTs.empty()) 795 return SDValue(); 796 797 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 798 799 // Assemble the legal parts into the final values. 800 SmallVector<SDValue, 4> Values(ValueVTs.size()); 801 SmallVector<SDValue, 8> Parts; 802 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 803 // Copy the legal parts from the registers. 804 EVT ValueVT = ValueVTs[Value]; 805 unsigned NumRegs = RegCount[Value]; 806 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 807 *DAG.getContext(), 808 CallConv.getValue(), RegVTs[Value]) 809 : RegVTs[Value]; 810 811 Parts.resize(NumRegs); 812 for (unsigned i = 0; i != NumRegs; ++i) { 813 SDValue P; 814 if (!Flag) { 815 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 816 } else { 817 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 818 *Flag = P.getValue(2); 819 } 820 821 Chain = P.getValue(1); 822 Parts[i] = P; 823 824 // If the source register was virtual and if we know something about it, 825 // add an assert node. 826 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 827 !RegisterVT.isInteger()) 828 continue; 829 830 const FunctionLoweringInfo::LiveOutInfo *LOI = 831 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 832 if (!LOI) 833 continue; 834 835 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 836 unsigned NumSignBits = LOI->NumSignBits; 837 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 838 839 if (NumZeroBits == RegSize) { 840 // The current value is a zero. 841 // Explicitly express that as it would be easier for 842 // optimizations to kick in. 843 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 844 continue; 845 } 846 847 // FIXME: We capture more information than the dag can represent. For 848 // now, just use the tightest assertzext/assertsext possible. 849 bool isSExt; 850 EVT FromVT(MVT::Other); 851 if (NumZeroBits) { 852 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 853 isSExt = false; 854 } else if (NumSignBits > 1) { 855 FromVT = 856 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 857 isSExt = true; 858 } else { 859 continue; 860 } 861 // Add an assertion node. 862 assert(FromVT != MVT::Other); 863 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 864 RegisterVT, P, DAG.getValueType(FromVT)); 865 } 866 867 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 868 RegisterVT, ValueVT, V, CallConv); 869 Part += NumRegs; 870 Parts.clear(); 871 } 872 873 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 874 } 875 876 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 877 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 878 const Value *V, 879 ISD::NodeType PreferredExtendType) const { 880 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 881 ISD::NodeType ExtendKind = PreferredExtendType; 882 883 // Get the list of the values's legal parts. 884 unsigned NumRegs = Regs.size(); 885 SmallVector<SDValue, 8> Parts(NumRegs); 886 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 887 unsigned NumParts = RegCount[Value]; 888 889 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 890 *DAG.getContext(), 891 CallConv.getValue(), RegVTs[Value]) 892 : RegVTs[Value]; 893 894 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 895 ExtendKind = ISD::ZERO_EXTEND; 896 897 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 898 NumParts, RegisterVT, V, CallConv, ExtendKind); 899 Part += NumParts; 900 } 901 902 // Copy the parts into the registers. 903 SmallVector<SDValue, 8> Chains(NumRegs); 904 for (unsigned i = 0; i != NumRegs; ++i) { 905 SDValue Part; 906 if (!Flag) { 907 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 908 } else { 909 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 910 *Flag = Part.getValue(1); 911 } 912 913 Chains[i] = Part.getValue(0); 914 } 915 916 if (NumRegs == 1 || Flag) 917 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 918 // flagged to it. That is the CopyToReg nodes and the user are considered 919 // a single scheduling unit. If we create a TokenFactor and return it as 920 // chain, then the TokenFactor is both a predecessor (operand) of the 921 // user as well as a successor (the TF operands are flagged to the user). 922 // c1, f1 = CopyToReg 923 // c2, f2 = CopyToReg 924 // c3 = TokenFactor c1, c2 925 // ... 926 // = op c3, ..., f2 927 Chain = Chains[NumRegs-1]; 928 else 929 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 930 } 931 932 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 933 unsigned MatchingIdx, const SDLoc &dl, 934 SelectionDAG &DAG, 935 std::vector<SDValue> &Ops) const { 936 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 937 938 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 939 if (HasMatching) 940 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 941 else if (!Regs.empty() && 942 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 943 // Put the register class of the virtual registers in the flag word. That 944 // way, later passes can recompute register class constraints for inline 945 // assembly as well as normal instructions. 946 // Don't do this for tied operands that can use the regclass information 947 // from the def. 948 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 949 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 950 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 951 } 952 953 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 954 Ops.push_back(Res); 955 956 if (Code == InlineAsm::Kind_Clobber) { 957 // Clobbers should always have a 1:1 mapping with registers, and may 958 // reference registers that have illegal (e.g. vector) types. Hence, we 959 // shouldn't try to apply any sort of splitting logic to them. 960 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 961 "No 1:1 mapping from clobbers to regs?"); 962 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 963 (void)SP; 964 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 965 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 966 assert( 967 (Regs[I] != SP || 968 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 969 "If we clobbered the stack pointer, MFI should know about it."); 970 } 971 return; 972 } 973 974 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 975 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 976 MVT RegisterVT = RegVTs[Value]; 977 for (unsigned i = 0; i != NumRegs; ++i) { 978 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 979 unsigned TheReg = Regs[Reg++]; 980 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 981 } 982 } 983 } 984 985 SmallVector<std::pair<unsigned, unsigned>, 4> 986 RegsForValue::getRegsAndSizes() const { 987 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 988 unsigned I = 0; 989 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 990 unsigned RegCount = std::get<0>(CountAndVT); 991 MVT RegisterVT = std::get<1>(CountAndVT); 992 unsigned RegisterSize = RegisterVT.getSizeInBits(); 993 for (unsigned E = I + RegCount; I != E; ++I) 994 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 995 } 996 return OutVec; 997 } 998 999 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 1000 const TargetLibraryInfo *li) { 1001 AA = aa; 1002 GFI = gfi; 1003 LibInfo = li; 1004 DL = &DAG.getDataLayout(); 1005 Context = DAG.getContext(); 1006 LPadToCallSiteMap.clear(); 1007 } 1008 1009 void SelectionDAGBuilder::clear() { 1010 NodeMap.clear(); 1011 UnusedArgNodeMap.clear(); 1012 PendingLoads.clear(); 1013 PendingExports.clear(); 1014 CurInst = nullptr; 1015 HasTailCall = false; 1016 SDNodeOrder = LowestSDNodeOrder; 1017 StatepointLowering.clear(); 1018 } 1019 1020 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1021 DanglingDebugInfoMap.clear(); 1022 } 1023 1024 SDValue SelectionDAGBuilder::getRoot() { 1025 if (PendingLoads.empty()) 1026 return DAG.getRoot(); 1027 1028 if (PendingLoads.size() == 1) { 1029 SDValue Root = PendingLoads[0]; 1030 DAG.setRoot(Root); 1031 PendingLoads.clear(); 1032 return Root; 1033 } 1034 1035 // Otherwise, we have to make a token factor node. 1036 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1037 PendingLoads.clear(); 1038 DAG.setRoot(Root); 1039 return Root; 1040 } 1041 1042 SDValue SelectionDAGBuilder::getControlRoot() { 1043 SDValue Root = DAG.getRoot(); 1044 1045 if (PendingExports.empty()) 1046 return Root; 1047 1048 // Turn all of the CopyToReg chains into one factored node. 1049 if (Root.getOpcode() != ISD::EntryToken) { 1050 unsigned i = 0, e = PendingExports.size(); 1051 for (; i != e; ++i) { 1052 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1053 if (PendingExports[i].getNode()->getOperand(0) == Root) 1054 break; // Don't add the root if we already indirectly depend on it. 1055 } 1056 1057 if (i == e) 1058 PendingExports.push_back(Root); 1059 } 1060 1061 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1062 PendingExports); 1063 PendingExports.clear(); 1064 DAG.setRoot(Root); 1065 return Root; 1066 } 1067 1068 void SelectionDAGBuilder::visit(const Instruction &I) { 1069 // Set up outgoing PHI node register values before emitting the terminator. 1070 if (I.isTerminator()) { 1071 HandlePHINodesInSuccessorBlocks(I.getParent()); 1072 } 1073 1074 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1075 if (!isa<DbgInfoIntrinsic>(I)) 1076 ++SDNodeOrder; 1077 1078 CurInst = &I; 1079 1080 visit(I.getOpcode(), I); 1081 1082 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1083 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1084 // maps to this instruction. 1085 // TODO: We could handle all flags (nsw, etc) here. 1086 // TODO: If an IR instruction maps to >1 node, only the final node will have 1087 // flags set. 1088 if (SDNode *Node = getNodeForIRValue(&I)) { 1089 SDNodeFlags IncomingFlags; 1090 IncomingFlags.copyFMF(*FPMO); 1091 if (!Node->getFlags().isDefined()) 1092 Node->setFlags(IncomingFlags); 1093 else 1094 Node->intersectFlagsWith(IncomingFlags); 1095 } 1096 } 1097 1098 if (!I.isTerminator() && !HasTailCall && 1099 !isStatepoint(&I)) // statepoints handle their exports internally 1100 CopyToExportRegsIfNeeded(&I); 1101 1102 CurInst = nullptr; 1103 } 1104 1105 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1106 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1107 } 1108 1109 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1110 // Note: this doesn't use InstVisitor, because it has to work with 1111 // ConstantExpr's in addition to instructions. 1112 switch (Opcode) { 1113 default: llvm_unreachable("Unknown instruction type encountered!"); 1114 // Build the switch statement using the Instruction.def file. 1115 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1116 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1117 #include "llvm/IR/Instruction.def" 1118 } 1119 } 1120 1121 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1122 const DIExpression *Expr) { 1123 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1124 const DbgValueInst *DI = DDI.getDI(); 1125 DIVariable *DanglingVariable = DI->getVariable(); 1126 DIExpression *DanglingExpr = DI->getExpression(); 1127 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1128 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1129 return true; 1130 } 1131 return false; 1132 }; 1133 1134 for (auto &DDIMI : DanglingDebugInfoMap) { 1135 DanglingDebugInfoVector &DDIV = DDIMI.second; 1136 1137 // If debug info is to be dropped, run it through final checks to see 1138 // whether it can be salvaged. 1139 for (auto &DDI : DDIV) 1140 if (isMatchingDbgValue(DDI)) 1141 salvageUnresolvedDbgValue(DDI); 1142 1143 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1144 } 1145 } 1146 1147 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1148 // generate the debug data structures now that we've seen its definition. 1149 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1150 SDValue Val) { 1151 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1152 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1153 return; 1154 1155 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1156 for (auto &DDI : DDIV) { 1157 const DbgValueInst *DI = DDI.getDI(); 1158 assert(DI && "Ill-formed DanglingDebugInfo"); 1159 DebugLoc dl = DDI.getdl(); 1160 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1161 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1162 DILocalVariable *Variable = DI->getVariable(); 1163 DIExpression *Expr = DI->getExpression(); 1164 assert(Variable->isValidLocationForIntrinsic(dl) && 1165 "Expected inlined-at fields to agree"); 1166 SDDbgValue *SDV; 1167 if (Val.getNode()) { 1168 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a 1169 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if 1170 // we couldn't resolve it directly when examining the DbgValue intrinsic 1171 // in the first place we should not be more successful here). Unless we 1172 // have some test case that prove this to be correct we should avoid 1173 // calling EmitFuncArgumentDbgValue here. 1174 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1175 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1176 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1177 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1178 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1179 // inserted after the definition of Val when emitting the instructions 1180 // after ISel. An alternative could be to teach 1181 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1182 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1183 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1184 << ValSDNodeOrder << "\n"); 1185 SDV = getDbgValue(Val, Variable, Expr, dl, 1186 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1187 DAG.AddDbgValue(SDV, Val.getNode(), false); 1188 } else 1189 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1190 << "in EmitFuncArgumentDbgValue\n"); 1191 } else { 1192 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1193 auto Undef = 1194 UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1195 auto SDV = 1196 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder); 1197 DAG.AddDbgValue(SDV, nullptr, false); 1198 } 1199 } 1200 DDIV.clear(); 1201 } 1202 1203 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) { 1204 Value *V = DDI.getDI()->getValue(); 1205 DILocalVariable *Var = DDI.getDI()->getVariable(); 1206 DIExpression *Expr = DDI.getDI()->getExpression(); 1207 DebugLoc DL = DDI.getdl(); 1208 DebugLoc InstDL = DDI.getDI()->getDebugLoc(); 1209 unsigned SDOrder = DDI.getSDNodeOrder(); 1210 1211 // Currently we consider only dbg.value intrinsics -- we tell the salvager 1212 // that DW_OP_stack_value is desired. 1213 assert(isa<DbgValueInst>(DDI.getDI())); 1214 bool StackValue = true; 1215 1216 // Can this Value can be encoded without any further work? 1217 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) 1218 return; 1219 1220 // Attempt to salvage back through as many instructions as possible. Bail if 1221 // a non-instruction is seen, such as a constant expression or global 1222 // variable. FIXME: Further work could recover those too. 1223 while (isa<Instruction>(V)) { 1224 Instruction &VAsInst = *cast<Instruction>(V); 1225 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue); 1226 1227 // If we cannot salvage any further, and haven't yet found a suitable debug 1228 // expression, bail out. 1229 if (!NewExpr) 1230 break; 1231 1232 // New value and expr now represent this debuginfo. 1233 V = VAsInst.getOperand(0); 1234 Expr = NewExpr; 1235 1236 // Some kind of simplification occurred: check whether the operand of the 1237 // salvaged debug expression can be encoded in this DAG. 1238 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) { 1239 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n " 1240 << DDI.getDI() << "\nBy stripping back to:\n " << V); 1241 return; 1242 } 1243 } 1244 1245 // This was the final opportunity to salvage this debug information, and it 1246 // couldn't be done. Place an undef DBG_VALUE at this location to terminate 1247 // any earlier variable location. 1248 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType()); 1249 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder); 1250 DAG.AddDbgValue(SDV, nullptr, false); 1251 1252 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI() 1253 << "\n"); 1254 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0) 1255 << "\n"); 1256 } 1257 1258 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var, 1259 DIExpression *Expr, DebugLoc dl, 1260 DebugLoc InstDL, unsigned Order) { 1261 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1262 SDDbgValue *SDV; 1263 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 1264 isa<ConstantPointerNull>(V)) { 1265 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder); 1266 DAG.AddDbgValue(SDV, nullptr, false); 1267 return true; 1268 } 1269 1270 // If the Value is a frame index, we can create a FrameIndex debug value 1271 // without relying on the DAG at all. 1272 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1273 auto SI = FuncInfo.StaticAllocaMap.find(AI); 1274 if (SI != FuncInfo.StaticAllocaMap.end()) { 1275 auto SDV = 1276 DAG.getFrameIndexDbgValue(Var, Expr, SI->second, 1277 /*IsIndirect*/ false, dl, SDNodeOrder); 1278 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 1279 // is still available even if the SDNode gets optimized out. 1280 DAG.AddDbgValue(SDV, nullptr, false); 1281 return true; 1282 } 1283 } 1284 1285 // Do not use getValue() in here; we don't want to generate code at 1286 // this point if it hasn't been done yet. 1287 SDValue N = NodeMap[V]; 1288 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 1289 N = UnusedArgNodeMap[V]; 1290 if (N.getNode()) { 1291 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N)) 1292 return true; 1293 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder); 1294 DAG.AddDbgValue(SDV, N.getNode(), false); 1295 return true; 1296 } 1297 1298 // Special rules apply for the first dbg.values of parameter variables in a 1299 // function. Identify them by the fact they reference Argument Values, that 1300 // they're parameters, and they are parameters of the current function. We 1301 // need to let them dangle until they get an SDNode. 1302 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() && 1303 !InstDL.getInlinedAt(); 1304 if (!IsParamOfFunc) { 1305 // The value is not used in this block yet (or it would have an SDNode). 1306 // We still want the value to appear for the user if possible -- if it has 1307 // an associated VReg, we can refer to that instead. 1308 auto VMI = FuncInfo.ValueMap.find(V); 1309 if (VMI != FuncInfo.ValueMap.end()) { 1310 unsigned Reg = VMI->second; 1311 // If this is a PHI node, it may be split up into several MI PHI nodes 1312 // (in FunctionLoweringInfo::set). 1313 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 1314 V->getType(), None); 1315 if (RFV.occupiesMultipleRegs()) { 1316 unsigned Offset = 0; 1317 unsigned BitsToDescribe = 0; 1318 if (auto VarSize = Var->getSizeInBits()) 1319 BitsToDescribe = *VarSize; 1320 if (auto Fragment = Expr->getFragmentInfo()) 1321 BitsToDescribe = Fragment->SizeInBits; 1322 for (auto RegAndSize : RFV.getRegsAndSizes()) { 1323 unsigned RegisterSize = RegAndSize.second; 1324 // Bail out if all bits are described already. 1325 if (Offset >= BitsToDescribe) 1326 break; 1327 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 1328 ? BitsToDescribe - Offset 1329 : RegisterSize; 1330 auto FragmentExpr = DIExpression::createFragmentExpression( 1331 Expr, Offset, FragmentSize); 1332 if (!FragmentExpr) 1333 continue; 1334 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first, 1335 false, dl, SDNodeOrder); 1336 DAG.AddDbgValue(SDV, nullptr, false); 1337 Offset += RegisterSize; 1338 } 1339 } else { 1340 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder); 1341 DAG.AddDbgValue(SDV, nullptr, false); 1342 } 1343 return true; 1344 } 1345 } 1346 1347 return false; 1348 } 1349 1350 void SelectionDAGBuilder::resolveOrClearDbgInfo() { 1351 // Try to fixup any remaining dangling debug info -- and drop it if we can't. 1352 for (auto &Pair : DanglingDebugInfoMap) 1353 for (auto &DDI : Pair.second) 1354 salvageUnresolvedDbgValue(DDI); 1355 clearDanglingDebugInfo(); 1356 } 1357 1358 /// getCopyFromRegs - If there was virtual register allocated for the value V 1359 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1360 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1361 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1362 SDValue Result; 1363 1364 if (It != FuncInfo.ValueMap.end()) { 1365 unsigned InReg = It->second; 1366 1367 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1368 DAG.getDataLayout(), InReg, Ty, 1369 None); // This is not an ABI copy. 1370 SDValue Chain = DAG.getEntryNode(); 1371 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1372 V); 1373 resolveDanglingDebugInfo(V, Result); 1374 } 1375 1376 return Result; 1377 } 1378 1379 /// getValue - Return an SDValue for the given Value. 1380 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1381 // If we already have an SDValue for this value, use it. It's important 1382 // to do this first, so that we don't create a CopyFromReg if we already 1383 // have a regular SDValue. 1384 SDValue &N = NodeMap[V]; 1385 if (N.getNode()) return N; 1386 1387 // If there's a virtual register allocated and initialized for this 1388 // value, use it. 1389 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1390 return copyFromReg; 1391 1392 // Otherwise create a new SDValue and remember it. 1393 SDValue Val = getValueImpl(V); 1394 NodeMap[V] = Val; 1395 resolveDanglingDebugInfo(V, Val); 1396 return Val; 1397 } 1398 1399 // Return true if SDValue exists for the given Value 1400 bool SelectionDAGBuilder::findValue(const Value *V) const { 1401 return (NodeMap.find(V) != NodeMap.end()) || 1402 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1403 } 1404 1405 /// getNonRegisterValue - Return an SDValue for the given Value, but 1406 /// don't look in FuncInfo.ValueMap for a virtual register. 1407 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1408 // If we already have an SDValue for this value, use it. 1409 SDValue &N = NodeMap[V]; 1410 if (N.getNode()) { 1411 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1412 // Remove the debug location from the node as the node is about to be used 1413 // in a location which may differ from the original debug location. This 1414 // is relevant to Constant and ConstantFP nodes because they can appear 1415 // as constant expressions inside PHI nodes. 1416 N->setDebugLoc(DebugLoc()); 1417 } 1418 return N; 1419 } 1420 1421 // Otherwise create a new SDValue and remember it. 1422 SDValue Val = getValueImpl(V); 1423 NodeMap[V] = Val; 1424 resolveDanglingDebugInfo(V, Val); 1425 return Val; 1426 } 1427 1428 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1429 /// Create an SDValue for the given value. 1430 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1431 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1432 1433 if (const Constant *C = dyn_cast<Constant>(V)) { 1434 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1435 1436 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1437 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1438 1439 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1440 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1441 1442 if (isa<ConstantPointerNull>(C)) { 1443 unsigned AS = V->getType()->getPointerAddressSpace(); 1444 return DAG.getConstant(0, getCurSDLoc(), 1445 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1446 } 1447 1448 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1449 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1450 1451 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1452 return DAG.getUNDEF(VT); 1453 1454 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1455 visit(CE->getOpcode(), *CE); 1456 SDValue N1 = NodeMap[V]; 1457 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1458 return N1; 1459 } 1460 1461 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1462 SmallVector<SDValue, 4> Constants; 1463 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1464 OI != OE; ++OI) { 1465 SDNode *Val = getValue(*OI).getNode(); 1466 // If the operand is an empty aggregate, there are no values. 1467 if (!Val) continue; 1468 // Add each leaf value from the operand to the Constants list 1469 // to form a flattened list of all the values. 1470 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1471 Constants.push_back(SDValue(Val, i)); 1472 } 1473 1474 return DAG.getMergeValues(Constants, getCurSDLoc()); 1475 } 1476 1477 if (const ConstantDataSequential *CDS = 1478 dyn_cast<ConstantDataSequential>(C)) { 1479 SmallVector<SDValue, 4> Ops; 1480 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1481 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1482 // Add each leaf value from the operand to the Constants list 1483 // to form a flattened list of all the values. 1484 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1485 Ops.push_back(SDValue(Val, i)); 1486 } 1487 1488 if (isa<ArrayType>(CDS->getType())) 1489 return DAG.getMergeValues(Ops, getCurSDLoc()); 1490 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1491 } 1492 1493 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1494 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1495 "Unknown struct or array constant!"); 1496 1497 SmallVector<EVT, 4> ValueVTs; 1498 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1499 unsigned NumElts = ValueVTs.size(); 1500 if (NumElts == 0) 1501 return SDValue(); // empty struct 1502 SmallVector<SDValue, 4> Constants(NumElts); 1503 for (unsigned i = 0; i != NumElts; ++i) { 1504 EVT EltVT = ValueVTs[i]; 1505 if (isa<UndefValue>(C)) 1506 Constants[i] = DAG.getUNDEF(EltVT); 1507 else if (EltVT.isFloatingPoint()) 1508 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1509 else 1510 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1511 } 1512 1513 return DAG.getMergeValues(Constants, getCurSDLoc()); 1514 } 1515 1516 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1517 return DAG.getBlockAddress(BA, VT); 1518 1519 VectorType *VecTy = cast<VectorType>(V->getType()); 1520 unsigned NumElements = VecTy->getNumElements(); 1521 1522 // Now that we know the number and type of the elements, get that number of 1523 // elements into the Ops array based on what kind of constant it is. 1524 SmallVector<SDValue, 16> Ops; 1525 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1526 for (unsigned i = 0; i != NumElements; ++i) 1527 Ops.push_back(getValue(CV->getOperand(i))); 1528 } else { 1529 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1530 EVT EltVT = 1531 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1532 1533 SDValue Op; 1534 if (EltVT.isFloatingPoint()) 1535 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1536 else 1537 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1538 Ops.assign(NumElements, Op); 1539 } 1540 1541 // Create a BUILD_VECTOR node. 1542 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1543 } 1544 1545 // If this is a static alloca, generate it as the frameindex instead of 1546 // computation. 1547 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1548 DenseMap<const AllocaInst*, int>::iterator SI = 1549 FuncInfo.StaticAllocaMap.find(AI); 1550 if (SI != FuncInfo.StaticAllocaMap.end()) 1551 return DAG.getFrameIndex(SI->second, 1552 TLI.getFrameIndexTy(DAG.getDataLayout())); 1553 } 1554 1555 // If this is an instruction which fast-isel has deferred, select it now. 1556 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1557 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1558 1559 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1560 Inst->getType(), getABIRegCopyCC(V)); 1561 SDValue Chain = DAG.getEntryNode(); 1562 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1563 } 1564 1565 llvm_unreachable("Can't get register for value!"); 1566 } 1567 1568 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1569 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1570 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1571 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1572 bool IsSEH = isAsynchronousEHPersonality(Pers); 1573 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1574 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1575 if (!IsSEH) 1576 CatchPadMBB->setIsEHScopeEntry(); 1577 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1578 if (IsMSVCCXX || IsCoreCLR) 1579 CatchPadMBB->setIsEHFuncletEntry(); 1580 // Wasm does not need catchpads anymore 1581 if (!IsWasmCXX) 1582 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1583 getControlRoot())); 1584 } 1585 1586 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1587 // Update machine-CFG edge. 1588 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1589 FuncInfo.MBB->addSuccessor(TargetMBB); 1590 1591 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1592 bool IsSEH = isAsynchronousEHPersonality(Pers); 1593 if (IsSEH) { 1594 // If this is not a fall-through branch or optimizations are switched off, 1595 // emit the branch. 1596 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1597 TM.getOptLevel() == CodeGenOpt::None) 1598 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1599 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1600 return; 1601 } 1602 1603 // Figure out the funclet membership for the catchret's successor. 1604 // This will be used by the FuncletLayout pass to determine how to order the 1605 // BB's. 1606 // A 'catchret' returns to the outer scope's color. 1607 Value *ParentPad = I.getCatchSwitchParentPad(); 1608 const BasicBlock *SuccessorColor; 1609 if (isa<ConstantTokenNone>(ParentPad)) 1610 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1611 else 1612 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1613 assert(SuccessorColor && "No parent funclet for catchret!"); 1614 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1615 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1616 1617 // Create the terminator node. 1618 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1619 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1620 DAG.getBasicBlock(SuccessorColorMBB)); 1621 DAG.setRoot(Ret); 1622 } 1623 1624 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1625 // Don't emit any special code for the cleanuppad instruction. It just marks 1626 // the start of an EH scope/funclet. 1627 FuncInfo.MBB->setIsEHScopeEntry(); 1628 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1629 if (Pers != EHPersonality::Wasm_CXX) { 1630 FuncInfo.MBB->setIsEHFuncletEntry(); 1631 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1632 } 1633 } 1634 1635 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and 1636 // the control flow always stops at the single catch pad, as it does for a 1637 // cleanup pad. In case the exception caught is not of the types the catch pad 1638 // catches, it will be rethrown by a rethrow. 1639 static void findWasmUnwindDestinations( 1640 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1641 BranchProbability Prob, 1642 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1643 &UnwindDests) { 1644 while (EHPadBB) { 1645 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1646 if (isa<CleanupPadInst>(Pad)) { 1647 // Stop on cleanup pads. 1648 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1649 UnwindDests.back().first->setIsEHScopeEntry(); 1650 break; 1651 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1652 // Add the catchpad handlers to the possible destinations. We don't 1653 // continue to the unwind destination of the catchswitch for wasm. 1654 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1655 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1656 UnwindDests.back().first->setIsEHScopeEntry(); 1657 } 1658 break; 1659 } else { 1660 continue; 1661 } 1662 } 1663 } 1664 1665 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1666 /// many places it could ultimately go. In the IR, we have a single unwind 1667 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1668 /// This function skips over imaginary basic blocks that hold catchswitch 1669 /// instructions, and finds all the "real" machine 1670 /// basic block destinations. As those destinations may not be successors of 1671 /// EHPadBB, here we also calculate the edge probability to those destinations. 1672 /// The passed-in Prob is the edge probability to EHPadBB. 1673 static void findUnwindDestinations( 1674 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1675 BranchProbability Prob, 1676 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1677 &UnwindDests) { 1678 EHPersonality Personality = 1679 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1680 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1681 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1682 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1683 bool IsSEH = isAsynchronousEHPersonality(Personality); 1684 1685 if (IsWasmCXX) { 1686 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests); 1687 assert(UnwindDests.size() <= 1 && 1688 "There should be at most one unwind destination for wasm"); 1689 return; 1690 } 1691 1692 while (EHPadBB) { 1693 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1694 BasicBlock *NewEHPadBB = nullptr; 1695 if (isa<LandingPadInst>(Pad)) { 1696 // Stop on landingpads. They are not funclets. 1697 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1698 break; 1699 } else if (isa<CleanupPadInst>(Pad)) { 1700 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1701 // personalities. 1702 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1703 UnwindDests.back().first->setIsEHScopeEntry(); 1704 UnwindDests.back().first->setIsEHFuncletEntry(); 1705 break; 1706 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1707 // Add the catchpad handlers to the possible destinations. 1708 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1709 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1710 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1711 if (IsMSVCCXX || IsCoreCLR) 1712 UnwindDests.back().first->setIsEHFuncletEntry(); 1713 if (!IsSEH) 1714 UnwindDests.back().first->setIsEHScopeEntry(); 1715 } 1716 NewEHPadBB = CatchSwitch->getUnwindDest(); 1717 } else { 1718 continue; 1719 } 1720 1721 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1722 if (BPI && NewEHPadBB) 1723 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1724 EHPadBB = NewEHPadBB; 1725 } 1726 } 1727 1728 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1729 // Update successor info. 1730 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1731 auto UnwindDest = I.getUnwindDest(); 1732 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1733 BranchProbability UnwindDestProb = 1734 (BPI && UnwindDest) 1735 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1736 : BranchProbability::getZero(); 1737 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1738 for (auto &UnwindDest : UnwindDests) { 1739 UnwindDest.first->setIsEHPad(); 1740 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1741 } 1742 FuncInfo.MBB->normalizeSuccProbs(); 1743 1744 // Create the terminator node. 1745 SDValue Ret = 1746 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1747 DAG.setRoot(Ret); 1748 } 1749 1750 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1751 report_fatal_error("visitCatchSwitch not yet implemented!"); 1752 } 1753 1754 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1756 auto &DL = DAG.getDataLayout(); 1757 SDValue Chain = getControlRoot(); 1758 SmallVector<ISD::OutputArg, 8> Outs; 1759 SmallVector<SDValue, 8> OutVals; 1760 1761 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1762 // lower 1763 // 1764 // %val = call <ty> @llvm.experimental.deoptimize() 1765 // ret <ty> %val 1766 // 1767 // differently. 1768 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1769 LowerDeoptimizingReturn(); 1770 return; 1771 } 1772 1773 if (!FuncInfo.CanLowerReturn) { 1774 unsigned DemoteReg = FuncInfo.DemoteRegister; 1775 const Function *F = I.getParent()->getParent(); 1776 1777 // Emit a store of the return value through the virtual register. 1778 // Leave Outs empty so that LowerReturn won't try to load return 1779 // registers the usual way. 1780 SmallVector<EVT, 1> PtrValueVTs; 1781 ComputeValueVTs(TLI, DL, 1782 F->getReturnType()->getPointerTo( 1783 DAG.getDataLayout().getAllocaAddrSpace()), 1784 PtrValueVTs); 1785 1786 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1787 DemoteReg, PtrValueVTs[0]); 1788 SDValue RetOp = getValue(I.getOperand(0)); 1789 1790 SmallVector<EVT, 4> ValueVTs; 1791 SmallVector<uint64_t, 4> Offsets; 1792 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1793 unsigned NumValues = ValueVTs.size(); 1794 1795 SmallVector<SDValue, 4> Chains(NumValues); 1796 for (unsigned i = 0; i != NumValues; ++i) { 1797 // An aggregate return value cannot wrap around the address space, so 1798 // offsets to its parts don't wrap either. 1799 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1800 Chains[i] = DAG.getStore( 1801 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1802 // FIXME: better loc info would be nice. 1803 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1804 } 1805 1806 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1807 MVT::Other, Chains); 1808 } else if (I.getNumOperands() != 0) { 1809 SmallVector<EVT, 4> ValueVTs; 1810 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1811 unsigned NumValues = ValueVTs.size(); 1812 if (NumValues) { 1813 SDValue RetOp = getValue(I.getOperand(0)); 1814 1815 const Function *F = I.getParent()->getParent(); 1816 1817 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1818 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1819 Attribute::SExt)) 1820 ExtendKind = ISD::SIGN_EXTEND; 1821 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1822 Attribute::ZExt)) 1823 ExtendKind = ISD::ZERO_EXTEND; 1824 1825 LLVMContext &Context = F->getContext(); 1826 bool RetInReg = F->getAttributes().hasAttribute( 1827 AttributeList::ReturnIndex, Attribute::InReg); 1828 1829 for (unsigned j = 0; j != NumValues; ++j) { 1830 EVT VT = ValueVTs[j]; 1831 1832 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1833 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1834 1835 CallingConv::ID CC = F->getCallingConv(); 1836 1837 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1838 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1839 SmallVector<SDValue, 4> Parts(NumParts); 1840 getCopyToParts(DAG, getCurSDLoc(), 1841 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1842 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1843 1844 // 'inreg' on function refers to return value 1845 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1846 if (RetInReg) 1847 Flags.setInReg(); 1848 1849 // Propagate extension type if any 1850 if (ExtendKind == ISD::SIGN_EXTEND) 1851 Flags.setSExt(); 1852 else if (ExtendKind == ISD::ZERO_EXTEND) 1853 Flags.setZExt(); 1854 1855 for (unsigned i = 0; i < NumParts; ++i) { 1856 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1857 VT, /*isfixed=*/true, 0, 0)); 1858 OutVals.push_back(Parts[i]); 1859 } 1860 } 1861 } 1862 } 1863 1864 // Push in swifterror virtual register as the last element of Outs. This makes 1865 // sure swifterror virtual register will be returned in the swifterror 1866 // physical register. 1867 const Function *F = I.getParent()->getParent(); 1868 if (TLI.supportSwiftError() && 1869 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1870 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1871 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1872 Flags.setSwiftError(); 1873 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1874 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1875 true /*isfixed*/, 1 /*origidx*/, 1876 0 /*partOffs*/)); 1877 // Create SDNode for the swifterror virtual register. 1878 OutVals.push_back( 1879 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1880 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1881 EVT(TLI.getPointerTy(DL)))); 1882 } 1883 1884 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1885 CallingConv::ID CallConv = 1886 DAG.getMachineFunction().getFunction().getCallingConv(); 1887 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1888 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1889 1890 // Verify that the target's LowerReturn behaved as expected. 1891 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1892 "LowerReturn didn't return a valid chain!"); 1893 1894 // Update the DAG with the new chain value resulting from return lowering. 1895 DAG.setRoot(Chain); 1896 } 1897 1898 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1899 /// created for it, emit nodes to copy the value into the virtual 1900 /// registers. 1901 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1902 // Skip empty types 1903 if (V->getType()->isEmptyTy()) 1904 return; 1905 1906 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1907 if (VMI != FuncInfo.ValueMap.end()) { 1908 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1909 CopyValueToVirtualRegister(V, VMI->second); 1910 } 1911 } 1912 1913 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1914 /// the current basic block, add it to ValueMap now so that we'll get a 1915 /// CopyTo/FromReg. 1916 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1917 // No need to export constants. 1918 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1919 1920 // Already exported? 1921 if (FuncInfo.isExportedInst(V)) return; 1922 1923 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1924 CopyValueToVirtualRegister(V, Reg); 1925 } 1926 1927 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1928 const BasicBlock *FromBB) { 1929 // The operands of the setcc have to be in this block. We don't know 1930 // how to export them from some other block. 1931 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1932 // Can export from current BB. 1933 if (VI->getParent() == FromBB) 1934 return true; 1935 1936 // Is already exported, noop. 1937 return FuncInfo.isExportedInst(V); 1938 } 1939 1940 // If this is an argument, we can export it if the BB is the entry block or 1941 // if it is already exported. 1942 if (isa<Argument>(V)) { 1943 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1944 return true; 1945 1946 // Otherwise, can only export this if it is already exported. 1947 return FuncInfo.isExportedInst(V); 1948 } 1949 1950 // Otherwise, constants can always be exported. 1951 return true; 1952 } 1953 1954 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1955 BranchProbability 1956 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1957 const MachineBasicBlock *Dst) const { 1958 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1959 const BasicBlock *SrcBB = Src->getBasicBlock(); 1960 const BasicBlock *DstBB = Dst->getBasicBlock(); 1961 if (!BPI) { 1962 // If BPI is not available, set the default probability as 1 / N, where N is 1963 // the number of successors. 1964 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1965 return BranchProbability(1, SuccSize); 1966 } 1967 return BPI->getEdgeProbability(SrcBB, DstBB); 1968 } 1969 1970 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1971 MachineBasicBlock *Dst, 1972 BranchProbability Prob) { 1973 if (!FuncInfo.BPI) 1974 Src->addSuccessorWithoutProb(Dst); 1975 else { 1976 if (Prob.isUnknown()) 1977 Prob = getEdgeProbability(Src, Dst); 1978 Src->addSuccessor(Dst, Prob); 1979 } 1980 } 1981 1982 static bool InBlock(const Value *V, const BasicBlock *BB) { 1983 if (const Instruction *I = dyn_cast<Instruction>(V)) 1984 return I->getParent() == BB; 1985 return true; 1986 } 1987 1988 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1989 /// This function emits a branch and is used at the leaves of an OR or an 1990 /// AND operator tree. 1991 void 1992 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1993 MachineBasicBlock *TBB, 1994 MachineBasicBlock *FBB, 1995 MachineBasicBlock *CurBB, 1996 MachineBasicBlock *SwitchBB, 1997 BranchProbability TProb, 1998 BranchProbability FProb, 1999 bool InvertCond) { 2000 const BasicBlock *BB = CurBB->getBasicBlock(); 2001 2002 // If the leaf of the tree is a comparison, merge the condition into 2003 // the caseblock. 2004 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 2005 // The operands of the cmp have to be in this block. We don't know 2006 // how to export them from some other block. If this is the first block 2007 // of the sequence, no exporting is needed. 2008 if (CurBB == SwitchBB || 2009 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 2010 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 2011 ISD::CondCode Condition; 2012 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 2013 ICmpInst::Predicate Pred = 2014 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 2015 Condition = getICmpCondCode(Pred); 2016 } else { 2017 const FCmpInst *FC = cast<FCmpInst>(Cond); 2018 FCmpInst::Predicate Pred = 2019 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 2020 Condition = getFCmpCondCode(Pred); 2021 if (TM.Options.NoNaNsFPMath) 2022 Condition = getFCmpCodeWithoutNaN(Condition); 2023 } 2024 2025 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 2026 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2027 SwitchCases.push_back(CB); 2028 return; 2029 } 2030 } 2031 2032 // Create a CaseBlock record representing this branch. 2033 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 2034 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 2035 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 2036 SwitchCases.push_back(CB); 2037 } 2038 2039 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 2040 MachineBasicBlock *TBB, 2041 MachineBasicBlock *FBB, 2042 MachineBasicBlock *CurBB, 2043 MachineBasicBlock *SwitchBB, 2044 Instruction::BinaryOps Opc, 2045 BranchProbability TProb, 2046 BranchProbability FProb, 2047 bool InvertCond) { 2048 // Skip over not part of the tree and remember to invert op and operands at 2049 // next level. 2050 Value *NotCond; 2051 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 2052 InBlock(NotCond, CurBB->getBasicBlock())) { 2053 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 2054 !InvertCond); 2055 return; 2056 } 2057 2058 const Instruction *BOp = dyn_cast<Instruction>(Cond); 2059 // Compute the effective opcode for Cond, taking into account whether it needs 2060 // to be inverted, e.g. 2061 // and (not (or A, B)), C 2062 // gets lowered as 2063 // and (and (not A, not B), C) 2064 unsigned BOpc = 0; 2065 if (BOp) { 2066 BOpc = BOp->getOpcode(); 2067 if (InvertCond) { 2068 if (BOpc == Instruction::And) 2069 BOpc = Instruction::Or; 2070 else if (BOpc == Instruction::Or) 2071 BOpc = Instruction::And; 2072 } 2073 } 2074 2075 // If this node is not part of the or/and tree, emit it as a branch. 2076 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 2077 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 2078 BOp->getParent() != CurBB->getBasicBlock() || 2079 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 2080 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 2081 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 2082 TProb, FProb, InvertCond); 2083 return; 2084 } 2085 2086 // Create TmpBB after CurBB. 2087 MachineFunction::iterator BBI(CurBB); 2088 MachineFunction &MF = DAG.getMachineFunction(); 2089 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 2090 CurBB->getParent()->insert(++BBI, TmpBB); 2091 2092 if (Opc == Instruction::Or) { 2093 // Codegen X | Y as: 2094 // BB1: 2095 // jmp_if_X TBB 2096 // jmp TmpBB 2097 // TmpBB: 2098 // jmp_if_Y TBB 2099 // jmp FBB 2100 // 2101 2102 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2103 // The requirement is that 2104 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 2105 // = TrueProb for original BB. 2106 // Assuming the original probabilities are A and B, one choice is to set 2107 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 2108 // A/(1+B) and 2B/(1+B). This choice assumes that 2109 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 2110 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 2111 // TmpBB, but the math is more complicated. 2112 2113 auto NewTrueProb = TProb / 2; 2114 auto NewFalseProb = TProb / 2 + FProb; 2115 // Emit the LHS condition. 2116 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 2117 NewTrueProb, NewFalseProb, InvertCond); 2118 2119 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 2120 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 2121 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2122 // Emit the RHS condition into TmpBB. 2123 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2124 Probs[0], Probs[1], InvertCond); 2125 } else { 2126 assert(Opc == Instruction::And && "Unknown merge op!"); 2127 // Codegen X & Y as: 2128 // BB1: 2129 // jmp_if_X TmpBB 2130 // jmp FBB 2131 // TmpBB: 2132 // jmp_if_Y TBB 2133 // jmp FBB 2134 // 2135 // This requires creation of TmpBB after CurBB. 2136 2137 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 2138 // The requirement is that 2139 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 2140 // = FalseProb for original BB. 2141 // Assuming the original probabilities are A and B, one choice is to set 2142 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 2143 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 2144 // TrueProb for BB1 * FalseProb for TmpBB. 2145 2146 auto NewTrueProb = TProb + FProb / 2; 2147 auto NewFalseProb = FProb / 2; 2148 // Emit the LHS condition. 2149 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 2150 NewTrueProb, NewFalseProb, InvertCond); 2151 2152 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 2153 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 2154 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 2155 // Emit the RHS condition into TmpBB. 2156 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 2157 Probs[0], Probs[1], InvertCond); 2158 } 2159 } 2160 2161 /// If the set of cases should be emitted as a series of branches, return true. 2162 /// If we should emit this as a bunch of and/or'd together conditions, return 2163 /// false. 2164 bool 2165 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 2166 if (Cases.size() != 2) return true; 2167 2168 // If this is two comparisons of the same values or'd or and'd together, they 2169 // will get folded into a single comparison, so don't emit two blocks. 2170 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 2171 Cases[0].CmpRHS == Cases[1].CmpRHS) || 2172 (Cases[0].CmpRHS == Cases[1].CmpLHS && 2173 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 2174 return false; 2175 } 2176 2177 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 2178 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 2179 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 2180 Cases[0].CC == Cases[1].CC && 2181 isa<Constant>(Cases[0].CmpRHS) && 2182 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 2183 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 2184 return false; 2185 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 2186 return false; 2187 } 2188 2189 return true; 2190 } 2191 2192 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 2193 MachineBasicBlock *BrMBB = FuncInfo.MBB; 2194 2195 // Update machine-CFG edges. 2196 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 2197 2198 if (I.isUnconditional()) { 2199 // Update machine-CFG edges. 2200 BrMBB->addSuccessor(Succ0MBB); 2201 2202 // If this is not a fall-through branch or optimizations are switched off, 2203 // emit the branch. 2204 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 2205 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2206 MVT::Other, getControlRoot(), 2207 DAG.getBasicBlock(Succ0MBB))); 2208 2209 return; 2210 } 2211 2212 // If this condition is one of the special cases we handle, do special stuff 2213 // now. 2214 const Value *CondVal = I.getCondition(); 2215 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2216 2217 // If this is a series of conditions that are or'd or and'd together, emit 2218 // this as a sequence of branches instead of setcc's with and/or operations. 2219 // As long as jumps are not expensive, this should improve performance. 2220 // For example, instead of something like: 2221 // cmp A, B 2222 // C = seteq 2223 // cmp D, E 2224 // F = setle 2225 // or C, F 2226 // jnz foo 2227 // Emit: 2228 // cmp A, B 2229 // je foo 2230 // cmp D, E 2231 // jle foo 2232 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2233 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2234 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2235 !I.getMetadata(LLVMContext::MD_unpredictable) && 2236 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2237 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2238 Opcode, 2239 getEdgeProbability(BrMBB, Succ0MBB), 2240 getEdgeProbability(BrMBB, Succ1MBB), 2241 /*InvertCond=*/false); 2242 // If the compares in later blocks need to use values not currently 2243 // exported from this block, export them now. This block should always 2244 // be the first entry. 2245 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2246 2247 // Allow some cases to be rejected. 2248 if (ShouldEmitAsBranches(SwitchCases)) { 2249 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2250 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2251 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2252 } 2253 2254 // Emit the branch for this block. 2255 visitSwitchCase(SwitchCases[0], BrMBB); 2256 SwitchCases.erase(SwitchCases.begin()); 2257 return; 2258 } 2259 2260 // Okay, we decided not to do this, remove any inserted MBB's and clear 2261 // SwitchCases. 2262 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2263 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2264 2265 SwitchCases.clear(); 2266 } 2267 } 2268 2269 // Create a CaseBlock record representing this branch. 2270 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2271 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2272 2273 // Use visitSwitchCase to actually insert the fast branch sequence for this 2274 // cond branch. 2275 visitSwitchCase(CB, BrMBB); 2276 } 2277 2278 /// visitSwitchCase - Emits the necessary code to represent a single node in 2279 /// the binary search tree resulting from lowering a switch instruction. 2280 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2281 MachineBasicBlock *SwitchBB) { 2282 SDValue Cond; 2283 SDValue CondLHS = getValue(CB.CmpLHS); 2284 SDLoc dl = CB.DL; 2285 2286 // Build the setcc now. 2287 if (!CB.CmpMHS) { 2288 // Fold "(X == true)" to X and "(X == false)" to !X to 2289 // handle common cases produced by branch lowering. 2290 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2291 CB.CC == ISD::SETEQ) 2292 Cond = CondLHS; 2293 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2294 CB.CC == ISD::SETEQ) { 2295 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2296 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2297 } else 2298 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2299 } else { 2300 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2301 2302 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2303 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2304 2305 SDValue CmpOp = getValue(CB.CmpMHS); 2306 EVT VT = CmpOp.getValueType(); 2307 2308 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2309 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2310 ISD::SETLE); 2311 } else { 2312 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2313 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2314 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2315 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2316 } 2317 } 2318 2319 // Update successor info 2320 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2321 // TrueBB and FalseBB are always different unless the incoming IR is 2322 // degenerate. This only happens when running llc on weird IR. 2323 if (CB.TrueBB != CB.FalseBB) 2324 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2325 SwitchBB->normalizeSuccProbs(); 2326 2327 // If the lhs block is the next block, invert the condition so that we can 2328 // fall through to the lhs instead of the rhs block. 2329 if (CB.TrueBB == NextBlock(SwitchBB)) { 2330 std::swap(CB.TrueBB, CB.FalseBB); 2331 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2332 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2333 } 2334 2335 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2336 MVT::Other, getControlRoot(), Cond, 2337 DAG.getBasicBlock(CB.TrueBB)); 2338 2339 // Insert the false branch. Do this even if it's a fall through branch, 2340 // this makes it easier to do DAG optimizations which require inverting 2341 // the branch condition. 2342 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2343 DAG.getBasicBlock(CB.FalseBB)); 2344 2345 DAG.setRoot(BrCond); 2346 } 2347 2348 /// visitJumpTable - Emit JumpTable node in the current MBB 2349 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2350 // Emit the code for the jump table 2351 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2352 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2353 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2354 JT.Reg, PTy); 2355 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2356 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2357 MVT::Other, Index.getValue(1), 2358 Table, Index); 2359 DAG.setRoot(BrJumpTable); 2360 } 2361 2362 /// visitJumpTableHeader - This function emits necessary code to produce index 2363 /// in the JumpTable from switch case. 2364 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2365 JumpTableHeader &JTH, 2366 MachineBasicBlock *SwitchBB) { 2367 SDLoc dl = getCurSDLoc(); 2368 2369 // Subtract the lowest switch case value from the value being switched on. 2370 SDValue SwitchOp = getValue(JTH.SValue); 2371 EVT VT = SwitchOp.getValueType(); 2372 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2373 DAG.getConstant(JTH.First, dl, VT)); 2374 2375 // The SDNode we just created, which holds the value being switched on minus 2376 // the smallest case value, needs to be copied to a virtual register so it 2377 // can be used as an index into the jump table in a subsequent basic block. 2378 // This value may be smaller or larger than the target's pointer type, and 2379 // therefore require extension or truncating. 2380 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2381 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2382 2383 unsigned JumpTableReg = 2384 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2385 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2386 JumpTableReg, SwitchOp); 2387 JT.Reg = JumpTableReg; 2388 2389 if (!JTH.OmitRangeCheck) { 2390 // Emit the range check for the jump table, and branch to the default block 2391 // for the switch statement if the value being switched on exceeds the 2392 // largest case in the switch. 2393 SDValue CMP = DAG.getSetCC( 2394 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2395 Sub.getValueType()), 2396 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2397 2398 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2399 MVT::Other, CopyTo, CMP, 2400 DAG.getBasicBlock(JT.Default)); 2401 2402 // Avoid emitting unnecessary branches to the next block. 2403 if (JT.MBB != NextBlock(SwitchBB)) 2404 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2405 DAG.getBasicBlock(JT.MBB)); 2406 2407 DAG.setRoot(BrCond); 2408 } else { 2409 // Avoid emitting unnecessary branches to the next block. 2410 if (JT.MBB != NextBlock(SwitchBB)) 2411 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo, 2412 DAG.getBasicBlock(JT.MBB))); 2413 else 2414 DAG.setRoot(CopyTo); 2415 } 2416 } 2417 2418 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2419 /// variable if there exists one. 2420 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2421 SDValue &Chain) { 2422 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2423 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2424 MachineFunction &MF = DAG.getMachineFunction(); 2425 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2426 MachineSDNode *Node = 2427 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2428 if (Global) { 2429 MachinePointerInfo MPInfo(Global); 2430 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2431 MachineMemOperand::MODereferenceable; 2432 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2433 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2434 DAG.setNodeMemRefs(Node, {MemRef}); 2435 } 2436 return SDValue(Node, 0); 2437 } 2438 2439 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2440 /// tail spliced into a stack protector check success bb. 2441 /// 2442 /// For a high level explanation of how this fits into the stack protector 2443 /// generation see the comment on the declaration of class 2444 /// StackProtectorDescriptor. 2445 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2446 MachineBasicBlock *ParentBB) { 2447 2448 // First create the loads to the guard/stack slot for the comparison. 2449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2450 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2451 2452 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2453 int FI = MFI.getStackProtectorIndex(); 2454 2455 SDValue Guard; 2456 SDLoc dl = getCurSDLoc(); 2457 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2458 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2459 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2460 2461 // Generate code to load the content of the guard slot. 2462 SDValue GuardVal = DAG.getLoad( 2463 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2464 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2465 MachineMemOperand::MOVolatile); 2466 2467 if (TLI.useStackGuardXorFP()) 2468 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2469 2470 // Retrieve guard check function, nullptr if instrumentation is inlined. 2471 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) { 2472 // The target provides a guard check function to validate the guard value. 2473 // Generate a call to that function with the content of the guard slot as 2474 // argument. 2475 FunctionType *FnTy = GuardCheckFn->getFunctionType(); 2476 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2477 2478 TargetLowering::ArgListTy Args; 2479 TargetLowering::ArgListEntry Entry; 2480 Entry.Node = GuardVal; 2481 Entry.Ty = FnTy->getParamType(0); 2482 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg)) 2483 Entry.IsInReg = true; 2484 Args.push_back(Entry); 2485 2486 TargetLowering::CallLoweringInfo CLI(DAG); 2487 CLI.setDebugLoc(getCurSDLoc()) 2488 .setChain(DAG.getEntryNode()) 2489 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(), 2490 getValue(GuardCheckFn), std::move(Args)); 2491 2492 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2493 DAG.setRoot(Result.second); 2494 return; 2495 } 2496 2497 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2498 // Otherwise, emit a volatile load to retrieve the stack guard value. 2499 SDValue Chain = DAG.getEntryNode(); 2500 if (TLI.useLoadStackGuardNode()) { 2501 Guard = getLoadStackGuard(DAG, dl, Chain); 2502 } else { 2503 const Value *IRGuard = TLI.getSDagStackGuard(M); 2504 SDValue GuardPtr = getValue(IRGuard); 2505 2506 Guard = 2507 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2508 Align, MachineMemOperand::MOVolatile); 2509 } 2510 2511 // Perform the comparison via a subtract/getsetcc. 2512 EVT VT = Guard.getValueType(); 2513 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2514 2515 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2516 *DAG.getContext(), 2517 Sub.getValueType()), 2518 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2519 2520 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2521 // branch to failure MBB. 2522 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2523 MVT::Other, GuardVal.getOperand(0), 2524 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2525 // Otherwise branch to success MBB. 2526 SDValue Br = DAG.getNode(ISD::BR, dl, 2527 MVT::Other, BrCond, 2528 DAG.getBasicBlock(SPD.getSuccessMBB())); 2529 2530 DAG.setRoot(Br); 2531 } 2532 2533 /// Codegen the failure basic block for a stack protector check. 2534 /// 2535 /// A failure stack protector machine basic block consists simply of a call to 2536 /// __stack_chk_fail(). 2537 /// 2538 /// For a high level explanation of how this fits into the stack protector 2539 /// generation see the comment on the declaration of class 2540 /// StackProtectorDescriptor. 2541 void 2542 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2544 SDValue Chain = 2545 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2546 None, false, getCurSDLoc(), false, false).second; 2547 // On PS4, the "return address" must still be within the calling function, 2548 // even if it's at the very end, so emit an explicit TRAP here. 2549 // Passing 'true' for doesNotReturn above won't generate the trap for us. 2550 if (TM.getTargetTriple().isPS4CPU()) 2551 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain); 2552 2553 DAG.setRoot(Chain); 2554 } 2555 2556 /// visitBitTestHeader - This function emits necessary code to produce value 2557 /// suitable for "bit tests" 2558 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2559 MachineBasicBlock *SwitchBB) { 2560 SDLoc dl = getCurSDLoc(); 2561 2562 // Subtract the minimum value 2563 SDValue SwitchOp = getValue(B.SValue); 2564 EVT VT = SwitchOp.getValueType(); 2565 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2566 DAG.getConstant(B.First, dl, VT)); 2567 2568 // Check range 2569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2570 SDValue RangeCmp = DAG.getSetCC( 2571 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2572 Sub.getValueType()), 2573 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2574 2575 // Determine the type of the test operands. 2576 bool UsePtrType = false; 2577 if (!TLI.isTypeLegal(VT)) 2578 UsePtrType = true; 2579 else { 2580 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2581 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2582 // Switch table case range are encoded into series of masks. 2583 // Just use pointer type, it's guaranteed to fit. 2584 UsePtrType = true; 2585 break; 2586 } 2587 } 2588 if (UsePtrType) { 2589 VT = TLI.getPointerTy(DAG.getDataLayout()); 2590 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2591 } 2592 2593 B.RegVT = VT.getSimpleVT(); 2594 B.Reg = FuncInfo.CreateReg(B.RegVT); 2595 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2596 2597 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2598 2599 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2600 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2601 SwitchBB->normalizeSuccProbs(); 2602 2603 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2604 MVT::Other, CopyTo, RangeCmp, 2605 DAG.getBasicBlock(B.Default)); 2606 2607 // Avoid emitting unnecessary branches to the next block. 2608 if (MBB != NextBlock(SwitchBB)) 2609 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2610 DAG.getBasicBlock(MBB)); 2611 2612 DAG.setRoot(BrRange); 2613 } 2614 2615 /// visitBitTestCase - this function produces one "bit test" 2616 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2617 MachineBasicBlock* NextMBB, 2618 BranchProbability BranchProbToNext, 2619 unsigned Reg, 2620 BitTestCase &B, 2621 MachineBasicBlock *SwitchBB) { 2622 SDLoc dl = getCurSDLoc(); 2623 MVT VT = BB.RegVT; 2624 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2625 SDValue Cmp; 2626 unsigned PopCount = countPopulation(B.Mask); 2627 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2628 if (PopCount == 1) { 2629 // Testing for a single bit; just compare the shift count with what it 2630 // would need to be to shift a 1 bit in that position. 2631 Cmp = DAG.getSetCC( 2632 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2633 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2634 ISD::SETEQ); 2635 } else if (PopCount == BB.Range) { 2636 // There is only one zero bit in the range, test for it directly. 2637 Cmp = DAG.getSetCC( 2638 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2639 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2640 ISD::SETNE); 2641 } else { 2642 // Make desired shift 2643 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2644 DAG.getConstant(1, dl, VT), ShiftOp); 2645 2646 // Emit bit tests and jumps 2647 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2648 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2649 Cmp = DAG.getSetCC( 2650 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2651 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2652 } 2653 2654 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2655 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2656 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2657 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2658 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2659 // one as they are relative probabilities (and thus work more like weights), 2660 // and hence we need to normalize them to let the sum of them become one. 2661 SwitchBB->normalizeSuccProbs(); 2662 2663 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2664 MVT::Other, getControlRoot(), 2665 Cmp, DAG.getBasicBlock(B.TargetBB)); 2666 2667 // Avoid emitting unnecessary branches to the next block. 2668 if (NextMBB != NextBlock(SwitchBB)) 2669 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2670 DAG.getBasicBlock(NextMBB)); 2671 2672 DAG.setRoot(BrAnd); 2673 } 2674 2675 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2676 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2677 2678 // Retrieve successors. Look through artificial IR level blocks like 2679 // catchswitch for successors. 2680 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2681 const BasicBlock *EHPadBB = I.getSuccessor(1); 2682 2683 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2684 // have to do anything here to lower funclet bundles. 2685 assert(!I.hasOperandBundlesOtherThan( 2686 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2687 "Cannot lower invokes with arbitrary operand bundles yet!"); 2688 2689 const Value *Callee(I.getCalledValue()); 2690 const Function *Fn = dyn_cast<Function>(Callee); 2691 if (isa<InlineAsm>(Callee)) 2692 visitInlineAsm(&I); 2693 else if (Fn && Fn->isIntrinsic()) { 2694 switch (Fn->getIntrinsicID()) { 2695 default: 2696 llvm_unreachable("Cannot invoke this intrinsic"); 2697 case Intrinsic::donothing: 2698 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2699 break; 2700 case Intrinsic::experimental_patchpoint_void: 2701 case Intrinsic::experimental_patchpoint_i64: 2702 visitPatchpoint(&I, EHPadBB); 2703 break; 2704 case Intrinsic::experimental_gc_statepoint: 2705 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2706 break; 2707 case Intrinsic::wasm_rethrow_in_catch: { 2708 // This is usually done in visitTargetIntrinsic, but this intrinsic is 2709 // special because it can be invoked, so we manually lower it to a DAG 2710 // node here. 2711 SmallVector<SDValue, 8> Ops; 2712 Ops.push_back(getRoot()); // inchain 2713 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2714 Ops.push_back( 2715 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(), 2716 TLI.getPointerTy(DAG.getDataLayout()))); 2717 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain 2718 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops)); 2719 break; 2720 } 2721 } 2722 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2723 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2724 // Eventually we will support lowering the @llvm.experimental.deoptimize 2725 // intrinsic, and right now there are no plans to support other intrinsics 2726 // with deopt state. 2727 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2728 } else { 2729 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2730 } 2731 2732 // If the value of the invoke is used outside of its defining block, make it 2733 // available as a virtual register. 2734 // We already took care of the exported value for the statepoint instruction 2735 // during call to the LowerStatepoint. 2736 if (!isStatepoint(I)) { 2737 CopyToExportRegsIfNeeded(&I); 2738 } 2739 2740 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2741 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2742 BranchProbability EHPadBBProb = 2743 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2744 : BranchProbability::getZero(); 2745 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2746 2747 // Update successor info. 2748 addSuccessorWithProb(InvokeMBB, Return); 2749 for (auto &UnwindDest : UnwindDests) { 2750 UnwindDest.first->setIsEHPad(); 2751 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2752 } 2753 InvokeMBB->normalizeSuccProbs(); 2754 2755 // Drop into normal successor. 2756 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(), 2757 DAG.getBasicBlock(Return))); 2758 } 2759 2760 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) { 2761 MachineBasicBlock *CallBrMBB = FuncInfo.MBB; 2762 2763 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2764 // have to do anything here to lower funclet bundles. 2765 assert(!I.hasOperandBundlesOtherThan( 2766 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2767 "Cannot lower callbrs with arbitrary operand bundles yet!"); 2768 2769 assert(isa<InlineAsm>(I.getCalledValue()) && 2770 "Only know how to handle inlineasm callbr"); 2771 visitInlineAsm(&I); 2772 2773 // Retrieve successors. 2774 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()]; 2775 2776 // Update successor info. 2777 addSuccessorWithProb(CallBrMBB, Return); 2778 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) { 2779 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)]; 2780 addSuccessorWithProb(CallBrMBB, Target); 2781 } 2782 CallBrMBB->normalizeSuccProbs(); 2783 2784 // Drop into default successor. 2785 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2786 MVT::Other, getControlRoot(), 2787 DAG.getBasicBlock(Return))); 2788 } 2789 2790 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2791 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2792 } 2793 2794 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2795 assert(FuncInfo.MBB->isEHPad() && 2796 "Call to landingpad not in landing pad!"); 2797 2798 // If there aren't registers to copy the values into (e.g., during SjLj 2799 // exceptions), then don't bother to create these DAG nodes. 2800 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2801 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2802 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2803 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2804 return; 2805 2806 // If landingpad's return type is token type, we don't create DAG nodes 2807 // for its exception pointer and selector value. The extraction of exception 2808 // pointer or selector value from token type landingpads is not currently 2809 // supported. 2810 if (LP.getType()->isTokenTy()) 2811 return; 2812 2813 SmallVector<EVT, 2> ValueVTs; 2814 SDLoc dl = getCurSDLoc(); 2815 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2816 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2817 2818 // Get the two live-in registers as SDValues. The physregs have already been 2819 // copied into virtual registers. 2820 SDValue Ops[2]; 2821 if (FuncInfo.ExceptionPointerVirtReg) { 2822 Ops[0] = DAG.getZExtOrTrunc( 2823 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2824 FuncInfo.ExceptionPointerVirtReg, 2825 TLI.getPointerTy(DAG.getDataLayout())), 2826 dl, ValueVTs[0]); 2827 } else { 2828 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2829 } 2830 Ops[1] = DAG.getZExtOrTrunc( 2831 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2832 FuncInfo.ExceptionSelectorVirtReg, 2833 TLI.getPointerTy(DAG.getDataLayout())), 2834 dl, ValueVTs[1]); 2835 2836 // Merge into one. 2837 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2838 DAG.getVTList(ValueVTs), Ops); 2839 setValue(&LP, Res); 2840 } 2841 2842 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2843 #ifndef NDEBUG 2844 for (const CaseCluster &CC : Clusters) 2845 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2846 #endif 2847 2848 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2849 return a.Low->getValue().slt(b.Low->getValue()); 2850 }); 2851 2852 // Merge adjacent clusters with the same destination. 2853 const unsigned N = Clusters.size(); 2854 unsigned DstIndex = 0; 2855 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2856 CaseCluster &CC = Clusters[SrcIndex]; 2857 const ConstantInt *CaseVal = CC.Low; 2858 MachineBasicBlock *Succ = CC.MBB; 2859 2860 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2861 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2862 // If this case has the same successor and is a neighbour, merge it into 2863 // the previous cluster. 2864 Clusters[DstIndex - 1].High = CaseVal; 2865 Clusters[DstIndex - 1].Prob += CC.Prob; 2866 } else { 2867 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2868 sizeof(Clusters[SrcIndex])); 2869 } 2870 } 2871 Clusters.resize(DstIndex); 2872 } 2873 2874 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2875 MachineBasicBlock *Last) { 2876 // Update JTCases. 2877 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2878 if (JTCases[i].first.HeaderBB == First) 2879 JTCases[i].first.HeaderBB = Last; 2880 2881 // Update BitTestCases. 2882 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2883 if (BitTestCases[i].Parent == First) 2884 BitTestCases[i].Parent = Last; 2885 } 2886 2887 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2888 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2889 2890 // Update machine-CFG edges with unique successors. 2891 SmallSet<BasicBlock*, 32> Done; 2892 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2893 BasicBlock *BB = I.getSuccessor(i); 2894 bool Inserted = Done.insert(BB).second; 2895 if (!Inserted) 2896 continue; 2897 2898 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2899 addSuccessorWithProb(IndirectBrMBB, Succ); 2900 } 2901 IndirectBrMBB->normalizeSuccProbs(); 2902 2903 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2904 MVT::Other, getControlRoot(), 2905 getValue(I.getAddress()))); 2906 } 2907 2908 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2909 if (!DAG.getTarget().Options.TrapUnreachable) 2910 return; 2911 2912 // We may be able to ignore unreachable behind a noreturn call. 2913 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2914 const BasicBlock &BB = *I.getParent(); 2915 if (&I != &BB.front()) { 2916 BasicBlock::const_iterator PredI = 2917 std::prev(BasicBlock::const_iterator(&I)); 2918 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2919 if (Call->doesNotReturn()) 2920 return; 2921 } 2922 } 2923 } 2924 2925 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2926 } 2927 2928 void SelectionDAGBuilder::visitFSub(const User &I) { 2929 // -0.0 - X --> fneg 2930 Type *Ty = I.getType(); 2931 if (isa<Constant>(I.getOperand(0)) && 2932 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2933 SDValue Op2 = getValue(I.getOperand(1)); 2934 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2935 Op2.getValueType(), Op2)); 2936 return; 2937 } 2938 2939 visitBinary(I, ISD::FSUB); 2940 } 2941 2942 /// Checks if the given instruction performs a vector reduction, in which case 2943 /// we have the freedom to alter the elements in the result as long as the 2944 /// reduction of them stays unchanged. 2945 static bool isVectorReductionOp(const User *I) { 2946 const Instruction *Inst = dyn_cast<Instruction>(I); 2947 if (!Inst || !Inst->getType()->isVectorTy()) 2948 return false; 2949 2950 auto OpCode = Inst->getOpcode(); 2951 switch (OpCode) { 2952 case Instruction::Add: 2953 case Instruction::Mul: 2954 case Instruction::And: 2955 case Instruction::Or: 2956 case Instruction::Xor: 2957 break; 2958 case Instruction::FAdd: 2959 case Instruction::FMul: 2960 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2961 if (FPOp->getFastMathFlags().isFast()) 2962 break; 2963 LLVM_FALLTHROUGH; 2964 default: 2965 return false; 2966 } 2967 2968 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2969 // Ensure the reduction size is a power of 2. 2970 if (!isPowerOf2_32(ElemNum)) 2971 return false; 2972 2973 unsigned ElemNumToReduce = ElemNum; 2974 2975 // Do DFS search on the def-use chain from the given instruction. We only 2976 // allow four kinds of operations during the search until we reach the 2977 // instruction that extracts the first element from the vector: 2978 // 2979 // 1. The reduction operation of the same opcode as the given instruction. 2980 // 2981 // 2. PHI node. 2982 // 2983 // 3. ShuffleVector instruction together with a reduction operation that 2984 // does a partial reduction. 2985 // 2986 // 4. ExtractElement that extracts the first element from the vector, and we 2987 // stop searching the def-use chain here. 2988 // 2989 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2990 // from 1-3 to the stack to continue the DFS. The given instruction is not 2991 // a reduction operation if we meet any other instructions other than those 2992 // listed above. 2993 2994 SmallVector<const User *, 16> UsersToVisit{Inst}; 2995 SmallPtrSet<const User *, 16> Visited; 2996 bool ReduxExtracted = false; 2997 2998 while (!UsersToVisit.empty()) { 2999 auto User = UsersToVisit.back(); 3000 UsersToVisit.pop_back(); 3001 if (!Visited.insert(User).second) 3002 continue; 3003 3004 for (const auto &U : User->users()) { 3005 auto Inst = dyn_cast<Instruction>(U); 3006 if (!Inst) 3007 return false; 3008 3009 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 3010 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 3011 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 3012 return false; 3013 UsersToVisit.push_back(U); 3014 } else if (const ShuffleVectorInst *ShufInst = 3015 dyn_cast<ShuffleVectorInst>(U)) { 3016 // Detect the following pattern: A ShuffleVector instruction together 3017 // with a reduction that do partial reduction on the first and second 3018 // ElemNumToReduce / 2 elements, and store the result in 3019 // ElemNumToReduce / 2 elements in another vector. 3020 3021 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 3022 if (ResultElements < ElemNum) 3023 return false; 3024 3025 if (ElemNumToReduce == 1) 3026 return false; 3027 if (!isa<UndefValue>(U->getOperand(1))) 3028 return false; 3029 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 3030 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 3031 return false; 3032 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 3033 if (ShufInst->getMaskValue(i) != -1) 3034 return false; 3035 3036 // There is only one user of this ShuffleVector instruction, which 3037 // must be a reduction operation. 3038 if (!U->hasOneUse()) 3039 return false; 3040 3041 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 3042 if (!U2 || U2->getOpcode() != OpCode) 3043 return false; 3044 3045 // Check operands of the reduction operation. 3046 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 3047 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 3048 UsersToVisit.push_back(U2); 3049 ElemNumToReduce /= 2; 3050 } else 3051 return false; 3052 } else if (isa<ExtractElementInst>(U)) { 3053 // At this moment we should have reduced all elements in the vector. 3054 if (ElemNumToReduce != 1) 3055 return false; 3056 3057 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 3058 if (!Val || !Val->isZero()) 3059 return false; 3060 3061 ReduxExtracted = true; 3062 } else 3063 return false; 3064 } 3065 } 3066 return ReduxExtracted; 3067 } 3068 3069 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 3070 SDNodeFlags Flags; 3071 3072 SDValue Op = getValue(I.getOperand(0)); 3073 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 3074 Op, Flags); 3075 setValue(&I, UnNodeValue); 3076 } 3077 3078 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 3079 SDNodeFlags Flags; 3080 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 3081 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 3082 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 3083 } 3084 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 3085 Flags.setExact(ExactOp->isExact()); 3086 } 3087 if (isVectorReductionOp(&I)) { 3088 Flags.setVectorReduction(true); 3089 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 3090 } 3091 3092 SDValue Op1 = getValue(I.getOperand(0)); 3093 SDValue Op2 = getValue(I.getOperand(1)); 3094 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 3095 Op1, Op2, Flags); 3096 setValue(&I, BinNodeValue); 3097 } 3098 3099 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 3100 SDValue Op1 = getValue(I.getOperand(0)); 3101 SDValue Op2 = getValue(I.getOperand(1)); 3102 3103 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 3104 Op1.getValueType(), DAG.getDataLayout()); 3105 3106 // Coerce the shift amount to the right type if we can. 3107 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 3108 unsigned ShiftSize = ShiftTy.getSizeInBits(); 3109 unsigned Op2Size = Op2.getValueSizeInBits(); 3110 SDLoc DL = getCurSDLoc(); 3111 3112 // If the operand is smaller than the shift count type, promote it. 3113 if (ShiftSize > Op2Size) 3114 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 3115 3116 // If the operand is larger than the shift count type but the shift 3117 // count type has enough bits to represent any shift value, truncate 3118 // it now. This is a common case and it exposes the truncate to 3119 // optimization early. 3120 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 3121 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 3122 // Otherwise we'll need to temporarily settle for some other convenient 3123 // type. Type legalization will make adjustments once the shiftee is split. 3124 else 3125 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 3126 } 3127 3128 bool nuw = false; 3129 bool nsw = false; 3130 bool exact = false; 3131 3132 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 3133 3134 if (const OverflowingBinaryOperator *OFBinOp = 3135 dyn_cast<const OverflowingBinaryOperator>(&I)) { 3136 nuw = OFBinOp->hasNoUnsignedWrap(); 3137 nsw = OFBinOp->hasNoSignedWrap(); 3138 } 3139 if (const PossiblyExactOperator *ExactOp = 3140 dyn_cast<const PossiblyExactOperator>(&I)) 3141 exact = ExactOp->isExact(); 3142 } 3143 SDNodeFlags Flags; 3144 Flags.setExact(exact); 3145 Flags.setNoSignedWrap(nsw); 3146 Flags.setNoUnsignedWrap(nuw); 3147 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 3148 Flags); 3149 setValue(&I, Res); 3150 } 3151 3152 void SelectionDAGBuilder::visitSDiv(const User &I) { 3153 SDValue Op1 = getValue(I.getOperand(0)); 3154 SDValue Op2 = getValue(I.getOperand(1)); 3155 3156 SDNodeFlags Flags; 3157 Flags.setExact(isa<PossiblyExactOperator>(&I) && 3158 cast<PossiblyExactOperator>(&I)->isExact()); 3159 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 3160 Op2, Flags)); 3161 } 3162 3163 void SelectionDAGBuilder::visitICmp(const User &I) { 3164 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 3165 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 3166 predicate = IC->getPredicate(); 3167 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 3168 predicate = ICmpInst::Predicate(IC->getPredicate()); 3169 SDValue Op1 = getValue(I.getOperand(0)); 3170 SDValue Op2 = getValue(I.getOperand(1)); 3171 ISD::CondCode Opcode = getICmpCondCode(predicate); 3172 3173 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3174 I.getType()); 3175 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 3176 } 3177 3178 void SelectionDAGBuilder::visitFCmp(const User &I) { 3179 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 3180 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 3181 predicate = FC->getPredicate(); 3182 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 3183 predicate = FCmpInst::Predicate(FC->getPredicate()); 3184 SDValue Op1 = getValue(I.getOperand(0)); 3185 SDValue Op2 = getValue(I.getOperand(1)); 3186 3187 ISD::CondCode Condition = getFCmpCondCode(predicate); 3188 auto *FPMO = dyn_cast<FPMathOperator>(&I); 3189 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 3190 Condition = getFCmpCodeWithoutNaN(Condition); 3191 3192 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3193 I.getType()); 3194 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 3195 } 3196 3197 // Check if the condition of the select has one use or two users that are both 3198 // selects with the same condition. 3199 static bool hasOnlySelectUsers(const Value *Cond) { 3200 return llvm::all_of(Cond->users(), [](const Value *V) { 3201 return isa<SelectInst>(V); 3202 }); 3203 } 3204 3205 void SelectionDAGBuilder::visitSelect(const User &I) { 3206 SmallVector<EVT, 4> ValueVTs; 3207 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 3208 ValueVTs); 3209 unsigned NumValues = ValueVTs.size(); 3210 if (NumValues == 0) return; 3211 3212 SmallVector<SDValue, 4> Values(NumValues); 3213 SDValue Cond = getValue(I.getOperand(0)); 3214 SDValue LHSVal = getValue(I.getOperand(1)); 3215 SDValue RHSVal = getValue(I.getOperand(2)); 3216 auto BaseOps = {Cond}; 3217 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 3218 ISD::VSELECT : ISD::SELECT; 3219 3220 bool IsUnaryAbs = false; 3221 3222 // Min/max matching is only viable if all output VTs are the same. 3223 if (is_splat(ValueVTs)) { 3224 EVT VT = ValueVTs[0]; 3225 LLVMContext &Ctx = *DAG.getContext(); 3226 auto &TLI = DAG.getTargetLoweringInfo(); 3227 3228 // We care about the legality of the operation after it has been type 3229 // legalized. 3230 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 3231 VT != TLI.getTypeToTransformTo(Ctx, VT)) 3232 VT = TLI.getTypeToTransformTo(Ctx, VT); 3233 3234 // If the vselect is legal, assume we want to leave this as a vector setcc + 3235 // vselect. Otherwise, if this is going to be scalarized, we want to see if 3236 // min/max is legal on the scalar type. 3237 bool UseScalarMinMax = VT.isVector() && 3238 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 3239 3240 Value *LHS, *RHS; 3241 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 3242 ISD::NodeType Opc = ISD::DELETED_NODE; 3243 switch (SPR.Flavor) { 3244 case SPF_UMAX: Opc = ISD::UMAX; break; 3245 case SPF_UMIN: Opc = ISD::UMIN; break; 3246 case SPF_SMAX: Opc = ISD::SMAX; break; 3247 case SPF_SMIN: Opc = ISD::SMIN; break; 3248 case SPF_FMINNUM: 3249 switch (SPR.NaNBehavior) { 3250 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3251 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 3252 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 3253 case SPNB_RETURNS_ANY: { 3254 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 3255 Opc = ISD::FMINNUM; 3256 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 3257 Opc = ISD::FMINIMUM; 3258 else if (UseScalarMinMax) 3259 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 3260 ISD::FMINNUM : ISD::FMINIMUM; 3261 break; 3262 } 3263 } 3264 break; 3265 case SPF_FMAXNUM: 3266 switch (SPR.NaNBehavior) { 3267 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 3268 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3269 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3270 case SPNB_RETURNS_ANY: 3271 3272 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3273 Opc = ISD::FMAXNUM; 3274 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3275 Opc = ISD::FMAXIMUM; 3276 else if (UseScalarMinMax) 3277 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3278 ISD::FMAXNUM : ISD::FMAXIMUM; 3279 break; 3280 } 3281 break; 3282 case SPF_ABS: 3283 IsUnaryAbs = true; 3284 Opc = ISD::ABS; 3285 break; 3286 case SPF_NABS: 3287 // TODO: we need to produce sub(0, abs(X)). 3288 default: break; 3289 } 3290 3291 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE && 3292 (TLI.isOperationLegalOrCustom(Opc, VT) || 3293 (UseScalarMinMax && 3294 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3295 // If the underlying comparison instruction is used by any other 3296 // instruction, the consumed instructions won't be destroyed, so it is 3297 // not profitable to convert to a min/max. 3298 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3299 OpCode = Opc; 3300 LHSVal = getValue(LHS); 3301 RHSVal = getValue(RHS); 3302 BaseOps = {}; 3303 } 3304 3305 if (IsUnaryAbs) { 3306 OpCode = Opc; 3307 LHSVal = getValue(LHS); 3308 BaseOps = {}; 3309 } 3310 } 3311 3312 if (IsUnaryAbs) { 3313 for (unsigned i = 0; i != NumValues; ++i) { 3314 Values[i] = 3315 DAG.getNode(OpCode, getCurSDLoc(), 3316 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), 3317 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3318 } 3319 } else { 3320 for (unsigned i = 0; i != NumValues; ++i) { 3321 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3322 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3323 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3324 Values[i] = DAG.getNode( 3325 OpCode, getCurSDLoc(), 3326 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops); 3327 } 3328 } 3329 3330 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3331 DAG.getVTList(ValueVTs), Values)); 3332 } 3333 3334 void SelectionDAGBuilder::visitTrunc(const User &I) { 3335 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3336 SDValue N = getValue(I.getOperand(0)); 3337 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3338 I.getType()); 3339 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3340 } 3341 3342 void SelectionDAGBuilder::visitZExt(const User &I) { 3343 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3344 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3345 SDValue N = getValue(I.getOperand(0)); 3346 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3347 I.getType()); 3348 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3349 } 3350 3351 void SelectionDAGBuilder::visitSExt(const User &I) { 3352 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3353 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3354 SDValue N = getValue(I.getOperand(0)); 3355 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3356 I.getType()); 3357 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3358 } 3359 3360 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3361 // FPTrunc is never a no-op cast, no need to check 3362 SDValue N = getValue(I.getOperand(0)); 3363 SDLoc dl = getCurSDLoc(); 3364 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3365 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3366 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3367 DAG.getTargetConstant( 3368 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3369 } 3370 3371 void SelectionDAGBuilder::visitFPExt(const User &I) { 3372 // FPExt is never a no-op cast, no need to check 3373 SDValue N = getValue(I.getOperand(0)); 3374 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3375 I.getType()); 3376 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3377 } 3378 3379 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3380 // FPToUI is never a no-op cast, no need to check 3381 SDValue N = getValue(I.getOperand(0)); 3382 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3383 I.getType()); 3384 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3385 } 3386 3387 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3388 // FPToSI is never a no-op cast, no need to check 3389 SDValue N = getValue(I.getOperand(0)); 3390 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3391 I.getType()); 3392 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3393 } 3394 3395 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3396 // UIToFP is never a no-op cast, no need to check 3397 SDValue N = getValue(I.getOperand(0)); 3398 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3399 I.getType()); 3400 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3401 } 3402 3403 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3404 // SIToFP is never a no-op cast, no need to check 3405 SDValue N = getValue(I.getOperand(0)); 3406 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3407 I.getType()); 3408 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3409 } 3410 3411 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3412 // What to do depends on the size of the integer and the size of the pointer. 3413 // We can either truncate, zero extend, or no-op, accordingly. 3414 SDValue N = getValue(I.getOperand(0)); 3415 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3416 I.getType()); 3417 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3418 } 3419 3420 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3421 // What to do depends on the size of the integer and the size of the pointer. 3422 // We can either truncate, zero extend, or no-op, accordingly. 3423 SDValue N = getValue(I.getOperand(0)); 3424 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3425 I.getType()); 3426 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3427 } 3428 3429 void SelectionDAGBuilder::visitBitCast(const User &I) { 3430 SDValue N = getValue(I.getOperand(0)); 3431 SDLoc dl = getCurSDLoc(); 3432 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3433 I.getType()); 3434 3435 // BitCast assures us that source and destination are the same size so this is 3436 // either a BITCAST or a no-op. 3437 if (DestVT != N.getValueType()) 3438 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3439 DestVT, N)); // convert types. 3440 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3441 // might fold any kind of constant expression to an integer constant and that 3442 // is not what we are looking for. Only recognize a bitcast of a genuine 3443 // constant integer as an opaque constant. 3444 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3445 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3446 /*isOpaque*/true)); 3447 else 3448 setValue(&I, N); // noop cast. 3449 } 3450 3451 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3452 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3453 const Value *SV = I.getOperand(0); 3454 SDValue N = getValue(SV); 3455 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3456 3457 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3458 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3459 3460 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3461 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3462 3463 setValue(&I, N); 3464 } 3465 3466 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3467 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3468 SDValue InVec = getValue(I.getOperand(0)); 3469 SDValue InVal = getValue(I.getOperand(1)); 3470 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3471 TLI.getVectorIdxTy(DAG.getDataLayout())); 3472 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3473 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3474 InVec, InVal, InIdx)); 3475 } 3476 3477 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3478 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3479 SDValue InVec = getValue(I.getOperand(0)); 3480 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3481 TLI.getVectorIdxTy(DAG.getDataLayout())); 3482 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3483 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3484 InVec, InIdx)); 3485 } 3486 3487 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3488 SDValue Src1 = getValue(I.getOperand(0)); 3489 SDValue Src2 = getValue(I.getOperand(1)); 3490 SDLoc DL = getCurSDLoc(); 3491 3492 SmallVector<int, 8> Mask; 3493 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3494 unsigned MaskNumElts = Mask.size(); 3495 3496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3497 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3498 EVT SrcVT = Src1.getValueType(); 3499 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3500 3501 if (SrcNumElts == MaskNumElts) { 3502 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3503 return; 3504 } 3505 3506 // Normalize the shuffle vector since mask and vector length don't match. 3507 if (SrcNumElts < MaskNumElts) { 3508 // Mask is longer than the source vectors. We can use concatenate vector to 3509 // make the mask and vectors lengths match. 3510 3511 if (MaskNumElts % SrcNumElts == 0) { 3512 // Mask length is a multiple of the source vector length. 3513 // Check if the shuffle is some kind of concatenation of the input 3514 // vectors. 3515 unsigned NumConcat = MaskNumElts / SrcNumElts; 3516 bool IsConcat = true; 3517 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3518 for (unsigned i = 0; i != MaskNumElts; ++i) { 3519 int Idx = Mask[i]; 3520 if (Idx < 0) 3521 continue; 3522 // Ensure the indices in each SrcVT sized piece are sequential and that 3523 // the same source is used for the whole piece. 3524 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3525 (ConcatSrcs[i / SrcNumElts] >= 0 && 3526 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3527 IsConcat = false; 3528 break; 3529 } 3530 // Remember which source this index came from. 3531 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3532 } 3533 3534 // The shuffle is concatenating multiple vectors together. Just emit 3535 // a CONCAT_VECTORS operation. 3536 if (IsConcat) { 3537 SmallVector<SDValue, 8> ConcatOps; 3538 for (auto Src : ConcatSrcs) { 3539 if (Src < 0) 3540 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3541 else if (Src == 0) 3542 ConcatOps.push_back(Src1); 3543 else 3544 ConcatOps.push_back(Src2); 3545 } 3546 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3547 return; 3548 } 3549 } 3550 3551 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3552 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3553 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3554 PaddedMaskNumElts); 3555 3556 // Pad both vectors with undefs to make them the same length as the mask. 3557 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3558 3559 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3560 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3561 MOps1[0] = Src1; 3562 MOps2[0] = Src2; 3563 3564 Src1 = Src1.isUndef() 3565 ? DAG.getUNDEF(PaddedVT) 3566 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3567 Src2 = Src2.isUndef() 3568 ? DAG.getUNDEF(PaddedVT) 3569 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3570 3571 // Readjust mask for new input vector length. 3572 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3573 for (unsigned i = 0; i != MaskNumElts; ++i) { 3574 int Idx = Mask[i]; 3575 if (Idx >= (int)SrcNumElts) 3576 Idx -= SrcNumElts - PaddedMaskNumElts; 3577 MappedOps[i] = Idx; 3578 } 3579 3580 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3581 3582 // If the concatenated vector was padded, extract a subvector with the 3583 // correct number of elements. 3584 if (MaskNumElts != PaddedMaskNumElts) 3585 Result = DAG.getNode( 3586 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3587 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3588 3589 setValue(&I, Result); 3590 return; 3591 } 3592 3593 if (SrcNumElts > MaskNumElts) { 3594 // Analyze the access pattern of the vector to see if we can extract 3595 // two subvectors and do the shuffle. 3596 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3597 bool CanExtract = true; 3598 for (int Idx : Mask) { 3599 unsigned Input = 0; 3600 if (Idx < 0) 3601 continue; 3602 3603 if (Idx >= (int)SrcNumElts) { 3604 Input = 1; 3605 Idx -= SrcNumElts; 3606 } 3607 3608 // If all the indices come from the same MaskNumElts sized portion of 3609 // the sources we can use extract. Also make sure the extract wouldn't 3610 // extract past the end of the source. 3611 int NewStartIdx = alignDown(Idx, MaskNumElts); 3612 if (NewStartIdx + MaskNumElts > SrcNumElts || 3613 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3614 CanExtract = false; 3615 // Make sure we always update StartIdx as we use it to track if all 3616 // elements are undef. 3617 StartIdx[Input] = NewStartIdx; 3618 } 3619 3620 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3621 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3622 return; 3623 } 3624 if (CanExtract) { 3625 // Extract appropriate subvector and generate a vector shuffle 3626 for (unsigned Input = 0; Input < 2; ++Input) { 3627 SDValue &Src = Input == 0 ? Src1 : Src2; 3628 if (StartIdx[Input] < 0) 3629 Src = DAG.getUNDEF(VT); 3630 else { 3631 Src = DAG.getNode( 3632 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3633 DAG.getConstant(StartIdx[Input], DL, 3634 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3635 } 3636 } 3637 3638 // Calculate new mask. 3639 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3640 for (int &Idx : MappedOps) { 3641 if (Idx >= (int)SrcNumElts) 3642 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3643 else if (Idx >= 0) 3644 Idx -= StartIdx[0]; 3645 } 3646 3647 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3648 return; 3649 } 3650 } 3651 3652 // We can't use either concat vectors or extract subvectors so fall back to 3653 // replacing the shuffle with extract and build vector. 3654 // to insert and build vector. 3655 EVT EltVT = VT.getVectorElementType(); 3656 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3657 SmallVector<SDValue,8> Ops; 3658 for (int Idx : Mask) { 3659 SDValue Res; 3660 3661 if (Idx < 0) { 3662 Res = DAG.getUNDEF(EltVT); 3663 } else { 3664 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3665 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3666 3667 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3668 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3669 } 3670 3671 Ops.push_back(Res); 3672 } 3673 3674 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3675 } 3676 3677 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3678 ArrayRef<unsigned> Indices; 3679 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3680 Indices = IV->getIndices(); 3681 else 3682 Indices = cast<ConstantExpr>(&I)->getIndices(); 3683 3684 const Value *Op0 = I.getOperand(0); 3685 const Value *Op1 = I.getOperand(1); 3686 Type *AggTy = I.getType(); 3687 Type *ValTy = Op1->getType(); 3688 bool IntoUndef = isa<UndefValue>(Op0); 3689 bool FromUndef = isa<UndefValue>(Op1); 3690 3691 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3692 3693 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3694 SmallVector<EVT, 4> AggValueVTs; 3695 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3696 SmallVector<EVT, 4> ValValueVTs; 3697 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3698 3699 unsigned NumAggValues = AggValueVTs.size(); 3700 unsigned NumValValues = ValValueVTs.size(); 3701 SmallVector<SDValue, 4> Values(NumAggValues); 3702 3703 // Ignore an insertvalue that produces an empty object 3704 if (!NumAggValues) { 3705 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3706 return; 3707 } 3708 3709 SDValue Agg = getValue(Op0); 3710 unsigned i = 0; 3711 // Copy the beginning value(s) from the original aggregate. 3712 for (; i != LinearIndex; ++i) 3713 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3714 SDValue(Agg.getNode(), Agg.getResNo() + i); 3715 // Copy values from the inserted value(s). 3716 if (NumValValues) { 3717 SDValue Val = getValue(Op1); 3718 for (; i != LinearIndex + NumValValues; ++i) 3719 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3720 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3721 } 3722 // Copy remaining value(s) from the original aggregate. 3723 for (; i != NumAggValues; ++i) 3724 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3725 SDValue(Agg.getNode(), Agg.getResNo() + i); 3726 3727 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3728 DAG.getVTList(AggValueVTs), Values)); 3729 } 3730 3731 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3732 ArrayRef<unsigned> Indices; 3733 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3734 Indices = EV->getIndices(); 3735 else 3736 Indices = cast<ConstantExpr>(&I)->getIndices(); 3737 3738 const Value *Op0 = I.getOperand(0); 3739 Type *AggTy = Op0->getType(); 3740 Type *ValTy = I.getType(); 3741 bool OutOfUndef = isa<UndefValue>(Op0); 3742 3743 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3744 3745 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3746 SmallVector<EVT, 4> ValValueVTs; 3747 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3748 3749 unsigned NumValValues = ValValueVTs.size(); 3750 3751 // Ignore a extractvalue that produces an empty object 3752 if (!NumValValues) { 3753 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3754 return; 3755 } 3756 3757 SmallVector<SDValue, 4> Values(NumValValues); 3758 3759 SDValue Agg = getValue(Op0); 3760 // Copy out the selected value(s). 3761 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3762 Values[i - LinearIndex] = 3763 OutOfUndef ? 3764 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3765 SDValue(Agg.getNode(), Agg.getResNo() + i); 3766 3767 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3768 DAG.getVTList(ValValueVTs), Values)); 3769 } 3770 3771 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3772 Value *Op0 = I.getOperand(0); 3773 // Note that the pointer operand may be a vector of pointers. Take the scalar 3774 // element which holds a pointer. 3775 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3776 SDValue N = getValue(Op0); 3777 SDLoc dl = getCurSDLoc(); 3778 3779 // Normalize Vector GEP - all scalar operands should be converted to the 3780 // splat vector. 3781 unsigned VectorWidth = I.getType()->isVectorTy() ? 3782 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3783 3784 if (VectorWidth && !N.getValueType().isVector()) { 3785 LLVMContext &Context = *DAG.getContext(); 3786 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3787 N = DAG.getSplatBuildVector(VT, dl, N); 3788 } 3789 3790 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3791 GTI != E; ++GTI) { 3792 const Value *Idx = GTI.getOperand(); 3793 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3794 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3795 if (Field) { 3796 // N = N + Offset 3797 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3798 3799 // In an inbounds GEP with an offset that is nonnegative even when 3800 // interpreted as signed, assume there is no unsigned overflow. 3801 SDNodeFlags Flags; 3802 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3803 Flags.setNoUnsignedWrap(true); 3804 3805 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3806 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3807 } 3808 } else { 3809 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3810 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3811 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3812 3813 // If this is a scalar constant or a splat vector of constants, 3814 // handle it quickly. 3815 const auto *CI = dyn_cast<ConstantInt>(Idx); 3816 if (!CI && isa<ConstantDataVector>(Idx) && 3817 cast<ConstantDataVector>(Idx)->getSplatValue()) 3818 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3819 3820 if (CI) { 3821 if (CI->isZero()) 3822 continue; 3823 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3824 LLVMContext &Context = *DAG.getContext(); 3825 SDValue OffsVal = VectorWidth ? 3826 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3827 DAG.getConstant(Offs, dl, IdxTy); 3828 3829 // In an inbouds GEP with an offset that is nonnegative even when 3830 // interpreted as signed, assume there is no unsigned overflow. 3831 SDNodeFlags Flags; 3832 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3833 Flags.setNoUnsignedWrap(true); 3834 3835 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3836 continue; 3837 } 3838 3839 // N = N + Idx * ElementSize; 3840 SDValue IdxN = getValue(Idx); 3841 3842 if (!IdxN.getValueType().isVector() && VectorWidth) { 3843 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3844 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3845 } 3846 3847 // If the index is smaller or larger than intptr_t, truncate or extend 3848 // it. 3849 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3850 3851 // If this is a multiply by a power of two, turn it into a shl 3852 // immediately. This is a very common case. 3853 if (ElementSize != 1) { 3854 if (ElementSize.isPowerOf2()) { 3855 unsigned Amt = ElementSize.logBase2(); 3856 IdxN = DAG.getNode(ISD::SHL, dl, 3857 N.getValueType(), IdxN, 3858 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3859 } else { 3860 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3861 IdxN = DAG.getNode(ISD::MUL, dl, 3862 N.getValueType(), IdxN, Scale); 3863 } 3864 } 3865 3866 N = DAG.getNode(ISD::ADD, dl, 3867 N.getValueType(), N, IdxN); 3868 } 3869 } 3870 3871 setValue(&I, N); 3872 } 3873 3874 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3875 // If this is a fixed sized alloca in the entry block of the function, 3876 // allocate it statically on the stack. 3877 if (FuncInfo.StaticAllocaMap.count(&I)) 3878 return; // getValue will auto-populate this. 3879 3880 SDLoc dl = getCurSDLoc(); 3881 Type *Ty = I.getAllocatedType(); 3882 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3883 auto &DL = DAG.getDataLayout(); 3884 uint64_t TySize = DL.getTypeAllocSize(Ty); 3885 unsigned Align = 3886 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3887 3888 SDValue AllocSize = getValue(I.getArraySize()); 3889 3890 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3891 if (AllocSize.getValueType() != IntPtr) 3892 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3893 3894 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3895 AllocSize, 3896 DAG.getConstant(TySize, dl, IntPtr)); 3897 3898 // Handle alignment. If the requested alignment is less than or equal to 3899 // the stack alignment, ignore it. If the size is greater than or equal to 3900 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3901 unsigned StackAlign = 3902 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3903 if (Align <= StackAlign) 3904 Align = 0; 3905 3906 // Round the size of the allocation up to the stack alignment size 3907 // by add SA-1 to the size. This doesn't overflow because we're computing 3908 // an address inside an alloca. 3909 SDNodeFlags Flags; 3910 Flags.setNoUnsignedWrap(true); 3911 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3912 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3913 3914 // Mask out the low bits for alignment purposes. 3915 AllocSize = 3916 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3917 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3918 3919 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3920 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3921 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3922 setValue(&I, DSA); 3923 DAG.setRoot(DSA.getValue(1)); 3924 3925 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3926 } 3927 3928 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3929 if (I.isAtomic()) 3930 return visitAtomicLoad(I); 3931 3932 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3933 const Value *SV = I.getOperand(0); 3934 if (TLI.supportSwiftError()) { 3935 // Swifterror values can come from either a function parameter with 3936 // swifterror attribute or an alloca with swifterror attribute. 3937 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3938 if (Arg->hasSwiftErrorAttr()) 3939 return visitLoadFromSwiftError(I); 3940 } 3941 3942 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3943 if (Alloca->isSwiftError()) 3944 return visitLoadFromSwiftError(I); 3945 } 3946 } 3947 3948 SDValue Ptr = getValue(SV); 3949 3950 Type *Ty = I.getType(); 3951 3952 bool isVolatile = I.isVolatile(); 3953 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3954 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3955 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3956 unsigned Alignment = I.getAlignment(); 3957 3958 AAMDNodes AAInfo; 3959 I.getAAMetadata(AAInfo); 3960 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3961 3962 SmallVector<EVT, 4> ValueVTs; 3963 SmallVector<uint64_t, 4> Offsets; 3964 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3965 unsigned NumValues = ValueVTs.size(); 3966 if (NumValues == 0) 3967 return; 3968 3969 SDValue Root; 3970 bool ConstantMemory = false; 3971 if (isVolatile || NumValues > MaxParallelChains) 3972 // Serialize volatile loads with other side effects. 3973 Root = getRoot(); 3974 else if (AA && 3975 AA->pointsToConstantMemory(MemoryLocation( 3976 SV, 3977 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3978 AAInfo))) { 3979 // Do not serialize (non-volatile) loads of constant memory with anything. 3980 Root = DAG.getEntryNode(); 3981 ConstantMemory = true; 3982 } else { 3983 // Do not serialize non-volatile loads against each other. 3984 Root = DAG.getRoot(); 3985 } 3986 3987 SDLoc dl = getCurSDLoc(); 3988 3989 if (isVolatile) 3990 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3991 3992 // An aggregate load cannot wrap around the address space, so offsets to its 3993 // parts don't wrap either. 3994 SDNodeFlags Flags; 3995 Flags.setNoUnsignedWrap(true); 3996 3997 SmallVector<SDValue, 4> Values(NumValues); 3998 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3999 EVT PtrVT = Ptr.getValueType(); 4000 unsigned ChainI = 0; 4001 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4002 // Serializing loads here may result in excessive register pressure, and 4003 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 4004 // could recover a bit by hoisting nodes upward in the chain by recognizing 4005 // they are side-effect free or do not alias. The optimizer should really 4006 // avoid this case by converting large object/array copies to llvm.memcpy 4007 // (MaxParallelChains should always remain as failsafe). 4008 if (ChainI == MaxParallelChains) { 4009 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 4010 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4011 makeArrayRef(Chains.data(), ChainI)); 4012 Root = Chain; 4013 ChainI = 0; 4014 } 4015 SDValue A = DAG.getNode(ISD::ADD, dl, 4016 PtrVT, Ptr, 4017 DAG.getConstant(Offsets[i], dl, PtrVT), 4018 Flags); 4019 auto MMOFlags = MachineMemOperand::MONone; 4020 if (isVolatile) 4021 MMOFlags |= MachineMemOperand::MOVolatile; 4022 if (isNonTemporal) 4023 MMOFlags |= MachineMemOperand::MONonTemporal; 4024 if (isInvariant) 4025 MMOFlags |= MachineMemOperand::MOInvariant; 4026 if (isDereferenceable) 4027 MMOFlags |= MachineMemOperand::MODereferenceable; 4028 MMOFlags |= TLI.getMMOFlags(I); 4029 4030 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 4031 MachinePointerInfo(SV, Offsets[i]), Alignment, 4032 MMOFlags, AAInfo, Ranges); 4033 4034 Values[i] = L; 4035 Chains[ChainI] = L.getValue(1); 4036 } 4037 4038 if (!ConstantMemory) { 4039 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4040 makeArrayRef(Chains.data(), ChainI)); 4041 if (isVolatile) 4042 DAG.setRoot(Chain); 4043 else 4044 PendingLoads.push_back(Chain); 4045 } 4046 4047 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 4048 DAG.getVTList(ValueVTs), Values)); 4049 } 4050 4051 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 4052 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4053 "call visitStoreToSwiftError when backend supports swifterror"); 4054 4055 SmallVector<EVT, 4> ValueVTs; 4056 SmallVector<uint64_t, 4> Offsets; 4057 const Value *SrcV = I.getOperand(0); 4058 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4059 SrcV->getType(), ValueVTs, &Offsets); 4060 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4061 "expect a single EVT for swifterror"); 4062 4063 SDValue Src = getValue(SrcV); 4064 // Create a virtual register, then update the virtual register. 4065 unsigned VReg; bool CreatedVReg; 4066 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 4067 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 4068 // Chain can be getRoot or getControlRoot. 4069 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 4070 SDValue(Src.getNode(), Src.getResNo())); 4071 DAG.setRoot(CopyNode); 4072 if (CreatedVReg) 4073 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 4074 } 4075 4076 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 4077 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 4078 "call visitLoadFromSwiftError when backend supports swifterror"); 4079 4080 assert(!I.isVolatile() && 4081 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 4082 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 4083 "Support volatile, non temporal, invariant for load_from_swift_error"); 4084 4085 const Value *SV = I.getOperand(0); 4086 Type *Ty = I.getType(); 4087 AAMDNodes AAInfo; 4088 I.getAAMetadata(AAInfo); 4089 assert( 4090 (!AA || 4091 !AA->pointsToConstantMemory(MemoryLocation( 4092 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 4093 AAInfo))) && 4094 "load_from_swift_error should not be constant memory"); 4095 4096 SmallVector<EVT, 4> ValueVTs; 4097 SmallVector<uint64_t, 4> Offsets; 4098 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 4099 ValueVTs, &Offsets); 4100 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 4101 "expect a single EVT for swifterror"); 4102 4103 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 4104 SDValue L = DAG.getCopyFromReg( 4105 getRoot(), getCurSDLoc(), 4106 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 4107 ValueVTs[0]); 4108 4109 setValue(&I, L); 4110 } 4111 4112 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 4113 if (I.isAtomic()) 4114 return visitAtomicStore(I); 4115 4116 const Value *SrcV = I.getOperand(0); 4117 const Value *PtrV = I.getOperand(1); 4118 4119 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4120 if (TLI.supportSwiftError()) { 4121 // Swifterror values can come from either a function parameter with 4122 // swifterror attribute or an alloca with swifterror attribute. 4123 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 4124 if (Arg->hasSwiftErrorAttr()) 4125 return visitStoreToSwiftError(I); 4126 } 4127 4128 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 4129 if (Alloca->isSwiftError()) 4130 return visitStoreToSwiftError(I); 4131 } 4132 } 4133 4134 SmallVector<EVT, 4> ValueVTs; 4135 SmallVector<uint64_t, 4> Offsets; 4136 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 4137 SrcV->getType(), ValueVTs, &Offsets); 4138 unsigned NumValues = ValueVTs.size(); 4139 if (NumValues == 0) 4140 return; 4141 4142 // Get the lowered operands. Note that we do this after 4143 // checking if NumResults is zero, because with zero results 4144 // the operands won't have values in the map. 4145 SDValue Src = getValue(SrcV); 4146 SDValue Ptr = getValue(PtrV); 4147 4148 SDValue Root = getRoot(); 4149 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 4150 SDLoc dl = getCurSDLoc(); 4151 EVT PtrVT = Ptr.getValueType(); 4152 unsigned Alignment = I.getAlignment(); 4153 AAMDNodes AAInfo; 4154 I.getAAMetadata(AAInfo); 4155 4156 auto MMOFlags = MachineMemOperand::MONone; 4157 if (I.isVolatile()) 4158 MMOFlags |= MachineMemOperand::MOVolatile; 4159 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 4160 MMOFlags |= MachineMemOperand::MONonTemporal; 4161 MMOFlags |= TLI.getMMOFlags(I); 4162 4163 // An aggregate load cannot wrap around the address space, so offsets to its 4164 // parts don't wrap either. 4165 SDNodeFlags Flags; 4166 Flags.setNoUnsignedWrap(true); 4167 4168 unsigned ChainI = 0; 4169 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 4170 // See visitLoad comments. 4171 if (ChainI == MaxParallelChains) { 4172 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4173 makeArrayRef(Chains.data(), ChainI)); 4174 Root = Chain; 4175 ChainI = 0; 4176 } 4177 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 4178 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 4179 SDValue St = DAG.getStore( 4180 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 4181 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 4182 Chains[ChainI] = St; 4183 } 4184 4185 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 4186 makeArrayRef(Chains.data(), ChainI)); 4187 DAG.setRoot(StoreNode); 4188 } 4189 4190 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 4191 bool IsCompressing) { 4192 SDLoc sdl = getCurSDLoc(); 4193 4194 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4195 unsigned& Alignment) { 4196 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 4197 Src0 = I.getArgOperand(0); 4198 Ptr = I.getArgOperand(1); 4199 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 4200 Mask = I.getArgOperand(3); 4201 }; 4202 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4203 unsigned& Alignment) { 4204 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 4205 Src0 = I.getArgOperand(0); 4206 Ptr = I.getArgOperand(1); 4207 Mask = I.getArgOperand(2); 4208 Alignment = 0; 4209 }; 4210 4211 Value *PtrOperand, *MaskOperand, *Src0Operand; 4212 unsigned Alignment; 4213 if (IsCompressing) 4214 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4215 else 4216 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4217 4218 SDValue Ptr = getValue(PtrOperand); 4219 SDValue Src0 = getValue(Src0Operand); 4220 SDValue Mask = getValue(MaskOperand); 4221 4222 EVT VT = Src0.getValueType(); 4223 if (!Alignment) 4224 Alignment = DAG.getEVTAlignment(VT); 4225 4226 AAMDNodes AAInfo; 4227 I.getAAMetadata(AAInfo); 4228 4229 MachineMemOperand *MMO = 4230 DAG.getMachineFunction(). 4231 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4232 MachineMemOperand::MOStore, VT.getStoreSize(), 4233 Alignment, AAInfo); 4234 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 4235 MMO, false /* Truncating */, 4236 IsCompressing); 4237 DAG.setRoot(StoreNode); 4238 setValue(&I, StoreNode); 4239 } 4240 4241 // Get a uniform base for the Gather/Scatter intrinsic. 4242 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 4243 // We try to represent it as a base pointer + vector of indices. 4244 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 4245 // The first operand of the GEP may be a single pointer or a vector of pointers 4246 // Example: 4247 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 4248 // or 4249 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 4250 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 4251 // 4252 // When the first GEP operand is a single pointer - it is the uniform base we 4253 // are looking for. If first operand of the GEP is a splat vector - we 4254 // extract the splat value and use it as a uniform base. 4255 // In all other cases the function returns 'false'. 4256 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 4257 SDValue &Scale, SelectionDAGBuilder* SDB) { 4258 SelectionDAG& DAG = SDB->DAG; 4259 LLVMContext &Context = *DAG.getContext(); 4260 4261 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 4262 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 4263 if (!GEP) 4264 return false; 4265 4266 const Value *GEPPtr = GEP->getPointerOperand(); 4267 if (!GEPPtr->getType()->isVectorTy()) 4268 Ptr = GEPPtr; 4269 else if (!(Ptr = getSplatValue(GEPPtr))) 4270 return false; 4271 4272 unsigned FinalIndex = GEP->getNumOperands() - 1; 4273 Value *IndexVal = GEP->getOperand(FinalIndex); 4274 4275 // Ensure all the other indices are 0. 4276 for (unsigned i = 1; i < FinalIndex; ++i) { 4277 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 4278 if (!C || !C->isZero()) 4279 return false; 4280 } 4281 4282 // The operands of the GEP may be defined in another basic block. 4283 // In this case we'll not find nodes for the operands. 4284 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 4285 return false; 4286 4287 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4288 const DataLayout &DL = DAG.getDataLayout(); 4289 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4290 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4291 Base = SDB->getValue(Ptr); 4292 Index = SDB->getValue(IndexVal); 4293 4294 if (!Index.getValueType().isVector()) { 4295 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4296 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4297 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4298 } 4299 return true; 4300 } 4301 4302 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4303 SDLoc sdl = getCurSDLoc(); 4304 4305 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4306 const Value *Ptr = I.getArgOperand(1); 4307 SDValue Src0 = getValue(I.getArgOperand(0)); 4308 SDValue Mask = getValue(I.getArgOperand(3)); 4309 EVT VT = Src0.getValueType(); 4310 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4311 if (!Alignment) 4312 Alignment = DAG.getEVTAlignment(VT); 4313 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4314 4315 AAMDNodes AAInfo; 4316 I.getAAMetadata(AAInfo); 4317 4318 SDValue Base; 4319 SDValue Index; 4320 SDValue Scale; 4321 const Value *BasePtr = Ptr; 4322 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4323 4324 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4325 MachineMemOperand *MMO = DAG.getMachineFunction(). 4326 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4327 MachineMemOperand::MOStore, VT.getStoreSize(), 4328 Alignment, AAInfo); 4329 if (!UniformBase) { 4330 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4331 Index = getValue(Ptr); 4332 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4333 } 4334 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4335 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4336 Ops, MMO); 4337 DAG.setRoot(Scatter); 4338 setValue(&I, Scatter); 4339 } 4340 4341 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4342 SDLoc sdl = getCurSDLoc(); 4343 4344 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4345 unsigned& Alignment) { 4346 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4347 Ptr = I.getArgOperand(0); 4348 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4349 Mask = I.getArgOperand(2); 4350 Src0 = I.getArgOperand(3); 4351 }; 4352 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4353 unsigned& Alignment) { 4354 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4355 Ptr = I.getArgOperand(0); 4356 Alignment = 0; 4357 Mask = I.getArgOperand(1); 4358 Src0 = I.getArgOperand(2); 4359 }; 4360 4361 Value *PtrOperand, *MaskOperand, *Src0Operand; 4362 unsigned Alignment; 4363 if (IsExpanding) 4364 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4365 else 4366 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4367 4368 SDValue Ptr = getValue(PtrOperand); 4369 SDValue Src0 = getValue(Src0Operand); 4370 SDValue Mask = getValue(MaskOperand); 4371 4372 EVT VT = Src0.getValueType(); 4373 if (!Alignment) 4374 Alignment = DAG.getEVTAlignment(VT); 4375 4376 AAMDNodes AAInfo; 4377 I.getAAMetadata(AAInfo); 4378 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4379 4380 // Do not serialize masked loads of constant memory with anything. 4381 bool AddToChain = 4382 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4383 PtrOperand, 4384 LocationSize::precise( 4385 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4386 AAInfo)); 4387 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4388 4389 MachineMemOperand *MMO = 4390 DAG.getMachineFunction(). 4391 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4392 MachineMemOperand::MOLoad, VT.getStoreSize(), 4393 Alignment, AAInfo, Ranges); 4394 4395 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4396 ISD::NON_EXTLOAD, IsExpanding); 4397 if (AddToChain) 4398 PendingLoads.push_back(Load.getValue(1)); 4399 setValue(&I, Load); 4400 } 4401 4402 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4403 SDLoc sdl = getCurSDLoc(); 4404 4405 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4406 const Value *Ptr = I.getArgOperand(0); 4407 SDValue Src0 = getValue(I.getArgOperand(3)); 4408 SDValue Mask = getValue(I.getArgOperand(2)); 4409 4410 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4411 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4412 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4413 if (!Alignment) 4414 Alignment = DAG.getEVTAlignment(VT); 4415 4416 AAMDNodes AAInfo; 4417 I.getAAMetadata(AAInfo); 4418 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4419 4420 SDValue Root = DAG.getRoot(); 4421 SDValue Base; 4422 SDValue Index; 4423 SDValue Scale; 4424 const Value *BasePtr = Ptr; 4425 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4426 bool ConstantMemory = false; 4427 if (UniformBase && AA && 4428 AA->pointsToConstantMemory( 4429 MemoryLocation(BasePtr, 4430 LocationSize::precise( 4431 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4432 AAInfo))) { 4433 // Do not serialize (non-volatile) loads of constant memory with anything. 4434 Root = DAG.getEntryNode(); 4435 ConstantMemory = true; 4436 } 4437 4438 MachineMemOperand *MMO = 4439 DAG.getMachineFunction(). 4440 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4441 MachineMemOperand::MOLoad, VT.getStoreSize(), 4442 Alignment, AAInfo, Ranges); 4443 4444 if (!UniformBase) { 4445 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4446 Index = getValue(Ptr); 4447 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4448 } 4449 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4450 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4451 Ops, MMO); 4452 4453 SDValue OutChain = Gather.getValue(1); 4454 if (!ConstantMemory) 4455 PendingLoads.push_back(OutChain); 4456 setValue(&I, Gather); 4457 } 4458 4459 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4460 SDLoc dl = getCurSDLoc(); 4461 AtomicOrdering SuccessOrdering = I.getSuccessOrdering(); 4462 AtomicOrdering FailureOrdering = I.getFailureOrdering(); 4463 SyncScope::ID SSID = I.getSyncScopeID(); 4464 4465 SDValue InChain = getRoot(); 4466 4467 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4468 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4469 4470 auto Alignment = DAG.getEVTAlignment(MemVT); 4471 4472 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4473 if (I.isVolatile()) 4474 Flags |= MachineMemOperand::MOVolatile; 4475 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4476 4477 MachineFunction &MF = DAG.getMachineFunction(); 4478 MachineMemOperand *MMO = 4479 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4480 Flags, MemVT.getStoreSize(), Alignment, 4481 AAMDNodes(), nullptr, SSID, SuccessOrdering, 4482 FailureOrdering); 4483 4484 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 4485 dl, MemVT, VTs, InChain, 4486 getValue(I.getPointerOperand()), 4487 getValue(I.getCompareOperand()), 4488 getValue(I.getNewValOperand()), MMO); 4489 4490 SDValue OutChain = L.getValue(2); 4491 4492 setValue(&I, L); 4493 DAG.setRoot(OutChain); 4494 } 4495 4496 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4497 SDLoc dl = getCurSDLoc(); 4498 ISD::NodeType NT; 4499 switch (I.getOperation()) { 4500 default: llvm_unreachable("Unknown atomicrmw operation"); 4501 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4502 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4503 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4504 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4505 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4506 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4507 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4508 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4509 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4510 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4511 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4512 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4513 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4514 } 4515 AtomicOrdering Ordering = I.getOrdering(); 4516 SyncScope::ID SSID = I.getSyncScopeID(); 4517 4518 SDValue InChain = getRoot(); 4519 4520 auto MemVT = getValue(I.getValOperand()).getSimpleValueType(); 4521 auto Alignment = DAG.getEVTAlignment(MemVT); 4522 4523 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4524 if (I.isVolatile()) 4525 Flags |= MachineMemOperand::MOVolatile; 4526 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I); 4527 4528 MachineFunction &MF = DAG.getMachineFunction(); 4529 MachineMemOperand *MMO = 4530 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4531 MemVT.getStoreSize(), Alignment, AAMDNodes(), 4532 nullptr, SSID, Ordering); 4533 4534 SDValue L = 4535 DAG.getAtomic(NT, dl, MemVT, InChain, 4536 getValue(I.getPointerOperand()), getValue(I.getValOperand()), 4537 MMO); 4538 4539 SDValue OutChain = L.getValue(1); 4540 4541 setValue(&I, L); 4542 DAG.setRoot(OutChain); 4543 } 4544 4545 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4546 SDLoc dl = getCurSDLoc(); 4547 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4548 SDValue Ops[3]; 4549 Ops[0] = getRoot(); 4550 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4551 TLI.getFenceOperandTy(DAG.getDataLayout())); 4552 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4553 TLI.getFenceOperandTy(DAG.getDataLayout())); 4554 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4555 } 4556 4557 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4558 SDLoc dl = getCurSDLoc(); 4559 AtomicOrdering Order = I.getOrdering(); 4560 SyncScope::ID SSID = I.getSyncScopeID(); 4561 4562 SDValue InChain = getRoot(); 4563 4564 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4565 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4566 4567 if (!TLI.supportsUnalignedAtomics() && 4568 I.getAlignment() < VT.getStoreSize()) 4569 report_fatal_error("Cannot generate unaligned atomic load"); 4570 4571 auto Flags = MachineMemOperand::MOLoad; 4572 if (I.isVolatile()) 4573 Flags |= MachineMemOperand::MOVolatile; 4574 if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr) 4575 Flags |= MachineMemOperand::MOInvariant; 4576 if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout())) 4577 Flags |= MachineMemOperand::MODereferenceable; 4578 4579 Flags |= TLI.getMMOFlags(I); 4580 4581 MachineMemOperand *MMO = 4582 DAG.getMachineFunction(). 4583 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4584 Flags, VT.getStoreSize(), 4585 I.getAlignment() ? I.getAlignment() : 4586 DAG.getEVTAlignment(VT), 4587 AAMDNodes(), nullptr, SSID, Order); 4588 4589 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4590 SDValue L = 4591 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4592 getValue(I.getPointerOperand()), MMO); 4593 4594 SDValue OutChain = L.getValue(1); 4595 4596 setValue(&I, L); 4597 DAG.setRoot(OutChain); 4598 } 4599 4600 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4601 SDLoc dl = getCurSDLoc(); 4602 4603 AtomicOrdering Ordering = I.getOrdering(); 4604 SyncScope::ID SSID = I.getSyncScopeID(); 4605 4606 SDValue InChain = getRoot(); 4607 4608 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4609 EVT VT = 4610 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4611 4612 if (I.getAlignment() < VT.getStoreSize()) 4613 report_fatal_error("Cannot generate unaligned atomic store"); 4614 4615 auto Flags = MachineMemOperand::MOStore; 4616 if (I.isVolatile()) 4617 Flags |= MachineMemOperand::MOVolatile; 4618 Flags |= TLI.getMMOFlags(I); 4619 4620 MachineFunction &MF = DAG.getMachineFunction(); 4621 MachineMemOperand *MMO = 4622 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags, 4623 VT.getStoreSize(), I.getAlignment(), AAMDNodes(), 4624 nullptr, SSID, Ordering); 4625 SDValue OutChain = 4626 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, InChain, 4627 getValue(I.getPointerOperand()), getValue(I.getValueOperand()), 4628 MMO); 4629 4630 4631 DAG.setRoot(OutChain); 4632 } 4633 4634 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4635 /// node. 4636 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4637 unsigned Intrinsic) { 4638 // Ignore the callsite's attributes. A specific call site may be marked with 4639 // readnone, but the lowering code will expect the chain based on the 4640 // definition. 4641 const Function *F = I.getCalledFunction(); 4642 bool HasChain = !F->doesNotAccessMemory(); 4643 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4644 4645 // Build the operand list. 4646 SmallVector<SDValue, 8> Ops; 4647 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4648 if (OnlyLoad) { 4649 // We don't need to serialize loads against other loads. 4650 Ops.push_back(DAG.getRoot()); 4651 } else { 4652 Ops.push_back(getRoot()); 4653 } 4654 } 4655 4656 // Info is set by getTgtMemInstrinsic 4657 TargetLowering::IntrinsicInfo Info; 4658 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4659 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4660 DAG.getMachineFunction(), 4661 Intrinsic); 4662 4663 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4664 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4665 Info.opc == ISD::INTRINSIC_W_CHAIN) 4666 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4667 TLI.getPointerTy(DAG.getDataLayout()))); 4668 4669 // Add all operands of the call to the operand list. 4670 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4671 SDValue Op = getValue(I.getArgOperand(i)); 4672 Ops.push_back(Op); 4673 } 4674 4675 SmallVector<EVT, 4> ValueVTs; 4676 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4677 4678 if (HasChain) 4679 ValueVTs.push_back(MVT::Other); 4680 4681 SDVTList VTs = DAG.getVTList(ValueVTs); 4682 4683 // Create the node. 4684 SDValue Result; 4685 if (IsTgtIntrinsic) { 4686 // This is target intrinsic that touches memory 4687 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4688 Ops, Info.memVT, 4689 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4690 Info.flags, Info.size); 4691 } else if (!HasChain) { 4692 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4693 } else if (!I.getType()->isVoidTy()) { 4694 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4695 } else { 4696 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4697 } 4698 4699 if (HasChain) { 4700 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4701 if (OnlyLoad) 4702 PendingLoads.push_back(Chain); 4703 else 4704 DAG.setRoot(Chain); 4705 } 4706 4707 if (!I.getType()->isVoidTy()) { 4708 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4709 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4710 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4711 } else 4712 Result = lowerRangeToAssertZExt(DAG, I, Result); 4713 4714 setValue(&I, Result); 4715 } 4716 } 4717 4718 /// GetSignificand - Get the significand and build it into a floating-point 4719 /// number with exponent of 1: 4720 /// 4721 /// Op = (Op & 0x007fffff) | 0x3f800000; 4722 /// 4723 /// where Op is the hexadecimal representation of floating point value. 4724 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4725 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4726 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4727 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4728 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4729 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4730 } 4731 4732 /// GetExponent - Get the exponent: 4733 /// 4734 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4735 /// 4736 /// where Op is the hexadecimal representation of floating point value. 4737 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4738 const TargetLowering &TLI, const SDLoc &dl) { 4739 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4740 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4741 SDValue t1 = DAG.getNode( 4742 ISD::SRL, dl, MVT::i32, t0, 4743 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4744 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4745 DAG.getConstant(127, dl, MVT::i32)); 4746 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4747 } 4748 4749 /// getF32Constant - Get 32-bit floating point constant. 4750 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4751 const SDLoc &dl) { 4752 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4753 MVT::f32); 4754 } 4755 4756 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4757 SelectionDAG &DAG) { 4758 // TODO: What fast-math-flags should be set on the floating-point nodes? 4759 4760 // IntegerPartOfX = ((int32_t)(t0); 4761 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4762 4763 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4764 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4765 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4766 4767 // IntegerPartOfX <<= 23; 4768 IntegerPartOfX = DAG.getNode( 4769 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4770 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4771 DAG.getDataLayout()))); 4772 4773 SDValue TwoToFractionalPartOfX; 4774 if (LimitFloatPrecision <= 6) { 4775 // For floating-point precision of 6: 4776 // 4777 // TwoToFractionalPartOfX = 4778 // 0.997535578f + 4779 // (0.735607626f + 0.252464424f * x) * x; 4780 // 4781 // error 0.0144103317, which is 6 bits 4782 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4783 getF32Constant(DAG, 0x3e814304, dl)); 4784 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4785 getF32Constant(DAG, 0x3f3c50c8, dl)); 4786 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4787 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4788 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4789 } else if (LimitFloatPrecision <= 12) { 4790 // For floating-point precision of 12: 4791 // 4792 // TwoToFractionalPartOfX = 4793 // 0.999892986f + 4794 // (0.696457318f + 4795 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4796 // 4797 // error 0.000107046256, which is 13 to 14 bits 4798 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4799 getF32Constant(DAG, 0x3da235e3, dl)); 4800 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4801 getF32Constant(DAG, 0x3e65b8f3, dl)); 4802 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4803 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4804 getF32Constant(DAG, 0x3f324b07, dl)); 4805 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4806 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4807 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4808 } else { // LimitFloatPrecision <= 18 4809 // For floating-point precision of 18: 4810 // 4811 // TwoToFractionalPartOfX = 4812 // 0.999999982f + 4813 // (0.693148872f + 4814 // (0.240227044f + 4815 // (0.554906021e-1f + 4816 // (0.961591928e-2f + 4817 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4818 // error 2.47208000*10^(-7), which is better than 18 bits 4819 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4820 getF32Constant(DAG, 0x3924b03e, dl)); 4821 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4822 getF32Constant(DAG, 0x3ab24b87, dl)); 4823 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4824 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4825 getF32Constant(DAG, 0x3c1d8c17, dl)); 4826 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4827 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4828 getF32Constant(DAG, 0x3d634a1d, dl)); 4829 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4830 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4831 getF32Constant(DAG, 0x3e75fe14, dl)); 4832 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4833 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4834 getF32Constant(DAG, 0x3f317234, dl)); 4835 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4836 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4837 getF32Constant(DAG, 0x3f800000, dl)); 4838 } 4839 4840 // Add the exponent into the result in integer domain. 4841 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4842 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4843 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4844 } 4845 4846 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4847 /// limited-precision mode. 4848 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4849 const TargetLowering &TLI) { 4850 if (Op.getValueType() == MVT::f32 && 4851 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4852 4853 // Put the exponent in the right bit position for later addition to the 4854 // final result: 4855 // 4856 // #define LOG2OFe 1.4426950f 4857 // t0 = Op * LOG2OFe 4858 4859 // TODO: What fast-math-flags should be set here? 4860 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4861 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4862 return getLimitedPrecisionExp2(t0, dl, DAG); 4863 } 4864 4865 // No special expansion. 4866 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4867 } 4868 4869 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4870 /// limited-precision mode. 4871 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4872 const TargetLowering &TLI) { 4873 // TODO: What fast-math-flags should be set on the floating-point nodes? 4874 4875 if (Op.getValueType() == MVT::f32 && 4876 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4877 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4878 4879 // Scale the exponent by log(2) [0.69314718f]. 4880 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4881 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4882 getF32Constant(DAG, 0x3f317218, dl)); 4883 4884 // Get the significand and build it into a floating-point number with 4885 // exponent of 1. 4886 SDValue X = GetSignificand(DAG, Op1, dl); 4887 4888 SDValue LogOfMantissa; 4889 if (LimitFloatPrecision <= 6) { 4890 // For floating-point precision of 6: 4891 // 4892 // LogofMantissa = 4893 // -1.1609546f + 4894 // (1.4034025f - 0.23903021f * x) * x; 4895 // 4896 // error 0.0034276066, which is better than 8 bits 4897 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4898 getF32Constant(DAG, 0xbe74c456, dl)); 4899 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4900 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4901 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4902 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4903 getF32Constant(DAG, 0x3f949a29, dl)); 4904 } else if (LimitFloatPrecision <= 12) { 4905 // For floating-point precision of 12: 4906 // 4907 // LogOfMantissa = 4908 // -1.7417939f + 4909 // (2.8212026f + 4910 // (-1.4699568f + 4911 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4912 // 4913 // error 0.000061011436, which is 14 bits 4914 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4915 getF32Constant(DAG, 0xbd67b6d6, dl)); 4916 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4917 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4918 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4919 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4920 getF32Constant(DAG, 0x3fbc278b, dl)); 4921 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4922 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4923 getF32Constant(DAG, 0x40348e95, dl)); 4924 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4925 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4926 getF32Constant(DAG, 0x3fdef31a, dl)); 4927 } else { // LimitFloatPrecision <= 18 4928 // For floating-point precision of 18: 4929 // 4930 // LogOfMantissa = 4931 // -2.1072184f + 4932 // (4.2372794f + 4933 // (-3.7029485f + 4934 // (2.2781945f + 4935 // (-0.87823314f + 4936 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4937 // 4938 // error 0.0000023660568, which is better than 18 bits 4939 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4940 getF32Constant(DAG, 0xbc91e5ac, dl)); 4941 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4942 getF32Constant(DAG, 0x3e4350aa, dl)); 4943 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4944 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4945 getF32Constant(DAG, 0x3f60d3e3, dl)); 4946 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4947 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4948 getF32Constant(DAG, 0x4011cdf0, dl)); 4949 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4950 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4951 getF32Constant(DAG, 0x406cfd1c, dl)); 4952 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4953 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4954 getF32Constant(DAG, 0x408797cb, dl)); 4955 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4956 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4957 getF32Constant(DAG, 0x4006dcab, dl)); 4958 } 4959 4960 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4961 } 4962 4963 // No special expansion. 4964 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4965 } 4966 4967 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4968 /// limited-precision mode. 4969 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4970 const TargetLowering &TLI) { 4971 // TODO: What fast-math-flags should be set on the floating-point nodes? 4972 4973 if (Op.getValueType() == MVT::f32 && 4974 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4975 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4976 4977 // Get the exponent. 4978 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4979 4980 // Get the significand and build it into a floating-point number with 4981 // exponent of 1. 4982 SDValue X = GetSignificand(DAG, Op1, dl); 4983 4984 // Different possible minimax approximations of significand in 4985 // floating-point for various degrees of accuracy over [1,2]. 4986 SDValue Log2ofMantissa; 4987 if (LimitFloatPrecision <= 6) { 4988 // For floating-point precision of 6: 4989 // 4990 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4991 // 4992 // error 0.0049451742, which is more than 7 bits 4993 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4994 getF32Constant(DAG, 0xbeb08fe0, dl)); 4995 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4996 getF32Constant(DAG, 0x40019463, dl)); 4997 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4998 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4999 getF32Constant(DAG, 0x3fd6633d, dl)); 5000 } else if (LimitFloatPrecision <= 12) { 5001 // For floating-point precision of 12: 5002 // 5003 // Log2ofMantissa = 5004 // -2.51285454f + 5005 // (4.07009056f + 5006 // (-2.12067489f + 5007 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 5008 // 5009 // error 0.0000876136000, which is better than 13 bits 5010 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5011 getF32Constant(DAG, 0xbda7262e, dl)); 5012 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5013 getF32Constant(DAG, 0x3f25280b, dl)); 5014 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5015 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5016 getF32Constant(DAG, 0x4007b923, dl)); 5017 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5018 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5019 getF32Constant(DAG, 0x40823e2f, dl)); 5020 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5021 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5022 getF32Constant(DAG, 0x4020d29c, dl)); 5023 } else { // LimitFloatPrecision <= 18 5024 // For floating-point precision of 18: 5025 // 5026 // Log2ofMantissa = 5027 // -3.0400495f + 5028 // (6.1129976f + 5029 // (-5.3420409f + 5030 // (3.2865683f + 5031 // (-1.2669343f + 5032 // (0.27515199f - 5033 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 5034 // 5035 // error 0.0000018516, which is better than 18 bits 5036 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5037 getF32Constant(DAG, 0xbcd2769e, dl)); 5038 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5039 getF32Constant(DAG, 0x3e8ce0b9, dl)); 5040 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5041 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5042 getF32Constant(DAG, 0x3fa22ae7, dl)); 5043 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5044 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 5045 getF32Constant(DAG, 0x40525723, dl)); 5046 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5047 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 5048 getF32Constant(DAG, 0x40aaf200, dl)); 5049 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5050 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 5051 getF32Constant(DAG, 0x40c39dad, dl)); 5052 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 5053 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 5054 getF32Constant(DAG, 0x4042902c, dl)); 5055 } 5056 5057 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 5058 } 5059 5060 // No special expansion. 5061 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 5062 } 5063 5064 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 5065 /// limited-precision mode. 5066 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5067 const TargetLowering &TLI) { 5068 // TODO: What fast-math-flags should be set on the floating-point nodes? 5069 5070 if (Op.getValueType() == MVT::f32 && 5071 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5072 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 5073 5074 // Scale the exponent by log10(2) [0.30102999f]. 5075 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 5076 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 5077 getF32Constant(DAG, 0x3e9a209a, dl)); 5078 5079 // Get the significand and build it into a floating-point number with 5080 // exponent of 1. 5081 SDValue X = GetSignificand(DAG, Op1, dl); 5082 5083 SDValue Log10ofMantissa; 5084 if (LimitFloatPrecision <= 6) { 5085 // For floating-point precision of 6: 5086 // 5087 // Log10ofMantissa = 5088 // -0.50419619f + 5089 // (0.60948995f - 0.10380950f * x) * x; 5090 // 5091 // error 0.0014886165, which is 6 bits 5092 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5093 getF32Constant(DAG, 0xbdd49a13, dl)); 5094 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 5095 getF32Constant(DAG, 0x3f1c0789, dl)); 5096 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5097 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 5098 getF32Constant(DAG, 0x3f011300, dl)); 5099 } else if (LimitFloatPrecision <= 12) { 5100 // For floating-point precision of 12: 5101 // 5102 // Log10ofMantissa = 5103 // -0.64831180f + 5104 // (0.91751397f + 5105 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 5106 // 5107 // error 0.00019228036, which is better than 12 bits 5108 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5109 getF32Constant(DAG, 0x3d431f31, dl)); 5110 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5111 getF32Constant(DAG, 0x3ea21fb2, dl)); 5112 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5113 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5114 getF32Constant(DAG, 0x3f6ae232, dl)); 5115 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5116 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5117 getF32Constant(DAG, 0x3f25f7c3, dl)); 5118 } else { // LimitFloatPrecision <= 18 5119 // For floating-point precision of 18: 5120 // 5121 // Log10ofMantissa = 5122 // -0.84299375f + 5123 // (1.5327582f + 5124 // (-1.0688956f + 5125 // (0.49102474f + 5126 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 5127 // 5128 // error 0.0000037995730, which is better than 18 bits 5129 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 5130 getF32Constant(DAG, 0x3c5d51ce, dl)); 5131 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 5132 getF32Constant(DAG, 0x3e00685a, dl)); 5133 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 5134 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 5135 getF32Constant(DAG, 0x3efb6798, dl)); 5136 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 5137 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 5138 getF32Constant(DAG, 0x3f88d192, dl)); 5139 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 5140 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 5141 getF32Constant(DAG, 0x3fc4316c, dl)); 5142 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 5143 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 5144 getF32Constant(DAG, 0x3f57ce70, dl)); 5145 } 5146 5147 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 5148 } 5149 5150 // No special expansion. 5151 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 5152 } 5153 5154 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 5155 /// limited-precision mode. 5156 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 5157 const TargetLowering &TLI) { 5158 if (Op.getValueType() == MVT::f32 && 5159 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 5160 return getLimitedPrecisionExp2(Op, dl, DAG); 5161 5162 // No special expansion. 5163 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 5164 } 5165 5166 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 5167 /// limited-precision mode with x == 10.0f. 5168 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 5169 SelectionDAG &DAG, const TargetLowering &TLI) { 5170 bool IsExp10 = false; 5171 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 5172 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 5173 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 5174 APFloat Ten(10.0f); 5175 IsExp10 = LHSC->isExactlyValue(Ten); 5176 } 5177 } 5178 5179 // TODO: What fast-math-flags should be set on the FMUL node? 5180 if (IsExp10) { 5181 // Put the exponent in the right bit position for later addition to the 5182 // final result: 5183 // 5184 // #define LOG2OF10 3.3219281f 5185 // t0 = Op * LOG2OF10; 5186 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 5187 getF32Constant(DAG, 0x40549a78, dl)); 5188 return getLimitedPrecisionExp2(t0, dl, DAG); 5189 } 5190 5191 // No special expansion. 5192 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 5193 } 5194 5195 /// ExpandPowI - Expand a llvm.powi intrinsic. 5196 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 5197 SelectionDAG &DAG) { 5198 // If RHS is a constant, we can expand this out to a multiplication tree, 5199 // otherwise we end up lowering to a call to __powidf2 (for example). When 5200 // optimizing for size, we only want to do this if the expansion would produce 5201 // a small number of multiplies, otherwise we do the full expansion. 5202 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 5203 // Get the exponent as a positive value. 5204 unsigned Val = RHSC->getSExtValue(); 5205 if ((int)Val < 0) Val = -Val; 5206 5207 // powi(x, 0) -> 1.0 5208 if (Val == 0) 5209 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 5210 5211 const Function &F = DAG.getMachineFunction().getFunction(); 5212 if (!F.optForSize() || 5213 // If optimizing for size, don't insert too many multiplies. 5214 // This inserts up to 5 multiplies. 5215 countPopulation(Val) + Log2_32(Val) < 7) { 5216 // We use the simple binary decomposition method to generate the multiply 5217 // sequence. There are more optimal ways to do this (for example, 5218 // powi(x,15) generates one more multiply than it should), but this has 5219 // the benefit of being both really simple and much better than a libcall. 5220 SDValue Res; // Logically starts equal to 1.0 5221 SDValue CurSquare = LHS; 5222 // TODO: Intrinsics should have fast-math-flags that propagate to these 5223 // nodes. 5224 while (Val) { 5225 if (Val & 1) { 5226 if (Res.getNode()) 5227 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 5228 else 5229 Res = CurSquare; // 1.0*CurSquare. 5230 } 5231 5232 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 5233 CurSquare, CurSquare); 5234 Val >>= 1; 5235 } 5236 5237 // If the original was negative, invert the result, producing 1/(x*x*x). 5238 if (RHSC->getSExtValue() < 0) 5239 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 5240 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 5241 return Res; 5242 } 5243 } 5244 5245 // Otherwise, expand to a libcall. 5246 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 5247 } 5248 5249 // getUnderlyingArgReg - Find underlying register used for a truncated or 5250 // bitcasted argument. 5251 static unsigned getUnderlyingArgReg(const SDValue &N) { 5252 switch (N.getOpcode()) { 5253 case ISD::CopyFromReg: 5254 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 5255 case ISD::BITCAST: 5256 case ISD::AssertZext: 5257 case ISD::AssertSext: 5258 case ISD::TRUNCATE: 5259 return getUnderlyingArgReg(N.getOperand(0)); 5260 default: 5261 return 0; 5262 } 5263 } 5264 5265 /// If the DbgValueInst is a dbg_value of a function argument, create the 5266 /// corresponding DBG_VALUE machine instruction for it now. At the end of 5267 /// instruction selection, they will be inserted to the entry BB. 5268 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 5269 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 5270 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 5271 const Argument *Arg = dyn_cast<Argument>(V); 5272 if (!Arg) 5273 return false; 5274 5275 if (!IsDbgDeclare) { 5276 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5277 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in 5278 // the entry block. 5279 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front(); 5280 if (!IsInEntryBlock) 5281 return false; 5282 5283 // ArgDbgValues are hoisted to the beginning of the entry block. So we 5284 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a 5285 // variable that also is a param. 5286 // 5287 // Although, if we are at the top of the entry block already, we can still 5288 // emit using ArgDbgValue. This might catch some situations when the 5289 // dbg.value refers to an argument that isn't used in the entry block, so 5290 // any CopyToReg node would be optimized out and the only way to express 5291 // this DBG_VALUE is by using the physical reg (or FI) as done in this 5292 // method. ArgDbgValues are hoisted to the beginning of the entry block. So 5293 // we should only emit as ArgDbgValue if the Variable is an argument to the 5294 // current function, and the dbg.value intrinsic is found in the entry 5295 // block. 5296 bool VariableIsFunctionInputArg = Variable->isParameter() && 5297 !DL->getInlinedAt(); 5298 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder; 5299 if (!IsInPrologue && !VariableIsFunctionInputArg) 5300 return false; 5301 5302 // Here we assume that a function argument on IR level only can be used to 5303 // describe one input parameter on source level. If we for example have 5304 // source code like this 5305 // 5306 // struct A { long x, y; }; 5307 // void foo(struct A a, long b) { 5308 // ... 5309 // b = a.x; 5310 // ... 5311 // } 5312 // 5313 // and IR like this 5314 // 5315 // define void @foo(i32 %a1, i32 %a2, i32 %b) { 5316 // entry: 5317 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment 5318 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment 5319 // call void @llvm.dbg.value(metadata i32 %b, "b", 5320 // ... 5321 // call void @llvm.dbg.value(metadata i32 %a1, "b" 5322 // ... 5323 // 5324 // then the last dbg.value is describing a parameter "b" using a value that 5325 // is an argument. But since we already has used %a1 to describe a parameter 5326 // we should not handle that last dbg.value here (that would result in an 5327 // incorrect hoisting of the DBG_VALUE to the function entry). 5328 // Notice that we allow one dbg.value per IR level argument, to accomodate 5329 // for the situation with fragments above. 5330 if (VariableIsFunctionInputArg) { 5331 unsigned ArgNo = Arg->getArgNo(); 5332 if (ArgNo >= FuncInfo.DescribedArgs.size()) 5333 FuncInfo.DescribedArgs.resize(ArgNo + 1, false); 5334 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo)) 5335 return false; 5336 FuncInfo.DescribedArgs.set(ArgNo); 5337 } 5338 } 5339 5340 MachineFunction &MF = DAG.getMachineFunction(); 5341 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5342 5343 bool IsIndirect = false; 5344 Optional<MachineOperand> Op; 5345 // Some arguments' frame index is recorded during argument lowering. 5346 int FI = FuncInfo.getArgumentFrameIndex(Arg); 5347 if (FI != std::numeric_limits<int>::max()) 5348 Op = MachineOperand::CreateFI(FI); 5349 5350 if (!Op && N.getNode()) { 5351 unsigned Reg = getUnderlyingArgReg(N); 5352 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 5353 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 5354 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 5355 if (PR) 5356 Reg = PR; 5357 } 5358 if (Reg) { 5359 Op = MachineOperand::CreateReg(Reg, false); 5360 IsIndirect = IsDbgDeclare; 5361 } 5362 } 5363 5364 if (!Op && N.getNode()) { 5365 // Check if frame index is available. 5366 SDValue LCandidate = peekThroughBitcasts(N); 5367 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode())) 5368 if (FrameIndexSDNode *FINode = 5369 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 5370 Op = MachineOperand::CreateFI(FINode->getIndex()); 5371 } 5372 5373 if (!Op) { 5374 // Check if ValueMap has reg number. 5375 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 5376 if (VMI != FuncInfo.ValueMap.end()) { 5377 const auto &TLI = DAG.getTargetLoweringInfo(); 5378 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 5379 V->getType(), getABIRegCopyCC(V)); 5380 if (RFV.occupiesMultipleRegs()) { 5381 unsigned Offset = 0; 5382 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5383 Op = MachineOperand::CreateReg(RegAndSize.first, false); 5384 auto FragmentExpr = DIExpression::createFragmentExpression( 5385 Expr, Offset, RegAndSize.second); 5386 if (!FragmentExpr) 5387 continue; 5388 FuncInfo.ArgDbgValues.push_back( 5389 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 5390 Op->getReg(), Variable, *FragmentExpr)); 5391 Offset += RegAndSize.second; 5392 } 5393 return true; 5394 } 5395 Op = MachineOperand::CreateReg(VMI->second, false); 5396 IsIndirect = IsDbgDeclare; 5397 } 5398 } 5399 5400 if (!Op) 5401 return false; 5402 5403 assert(Variable->isValidLocationForIntrinsic(DL) && 5404 "Expected inlined-at fields to agree"); 5405 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5406 FuncInfo.ArgDbgValues.push_back( 5407 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5408 *Op, Variable, Expr)); 5409 5410 return true; 5411 } 5412 5413 /// Return the appropriate SDDbgValue based on N. 5414 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5415 DILocalVariable *Variable, 5416 DIExpression *Expr, 5417 const DebugLoc &dl, 5418 unsigned DbgSDNodeOrder) { 5419 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5420 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5421 // stack slot locations. 5422 // 5423 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5424 // debug values here after optimization: 5425 // 5426 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5427 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5428 // 5429 // Both describe the direct values of their associated variables. 5430 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5431 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5432 } 5433 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5434 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5435 } 5436 5437 // VisualStudio defines setjmp as _setjmp 5438 #if defined(_MSC_VER) && defined(setjmp) && \ 5439 !defined(setjmp_undefined_for_msvc) 5440 # pragma push_macro("setjmp") 5441 # undef setjmp 5442 # define setjmp_undefined_for_msvc 5443 #endif 5444 5445 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) { 5446 switch (Intrinsic) { 5447 case Intrinsic::smul_fix: 5448 return ISD::SMULFIX; 5449 case Intrinsic::umul_fix: 5450 return ISD::UMULFIX; 5451 default: 5452 llvm_unreachable("Unhandled fixed point intrinsic"); 5453 } 5454 } 5455 5456 /// Lower the call to the specified intrinsic function. If we want to emit this 5457 /// as a call to a named external function, return the name. Otherwise, lower it 5458 /// and return null. 5459 const char * 5460 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5461 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5462 SDLoc sdl = getCurSDLoc(); 5463 DebugLoc dl = getCurDebugLoc(); 5464 SDValue Res; 5465 5466 switch (Intrinsic) { 5467 default: 5468 // By default, turn this into a target intrinsic node. 5469 visitTargetIntrinsic(I, Intrinsic); 5470 return nullptr; 5471 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5472 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5473 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5474 case Intrinsic::returnaddress: 5475 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5476 TLI.getPointerTy(DAG.getDataLayout()), 5477 getValue(I.getArgOperand(0)))); 5478 return nullptr; 5479 case Intrinsic::addressofreturnaddress: 5480 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5481 TLI.getPointerTy(DAG.getDataLayout()))); 5482 return nullptr; 5483 case Intrinsic::sponentry: 5484 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5485 TLI.getPointerTy(DAG.getDataLayout()))); 5486 return nullptr; 5487 case Intrinsic::frameaddress: 5488 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5489 TLI.getPointerTy(DAG.getDataLayout()), 5490 getValue(I.getArgOperand(0)))); 5491 return nullptr; 5492 case Intrinsic::read_register: { 5493 Value *Reg = I.getArgOperand(0); 5494 SDValue Chain = getRoot(); 5495 SDValue RegName = 5496 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5497 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5498 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5499 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5500 setValue(&I, Res); 5501 DAG.setRoot(Res.getValue(1)); 5502 return nullptr; 5503 } 5504 case Intrinsic::write_register: { 5505 Value *Reg = I.getArgOperand(0); 5506 Value *RegValue = I.getArgOperand(1); 5507 SDValue Chain = getRoot(); 5508 SDValue RegName = 5509 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5510 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5511 RegName, getValue(RegValue))); 5512 return nullptr; 5513 } 5514 case Intrinsic::setjmp: 5515 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5516 case Intrinsic::longjmp: 5517 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5518 case Intrinsic::memcpy: { 5519 const auto &MCI = cast<MemCpyInst>(I); 5520 SDValue Op1 = getValue(I.getArgOperand(0)); 5521 SDValue Op2 = getValue(I.getArgOperand(1)); 5522 SDValue Op3 = getValue(I.getArgOperand(2)); 5523 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5524 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5525 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5526 unsigned Align = MinAlign(DstAlign, SrcAlign); 5527 bool isVol = MCI.isVolatile(); 5528 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5529 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5530 // node. 5531 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5532 false, isTC, 5533 MachinePointerInfo(I.getArgOperand(0)), 5534 MachinePointerInfo(I.getArgOperand(1))); 5535 updateDAGForMaybeTailCall(MC); 5536 return nullptr; 5537 } 5538 case Intrinsic::memset: { 5539 const auto &MSI = cast<MemSetInst>(I); 5540 SDValue Op1 = getValue(I.getArgOperand(0)); 5541 SDValue Op2 = getValue(I.getArgOperand(1)); 5542 SDValue Op3 = getValue(I.getArgOperand(2)); 5543 // @llvm.memset defines 0 and 1 to both mean no alignment. 5544 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5545 bool isVol = MSI.isVolatile(); 5546 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5547 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5548 isTC, MachinePointerInfo(I.getArgOperand(0))); 5549 updateDAGForMaybeTailCall(MS); 5550 return nullptr; 5551 } 5552 case Intrinsic::memmove: { 5553 const auto &MMI = cast<MemMoveInst>(I); 5554 SDValue Op1 = getValue(I.getArgOperand(0)); 5555 SDValue Op2 = getValue(I.getArgOperand(1)); 5556 SDValue Op3 = getValue(I.getArgOperand(2)); 5557 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5558 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5559 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5560 unsigned Align = MinAlign(DstAlign, SrcAlign); 5561 bool isVol = MMI.isVolatile(); 5562 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5563 // FIXME: Support passing different dest/src alignments to the memmove DAG 5564 // node. 5565 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5566 isTC, MachinePointerInfo(I.getArgOperand(0)), 5567 MachinePointerInfo(I.getArgOperand(1))); 5568 updateDAGForMaybeTailCall(MM); 5569 return nullptr; 5570 } 5571 case Intrinsic::memcpy_element_unordered_atomic: { 5572 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5573 SDValue Dst = getValue(MI.getRawDest()); 5574 SDValue Src = getValue(MI.getRawSource()); 5575 SDValue Length = getValue(MI.getLength()); 5576 5577 unsigned DstAlign = MI.getDestAlignment(); 5578 unsigned SrcAlign = MI.getSourceAlignment(); 5579 Type *LengthTy = MI.getLength()->getType(); 5580 unsigned ElemSz = MI.getElementSizeInBytes(); 5581 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5582 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5583 SrcAlign, Length, LengthTy, ElemSz, isTC, 5584 MachinePointerInfo(MI.getRawDest()), 5585 MachinePointerInfo(MI.getRawSource())); 5586 updateDAGForMaybeTailCall(MC); 5587 return nullptr; 5588 } 5589 case Intrinsic::memmove_element_unordered_atomic: { 5590 auto &MI = cast<AtomicMemMoveInst>(I); 5591 SDValue Dst = getValue(MI.getRawDest()); 5592 SDValue Src = getValue(MI.getRawSource()); 5593 SDValue Length = getValue(MI.getLength()); 5594 5595 unsigned DstAlign = MI.getDestAlignment(); 5596 unsigned SrcAlign = MI.getSourceAlignment(); 5597 Type *LengthTy = MI.getLength()->getType(); 5598 unsigned ElemSz = MI.getElementSizeInBytes(); 5599 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5600 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5601 SrcAlign, Length, LengthTy, ElemSz, isTC, 5602 MachinePointerInfo(MI.getRawDest()), 5603 MachinePointerInfo(MI.getRawSource())); 5604 updateDAGForMaybeTailCall(MC); 5605 return nullptr; 5606 } 5607 case Intrinsic::memset_element_unordered_atomic: { 5608 auto &MI = cast<AtomicMemSetInst>(I); 5609 SDValue Dst = getValue(MI.getRawDest()); 5610 SDValue Val = getValue(MI.getValue()); 5611 SDValue Length = getValue(MI.getLength()); 5612 5613 unsigned DstAlign = MI.getDestAlignment(); 5614 Type *LengthTy = MI.getLength()->getType(); 5615 unsigned ElemSz = MI.getElementSizeInBytes(); 5616 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5617 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5618 LengthTy, ElemSz, isTC, 5619 MachinePointerInfo(MI.getRawDest())); 5620 updateDAGForMaybeTailCall(MC); 5621 return nullptr; 5622 } 5623 case Intrinsic::dbg_addr: 5624 case Intrinsic::dbg_declare: { 5625 const auto &DI = cast<DbgVariableIntrinsic>(I); 5626 DILocalVariable *Variable = DI.getVariable(); 5627 DIExpression *Expression = DI.getExpression(); 5628 dropDanglingDebugInfo(Variable, Expression); 5629 assert(Variable && "Missing variable"); 5630 5631 // Check if address has undef value. 5632 const Value *Address = DI.getVariableLocation(); 5633 if (!Address || isa<UndefValue>(Address) || 5634 (Address->use_empty() && !isa<Argument>(Address))) { 5635 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5636 return nullptr; 5637 } 5638 5639 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5640 5641 // Check if this variable can be described by a frame index, typically 5642 // either as a static alloca or a byval parameter. 5643 int FI = std::numeric_limits<int>::max(); 5644 if (const auto *AI = 5645 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5646 if (AI->isStaticAlloca()) { 5647 auto I = FuncInfo.StaticAllocaMap.find(AI); 5648 if (I != FuncInfo.StaticAllocaMap.end()) 5649 FI = I->second; 5650 } 5651 } else if (const auto *Arg = dyn_cast<Argument>( 5652 Address->stripInBoundsConstantOffsets())) { 5653 FI = FuncInfo.getArgumentFrameIndex(Arg); 5654 } 5655 5656 // llvm.dbg.addr is control dependent and always generates indirect 5657 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5658 // the MachineFunction variable table. 5659 if (FI != std::numeric_limits<int>::max()) { 5660 if (Intrinsic == Intrinsic::dbg_addr) { 5661 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5662 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5663 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5664 } 5665 return nullptr; 5666 } 5667 5668 SDValue &N = NodeMap[Address]; 5669 if (!N.getNode() && isa<Argument>(Address)) 5670 // Check unused arguments map. 5671 N = UnusedArgNodeMap[Address]; 5672 SDDbgValue *SDV; 5673 if (N.getNode()) { 5674 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5675 Address = BCI->getOperand(0); 5676 // Parameters are handled specially. 5677 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5678 if (isParameter && FINode) { 5679 // Byval parameter. We have a frame index at this point. 5680 SDV = 5681 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5682 /*IsIndirect*/ true, dl, SDNodeOrder); 5683 } else if (isa<Argument>(Address)) { 5684 // Address is an argument, so try to emit its dbg value using 5685 // virtual register info from the FuncInfo.ValueMap. 5686 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5687 return nullptr; 5688 } else { 5689 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5690 true, dl, SDNodeOrder); 5691 } 5692 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5693 } else { 5694 // If Address is an argument then try to emit its dbg value using 5695 // virtual register info from the FuncInfo.ValueMap. 5696 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5697 N)) { 5698 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5699 } 5700 } 5701 return nullptr; 5702 } 5703 case Intrinsic::dbg_label: { 5704 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5705 DILabel *Label = DI.getLabel(); 5706 assert(Label && "Missing label"); 5707 5708 SDDbgLabel *SDV; 5709 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5710 DAG.AddDbgLabel(SDV); 5711 return nullptr; 5712 } 5713 case Intrinsic::dbg_value: { 5714 const DbgValueInst &DI = cast<DbgValueInst>(I); 5715 assert(DI.getVariable() && "Missing variable"); 5716 5717 DILocalVariable *Variable = DI.getVariable(); 5718 DIExpression *Expression = DI.getExpression(); 5719 dropDanglingDebugInfo(Variable, Expression); 5720 const Value *V = DI.getValue(); 5721 if (!V) 5722 return nullptr; 5723 5724 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(), 5725 SDNodeOrder)) 5726 return nullptr; 5727 5728 // TODO: Dangling debug info will eventually either be resolved or produce 5729 // an Undef DBG_VALUE. However in the resolution case, a gap may appear 5730 // between the original dbg.value location and its resolved DBG_VALUE, which 5731 // we should ideally fill with an extra Undef DBG_VALUE. 5732 5733 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5734 return nullptr; 5735 } 5736 5737 case Intrinsic::eh_typeid_for: { 5738 // Find the type id for the given typeinfo. 5739 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5740 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5741 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5742 setValue(&I, Res); 5743 return nullptr; 5744 } 5745 5746 case Intrinsic::eh_return_i32: 5747 case Intrinsic::eh_return_i64: 5748 DAG.getMachineFunction().setCallsEHReturn(true); 5749 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5750 MVT::Other, 5751 getControlRoot(), 5752 getValue(I.getArgOperand(0)), 5753 getValue(I.getArgOperand(1)))); 5754 return nullptr; 5755 case Intrinsic::eh_unwind_init: 5756 DAG.getMachineFunction().setCallsUnwindInit(true); 5757 return nullptr; 5758 case Intrinsic::eh_dwarf_cfa: 5759 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5760 TLI.getPointerTy(DAG.getDataLayout()), 5761 getValue(I.getArgOperand(0)))); 5762 return nullptr; 5763 case Intrinsic::eh_sjlj_callsite: { 5764 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5765 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5766 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5767 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5768 5769 MMI.setCurrentCallSite(CI->getZExtValue()); 5770 return nullptr; 5771 } 5772 case Intrinsic::eh_sjlj_functioncontext: { 5773 // Get and store the index of the function context. 5774 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5775 AllocaInst *FnCtx = 5776 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5777 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5778 MFI.setFunctionContextIndex(FI); 5779 return nullptr; 5780 } 5781 case Intrinsic::eh_sjlj_setjmp: { 5782 SDValue Ops[2]; 5783 Ops[0] = getRoot(); 5784 Ops[1] = getValue(I.getArgOperand(0)); 5785 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5786 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5787 setValue(&I, Op.getValue(0)); 5788 DAG.setRoot(Op.getValue(1)); 5789 return nullptr; 5790 } 5791 case Intrinsic::eh_sjlj_longjmp: 5792 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5793 getRoot(), getValue(I.getArgOperand(0)))); 5794 return nullptr; 5795 case Intrinsic::eh_sjlj_setup_dispatch: 5796 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5797 getRoot())); 5798 return nullptr; 5799 case Intrinsic::masked_gather: 5800 visitMaskedGather(I); 5801 return nullptr; 5802 case Intrinsic::masked_load: 5803 visitMaskedLoad(I); 5804 return nullptr; 5805 case Intrinsic::masked_scatter: 5806 visitMaskedScatter(I); 5807 return nullptr; 5808 case Intrinsic::masked_store: 5809 visitMaskedStore(I); 5810 return nullptr; 5811 case Intrinsic::masked_expandload: 5812 visitMaskedLoad(I, true /* IsExpanding */); 5813 return nullptr; 5814 case Intrinsic::masked_compressstore: 5815 visitMaskedStore(I, true /* IsCompressing */); 5816 return nullptr; 5817 case Intrinsic::x86_mmx_pslli_w: 5818 case Intrinsic::x86_mmx_pslli_d: 5819 case Intrinsic::x86_mmx_pslli_q: 5820 case Intrinsic::x86_mmx_psrli_w: 5821 case Intrinsic::x86_mmx_psrli_d: 5822 case Intrinsic::x86_mmx_psrli_q: 5823 case Intrinsic::x86_mmx_psrai_w: 5824 case Intrinsic::x86_mmx_psrai_d: { 5825 SDValue ShAmt = getValue(I.getArgOperand(1)); 5826 if (isa<ConstantSDNode>(ShAmt)) { 5827 visitTargetIntrinsic(I, Intrinsic); 5828 return nullptr; 5829 } 5830 unsigned NewIntrinsic = 0; 5831 EVT ShAmtVT = MVT::v2i32; 5832 switch (Intrinsic) { 5833 case Intrinsic::x86_mmx_pslli_w: 5834 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5835 break; 5836 case Intrinsic::x86_mmx_pslli_d: 5837 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5838 break; 5839 case Intrinsic::x86_mmx_pslli_q: 5840 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5841 break; 5842 case Intrinsic::x86_mmx_psrli_w: 5843 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5844 break; 5845 case Intrinsic::x86_mmx_psrli_d: 5846 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5847 break; 5848 case Intrinsic::x86_mmx_psrli_q: 5849 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5850 break; 5851 case Intrinsic::x86_mmx_psrai_w: 5852 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5853 break; 5854 case Intrinsic::x86_mmx_psrai_d: 5855 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5856 break; 5857 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5858 } 5859 5860 // The vector shift intrinsics with scalars uses 32b shift amounts but 5861 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5862 // to be zero. 5863 // We must do this early because v2i32 is not a legal type. 5864 SDValue ShOps[2]; 5865 ShOps[0] = ShAmt; 5866 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5867 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5868 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5869 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5870 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5871 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5872 getValue(I.getArgOperand(0)), ShAmt); 5873 setValue(&I, Res); 5874 return nullptr; 5875 } 5876 case Intrinsic::powi: 5877 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5878 getValue(I.getArgOperand(1)), DAG)); 5879 return nullptr; 5880 case Intrinsic::log: 5881 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5882 return nullptr; 5883 case Intrinsic::log2: 5884 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5885 return nullptr; 5886 case Intrinsic::log10: 5887 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5888 return nullptr; 5889 case Intrinsic::exp: 5890 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5891 return nullptr; 5892 case Intrinsic::exp2: 5893 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5894 return nullptr; 5895 case Intrinsic::pow: 5896 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5897 getValue(I.getArgOperand(1)), DAG, TLI)); 5898 return nullptr; 5899 case Intrinsic::sqrt: 5900 case Intrinsic::fabs: 5901 case Intrinsic::sin: 5902 case Intrinsic::cos: 5903 case Intrinsic::floor: 5904 case Intrinsic::ceil: 5905 case Intrinsic::trunc: 5906 case Intrinsic::rint: 5907 case Intrinsic::nearbyint: 5908 case Intrinsic::round: 5909 case Intrinsic::canonicalize: { 5910 unsigned Opcode; 5911 switch (Intrinsic) { 5912 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5913 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5914 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5915 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5916 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5917 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5918 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5919 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5920 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5921 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5922 case Intrinsic::round: Opcode = ISD::FROUND; break; 5923 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5924 } 5925 5926 setValue(&I, DAG.getNode(Opcode, sdl, 5927 getValue(I.getArgOperand(0)).getValueType(), 5928 getValue(I.getArgOperand(0)))); 5929 return nullptr; 5930 } 5931 case Intrinsic::minnum: { 5932 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5933 unsigned Opc = 5934 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5935 ? ISD::FMINIMUM 5936 : ISD::FMINNUM; 5937 setValue(&I, DAG.getNode(Opc, sdl, VT, 5938 getValue(I.getArgOperand(0)), 5939 getValue(I.getArgOperand(1)))); 5940 return nullptr; 5941 } 5942 case Intrinsic::maxnum: { 5943 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5944 unsigned Opc = 5945 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5946 ? ISD::FMAXIMUM 5947 : ISD::FMAXNUM; 5948 setValue(&I, DAG.getNode(Opc, sdl, VT, 5949 getValue(I.getArgOperand(0)), 5950 getValue(I.getArgOperand(1)))); 5951 return nullptr; 5952 } 5953 case Intrinsic::minimum: 5954 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5955 getValue(I.getArgOperand(0)).getValueType(), 5956 getValue(I.getArgOperand(0)), 5957 getValue(I.getArgOperand(1)))); 5958 return nullptr; 5959 case Intrinsic::maximum: 5960 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5961 getValue(I.getArgOperand(0)).getValueType(), 5962 getValue(I.getArgOperand(0)), 5963 getValue(I.getArgOperand(1)))); 5964 return nullptr; 5965 case Intrinsic::copysign: 5966 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5967 getValue(I.getArgOperand(0)).getValueType(), 5968 getValue(I.getArgOperand(0)), 5969 getValue(I.getArgOperand(1)))); 5970 return nullptr; 5971 case Intrinsic::fma: 5972 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5973 getValue(I.getArgOperand(0)).getValueType(), 5974 getValue(I.getArgOperand(0)), 5975 getValue(I.getArgOperand(1)), 5976 getValue(I.getArgOperand(2)))); 5977 return nullptr; 5978 case Intrinsic::experimental_constrained_fadd: 5979 case Intrinsic::experimental_constrained_fsub: 5980 case Intrinsic::experimental_constrained_fmul: 5981 case Intrinsic::experimental_constrained_fdiv: 5982 case Intrinsic::experimental_constrained_frem: 5983 case Intrinsic::experimental_constrained_fma: 5984 case Intrinsic::experimental_constrained_sqrt: 5985 case Intrinsic::experimental_constrained_pow: 5986 case Intrinsic::experimental_constrained_powi: 5987 case Intrinsic::experimental_constrained_sin: 5988 case Intrinsic::experimental_constrained_cos: 5989 case Intrinsic::experimental_constrained_exp: 5990 case Intrinsic::experimental_constrained_exp2: 5991 case Intrinsic::experimental_constrained_log: 5992 case Intrinsic::experimental_constrained_log10: 5993 case Intrinsic::experimental_constrained_log2: 5994 case Intrinsic::experimental_constrained_rint: 5995 case Intrinsic::experimental_constrained_nearbyint: 5996 case Intrinsic::experimental_constrained_maxnum: 5997 case Intrinsic::experimental_constrained_minnum: 5998 case Intrinsic::experimental_constrained_ceil: 5999 case Intrinsic::experimental_constrained_floor: 6000 case Intrinsic::experimental_constrained_round: 6001 case Intrinsic::experimental_constrained_trunc: 6002 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 6003 return nullptr; 6004 case Intrinsic::fmuladd: { 6005 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6006 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 6007 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 6008 setValue(&I, DAG.getNode(ISD::FMA, sdl, 6009 getValue(I.getArgOperand(0)).getValueType(), 6010 getValue(I.getArgOperand(0)), 6011 getValue(I.getArgOperand(1)), 6012 getValue(I.getArgOperand(2)))); 6013 } else { 6014 // TODO: Intrinsic calls should have fast-math-flags. 6015 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 6016 getValue(I.getArgOperand(0)).getValueType(), 6017 getValue(I.getArgOperand(0)), 6018 getValue(I.getArgOperand(1))); 6019 SDValue Add = DAG.getNode(ISD::FADD, sdl, 6020 getValue(I.getArgOperand(0)).getValueType(), 6021 Mul, 6022 getValue(I.getArgOperand(2))); 6023 setValue(&I, Add); 6024 } 6025 return nullptr; 6026 } 6027 case Intrinsic::convert_to_fp16: 6028 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 6029 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 6030 getValue(I.getArgOperand(0)), 6031 DAG.getTargetConstant(0, sdl, 6032 MVT::i32)))); 6033 return nullptr; 6034 case Intrinsic::convert_from_fp16: 6035 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 6036 TLI.getValueType(DAG.getDataLayout(), I.getType()), 6037 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 6038 getValue(I.getArgOperand(0))))); 6039 return nullptr; 6040 case Intrinsic::pcmarker: { 6041 SDValue Tmp = getValue(I.getArgOperand(0)); 6042 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 6043 return nullptr; 6044 } 6045 case Intrinsic::readcyclecounter: { 6046 SDValue Op = getRoot(); 6047 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 6048 DAG.getVTList(MVT::i64, MVT::Other), Op); 6049 setValue(&I, Res); 6050 DAG.setRoot(Res.getValue(1)); 6051 return nullptr; 6052 } 6053 case Intrinsic::bitreverse: 6054 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 6055 getValue(I.getArgOperand(0)).getValueType(), 6056 getValue(I.getArgOperand(0)))); 6057 return nullptr; 6058 case Intrinsic::bswap: 6059 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 6060 getValue(I.getArgOperand(0)).getValueType(), 6061 getValue(I.getArgOperand(0)))); 6062 return nullptr; 6063 case Intrinsic::cttz: { 6064 SDValue Arg = getValue(I.getArgOperand(0)); 6065 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6066 EVT Ty = Arg.getValueType(); 6067 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 6068 sdl, Ty, Arg)); 6069 return nullptr; 6070 } 6071 case Intrinsic::ctlz: { 6072 SDValue Arg = getValue(I.getArgOperand(0)); 6073 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 6074 EVT Ty = Arg.getValueType(); 6075 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 6076 sdl, Ty, Arg)); 6077 return nullptr; 6078 } 6079 case Intrinsic::ctpop: { 6080 SDValue Arg = getValue(I.getArgOperand(0)); 6081 EVT Ty = Arg.getValueType(); 6082 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 6083 return nullptr; 6084 } 6085 case Intrinsic::fshl: 6086 case Intrinsic::fshr: { 6087 bool IsFSHL = Intrinsic == Intrinsic::fshl; 6088 SDValue X = getValue(I.getArgOperand(0)); 6089 SDValue Y = getValue(I.getArgOperand(1)); 6090 SDValue Z = getValue(I.getArgOperand(2)); 6091 EVT VT = X.getValueType(); 6092 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 6093 SDValue Zero = DAG.getConstant(0, sdl, VT); 6094 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 6095 6096 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 6097 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 6098 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 6099 return nullptr; 6100 } 6101 6102 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 6103 // avoid the select that is necessary in the general case to filter out 6104 // the 0-shift possibility that leads to UB. 6105 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 6106 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 6107 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6108 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 6109 return nullptr; 6110 } 6111 6112 // Some targets only rotate one way. Try the opposite direction. 6113 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 6114 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 6115 // Negate the shift amount because it is safe to ignore the high bits. 6116 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6117 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 6118 return nullptr; 6119 } 6120 6121 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 6122 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 6123 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 6124 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 6125 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 6126 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 6127 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 6128 return nullptr; 6129 } 6130 6131 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 6132 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 6133 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 6134 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 6135 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 6136 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 6137 6138 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 6139 // and that is undefined. We must compare and select to avoid UB. 6140 EVT CCVT = MVT::i1; 6141 if (VT.isVector()) 6142 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 6143 6144 // For fshl, 0-shift returns the 1st arg (X). 6145 // For fshr, 0-shift returns the 2nd arg (Y). 6146 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 6147 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 6148 return nullptr; 6149 } 6150 case Intrinsic::sadd_sat: { 6151 SDValue Op1 = getValue(I.getArgOperand(0)); 6152 SDValue Op2 = getValue(I.getArgOperand(1)); 6153 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6154 return nullptr; 6155 } 6156 case Intrinsic::uadd_sat: { 6157 SDValue Op1 = getValue(I.getArgOperand(0)); 6158 SDValue Op2 = getValue(I.getArgOperand(1)); 6159 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 6160 return nullptr; 6161 } 6162 case Intrinsic::ssub_sat: { 6163 SDValue Op1 = getValue(I.getArgOperand(0)); 6164 SDValue Op2 = getValue(I.getArgOperand(1)); 6165 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6166 return nullptr; 6167 } 6168 case Intrinsic::usub_sat: { 6169 SDValue Op1 = getValue(I.getArgOperand(0)); 6170 SDValue Op2 = getValue(I.getArgOperand(1)); 6171 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 6172 return nullptr; 6173 } 6174 case Intrinsic::smul_fix: 6175 case Intrinsic::umul_fix: { 6176 SDValue Op1 = getValue(I.getArgOperand(0)); 6177 SDValue Op2 = getValue(I.getArgOperand(1)); 6178 SDValue Op3 = getValue(I.getArgOperand(2)); 6179 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl, 6180 Op1.getValueType(), Op1, Op2, Op3)); 6181 return nullptr; 6182 } 6183 case Intrinsic::stacksave: { 6184 SDValue Op = getRoot(); 6185 Res = DAG.getNode( 6186 ISD::STACKSAVE, sdl, 6187 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 6188 setValue(&I, Res); 6189 DAG.setRoot(Res.getValue(1)); 6190 return nullptr; 6191 } 6192 case Intrinsic::stackrestore: 6193 Res = getValue(I.getArgOperand(0)); 6194 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 6195 return nullptr; 6196 case Intrinsic::get_dynamic_area_offset: { 6197 SDValue Op = getRoot(); 6198 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6199 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 6200 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 6201 // target. 6202 if (PtrTy != ResTy) 6203 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 6204 " intrinsic!"); 6205 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 6206 Op); 6207 DAG.setRoot(Op); 6208 setValue(&I, Res); 6209 return nullptr; 6210 } 6211 case Intrinsic::stackguard: { 6212 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6213 MachineFunction &MF = DAG.getMachineFunction(); 6214 const Module &M = *MF.getFunction().getParent(); 6215 SDValue Chain = getRoot(); 6216 if (TLI.useLoadStackGuardNode()) { 6217 Res = getLoadStackGuard(DAG, sdl, Chain); 6218 } else { 6219 const Value *Global = TLI.getSDagStackGuard(M); 6220 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 6221 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 6222 MachinePointerInfo(Global, 0), Align, 6223 MachineMemOperand::MOVolatile); 6224 } 6225 if (TLI.useStackGuardXorFP()) 6226 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 6227 DAG.setRoot(Chain); 6228 setValue(&I, Res); 6229 return nullptr; 6230 } 6231 case Intrinsic::stackprotector: { 6232 // Emit code into the DAG to store the stack guard onto the stack. 6233 MachineFunction &MF = DAG.getMachineFunction(); 6234 MachineFrameInfo &MFI = MF.getFrameInfo(); 6235 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 6236 SDValue Src, Chain = getRoot(); 6237 6238 if (TLI.useLoadStackGuardNode()) 6239 Src = getLoadStackGuard(DAG, sdl, Chain); 6240 else 6241 Src = getValue(I.getArgOperand(0)); // The guard's value. 6242 6243 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 6244 6245 int FI = FuncInfo.StaticAllocaMap[Slot]; 6246 MFI.setStackProtectorIndex(FI); 6247 6248 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 6249 6250 // Store the stack protector onto the stack. 6251 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 6252 DAG.getMachineFunction(), FI), 6253 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 6254 setValue(&I, Res); 6255 DAG.setRoot(Res); 6256 return nullptr; 6257 } 6258 case Intrinsic::objectsize: { 6259 // If we don't know by now, we're never going to know. 6260 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 6261 6262 assert(CI && "Non-constant type in __builtin_object_size?"); 6263 6264 SDValue Arg = getValue(I.getCalledValue()); 6265 EVT Ty = Arg.getValueType(); 6266 6267 if (CI->isZero()) 6268 Res = DAG.getConstant(-1ULL, sdl, Ty); 6269 else 6270 Res = DAG.getConstant(0, sdl, Ty); 6271 6272 setValue(&I, Res); 6273 return nullptr; 6274 } 6275 6276 case Intrinsic::is_constant: 6277 // If this wasn't constant-folded away by now, then it's not a 6278 // constant. 6279 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 6280 return nullptr; 6281 6282 case Intrinsic::annotation: 6283 case Intrinsic::ptr_annotation: 6284 case Intrinsic::launder_invariant_group: 6285 case Intrinsic::strip_invariant_group: 6286 // Drop the intrinsic, but forward the value 6287 setValue(&I, getValue(I.getOperand(0))); 6288 return nullptr; 6289 case Intrinsic::assume: 6290 case Intrinsic::var_annotation: 6291 case Intrinsic::sideeffect: 6292 // Discard annotate attributes, assumptions, and artificial side-effects. 6293 return nullptr; 6294 6295 case Intrinsic::codeview_annotation: { 6296 // Emit a label associated with this metadata. 6297 MachineFunction &MF = DAG.getMachineFunction(); 6298 MCSymbol *Label = 6299 MF.getMMI().getContext().createTempSymbol("annotation", true); 6300 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 6301 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 6302 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 6303 DAG.setRoot(Res); 6304 return nullptr; 6305 } 6306 6307 case Intrinsic::init_trampoline: { 6308 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 6309 6310 SDValue Ops[6]; 6311 Ops[0] = getRoot(); 6312 Ops[1] = getValue(I.getArgOperand(0)); 6313 Ops[2] = getValue(I.getArgOperand(1)); 6314 Ops[3] = getValue(I.getArgOperand(2)); 6315 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 6316 Ops[5] = DAG.getSrcValue(F); 6317 6318 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 6319 6320 DAG.setRoot(Res); 6321 return nullptr; 6322 } 6323 case Intrinsic::adjust_trampoline: 6324 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6325 TLI.getPointerTy(DAG.getDataLayout()), 6326 getValue(I.getArgOperand(0)))); 6327 return nullptr; 6328 case Intrinsic::gcroot: { 6329 assert(DAG.getMachineFunction().getFunction().hasGC() && 6330 "only valid in functions with gc specified, enforced by Verifier"); 6331 assert(GFI && "implied by previous"); 6332 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6333 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6334 6335 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6336 GFI->addStackRoot(FI->getIndex(), TypeMap); 6337 return nullptr; 6338 } 6339 case Intrinsic::gcread: 6340 case Intrinsic::gcwrite: 6341 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6342 case Intrinsic::flt_rounds: 6343 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6344 return nullptr; 6345 6346 case Intrinsic::expect: 6347 // Just replace __builtin_expect(exp, c) with EXP. 6348 setValue(&I, getValue(I.getArgOperand(0))); 6349 return nullptr; 6350 6351 case Intrinsic::debugtrap: 6352 case Intrinsic::trap: { 6353 StringRef TrapFuncName = 6354 I.getAttributes() 6355 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6356 .getValueAsString(); 6357 if (TrapFuncName.empty()) { 6358 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6359 ISD::TRAP : ISD::DEBUGTRAP; 6360 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6361 return nullptr; 6362 } 6363 TargetLowering::ArgListTy Args; 6364 6365 TargetLowering::CallLoweringInfo CLI(DAG); 6366 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6367 CallingConv::C, I.getType(), 6368 DAG.getExternalSymbol(TrapFuncName.data(), 6369 TLI.getPointerTy(DAG.getDataLayout())), 6370 std::move(Args)); 6371 6372 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6373 DAG.setRoot(Result.second); 6374 return nullptr; 6375 } 6376 6377 case Intrinsic::uadd_with_overflow: 6378 case Intrinsic::sadd_with_overflow: 6379 case Intrinsic::usub_with_overflow: 6380 case Intrinsic::ssub_with_overflow: 6381 case Intrinsic::umul_with_overflow: 6382 case Intrinsic::smul_with_overflow: { 6383 ISD::NodeType Op; 6384 switch (Intrinsic) { 6385 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6386 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6387 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6388 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6389 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6390 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6391 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6392 } 6393 SDValue Op1 = getValue(I.getArgOperand(0)); 6394 SDValue Op2 = getValue(I.getArgOperand(1)); 6395 6396 EVT ResultVT = Op1.getValueType(); 6397 EVT OverflowVT = MVT::i1; 6398 if (ResultVT.isVector()) 6399 OverflowVT = EVT::getVectorVT( 6400 *Context, OverflowVT, ResultVT.getVectorNumElements()); 6401 6402 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT); 6403 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6404 return nullptr; 6405 } 6406 case Intrinsic::prefetch: { 6407 SDValue Ops[5]; 6408 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6409 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6410 Ops[0] = DAG.getRoot(); 6411 Ops[1] = getValue(I.getArgOperand(0)); 6412 Ops[2] = getValue(I.getArgOperand(1)); 6413 Ops[3] = getValue(I.getArgOperand(2)); 6414 Ops[4] = getValue(I.getArgOperand(3)); 6415 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6416 DAG.getVTList(MVT::Other), Ops, 6417 EVT::getIntegerVT(*Context, 8), 6418 MachinePointerInfo(I.getArgOperand(0)), 6419 0, /* align */ 6420 Flags); 6421 6422 // Chain the prefetch in parallell with any pending loads, to stay out of 6423 // the way of later optimizations. 6424 PendingLoads.push_back(Result); 6425 Result = getRoot(); 6426 DAG.setRoot(Result); 6427 return nullptr; 6428 } 6429 case Intrinsic::lifetime_start: 6430 case Intrinsic::lifetime_end: { 6431 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6432 // Stack coloring is not enabled in O0, discard region information. 6433 if (TM.getOptLevel() == CodeGenOpt::None) 6434 return nullptr; 6435 6436 const int64_t ObjectSize = 6437 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue(); 6438 Value *const ObjectPtr = I.getArgOperand(1); 6439 SmallVector<Value *, 4> Allocas; 6440 GetUnderlyingObjects(ObjectPtr, Allocas, *DL); 6441 6442 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6443 E = Allocas.end(); Object != E; ++Object) { 6444 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6445 6446 // Could not find an Alloca. 6447 if (!LifetimeObject) 6448 continue; 6449 6450 // First check that the Alloca is static, otherwise it won't have a 6451 // valid frame index. 6452 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6453 if (SI == FuncInfo.StaticAllocaMap.end()) 6454 return nullptr; 6455 6456 const int FrameIndex = SI->second; 6457 int64_t Offset; 6458 if (GetPointerBaseWithConstantOffset( 6459 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject) 6460 Offset = -1; // Cannot determine offset from alloca to lifetime object. 6461 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize, 6462 Offset); 6463 DAG.setRoot(Res); 6464 } 6465 return nullptr; 6466 } 6467 case Intrinsic::invariant_start: 6468 // Discard region information. 6469 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6470 return nullptr; 6471 case Intrinsic::invariant_end: 6472 // Discard region information. 6473 return nullptr; 6474 case Intrinsic::clear_cache: 6475 return TLI.getClearCacheBuiltinName(); 6476 case Intrinsic::donothing: 6477 // ignore 6478 return nullptr; 6479 case Intrinsic::experimental_stackmap: 6480 visitStackmap(I); 6481 return nullptr; 6482 case Intrinsic::experimental_patchpoint_void: 6483 case Intrinsic::experimental_patchpoint_i64: 6484 visitPatchpoint(&I); 6485 return nullptr; 6486 case Intrinsic::experimental_gc_statepoint: 6487 LowerStatepoint(ImmutableStatepoint(&I)); 6488 return nullptr; 6489 case Intrinsic::experimental_gc_result: 6490 visitGCResult(cast<GCResultInst>(I)); 6491 return nullptr; 6492 case Intrinsic::experimental_gc_relocate: 6493 visitGCRelocate(cast<GCRelocateInst>(I)); 6494 return nullptr; 6495 case Intrinsic::instrprof_increment: 6496 llvm_unreachable("instrprof failed to lower an increment"); 6497 case Intrinsic::instrprof_value_profile: 6498 llvm_unreachable("instrprof failed to lower a value profiling call"); 6499 case Intrinsic::localescape: { 6500 MachineFunction &MF = DAG.getMachineFunction(); 6501 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6502 6503 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6504 // is the same on all targets. 6505 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6506 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6507 if (isa<ConstantPointerNull>(Arg)) 6508 continue; // Skip null pointers. They represent a hole in index space. 6509 AllocaInst *Slot = cast<AllocaInst>(Arg); 6510 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6511 "can only escape static allocas"); 6512 int FI = FuncInfo.StaticAllocaMap[Slot]; 6513 MCSymbol *FrameAllocSym = 6514 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6515 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6517 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6518 .addSym(FrameAllocSym) 6519 .addFrameIndex(FI); 6520 } 6521 6522 return nullptr; 6523 } 6524 6525 case Intrinsic::localrecover: { 6526 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6527 MachineFunction &MF = DAG.getMachineFunction(); 6528 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6529 6530 // Get the symbol that defines the frame offset. 6531 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6532 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6533 unsigned IdxVal = 6534 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6535 MCSymbol *FrameAllocSym = 6536 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6537 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6538 6539 // Create a MCSymbol for the label to avoid any target lowering 6540 // that would make this PC relative. 6541 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6542 SDValue OffsetVal = 6543 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6544 6545 // Add the offset to the FP. 6546 Value *FP = I.getArgOperand(1); 6547 SDValue FPVal = getValue(FP); 6548 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6549 setValue(&I, Add); 6550 6551 return nullptr; 6552 } 6553 6554 case Intrinsic::eh_exceptionpointer: 6555 case Intrinsic::eh_exceptioncode: { 6556 // Get the exception pointer vreg, copy from it, and resize it to fit. 6557 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6558 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6559 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6560 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6561 SDValue N = 6562 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6563 if (Intrinsic == Intrinsic::eh_exceptioncode) 6564 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6565 setValue(&I, N); 6566 return nullptr; 6567 } 6568 case Intrinsic::xray_customevent: { 6569 // Here we want to make sure that the intrinsic behaves as if it has a 6570 // specific calling convention, and only for x86_64. 6571 // FIXME: Support other platforms later. 6572 const auto &Triple = DAG.getTarget().getTargetTriple(); 6573 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6574 return nullptr; 6575 6576 SDLoc DL = getCurSDLoc(); 6577 SmallVector<SDValue, 8> Ops; 6578 6579 // We want to say that we always want the arguments in registers. 6580 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6581 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6582 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6583 SDValue Chain = getRoot(); 6584 Ops.push_back(LogEntryVal); 6585 Ops.push_back(StrSizeVal); 6586 Ops.push_back(Chain); 6587 6588 // We need to enforce the calling convention for the callsite, so that 6589 // argument ordering is enforced correctly, and that register allocation can 6590 // see that some registers may be assumed clobbered and have to preserve 6591 // them across calls to the intrinsic. 6592 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6593 DL, NodeTys, Ops); 6594 SDValue patchableNode = SDValue(MN, 0); 6595 DAG.setRoot(patchableNode); 6596 setValue(&I, patchableNode); 6597 return nullptr; 6598 } 6599 case Intrinsic::xray_typedevent: { 6600 // Here we want to make sure that the intrinsic behaves as if it has a 6601 // specific calling convention, and only for x86_64. 6602 // FIXME: Support other platforms later. 6603 const auto &Triple = DAG.getTarget().getTargetTriple(); 6604 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6605 return nullptr; 6606 6607 SDLoc DL = getCurSDLoc(); 6608 SmallVector<SDValue, 8> Ops; 6609 6610 // We want to say that we always want the arguments in registers. 6611 // It's unclear to me how manipulating the selection DAG here forces callers 6612 // to provide arguments in registers instead of on the stack. 6613 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6614 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6615 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6616 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6617 SDValue Chain = getRoot(); 6618 Ops.push_back(LogTypeId); 6619 Ops.push_back(LogEntryVal); 6620 Ops.push_back(StrSizeVal); 6621 Ops.push_back(Chain); 6622 6623 // We need to enforce the calling convention for the callsite, so that 6624 // argument ordering is enforced correctly, and that register allocation can 6625 // see that some registers may be assumed clobbered and have to preserve 6626 // them across calls to the intrinsic. 6627 MachineSDNode *MN = DAG.getMachineNode( 6628 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6629 SDValue patchableNode = SDValue(MN, 0); 6630 DAG.setRoot(patchableNode); 6631 setValue(&I, patchableNode); 6632 return nullptr; 6633 } 6634 case Intrinsic::experimental_deoptimize: 6635 LowerDeoptimizeCall(&I); 6636 return nullptr; 6637 6638 case Intrinsic::experimental_vector_reduce_fadd: 6639 case Intrinsic::experimental_vector_reduce_fmul: 6640 case Intrinsic::experimental_vector_reduce_add: 6641 case Intrinsic::experimental_vector_reduce_mul: 6642 case Intrinsic::experimental_vector_reduce_and: 6643 case Intrinsic::experimental_vector_reduce_or: 6644 case Intrinsic::experimental_vector_reduce_xor: 6645 case Intrinsic::experimental_vector_reduce_smax: 6646 case Intrinsic::experimental_vector_reduce_smin: 6647 case Intrinsic::experimental_vector_reduce_umax: 6648 case Intrinsic::experimental_vector_reduce_umin: 6649 case Intrinsic::experimental_vector_reduce_fmax: 6650 case Intrinsic::experimental_vector_reduce_fmin: 6651 visitVectorReduce(I, Intrinsic); 6652 return nullptr; 6653 6654 case Intrinsic::icall_branch_funnel: { 6655 SmallVector<SDValue, 16> Ops; 6656 Ops.push_back(DAG.getRoot()); 6657 Ops.push_back(getValue(I.getArgOperand(0))); 6658 6659 int64_t Offset; 6660 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6661 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6662 if (!Base) 6663 report_fatal_error( 6664 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6665 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6666 6667 struct BranchFunnelTarget { 6668 int64_t Offset; 6669 SDValue Target; 6670 }; 6671 SmallVector<BranchFunnelTarget, 8> Targets; 6672 6673 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6674 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6675 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6676 if (ElemBase != Base) 6677 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6678 "to the same GlobalValue"); 6679 6680 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6681 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6682 if (!GA) 6683 report_fatal_error( 6684 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6685 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6686 GA->getGlobal(), getCurSDLoc(), 6687 Val.getValueType(), GA->getOffset())}); 6688 } 6689 llvm::sort(Targets, 6690 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6691 return T1.Offset < T2.Offset; 6692 }); 6693 6694 for (auto &T : Targets) { 6695 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6696 Ops.push_back(T.Target); 6697 } 6698 6699 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6700 getCurSDLoc(), MVT::Other, Ops), 6701 0); 6702 DAG.setRoot(N); 6703 setValue(&I, N); 6704 HasTailCall = true; 6705 return nullptr; 6706 } 6707 6708 case Intrinsic::wasm_landingpad_index: 6709 // Information this intrinsic contained has been transferred to 6710 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6711 // delete it now. 6712 return nullptr; 6713 } 6714 } 6715 6716 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6717 const ConstrainedFPIntrinsic &FPI) { 6718 SDLoc sdl = getCurSDLoc(); 6719 unsigned Opcode; 6720 switch (FPI.getIntrinsicID()) { 6721 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6722 case Intrinsic::experimental_constrained_fadd: 6723 Opcode = ISD::STRICT_FADD; 6724 break; 6725 case Intrinsic::experimental_constrained_fsub: 6726 Opcode = ISD::STRICT_FSUB; 6727 break; 6728 case Intrinsic::experimental_constrained_fmul: 6729 Opcode = ISD::STRICT_FMUL; 6730 break; 6731 case Intrinsic::experimental_constrained_fdiv: 6732 Opcode = ISD::STRICT_FDIV; 6733 break; 6734 case Intrinsic::experimental_constrained_frem: 6735 Opcode = ISD::STRICT_FREM; 6736 break; 6737 case Intrinsic::experimental_constrained_fma: 6738 Opcode = ISD::STRICT_FMA; 6739 break; 6740 case Intrinsic::experimental_constrained_sqrt: 6741 Opcode = ISD::STRICT_FSQRT; 6742 break; 6743 case Intrinsic::experimental_constrained_pow: 6744 Opcode = ISD::STRICT_FPOW; 6745 break; 6746 case Intrinsic::experimental_constrained_powi: 6747 Opcode = ISD::STRICT_FPOWI; 6748 break; 6749 case Intrinsic::experimental_constrained_sin: 6750 Opcode = ISD::STRICT_FSIN; 6751 break; 6752 case Intrinsic::experimental_constrained_cos: 6753 Opcode = ISD::STRICT_FCOS; 6754 break; 6755 case Intrinsic::experimental_constrained_exp: 6756 Opcode = ISD::STRICT_FEXP; 6757 break; 6758 case Intrinsic::experimental_constrained_exp2: 6759 Opcode = ISD::STRICT_FEXP2; 6760 break; 6761 case Intrinsic::experimental_constrained_log: 6762 Opcode = ISD::STRICT_FLOG; 6763 break; 6764 case Intrinsic::experimental_constrained_log10: 6765 Opcode = ISD::STRICT_FLOG10; 6766 break; 6767 case Intrinsic::experimental_constrained_log2: 6768 Opcode = ISD::STRICT_FLOG2; 6769 break; 6770 case Intrinsic::experimental_constrained_rint: 6771 Opcode = ISD::STRICT_FRINT; 6772 break; 6773 case Intrinsic::experimental_constrained_nearbyint: 6774 Opcode = ISD::STRICT_FNEARBYINT; 6775 break; 6776 case Intrinsic::experimental_constrained_maxnum: 6777 Opcode = ISD::STRICT_FMAXNUM; 6778 break; 6779 case Intrinsic::experimental_constrained_minnum: 6780 Opcode = ISD::STRICT_FMINNUM; 6781 break; 6782 case Intrinsic::experimental_constrained_ceil: 6783 Opcode = ISD::STRICT_FCEIL; 6784 break; 6785 case Intrinsic::experimental_constrained_floor: 6786 Opcode = ISD::STRICT_FFLOOR; 6787 break; 6788 case Intrinsic::experimental_constrained_round: 6789 Opcode = ISD::STRICT_FROUND; 6790 break; 6791 case Intrinsic::experimental_constrained_trunc: 6792 Opcode = ISD::STRICT_FTRUNC; 6793 break; 6794 } 6795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6796 SDValue Chain = getRoot(); 6797 SmallVector<EVT, 4> ValueVTs; 6798 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6799 ValueVTs.push_back(MVT::Other); // Out chain 6800 6801 SDVTList VTs = DAG.getVTList(ValueVTs); 6802 SDValue Result; 6803 if (FPI.isUnaryOp()) 6804 Result = DAG.getNode(Opcode, sdl, VTs, 6805 { Chain, getValue(FPI.getArgOperand(0)) }); 6806 else if (FPI.isTernaryOp()) 6807 Result = DAG.getNode(Opcode, sdl, VTs, 6808 { Chain, getValue(FPI.getArgOperand(0)), 6809 getValue(FPI.getArgOperand(1)), 6810 getValue(FPI.getArgOperand(2)) }); 6811 else 6812 Result = DAG.getNode(Opcode, sdl, VTs, 6813 { Chain, getValue(FPI.getArgOperand(0)), 6814 getValue(FPI.getArgOperand(1)) }); 6815 6816 assert(Result.getNode()->getNumValues() == 2); 6817 SDValue OutChain = Result.getValue(1); 6818 DAG.setRoot(OutChain); 6819 SDValue FPResult = Result.getValue(0); 6820 setValue(&FPI, FPResult); 6821 } 6822 6823 std::pair<SDValue, SDValue> 6824 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6825 const BasicBlock *EHPadBB) { 6826 MachineFunction &MF = DAG.getMachineFunction(); 6827 MachineModuleInfo &MMI = MF.getMMI(); 6828 MCSymbol *BeginLabel = nullptr; 6829 6830 if (EHPadBB) { 6831 // Insert a label before the invoke call to mark the try range. This can be 6832 // used to detect deletion of the invoke via the MachineModuleInfo. 6833 BeginLabel = MMI.getContext().createTempSymbol(); 6834 6835 // For SjLj, keep track of which landing pads go with which invokes 6836 // so as to maintain the ordering of pads in the LSDA. 6837 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6838 if (CallSiteIndex) { 6839 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6840 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6841 6842 // Now that the call site is handled, stop tracking it. 6843 MMI.setCurrentCallSite(0); 6844 } 6845 6846 // Both PendingLoads and PendingExports must be flushed here; 6847 // this call might not return. 6848 (void)getRoot(); 6849 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6850 6851 CLI.setChain(getRoot()); 6852 } 6853 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6854 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6855 6856 assert((CLI.IsTailCall || Result.second.getNode()) && 6857 "Non-null chain expected with non-tail call!"); 6858 assert((Result.second.getNode() || !Result.first.getNode()) && 6859 "Null value expected with tail call!"); 6860 6861 if (!Result.second.getNode()) { 6862 // As a special case, a null chain means that a tail call has been emitted 6863 // and the DAG root is already updated. 6864 HasTailCall = true; 6865 6866 // Since there's no actual continuation from this block, nothing can be 6867 // relying on us setting vregs for them. 6868 PendingExports.clear(); 6869 } else { 6870 DAG.setRoot(Result.second); 6871 } 6872 6873 if (EHPadBB) { 6874 // Insert a label at the end of the invoke call to mark the try range. This 6875 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6876 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6877 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6878 6879 // Inform MachineModuleInfo of range. 6880 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6881 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6882 // actually use outlined funclets and their LSDA info style. 6883 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6884 assert(CLI.CS); 6885 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6886 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6887 BeginLabel, EndLabel); 6888 } else if (!isScopedEHPersonality(Pers)) { 6889 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6890 } 6891 } 6892 6893 return Result; 6894 } 6895 6896 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6897 bool isTailCall, 6898 const BasicBlock *EHPadBB) { 6899 auto &DL = DAG.getDataLayout(); 6900 FunctionType *FTy = CS.getFunctionType(); 6901 Type *RetTy = CS.getType(); 6902 6903 TargetLowering::ArgListTy Args; 6904 Args.reserve(CS.arg_size()); 6905 6906 const Value *SwiftErrorVal = nullptr; 6907 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6908 6909 // We can't tail call inside a function with a swifterror argument. Lowering 6910 // does not support this yet. It would have to move into the swifterror 6911 // register before the call. 6912 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6913 if (TLI.supportSwiftError() && 6914 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6915 isTailCall = false; 6916 6917 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6918 i != e; ++i) { 6919 TargetLowering::ArgListEntry Entry; 6920 const Value *V = *i; 6921 6922 // Skip empty types 6923 if (V->getType()->isEmptyTy()) 6924 continue; 6925 6926 SDValue ArgNode = getValue(V); 6927 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6928 6929 Entry.setAttributes(&CS, i - CS.arg_begin()); 6930 6931 // Use swifterror virtual register as input to the call. 6932 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6933 SwiftErrorVal = V; 6934 // We find the virtual register for the actual swifterror argument. 6935 // Instead of using the Value, we use the virtual register instead. 6936 Entry.Node = DAG.getRegister(FuncInfo 6937 .getOrCreateSwiftErrorVRegUseAt( 6938 CS.getInstruction(), FuncInfo.MBB, V) 6939 .first, 6940 EVT(TLI.getPointerTy(DL))); 6941 } 6942 6943 Args.push_back(Entry); 6944 6945 // If we have an explicit sret argument that is an Instruction, (i.e., it 6946 // might point to function-local memory), we can't meaningfully tail-call. 6947 if (Entry.IsSRet && isa<Instruction>(V)) 6948 isTailCall = false; 6949 } 6950 6951 // Check if target-independent constraints permit a tail call here. 6952 // Target-dependent constraints are checked within TLI->LowerCallTo. 6953 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6954 isTailCall = false; 6955 6956 // Disable tail calls if there is an swifterror argument. Targets have not 6957 // been updated to support tail calls. 6958 if (TLI.supportSwiftError() && SwiftErrorVal) 6959 isTailCall = false; 6960 6961 TargetLowering::CallLoweringInfo CLI(DAG); 6962 CLI.setDebugLoc(getCurSDLoc()) 6963 .setChain(getRoot()) 6964 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6965 .setTailCall(isTailCall) 6966 .setConvergent(CS.isConvergent()); 6967 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6968 6969 if (Result.first.getNode()) { 6970 const Instruction *Inst = CS.getInstruction(); 6971 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6972 setValue(Inst, Result.first); 6973 } 6974 6975 // The last element of CLI.InVals has the SDValue for swifterror return. 6976 // Here we copy it to a virtual register and update SwiftErrorMap for 6977 // book-keeping. 6978 if (SwiftErrorVal && TLI.supportSwiftError()) { 6979 // Get the last element of InVals. 6980 SDValue Src = CLI.InVals.back(); 6981 unsigned VReg; bool CreatedVReg; 6982 std::tie(VReg, CreatedVReg) = 6983 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6984 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6985 // We update the virtual register for the actual swifterror argument. 6986 if (CreatedVReg) 6987 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6988 DAG.setRoot(CopyNode); 6989 } 6990 } 6991 6992 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6993 SelectionDAGBuilder &Builder) { 6994 // Check to see if this load can be trivially constant folded, e.g. if the 6995 // input is from a string literal. 6996 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6997 // Cast pointer to the type we really want to load. 6998 Type *LoadTy = 6999 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 7000 if (LoadVT.isVector()) 7001 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 7002 7003 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 7004 PointerType::getUnqual(LoadTy)); 7005 7006 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 7007 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 7008 return Builder.getValue(LoadCst); 7009 } 7010 7011 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 7012 // still constant memory, the input chain can be the entry node. 7013 SDValue Root; 7014 bool ConstantMemory = false; 7015 7016 // Do not serialize (non-volatile) loads of constant memory with anything. 7017 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 7018 Root = Builder.DAG.getEntryNode(); 7019 ConstantMemory = true; 7020 } else { 7021 // Do not serialize non-volatile loads against each other. 7022 Root = Builder.DAG.getRoot(); 7023 } 7024 7025 SDValue Ptr = Builder.getValue(PtrVal); 7026 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 7027 Ptr, MachinePointerInfo(PtrVal), 7028 /* Alignment = */ 1); 7029 7030 if (!ConstantMemory) 7031 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 7032 return LoadVal; 7033 } 7034 7035 /// Record the value for an instruction that produces an integer result, 7036 /// converting the type where necessary. 7037 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 7038 SDValue Value, 7039 bool IsSigned) { 7040 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7041 I.getType(), true); 7042 if (IsSigned) 7043 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 7044 else 7045 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 7046 setValue(&I, Value); 7047 } 7048 7049 /// See if we can lower a memcmp call into an optimized form. If so, return 7050 /// true and lower it. Otherwise return false, and it will be lowered like a 7051 /// normal call. 7052 /// The caller already checked that \p I calls the appropriate LibFunc with a 7053 /// correct prototype. 7054 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 7055 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 7056 const Value *Size = I.getArgOperand(2); 7057 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 7058 if (CSize && CSize->getZExtValue() == 0) { 7059 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 7060 I.getType(), true); 7061 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 7062 return true; 7063 } 7064 7065 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7066 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 7067 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 7068 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 7069 if (Res.first.getNode()) { 7070 processIntegerCallValue(I, Res.first, true); 7071 PendingLoads.push_back(Res.second); 7072 return true; 7073 } 7074 7075 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 7076 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 7077 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 7078 return false; 7079 7080 // If the target has a fast compare for the given size, it will return a 7081 // preferred load type for that size. Require that the load VT is legal and 7082 // that the target supports unaligned loads of that type. Otherwise, return 7083 // INVALID. 7084 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 7085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7086 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 7087 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 7088 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 7089 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 7090 // TODO: Check alignment of src and dest ptrs. 7091 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 7092 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 7093 if (!TLI.isTypeLegal(LVT) || 7094 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 7095 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 7096 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 7097 } 7098 7099 return LVT; 7100 }; 7101 7102 // This turns into unaligned loads. We only do this if the target natively 7103 // supports the MVT we'll be loading or if it is small enough (<= 4) that 7104 // we'll only produce a small number of byte loads. 7105 MVT LoadVT; 7106 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 7107 switch (NumBitsToCompare) { 7108 default: 7109 return false; 7110 case 16: 7111 LoadVT = MVT::i16; 7112 break; 7113 case 32: 7114 LoadVT = MVT::i32; 7115 break; 7116 case 64: 7117 case 128: 7118 case 256: 7119 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 7120 break; 7121 } 7122 7123 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 7124 return false; 7125 7126 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 7127 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 7128 7129 // Bitcast to a wide integer type if the loads are vectors. 7130 if (LoadVT.isVector()) { 7131 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 7132 LoadL = DAG.getBitcast(CmpVT, LoadL); 7133 LoadR = DAG.getBitcast(CmpVT, LoadR); 7134 } 7135 7136 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 7137 processIntegerCallValue(I, Cmp, false); 7138 return true; 7139 } 7140 7141 /// See if we can lower a memchr call into an optimized form. If so, return 7142 /// true and lower it. Otherwise return false, and it will be lowered like a 7143 /// normal call. 7144 /// The caller already checked that \p I calls the appropriate LibFunc with a 7145 /// correct prototype. 7146 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 7147 const Value *Src = I.getArgOperand(0); 7148 const Value *Char = I.getArgOperand(1); 7149 const Value *Length = I.getArgOperand(2); 7150 7151 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7152 std::pair<SDValue, SDValue> Res = 7153 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 7154 getValue(Src), getValue(Char), getValue(Length), 7155 MachinePointerInfo(Src)); 7156 if (Res.first.getNode()) { 7157 setValue(&I, Res.first); 7158 PendingLoads.push_back(Res.second); 7159 return true; 7160 } 7161 7162 return false; 7163 } 7164 7165 /// See if we can lower a mempcpy call into an optimized form. If so, return 7166 /// true and lower it. Otherwise return false, and it will be lowered like a 7167 /// normal call. 7168 /// The caller already checked that \p I calls the appropriate LibFunc with a 7169 /// correct prototype. 7170 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 7171 SDValue Dst = getValue(I.getArgOperand(0)); 7172 SDValue Src = getValue(I.getArgOperand(1)); 7173 SDValue Size = getValue(I.getArgOperand(2)); 7174 7175 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 7176 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 7177 unsigned Align = std::min(DstAlign, SrcAlign); 7178 if (Align == 0) // Alignment of one or both could not be inferred. 7179 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 7180 7181 bool isVol = false; 7182 SDLoc sdl = getCurSDLoc(); 7183 7184 // In the mempcpy context we need to pass in a false value for isTailCall 7185 // because the return pointer needs to be adjusted by the size of 7186 // the copied memory. 7187 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 7188 false, /*isTailCall=*/false, 7189 MachinePointerInfo(I.getArgOperand(0)), 7190 MachinePointerInfo(I.getArgOperand(1))); 7191 assert(MC.getNode() != nullptr && 7192 "** memcpy should not be lowered as TailCall in mempcpy context **"); 7193 DAG.setRoot(MC); 7194 7195 // Check if Size needs to be truncated or extended. 7196 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 7197 7198 // Adjust return pointer to point just past the last dst byte. 7199 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 7200 Dst, Size); 7201 setValue(&I, DstPlusSize); 7202 return true; 7203 } 7204 7205 /// See if we can lower a strcpy call into an optimized form. If so, return 7206 /// true and lower it, otherwise return false and it will be lowered like a 7207 /// normal call. 7208 /// The caller already checked that \p I calls the appropriate LibFunc with a 7209 /// correct prototype. 7210 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 7211 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7212 7213 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7214 std::pair<SDValue, SDValue> Res = 7215 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 7216 getValue(Arg0), getValue(Arg1), 7217 MachinePointerInfo(Arg0), 7218 MachinePointerInfo(Arg1), isStpcpy); 7219 if (Res.first.getNode()) { 7220 setValue(&I, Res.first); 7221 DAG.setRoot(Res.second); 7222 return true; 7223 } 7224 7225 return false; 7226 } 7227 7228 /// See if we can lower a strcmp call into an optimized form. If so, return 7229 /// true and lower it, otherwise return false and it will be lowered like a 7230 /// normal call. 7231 /// The caller already checked that \p I calls the appropriate LibFunc with a 7232 /// correct prototype. 7233 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 7234 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7235 7236 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7237 std::pair<SDValue, SDValue> Res = 7238 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 7239 getValue(Arg0), getValue(Arg1), 7240 MachinePointerInfo(Arg0), 7241 MachinePointerInfo(Arg1)); 7242 if (Res.first.getNode()) { 7243 processIntegerCallValue(I, Res.first, true); 7244 PendingLoads.push_back(Res.second); 7245 return true; 7246 } 7247 7248 return false; 7249 } 7250 7251 /// See if we can lower a strlen call into an optimized form. If so, return 7252 /// true and lower it, otherwise return false and it will be lowered like a 7253 /// normal call. 7254 /// The caller already checked that \p I calls the appropriate LibFunc with a 7255 /// correct prototype. 7256 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 7257 const Value *Arg0 = I.getArgOperand(0); 7258 7259 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7260 std::pair<SDValue, SDValue> Res = 7261 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 7262 getValue(Arg0), MachinePointerInfo(Arg0)); 7263 if (Res.first.getNode()) { 7264 processIntegerCallValue(I, Res.first, false); 7265 PendingLoads.push_back(Res.second); 7266 return true; 7267 } 7268 7269 return false; 7270 } 7271 7272 /// See if we can lower a strnlen call into an optimized form. If so, return 7273 /// true and lower it, otherwise return false and it will be lowered like a 7274 /// normal call. 7275 /// The caller already checked that \p I calls the appropriate LibFunc with a 7276 /// correct prototype. 7277 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 7278 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 7279 7280 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 7281 std::pair<SDValue, SDValue> Res = 7282 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 7283 getValue(Arg0), getValue(Arg1), 7284 MachinePointerInfo(Arg0)); 7285 if (Res.first.getNode()) { 7286 processIntegerCallValue(I, Res.first, false); 7287 PendingLoads.push_back(Res.second); 7288 return true; 7289 } 7290 7291 return false; 7292 } 7293 7294 /// See if we can lower a unary floating-point operation into an SDNode with 7295 /// the specified Opcode. If so, return true and lower it, otherwise return 7296 /// false and it will be lowered like a normal call. 7297 /// The caller already checked that \p I calls the appropriate LibFunc with a 7298 /// correct prototype. 7299 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 7300 unsigned Opcode) { 7301 // We already checked this call's prototype; verify it doesn't modify errno. 7302 if (!I.onlyReadsMemory()) 7303 return false; 7304 7305 SDValue Tmp = getValue(I.getArgOperand(0)); 7306 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 7307 return true; 7308 } 7309 7310 /// See if we can lower a binary floating-point operation into an SDNode with 7311 /// the specified Opcode. If so, return true and lower it. Otherwise return 7312 /// false, and it will be lowered like a normal call. 7313 /// The caller already checked that \p I calls the appropriate LibFunc with a 7314 /// correct prototype. 7315 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 7316 unsigned Opcode) { 7317 // We already checked this call's prototype; verify it doesn't modify errno. 7318 if (!I.onlyReadsMemory()) 7319 return false; 7320 7321 SDValue Tmp0 = getValue(I.getArgOperand(0)); 7322 SDValue Tmp1 = getValue(I.getArgOperand(1)); 7323 EVT VT = Tmp0.getValueType(); 7324 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 7325 return true; 7326 } 7327 7328 void SelectionDAGBuilder::visitCall(const CallInst &I) { 7329 // Handle inline assembly differently. 7330 if (isa<InlineAsm>(I.getCalledValue())) { 7331 visitInlineAsm(&I); 7332 return; 7333 } 7334 7335 const char *RenameFn = nullptr; 7336 if (Function *F = I.getCalledFunction()) { 7337 if (F->isDeclaration()) { 7338 // Is this an LLVM intrinsic or a target-specific intrinsic? 7339 unsigned IID = F->getIntrinsicID(); 7340 if (!IID) 7341 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7342 IID = II->getIntrinsicID(F); 7343 7344 if (IID) { 7345 RenameFn = visitIntrinsicCall(I, IID); 7346 if (!RenameFn) 7347 return; 7348 } 7349 } 7350 7351 // Check for well-known libc/libm calls. If the function is internal, it 7352 // can't be a library call. Don't do the check if marked as nobuiltin for 7353 // some reason or the call site requires strict floating point semantics. 7354 LibFunc Func; 7355 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7356 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7357 LibInfo->hasOptimizedCodeGen(Func)) { 7358 switch (Func) { 7359 default: break; 7360 case LibFunc_copysign: 7361 case LibFunc_copysignf: 7362 case LibFunc_copysignl: 7363 // We already checked this call's prototype; verify it doesn't modify 7364 // errno. 7365 if (I.onlyReadsMemory()) { 7366 SDValue LHS = getValue(I.getArgOperand(0)); 7367 SDValue RHS = getValue(I.getArgOperand(1)); 7368 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7369 LHS.getValueType(), LHS, RHS)); 7370 return; 7371 } 7372 break; 7373 case LibFunc_fabs: 7374 case LibFunc_fabsf: 7375 case LibFunc_fabsl: 7376 if (visitUnaryFloatCall(I, ISD::FABS)) 7377 return; 7378 break; 7379 case LibFunc_fmin: 7380 case LibFunc_fminf: 7381 case LibFunc_fminl: 7382 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7383 return; 7384 break; 7385 case LibFunc_fmax: 7386 case LibFunc_fmaxf: 7387 case LibFunc_fmaxl: 7388 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7389 return; 7390 break; 7391 case LibFunc_sin: 7392 case LibFunc_sinf: 7393 case LibFunc_sinl: 7394 if (visitUnaryFloatCall(I, ISD::FSIN)) 7395 return; 7396 break; 7397 case LibFunc_cos: 7398 case LibFunc_cosf: 7399 case LibFunc_cosl: 7400 if (visitUnaryFloatCall(I, ISD::FCOS)) 7401 return; 7402 break; 7403 case LibFunc_sqrt: 7404 case LibFunc_sqrtf: 7405 case LibFunc_sqrtl: 7406 case LibFunc_sqrt_finite: 7407 case LibFunc_sqrtf_finite: 7408 case LibFunc_sqrtl_finite: 7409 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7410 return; 7411 break; 7412 case LibFunc_floor: 7413 case LibFunc_floorf: 7414 case LibFunc_floorl: 7415 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7416 return; 7417 break; 7418 case LibFunc_nearbyint: 7419 case LibFunc_nearbyintf: 7420 case LibFunc_nearbyintl: 7421 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7422 return; 7423 break; 7424 case LibFunc_ceil: 7425 case LibFunc_ceilf: 7426 case LibFunc_ceill: 7427 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7428 return; 7429 break; 7430 case LibFunc_rint: 7431 case LibFunc_rintf: 7432 case LibFunc_rintl: 7433 if (visitUnaryFloatCall(I, ISD::FRINT)) 7434 return; 7435 break; 7436 case LibFunc_round: 7437 case LibFunc_roundf: 7438 case LibFunc_roundl: 7439 if (visitUnaryFloatCall(I, ISD::FROUND)) 7440 return; 7441 break; 7442 case LibFunc_trunc: 7443 case LibFunc_truncf: 7444 case LibFunc_truncl: 7445 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7446 return; 7447 break; 7448 case LibFunc_log2: 7449 case LibFunc_log2f: 7450 case LibFunc_log2l: 7451 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7452 return; 7453 break; 7454 case LibFunc_exp2: 7455 case LibFunc_exp2f: 7456 case LibFunc_exp2l: 7457 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7458 return; 7459 break; 7460 case LibFunc_memcmp: 7461 if (visitMemCmpCall(I)) 7462 return; 7463 break; 7464 case LibFunc_mempcpy: 7465 if (visitMemPCpyCall(I)) 7466 return; 7467 break; 7468 case LibFunc_memchr: 7469 if (visitMemChrCall(I)) 7470 return; 7471 break; 7472 case LibFunc_strcpy: 7473 if (visitStrCpyCall(I, false)) 7474 return; 7475 break; 7476 case LibFunc_stpcpy: 7477 if (visitStrCpyCall(I, true)) 7478 return; 7479 break; 7480 case LibFunc_strcmp: 7481 if (visitStrCmpCall(I)) 7482 return; 7483 break; 7484 case LibFunc_strlen: 7485 if (visitStrLenCall(I)) 7486 return; 7487 break; 7488 case LibFunc_strnlen: 7489 if (visitStrNLenCall(I)) 7490 return; 7491 break; 7492 } 7493 } 7494 } 7495 7496 SDValue Callee; 7497 if (!RenameFn) 7498 Callee = getValue(I.getCalledValue()); 7499 else 7500 Callee = DAG.getExternalSymbol( 7501 RenameFn, 7502 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7503 7504 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7505 // have to do anything here to lower funclet bundles. 7506 assert(!I.hasOperandBundlesOtherThan( 7507 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7508 "Cannot lower calls with arbitrary operand bundles!"); 7509 7510 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7511 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7512 else 7513 // Check if we can potentially perform a tail call. More detailed checking 7514 // is be done within LowerCallTo, after more information about the call is 7515 // known. 7516 LowerCallTo(&I, Callee, I.isTailCall()); 7517 } 7518 7519 namespace { 7520 7521 /// AsmOperandInfo - This contains information for each constraint that we are 7522 /// lowering. 7523 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7524 public: 7525 /// CallOperand - If this is the result output operand or a clobber 7526 /// this is null, otherwise it is the incoming operand to the CallInst. 7527 /// This gets modified as the asm is processed. 7528 SDValue CallOperand; 7529 7530 /// AssignedRegs - If this is a register or register class operand, this 7531 /// contains the set of register corresponding to the operand. 7532 RegsForValue AssignedRegs; 7533 7534 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7535 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7536 } 7537 7538 /// Whether or not this operand accesses memory 7539 bool hasMemory(const TargetLowering &TLI) const { 7540 // Indirect operand accesses access memory. 7541 if (isIndirect) 7542 return true; 7543 7544 for (const auto &Code : Codes) 7545 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7546 return true; 7547 7548 return false; 7549 } 7550 7551 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7552 /// corresponds to. If there is no Value* for this operand, it returns 7553 /// MVT::Other. 7554 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7555 const DataLayout &DL) const { 7556 if (!CallOperandVal) return MVT::Other; 7557 7558 if (isa<BasicBlock>(CallOperandVal)) 7559 return TLI.getPointerTy(DL); 7560 7561 llvm::Type *OpTy = CallOperandVal->getType(); 7562 7563 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7564 // If this is an indirect operand, the operand is a pointer to the 7565 // accessed type. 7566 if (isIndirect) { 7567 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7568 if (!PtrTy) 7569 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7570 OpTy = PtrTy->getElementType(); 7571 } 7572 7573 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7574 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7575 if (STy->getNumElements() == 1) 7576 OpTy = STy->getElementType(0); 7577 7578 // If OpTy is not a single value, it may be a struct/union that we 7579 // can tile with integers. 7580 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7581 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7582 switch (BitSize) { 7583 default: break; 7584 case 1: 7585 case 8: 7586 case 16: 7587 case 32: 7588 case 64: 7589 case 128: 7590 OpTy = IntegerType::get(Context, BitSize); 7591 break; 7592 } 7593 } 7594 7595 return TLI.getValueType(DL, OpTy, true); 7596 } 7597 }; 7598 7599 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7600 7601 } // end anonymous namespace 7602 7603 /// Make sure that the output operand \p OpInfo and its corresponding input 7604 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7605 /// out). 7606 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7607 SDISelAsmOperandInfo &MatchingOpInfo, 7608 SelectionDAG &DAG) { 7609 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7610 return; 7611 7612 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7613 const auto &TLI = DAG.getTargetLoweringInfo(); 7614 7615 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7616 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7617 OpInfo.ConstraintVT); 7618 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7619 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7620 MatchingOpInfo.ConstraintVT); 7621 if ((OpInfo.ConstraintVT.isInteger() != 7622 MatchingOpInfo.ConstraintVT.isInteger()) || 7623 (MatchRC.second != InputRC.second)) { 7624 // FIXME: error out in a more elegant fashion 7625 report_fatal_error("Unsupported asm: input constraint" 7626 " with a matching output constraint of" 7627 " incompatible type!"); 7628 } 7629 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7630 } 7631 7632 /// Get a direct memory input to behave well as an indirect operand. 7633 /// This may introduce stores, hence the need for a \p Chain. 7634 /// \return The (possibly updated) chain. 7635 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7636 SDISelAsmOperandInfo &OpInfo, 7637 SelectionDAG &DAG) { 7638 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7639 7640 // If we don't have an indirect input, put it in the constpool if we can, 7641 // otherwise spill it to a stack slot. 7642 // TODO: This isn't quite right. We need to handle these according to 7643 // the addressing mode that the constraint wants. Also, this may take 7644 // an additional register for the computation and we don't want that 7645 // either. 7646 7647 // If the operand is a float, integer, or vector constant, spill to a 7648 // constant pool entry to get its address. 7649 const Value *OpVal = OpInfo.CallOperandVal; 7650 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7651 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7652 OpInfo.CallOperand = DAG.getConstantPool( 7653 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7654 return Chain; 7655 } 7656 7657 // Otherwise, create a stack slot and emit a store to it before the asm. 7658 Type *Ty = OpVal->getType(); 7659 auto &DL = DAG.getDataLayout(); 7660 uint64_t TySize = DL.getTypeAllocSize(Ty); 7661 unsigned Align = DL.getPrefTypeAlignment(Ty); 7662 MachineFunction &MF = DAG.getMachineFunction(); 7663 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7664 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7665 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7666 MachinePointerInfo::getFixedStack(MF, SSFI)); 7667 OpInfo.CallOperand = StackSlot; 7668 7669 return Chain; 7670 } 7671 7672 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7673 /// specified operand. We prefer to assign virtual registers, to allow the 7674 /// register allocator to handle the assignment process. However, if the asm 7675 /// uses features that we can't model on machineinstrs, we have SDISel do the 7676 /// allocation. This produces generally horrible, but correct, code. 7677 /// 7678 /// OpInfo describes the operand 7679 /// RefOpInfo describes the matching operand if any, the operand otherwise 7680 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7681 SDISelAsmOperandInfo &OpInfo, 7682 SDISelAsmOperandInfo &RefOpInfo) { 7683 LLVMContext &Context = *DAG.getContext(); 7684 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7685 7686 MachineFunction &MF = DAG.getMachineFunction(); 7687 SmallVector<unsigned, 4> Regs; 7688 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7689 7690 // No work to do for memory operations. 7691 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7692 return; 7693 7694 // If this is a constraint for a single physreg, or a constraint for a 7695 // register class, find it. 7696 unsigned AssignedReg; 7697 const TargetRegisterClass *RC; 7698 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7699 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7700 // RC is unset only on failure. Return immediately. 7701 if (!RC) 7702 return; 7703 7704 // Get the actual register value type. This is important, because the user 7705 // may have asked for (e.g.) the AX register in i32 type. We need to 7706 // remember that AX is actually i16 to get the right extension. 7707 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7708 7709 if (OpInfo.ConstraintVT != MVT::Other) { 7710 // If this is an FP operand in an integer register (or visa versa), or more 7711 // generally if the operand value disagrees with the register class we plan 7712 // to stick it in, fix the operand type. 7713 // 7714 // If this is an input value, the bitcast to the new type is done now. 7715 // Bitcast for output value is done at the end of visitInlineAsm(). 7716 if ((OpInfo.Type == InlineAsm::isOutput || 7717 OpInfo.Type == InlineAsm::isInput) && 7718 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7719 // Try to convert to the first EVT that the reg class contains. If the 7720 // types are identical size, use a bitcast to convert (e.g. two differing 7721 // vector types). Note: output bitcast is done at the end of 7722 // visitInlineAsm(). 7723 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7724 // Exclude indirect inputs while they are unsupported because the code 7725 // to perform the load is missing and thus OpInfo.CallOperand still 7726 // refers to the input address rather than the pointed-to value. 7727 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7728 OpInfo.CallOperand = 7729 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7730 OpInfo.ConstraintVT = RegVT; 7731 // If the operand is an FP value and we want it in integer registers, 7732 // use the corresponding integer type. This turns an f64 value into 7733 // i64, which can be passed with two i32 values on a 32-bit machine. 7734 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7735 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7736 if (OpInfo.Type == InlineAsm::isInput) 7737 OpInfo.CallOperand = 7738 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7739 OpInfo.ConstraintVT = VT; 7740 } 7741 } 7742 } 7743 7744 // No need to allocate a matching input constraint since the constraint it's 7745 // matching to has already been allocated. 7746 if (OpInfo.isMatchingInputConstraint()) 7747 return; 7748 7749 EVT ValueVT = OpInfo.ConstraintVT; 7750 if (OpInfo.ConstraintVT == MVT::Other) 7751 ValueVT = RegVT; 7752 7753 // Initialize NumRegs. 7754 unsigned NumRegs = 1; 7755 if (OpInfo.ConstraintVT != MVT::Other) 7756 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7757 7758 // If this is a constraint for a specific physical register, like {r17}, 7759 // assign it now. 7760 7761 // If this associated to a specific register, initialize iterator to correct 7762 // place. If virtual, make sure we have enough registers 7763 7764 // Initialize iterator if necessary 7765 TargetRegisterClass::iterator I = RC->begin(); 7766 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7767 7768 // Do not check for single registers. 7769 if (AssignedReg) { 7770 for (; *I != AssignedReg; ++I) 7771 assert(I != RC->end() && "AssignedReg should be member of RC"); 7772 } 7773 7774 for (; NumRegs; --NumRegs, ++I) { 7775 assert(I != RC->end() && "Ran out of registers to allocate!"); 7776 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7777 Regs.push_back(R); 7778 } 7779 7780 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7781 } 7782 7783 static unsigned 7784 findMatchingInlineAsmOperand(unsigned OperandNo, 7785 const std::vector<SDValue> &AsmNodeOperands) { 7786 // Scan until we find the definition we already emitted of this operand. 7787 unsigned CurOp = InlineAsm::Op_FirstOperand; 7788 for (; OperandNo; --OperandNo) { 7789 // Advance to the next operand. 7790 unsigned OpFlag = 7791 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7792 assert((InlineAsm::isRegDefKind(OpFlag) || 7793 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7794 InlineAsm::isMemKind(OpFlag)) && 7795 "Skipped past definitions?"); 7796 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7797 } 7798 return CurOp; 7799 } 7800 7801 namespace { 7802 7803 class ExtraFlags { 7804 unsigned Flags = 0; 7805 7806 public: 7807 explicit ExtraFlags(ImmutableCallSite CS) { 7808 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7809 if (IA->hasSideEffects()) 7810 Flags |= InlineAsm::Extra_HasSideEffects; 7811 if (IA->isAlignStack()) 7812 Flags |= InlineAsm::Extra_IsAlignStack; 7813 if (CS.isConvergent()) 7814 Flags |= InlineAsm::Extra_IsConvergent; 7815 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7816 } 7817 7818 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7819 // Ideally, we would only check against memory constraints. However, the 7820 // meaning of an Other constraint can be target-specific and we can't easily 7821 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7822 // for Other constraints as well. 7823 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7824 OpInfo.ConstraintType == TargetLowering::C_Other) { 7825 if (OpInfo.Type == InlineAsm::isInput) 7826 Flags |= InlineAsm::Extra_MayLoad; 7827 else if (OpInfo.Type == InlineAsm::isOutput) 7828 Flags |= InlineAsm::Extra_MayStore; 7829 else if (OpInfo.Type == InlineAsm::isClobber) 7830 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7831 } 7832 } 7833 7834 unsigned get() const { return Flags; } 7835 }; 7836 7837 } // end anonymous namespace 7838 7839 /// visitInlineAsm - Handle a call to an InlineAsm object. 7840 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7841 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7842 7843 /// ConstraintOperands - Information about all of the constraints. 7844 SDISelAsmOperandInfoVector ConstraintOperands; 7845 7846 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7847 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7848 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7849 7850 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7851 // AsmDialect, MayLoad, MayStore). 7852 bool HasSideEffect = IA->hasSideEffects(); 7853 ExtraFlags ExtraInfo(CS); 7854 7855 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7856 unsigned ResNo = 0; // ResNo - The result number of the next output. 7857 for (auto &T : TargetConstraints) { 7858 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7859 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7860 7861 // Compute the value type for each operand. 7862 if (OpInfo.Type == InlineAsm::isInput || 7863 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7864 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7865 7866 // Process the call argument. BasicBlocks are labels, currently appearing 7867 // only in asm's. 7868 const Instruction *I = CS.getInstruction(); 7869 if (isa<CallBrInst>(I) && 7870 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() - 7871 cast<CallBrInst>(I)->getNumIndirectDests())) { 7872 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal); 7873 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true); 7874 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT); 7875 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7876 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7877 } else { 7878 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7879 } 7880 7881 OpInfo.ConstraintVT = 7882 OpInfo 7883 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7884 .getSimpleVT(); 7885 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7886 // The return value of the call is this value. As such, there is no 7887 // corresponding argument. 7888 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7889 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7890 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7891 DAG.getDataLayout(), STy->getElementType(ResNo)); 7892 } else { 7893 assert(ResNo == 0 && "Asm only has one result!"); 7894 OpInfo.ConstraintVT = 7895 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7896 } 7897 ++ResNo; 7898 } else { 7899 OpInfo.ConstraintVT = MVT::Other; 7900 } 7901 7902 if (!HasSideEffect) 7903 HasSideEffect = OpInfo.hasMemory(TLI); 7904 7905 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7906 // FIXME: Could we compute this on OpInfo rather than T? 7907 7908 // Compute the constraint code and ConstraintType to use. 7909 TLI.ComputeConstraintToUse(T, SDValue()); 7910 7911 ExtraInfo.update(T); 7912 } 7913 7914 // We won't need to flush pending loads if this asm doesn't touch 7915 // memory and is nonvolatile. 7916 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 7917 7918 // Second pass over the constraints: compute which constraint option to use. 7919 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7920 // If this is an output operand with a matching input operand, look up the 7921 // matching input. If their types mismatch, e.g. one is an integer, the 7922 // other is floating point, or their sizes are different, flag it as an 7923 // error. 7924 if (OpInfo.hasMatchingInput()) { 7925 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7926 patchMatchingInput(OpInfo, Input, DAG); 7927 } 7928 7929 // Compute the constraint code and ConstraintType to use. 7930 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7931 7932 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7933 OpInfo.Type == InlineAsm::isClobber) 7934 continue; 7935 7936 // If this is a memory input, and if the operand is not indirect, do what we 7937 // need to provide an address for the memory input. 7938 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7939 !OpInfo.isIndirect) { 7940 assert((OpInfo.isMultipleAlternative || 7941 (OpInfo.Type == InlineAsm::isInput)) && 7942 "Can only indirectify direct input operands!"); 7943 7944 // Memory operands really want the address of the value. 7945 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7946 7947 // There is no longer a Value* corresponding to this operand. 7948 OpInfo.CallOperandVal = nullptr; 7949 7950 // It is now an indirect operand. 7951 OpInfo.isIndirect = true; 7952 } 7953 7954 } 7955 7956 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7957 std::vector<SDValue> AsmNodeOperands; 7958 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7959 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7960 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7961 7962 // If we have a !srcloc metadata node associated with it, we want to attach 7963 // this to the ultimately generated inline asm machineinstr. To do this, we 7964 // pass in the third operand as this (potentially null) inline asm MDNode. 7965 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7966 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7967 7968 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7969 // bits as operand 3. 7970 AsmNodeOperands.push_back(DAG.getTargetConstant( 7971 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7972 7973 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 7974 // this, assign virtual and physical registers for inputs and otput. 7975 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7976 // Assign Registers. 7977 SDISelAsmOperandInfo &RefOpInfo = 7978 OpInfo.isMatchingInputConstraint() 7979 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7980 : OpInfo; 7981 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7982 7983 switch (OpInfo.Type) { 7984 case InlineAsm::isOutput: 7985 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7986 (OpInfo.ConstraintType == TargetLowering::C_Other && 7987 OpInfo.isIndirect)) { 7988 unsigned ConstraintID = 7989 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7990 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7991 "Failed to convert memory constraint code to constraint id."); 7992 7993 // Add information to the INLINEASM node to know about this output. 7994 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7995 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7996 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7997 MVT::i32)); 7998 AsmNodeOperands.push_back(OpInfo.CallOperand); 7999 break; 8000 } else if ((OpInfo.ConstraintType == TargetLowering::C_Other && 8001 !OpInfo.isIndirect) || 8002 OpInfo.ConstraintType == TargetLowering::C_Register || 8003 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 8004 // Otherwise, this outputs to a register (directly for C_Register / 8005 // C_RegisterClass, and a target-defined fashion for C_Other). Find a 8006 // register that we can use. 8007 if (OpInfo.AssignedRegs.Regs.empty()) { 8008 emitInlineAsmError( 8009 CS, "couldn't allocate output register for constraint '" + 8010 Twine(OpInfo.ConstraintCode) + "'"); 8011 return; 8012 } 8013 8014 // Add information to the INLINEASM node to know that this register is 8015 // set. 8016 OpInfo.AssignedRegs.AddInlineAsmOperands( 8017 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 8018 : InlineAsm::Kind_RegDef, 8019 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 8020 } 8021 break; 8022 8023 case InlineAsm::isInput: { 8024 SDValue InOperandVal = OpInfo.CallOperand; 8025 8026 if (OpInfo.isMatchingInputConstraint()) { 8027 // If this is required to match an output register we have already set, 8028 // just use its register. 8029 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 8030 AsmNodeOperands); 8031 unsigned OpFlag = 8032 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 8033 if (InlineAsm::isRegDefKind(OpFlag) || 8034 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 8035 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 8036 if (OpInfo.isIndirect) { 8037 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 8038 emitInlineAsmError(CS, "inline asm not supported yet:" 8039 " don't know how to handle tied " 8040 "indirect register inputs"); 8041 return; 8042 } 8043 8044 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 8045 SmallVector<unsigned, 4> Regs; 8046 8047 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 8048 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 8049 MachineRegisterInfo &RegInfo = 8050 DAG.getMachineFunction().getRegInfo(); 8051 for (unsigned i = 0; i != NumRegs; ++i) 8052 Regs.push_back(RegInfo.createVirtualRegister(RC)); 8053 } else { 8054 emitInlineAsmError(CS, "inline asm error: This value type register " 8055 "class is not natively supported!"); 8056 return; 8057 } 8058 8059 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 8060 8061 SDLoc dl = getCurSDLoc(); 8062 // Use the produced MatchedRegs object to 8063 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 8064 CS.getInstruction()); 8065 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 8066 true, OpInfo.getMatchedOperand(), dl, 8067 DAG, AsmNodeOperands); 8068 break; 8069 } 8070 8071 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 8072 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 8073 "Unexpected number of operands"); 8074 // Add information to the INLINEASM node to know about this input. 8075 // See InlineAsm.h isUseOperandTiedToDef. 8076 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 8077 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 8078 OpInfo.getMatchedOperand()); 8079 AsmNodeOperands.push_back(DAG.getTargetConstant( 8080 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8081 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 8082 break; 8083 } 8084 8085 // Treat indirect 'X' constraint as memory. 8086 if (OpInfo.ConstraintType == TargetLowering::C_Other && 8087 OpInfo.isIndirect) 8088 OpInfo.ConstraintType = TargetLowering::C_Memory; 8089 8090 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 8091 std::vector<SDValue> Ops; 8092 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 8093 Ops, DAG); 8094 if (Ops.empty()) { 8095 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 8096 Twine(OpInfo.ConstraintCode) + "'"); 8097 return; 8098 } 8099 8100 // Add information to the INLINEASM node to know about this input. 8101 unsigned ResOpType = 8102 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 8103 AsmNodeOperands.push_back(DAG.getTargetConstant( 8104 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 8105 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 8106 break; 8107 } 8108 8109 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 8110 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 8111 assert(InOperandVal.getValueType() == 8112 TLI.getPointerTy(DAG.getDataLayout()) && 8113 "Memory operands expect pointer values"); 8114 8115 unsigned ConstraintID = 8116 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 8117 assert(ConstraintID != InlineAsm::Constraint_Unknown && 8118 "Failed to convert memory constraint code to constraint id."); 8119 8120 // Add information to the INLINEASM node to know about this input. 8121 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 8122 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 8123 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 8124 getCurSDLoc(), 8125 MVT::i32)); 8126 AsmNodeOperands.push_back(InOperandVal); 8127 break; 8128 } 8129 8130 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 8131 OpInfo.ConstraintType == TargetLowering::C_Register) && 8132 "Unknown constraint type!"); 8133 8134 // TODO: Support this. 8135 if (OpInfo.isIndirect) { 8136 emitInlineAsmError( 8137 CS, "Don't know how to handle indirect register inputs yet " 8138 "for constraint '" + 8139 Twine(OpInfo.ConstraintCode) + "'"); 8140 return; 8141 } 8142 8143 // Copy the input into the appropriate registers. 8144 if (OpInfo.AssignedRegs.Regs.empty()) { 8145 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 8146 Twine(OpInfo.ConstraintCode) + "'"); 8147 return; 8148 } 8149 8150 SDLoc dl = getCurSDLoc(); 8151 8152 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 8153 Chain, &Flag, CS.getInstruction()); 8154 8155 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 8156 dl, DAG, AsmNodeOperands); 8157 break; 8158 } 8159 case InlineAsm::isClobber: 8160 // Add the clobbered value to the operand list, so that the register 8161 // allocator is aware that the physreg got clobbered. 8162 if (!OpInfo.AssignedRegs.Regs.empty()) 8163 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 8164 false, 0, getCurSDLoc(), DAG, 8165 AsmNodeOperands); 8166 break; 8167 } 8168 } 8169 8170 // Finish up input operands. Set the input chain and add the flag last. 8171 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 8172 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 8173 8174 unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR 8175 : ISD::INLINEASM; 8176 Chain = DAG.getNode(ISDOpc, getCurSDLoc(), 8177 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 8178 Flag = Chain.getValue(1); 8179 8180 // Do additional work to generate outputs. 8181 8182 SmallVector<EVT, 1> ResultVTs; 8183 SmallVector<SDValue, 1> ResultValues; 8184 SmallVector<SDValue, 8> OutChains; 8185 8186 llvm::Type *CSResultType = CS.getType(); 8187 ArrayRef<Type *> ResultTypes; 8188 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) 8189 ResultTypes = StructResult->elements(); 8190 else if (!CSResultType->isVoidTy()) 8191 ResultTypes = makeArrayRef(CSResultType); 8192 8193 auto CurResultType = ResultTypes.begin(); 8194 auto handleRegAssign = [&](SDValue V) { 8195 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 8196 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 8197 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 8198 ++CurResultType; 8199 // If the type of the inline asm call site return value is different but has 8200 // same size as the type of the asm output bitcast it. One example of this 8201 // is for vectors with different width / number of elements. This can 8202 // happen for register classes that can contain multiple different value 8203 // types. The preg or vreg allocated may not have the same VT as was 8204 // expected. 8205 // 8206 // This can also happen for a return value that disagrees with the register 8207 // class it is put in, eg. a double in a general-purpose register on a 8208 // 32-bit machine. 8209 if (ResultVT != V.getValueType() && 8210 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 8211 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 8212 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 8213 V.getValueType().isInteger()) { 8214 // If a result value was tied to an input value, the computed result 8215 // may have a wider width than the expected result. Extract the 8216 // relevant portion. 8217 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 8218 } 8219 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 8220 ResultVTs.push_back(ResultVT); 8221 ResultValues.push_back(V); 8222 }; 8223 8224 // Deal with output operands. 8225 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 8226 if (OpInfo.Type == InlineAsm::isOutput) { 8227 SDValue Val; 8228 // Skip trivial output operands. 8229 if (OpInfo.AssignedRegs.Regs.empty()) 8230 continue; 8231 8232 switch (OpInfo.ConstraintType) { 8233 case TargetLowering::C_Register: 8234 case TargetLowering::C_RegisterClass: 8235 Val = OpInfo.AssignedRegs.getCopyFromRegs( 8236 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 8237 break; 8238 case TargetLowering::C_Other: 8239 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(), 8240 OpInfo, DAG); 8241 break; 8242 case TargetLowering::C_Memory: 8243 break; // Already handled. 8244 case TargetLowering::C_Unknown: 8245 assert(false && "Unexpected unknown constraint"); 8246 } 8247 8248 // Indirect output manifest as stores. Record output chains. 8249 if (OpInfo.isIndirect) { 8250 const Value *Ptr = OpInfo.CallOperandVal; 8251 assert(Ptr && "Expected value CallOperandVal for indirect asm operand"); 8252 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr), 8253 MachinePointerInfo(Ptr)); 8254 OutChains.push_back(Store); 8255 } else { 8256 // generate CopyFromRegs to associated registers. 8257 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 8258 if (Val.getOpcode() == ISD::MERGE_VALUES) { 8259 for (const SDValue &V : Val->op_values()) 8260 handleRegAssign(V); 8261 } else 8262 handleRegAssign(Val); 8263 } 8264 } 8265 } 8266 8267 // Set results. 8268 if (!ResultValues.empty()) { 8269 assert(CurResultType == ResultTypes.end() && 8270 "Mismatch in number of ResultTypes"); 8271 assert(ResultValues.size() == ResultTypes.size() && 8272 "Mismatch in number of output operands in asm result"); 8273 8274 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 8275 DAG.getVTList(ResultVTs), ResultValues); 8276 setValue(CS.getInstruction(), V); 8277 } 8278 8279 // Collect store chains. 8280 if (!OutChains.empty()) 8281 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 8282 8283 // Only Update Root if inline assembly has a memory effect. 8284 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 8285 DAG.setRoot(Chain); 8286 } 8287 8288 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 8289 const Twine &Message) { 8290 LLVMContext &Ctx = *DAG.getContext(); 8291 Ctx.emitError(CS.getInstruction(), Message); 8292 8293 // Make sure we leave the DAG in a valid state 8294 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8295 SmallVector<EVT, 1> ValueVTs; 8296 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8297 8298 if (ValueVTs.empty()) 8299 return; 8300 8301 SmallVector<SDValue, 1> Ops; 8302 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 8303 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 8304 8305 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 8306 } 8307 8308 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 8309 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 8310 MVT::Other, getRoot(), 8311 getValue(I.getArgOperand(0)), 8312 DAG.getSrcValue(I.getArgOperand(0)))); 8313 } 8314 8315 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 8316 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8317 const DataLayout &DL = DAG.getDataLayout(); 8318 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 8319 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 8320 DAG.getSrcValue(I.getOperand(0)), 8321 DL.getABITypeAlignment(I.getType())); 8322 setValue(&I, V); 8323 DAG.setRoot(V.getValue(1)); 8324 } 8325 8326 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 8327 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 8328 MVT::Other, getRoot(), 8329 getValue(I.getArgOperand(0)), 8330 DAG.getSrcValue(I.getArgOperand(0)))); 8331 } 8332 8333 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 8334 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 8335 MVT::Other, getRoot(), 8336 getValue(I.getArgOperand(0)), 8337 getValue(I.getArgOperand(1)), 8338 DAG.getSrcValue(I.getArgOperand(0)), 8339 DAG.getSrcValue(I.getArgOperand(1)))); 8340 } 8341 8342 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 8343 const Instruction &I, 8344 SDValue Op) { 8345 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 8346 if (!Range) 8347 return Op; 8348 8349 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8350 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped()) 8351 return Op; 8352 8353 APInt Lo = CR.getUnsignedMin(); 8354 if (!Lo.isMinValue()) 8355 return Op; 8356 8357 APInt Hi = CR.getUnsignedMax(); 8358 unsigned Bits = std::max(Hi.getActiveBits(), 8359 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8360 8361 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8362 8363 SDLoc SL = getCurSDLoc(); 8364 8365 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8366 DAG.getValueType(SmallVT)); 8367 unsigned NumVals = Op.getNode()->getNumValues(); 8368 if (NumVals == 1) 8369 return ZExt; 8370 8371 SmallVector<SDValue, 4> Ops; 8372 8373 Ops.push_back(ZExt); 8374 for (unsigned I = 1; I != NumVals; ++I) 8375 Ops.push_back(Op.getValue(I)); 8376 8377 return DAG.getMergeValues(Ops, SL); 8378 } 8379 8380 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8381 /// the call being lowered. 8382 /// 8383 /// This is a helper for lowering intrinsics that follow a target calling 8384 /// convention or require stack pointer adjustment. Only a subset of the 8385 /// intrinsic's operands need to participate in the calling convention. 8386 void SelectionDAGBuilder::populateCallLoweringInfo( 8387 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call, 8388 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8389 bool IsPatchPoint) { 8390 TargetLowering::ArgListTy Args; 8391 Args.reserve(NumArgs); 8392 8393 // Populate the argument list. 8394 // Attributes for args start at offset 1, after the return attribute. 8395 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8396 ArgI != ArgE; ++ArgI) { 8397 const Value *V = Call->getOperand(ArgI); 8398 8399 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8400 8401 TargetLowering::ArgListEntry Entry; 8402 Entry.Node = getValue(V); 8403 Entry.Ty = V->getType(); 8404 Entry.setAttributes(Call, ArgI); 8405 Args.push_back(Entry); 8406 } 8407 8408 CLI.setDebugLoc(getCurSDLoc()) 8409 .setChain(getRoot()) 8410 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args)) 8411 .setDiscardResult(Call->use_empty()) 8412 .setIsPatchPoint(IsPatchPoint); 8413 } 8414 8415 /// Add a stack map intrinsic call's live variable operands to a stackmap 8416 /// or patchpoint target node's operand list. 8417 /// 8418 /// Constants are converted to TargetConstants purely as an optimization to 8419 /// avoid constant materialization and register allocation. 8420 /// 8421 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8422 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8423 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8424 /// address materialization and register allocation, but may also be required 8425 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8426 /// alloca in the entry block, then the runtime may assume that the alloca's 8427 /// StackMap location can be read immediately after compilation and that the 8428 /// location is valid at any point during execution (this is similar to the 8429 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8430 /// only available in a register, then the runtime would need to trap when 8431 /// execution reaches the StackMap in order to read the alloca's location. 8432 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8433 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8434 SelectionDAGBuilder &Builder) { 8435 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8436 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8438 Ops.push_back( 8439 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8440 Ops.push_back( 8441 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8442 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8443 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8444 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8445 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8446 } else 8447 Ops.push_back(OpVal); 8448 } 8449 } 8450 8451 /// Lower llvm.experimental.stackmap directly to its target opcode. 8452 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8453 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8454 // [live variables...]) 8455 8456 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8457 8458 SDValue Chain, InFlag, Callee, NullPtr; 8459 SmallVector<SDValue, 32> Ops; 8460 8461 SDLoc DL = getCurSDLoc(); 8462 Callee = getValue(CI.getCalledValue()); 8463 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8464 8465 // The stackmap intrinsic only records the live variables (the arguemnts 8466 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8467 // intrinsic, this won't be lowered to a function call. This means we don't 8468 // have to worry about calling conventions and target specific lowering code. 8469 // Instead we perform the call lowering right here. 8470 // 8471 // chain, flag = CALLSEQ_START(chain, 0, 0) 8472 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8473 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8474 // 8475 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8476 InFlag = Chain.getValue(1); 8477 8478 // Add the <id> and <numBytes> constants. 8479 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8480 Ops.push_back(DAG.getTargetConstant( 8481 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8482 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8483 Ops.push_back(DAG.getTargetConstant( 8484 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8485 MVT::i32)); 8486 8487 // Push live variables for the stack map. 8488 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8489 8490 // We are not pushing any register mask info here on the operands list, 8491 // because the stackmap doesn't clobber anything. 8492 8493 // Push the chain and the glue flag. 8494 Ops.push_back(Chain); 8495 Ops.push_back(InFlag); 8496 8497 // Create the STACKMAP node. 8498 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8499 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8500 Chain = SDValue(SM, 0); 8501 InFlag = Chain.getValue(1); 8502 8503 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8504 8505 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8506 8507 // Set the root to the target-lowered call chain. 8508 DAG.setRoot(Chain); 8509 8510 // Inform the Frame Information that we have a stackmap in this function. 8511 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8512 } 8513 8514 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8515 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8516 const BasicBlock *EHPadBB) { 8517 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8518 // i32 <numBytes>, 8519 // i8* <target>, 8520 // i32 <numArgs>, 8521 // [Args...], 8522 // [live variables...]) 8523 8524 CallingConv::ID CC = CS.getCallingConv(); 8525 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8526 bool HasDef = !CS->getType()->isVoidTy(); 8527 SDLoc dl = getCurSDLoc(); 8528 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8529 8530 // Handle immediate and symbolic callees. 8531 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8532 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8533 /*isTarget=*/true); 8534 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8535 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8536 SDLoc(SymbolicCallee), 8537 SymbolicCallee->getValueType(0)); 8538 8539 // Get the real number of arguments participating in the call <numArgs> 8540 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8541 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8542 8543 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8544 // Intrinsics include all meta-operands up to but not including CC. 8545 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8546 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8547 "Not enough arguments provided to the patchpoint intrinsic"); 8548 8549 // For AnyRegCC the arguments are lowered later on manually. 8550 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8551 Type *ReturnTy = 8552 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8553 8554 TargetLowering::CallLoweringInfo CLI(DAG); 8555 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()), 8556 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true); 8557 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8558 8559 SDNode *CallEnd = Result.second.getNode(); 8560 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8561 CallEnd = CallEnd->getOperand(0).getNode(); 8562 8563 /// Get a call instruction from the call sequence chain. 8564 /// Tail calls are not allowed. 8565 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8566 "Expected a callseq node."); 8567 SDNode *Call = CallEnd->getOperand(0).getNode(); 8568 bool HasGlue = Call->getGluedNode(); 8569 8570 // Replace the target specific call node with the patchable intrinsic. 8571 SmallVector<SDValue, 8> Ops; 8572 8573 // Add the <id> and <numBytes> constants. 8574 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8575 Ops.push_back(DAG.getTargetConstant( 8576 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8577 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8578 Ops.push_back(DAG.getTargetConstant( 8579 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8580 MVT::i32)); 8581 8582 // Add the callee. 8583 Ops.push_back(Callee); 8584 8585 // Adjust <numArgs> to account for any arguments that have been passed on the 8586 // stack instead. 8587 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8588 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8589 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8590 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8591 8592 // Add the calling convention 8593 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8594 8595 // Add the arguments we omitted previously. The register allocator should 8596 // place these in any free register. 8597 if (IsAnyRegCC) 8598 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8599 Ops.push_back(getValue(CS.getArgument(i))); 8600 8601 // Push the arguments from the call instruction up to the register mask. 8602 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8603 Ops.append(Call->op_begin() + 2, e); 8604 8605 // Push live variables for the stack map. 8606 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8607 8608 // Push the register mask info. 8609 if (HasGlue) 8610 Ops.push_back(*(Call->op_end()-2)); 8611 else 8612 Ops.push_back(*(Call->op_end()-1)); 8613 8614 // Push the chain (this is originally the first operand of the call, but 8615 // becomes now the last or second to last operand). 8616 Ops.push_back(*(Call->op_begin())); 8617 8618 // Push the glue flag (last operand). 8619 if (HasGlue) 8620 Ops.push_back(*(Call->op_end()-1)); 8621 8622 SDVTList NodeTys; 8623 if (IsAnyRegCC && HasDef) { 8624 // Create the return types based on the intrinsic definition 8625 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8626 SmallVector<EVT, 3> ValueVTs; 8627 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8628 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8629 8630 // There is always a chain and a glue type at the end 8631 ValueVTs.push_back(MVT::Other); 8632 ValueVTs.push_back(MVT::Glue); 8633 NodeTys = DAG.getVTList(ValueVTs); 8634 } else 8635 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8636 8637 // Replace the target specific call node with a PATCHPOINT node. 8638 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8639 dl, NodeTys, Ops); 8640 8641 // Update the NodeMap. 8642 if (HasDef) { 8643 if (IsAnyRegCC) 8644 setValue(CS.getInstruction(), SDValue(MN, 0)); 8645 else 8646 setValue(CS.getInstruction(), Result.first); 8647 } 8648 8649 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8650 // call sequence. Furthermore the location of the chain and glue can change 8651 // when the AnyReg calling convention is used and the intrinsic returns a 8652 // value. 8653 if (IsAnyRegCC && HasDef) { 8654 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8655 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8656 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8657 } else 8658 DAG.ReplaceAllUsesWith(Call, MN); 8659 DAG.DeleteNode(Call); 8660 8661 // Inform the Frame Information that we have a patchpoint in this function. 8662 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8663 } 8664 8665 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8666 unsigned Intrinsic) { 8667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8668 SDValue Op1 = getValue(I.getArgOperand(0)); 8669 SDValue Op2; 8670 if (I.getNumArgOperands() > 1) 8671 Op2 = getValue(I.getArgOperand(1)); 8672 SDLoc dl = getCurSDLoc(); 8673 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8674 SDValue Res; 8675 FastMathFlags FMF; 8676 if (isa<FPMathOperator>(I)) 8677 FMF = I.getFastMathFlags(); 8678 8679 switch (Intrinsic) { 8680 case Intrinsic::experimental_vector_reduce_fadd: 8681 if (FMF.isFast()) 8682 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8683 else 8684 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8685 break; 8686 case Intrinsic::experimental_vector_reduce_fmul: 8687 if (FMF.isFast()) 8688 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8689 else 8690 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8691 break; 8692 case Intrinsic::experimental_vector_reduce_add: 8693 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8694 break; 8695 case Intrinsic::experimental_vector_reduce_mul: 8696 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8697 break; 8698 case Intrinsic::experimental_vector_reduce_and: 8699 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8700 break; 8701 case Intrinsic::experimental_vector_reduce_or: 8702 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8703 break; 8704 case Intrinsic::experimental_vector_reduce_xor: 8705 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8706 break; 8707 case Intrinsic::experimental_vector_reduce_smax: 8708 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8709 break; 8710 case Intrinsic::experimental_vector_reduce_smin: 8711 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8712 break; 8713 case Intrinsic::experimental_vector_reduce_umax: 8714 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8715 break; 8716 case Intrinsic::experimental_vector_reduce_umin: 8717 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8718 break; 8719 case Intrinsic::experimental_vector_reduce_fmax: 8720 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8721 break; 8722 case Intrinsic::experimental_vector_reduce_fmin: 8723 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8724 break; 8725 default: 8726 llvm_unreachable("Unhandled vector reduce intrinsic"); 8727 } 8728 setValue(&I, Res); 8729 } 8730 8731 /// Returns an AttributeList representing the attributes applied to the return 8732 /// value of the given call. 8733 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8734 SmallVector<Attribute::AttrKind, 2> Attrs; 8735 if (CLI.RetSExt) 8736 Attrs.push_back(Attribute::SExt); 8737 if (CLI.RetZExt) 8738 Attrs.push_back(Attribute::ZExt); 8739 if (CLI.IsInReg) 8740 Attrs.push_back(Attribute::InReg); 8741 8742 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8743 Attrs); 8744 } 8745 8746 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8747 /// implementation, which just calls LowerCall. 8748 /// FIXME: When all targets are 8749 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8750 std::pair<SDValue, SDValue> 8751 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8752 // Handle the incoming return values from the call. 8753 CLI.Ins.clear(); 8754 Type *OrigRetTy = CLI.RetTy; 8755 SmallVector<EVT, 4> RetTys; 8756 SmallVector<uint64_t, 4> Offsets; 8757 auto &DL = CLI.DAG.getDataLayout(); 8758 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8759 8760 if (CLI.IsPostTypeLegalization) { 8761 // If we are lowering a libcall after legalization, split the return type. 8762 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8763 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8764 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8765 EVT RetVT = OldRetTys[i]; 8766 uint64_t Offset = OldOffsets[i]; 8767 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8768 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8769 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8770 RetTys.append(NumRegs, RegisterVT); 8771 for (unsigned j = 0; j != NumRegs; ++j) 8772 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8773 } 8774 } 8775 8776 SmallVector<ISD::OutputArg, 4> Outs; 8777 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8778 8779 bool CanLowerReturn = 8780 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8781 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8782 8783 SDValue DemoteStackSlot; 8784 int DemoteStackIdx = -100; 8785 if (!CanLowerReturn) { 8786 // FIXME: equivalent assert? 8787 // assert(!CS.hasInAllocaArgument() && 8788 // "sret demotion is incompatible with inalloca"); 8789 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8790 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8791 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8792 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8793 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8794 DL.getAllocaAddrSpace()); 8795 8796 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8797 ArgListEntry Entry; 8798 Entry.Node = DemoteStackSlot; 8799 Entry.Ty = StackSlotPtrType; 8800 Entry.IsSExt = false; 8801 Entry.IsZExt = false; 8802 Entry.IsInReg = false; 8803 Entry.IsSRet = true; 8804 Entry.IsNest = false; 8805 Entry.IsByVal = false; 8806 Entry.IsReturned = false; 8807 Entry.IsSwiftSelf = false; 8808 Entry.IsSwiftError = false; 8809 Entry.Alignment = Align; 8810 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8811 CLI.NumFixedArgs += 1; 8812 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8813 8814 // sret demotion isn't compatible with tail-calls, since the sret argument 8815 // points into the callers stack frame. 8816 CLI.IsTailCall = false; 8817 } else { 8818 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8819 EVT VT = RetTys[I]; 8820 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8821 CLI.CallConv, VT); 8822 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8823 CLI.CallConv, VT); 8824 for (unsigned i = 0; i != NumRegs; ++i) { 8825 ISD::InputArg MyFlags; 8826 MyFlags.VT = RegisterVT; 8827 MyFlags.ArgVT = VT; 8828 MyFlags.Used = CLI.IsReturnValueUsed; 8829 if (CLI.RetSExt) 8830 MyFlags.Flags.setSExt(); 8831 if (CLI.RetZExt) 8832 MyFlags.Flags.setZExt(); 8833 if (CLI.IsInReg) 8834 MyFlags.Flags.setInReg(); 8835 CLI.Ins.push_back(MyFlags); 8836 } 8837 } 8838 } 8839 8840 // We push in swifterror return as the last element of CLI.Ins. 8841 ArgListTy &Args = CLI.getArgs(); 8842 if (supportSwiftError()) { 8843 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8844 if (Args[i].IsSwiftError) { 8845 ISD::InputArg MyFlags; 8846 MyFlags.VT = getPointerTy(DL); 8847 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8848 MyFlags.Flags.setSwiftError(); 8849 CLI.Ins.push_back(MyFlags); 8850 } 8851 } 8852 } 8853 8854 // Handle all of the outgoing arguments. 8855 CLI.Outs.clear(); 8856 CLI.OutVals.clear(); 8857 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8858 SmallVector<EVT, 4> ValueVTs; 8859 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8860 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8861 Type *FinalType = Args[i].Ty; 8862 if (Args[i].IsByVal) 8863 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8864 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8865 FinalType, CLI.CallConv, CLI.IsVarArg); 8866 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8867 ++Value) { 8868 EVT VT = ValueVTs[Value]; 8869 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8870 SDValue Op = SDValue(Args[i].Node.getNode(), 8871 Args[i].Node.getResNo() + Value); 8872 ISD::ArgFlagsTy Flags; 8873 8874 // Certain targets (such as MIPS), may have a different ABI alignment 8875 // for a type depending on the context. Give the target a chance to 8876 // specify the alignment it wants. 8877 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8878 8879 if (Args[i].IsZExt) 8880 Flags.setZExt(); 8881 if (Args[i].IsSExt) 8882 Flags.setSExt(); 8883 if (Args[i].IsInReg) { 8884 // If we are using vectorcall calling convention, a structure that is 8885 // passed InReg - is surely an HVA 8886 if (CLI.CallConv == CallingConv::X86_VectorCall && 8887 isa<StructType>(FinalType)) { 8888 // The first value of a structure is marked 8889 if (0 == Value) 8890 Flags.setHvaStart(); 8891 Flags.setHva(); 8892 } 8893 // Set InReg Flag 8894 Flags.setInReg(); 8895 } 8896 if (Args[i].IsSRet) 8897 Flags.setSRet(); 8898 if (Args[i].IsSwiftSelf) 8899 Flags.setSwiftSelf(); 8900 if (Args[i].IsSwiftError) 8901 Flags.setSwiftError(); 8902 if (Args[i].IsByVal) 8903 Flags.setByVal(); 8904 if (Args[i].IsInAlloca) { 8905 Flags.setInAlloca(); 8906 // Set the byval flag for CCAssignFn callbacks that don't know about 8907 // inalloca. This way we can know how many bytes we should've allocated 8908 // and how many bytes a callee cleanup function will pop. If we port 8909 // inalloca to more targets, we'll have to add custom inalloca handling 8910 // in the various CC lowering callbacks. 8911 Flags.setByVal(); 8912 } 8913 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8914 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8915 Type *ElementTy = Ty->getElementType(); 8916 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8917 // For ByVal, alignment should come from FE. BE will guess if this 8918 // info is not there but there are cases it cannot get right. 8919 unsigned FrameAlign; 8920 if (Args[i].Alignment) 8921 FrameAlign = Args[i].Alignment; 8922 else 8923 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8924 Flags.setByValAlign(FrameAlign); 8925 } 8926 if (Args[i].IsNest) 8927 Flags.setNest(); 8928 if (NeedsRegBlock) 8929 Flags.setInConsecutiveRegs(); 8930 Flags.setOrigAlign(OriginalAlignment); 8931 8932 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8933 CLI.CallConv, VT); 8934 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8935 CLI.CallConv, VT); 8936 SmallVector<SDValue, 4> Parts(NumParts); 8937 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8938 8939 if (Args[i].IsSExt) 8940 ExtendKind = ISD::SIGN_EXTEND; 8941 else if (Args[i].IsZExt) 8942 ExtendKind = ISD::ZERO_EXTEND; 8943 8944 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8945 // for now. 8946 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8947 CanLowerReturn) { 8948 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8949 "unexpected use of 'returned'"); 8950 // Before passing 'returned' to the target lowering code, ensure that 8951 // either the register MVT and the actual EVT are the same size or that 8952 // the return value and argument are extended in the same way; in these 8953 // cases it's safe to pass the argument register value unchanged as the 8954 // return register value (although it's at the target's option whether 8955 // to do so) 8956 // TODO: allow code generation to take advantage of partially preserved 8957 // registers rather than clobbering the entire register when the 8958 // parameter extension method is not compatible with the return 8959 // extension method 8960 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8961 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8962 CLI.RetZExt == Args[i].IsZExt)) 8963 Flags.setReturned(); 8964 } 8965 8966 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8967 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8968 8969 for (unsigned j = 0; j != NumParts; ++j) { 8970 // if it isn't first piece, alignment must be 1 8971 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8972 i < CLI.NumFixedArgs, 8973 i, j*Parts[j].getValueType().getStoreSize()); 8974 if (NumParts > 1 && j == 0) 8975 MyFlags.Flags.setSplit(); 8976 else if (j != 0) { 8977 MyFlags.Flags.setOrigAlign(1); 8978 if (j == NumParts - 1) 8979 MyFlags.Flags.setSplitEnd(); 8980 } 8981 8982 CLI.Outs.push_back(MyFlags); 8983 CLI.OutVals.push_back(Parts[j]); 8984 } 8985 8986 if (NeedsRegBlock && Value == NumValues - 1) 8987 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8988 } 8989 } 8990 8991 SmallVector<SDValue, 4> InVals; 8992 CLI.Chain = LowerCall(CLI, InVals); 8993 8994 // Update CLI.InVals to use outside of this function. 8995 CLI.InVals = InVals; 8996 8997 // Verify that the target's LowerCall behaved as expected. 8998 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8999 "LowerCall didn't return a valid chain!"); 9000 assert((!CLI.IsTailCall || InVals.empty()) && 9001 "LowerCall emitted a return value for a tail call!"); 9002 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 9003 "LowerCall didn't emit the correct number of values!"); 9004 9005 // For a tail call, the return value is merely live-out and there aren't 9006 // any nodes in the DAG representing it. Return a special value to 9007 // indicate that a tail call has been emitted and no more Instructions 9008 // should be processed in the current block. 9009 if (CLI.IsTailCall) { 9010 CLI.DAG.setRoot(CLI.Chain); 9011 return std::make_pair(SDValue(), SDValue()); 9012 } 9013 9014 #ifndef NDEBUG 9015 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 9016 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 9017 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 9018 "LowerCall emitted a value with the wrong type!"); 9019 } 9020 #endif 9021 9022 SmallVector<SDValue, 4> ReturnValues; 9023 if (!CanLowerReturn) { 9024 // The instruction result is the result of loading from the 9025 // hidden sret parameter. 9026 SmallVector<EVT, 1> PVTs; 9027 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 9028 9029 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 9030 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 9031 EVT PtrVT = PVTs[0]; 9032 9033 unsigned NumValues = RetTys.size(); 9034 ReturnValues.resize(NumValues); 9035 SmallVector<SDValue, 4> Chains(NumValues); 9036 9037 // An aggregate return value cannot wrap around the address space, so 9038 // offsets to its parts don't wrap either. 9039 SDNodeFlags Flags; 9040 Flags.setNoUnsignedWrap(true); 9041 9042 for (unsigned i = 0; i < NumValues; ++i) { 9043 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 9044 CLI.DAG.getConstant(Offsets[i], CLI.DL, 9045 PtrVT), Flags); 9046 SDValue L = CLI.DAG.getLoad( 9047 RetTys[i], CLI.DL, CLI.Chain, Add, 9048 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 9049 DemoteStackIdx, Offsets[i]), 9050 /* Alignment = */ 1); 9051 ReturnValues[i] = L; 9052 Chains[i] = L.getValue(1); 9053 } 9054 9055 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 9056 } else { 9057 // Collect the legal value parts into potentially illegal values 9058 // that correspond to the original function's return values. 9059 Optional<ISD::NodeType> AssertOp; 9060 if (CLI.RetSExt) 9061 AssertOp = ISD::AssertSext; 9062 else if (CLI.RetZExt) 9063 AssertOp = ISD::AssertZext; 9064 unsigned CurReg = 0; 9065 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 9066 EVT VT = RetTys[I]; 9067 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 9068 CLI.CallConv, VT); 9069 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 9070 CLI.CallConv, VT); 9071 9072 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 9073 NumRegs, RegisterVT, VT, nullptr, 9074 CLI.CallConv, AssertOp)); 9075 CurReg += NumRegs; 9076 } 9077 9078 // For a function returning void, there is no return value. We can't create 9079 // such a node, so we just return a null return value in that case. In 9080 // that case, nothing will actually look at the value. 9081 if (ReturnValues.empty()) 9082 return std::make_pair(SDValue(), CLI.Chain); 9083 } 9084 9085 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 9086 CLI.DAG.getVTList(RetTys), ReturnValues); 9087 return std::make_pair(Res, CLI.Chain); 9088 } 9089 9090 void TargetLowering::LowerOperationWrapper(SDNode *N, 9091 SmallVectorImpl<SDValue> &Results, 9092 SelectionDAG &DAG) const { 9093 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 9094 Results.push_back(Res); 9095 } 9096 9097 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 9098 llvm_unreachable("LowerOperation not implemented for this target!"); 9099 } 9100 9101 void 9102 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 9103 SDValue Op = getNonRegisterValue(V); 9104 assert((Op.getOpcode() != ISD::CopyFromReg || 9105 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 9106 "Copy from a reg to the same reg!"); 9107 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 9108 9109 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9110 // If this is an InlineAsm we have to match the registers required, not the 9111 // notional registers required by the type. 9112 9113 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 9114 None); // This is not an ABI copy. 9115 SDValue Chain = DAG.getEntryNode(); 9116 9117 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 9118 FuncInfo.PreferredExtendType.end()) 9119 ? ISD::ANY_EXTEND 9120 : FuncInfo.PreferredExtendType[V]; 9121 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 9122 PendingExports.push_back(Chain); 9123 } 9124 9125 #include "llvm/CodeGen/SelectionDAGISel.h" 9126 9127 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 9128 /// entry block, return true. This includes arguments used by switches, since 9129 /// the switch may expand into multiple basic blocks. 9130 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 9131 // With FastISel active, we may be splitting blocks, so force creation 9132 // of virtual registers for all non-dead arguments. 9133 if (FastISel) 9134 return A->use_empty(); 9135 9136 const BasicBlock &Entry = A->getParent()->front(); 9137 for (const User *U : A->users()) 9138 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 9139 return false; // Use not in entry block. 9140 9141 return true; 9142 } 9143 9144 using ArgCopyElisionMapTy = 9145 DenseMap<const Argument *, 9146 std::pair<const AllocaInst *, const StoreInst *>>; 9147 9148 /// Scan the entry block of the function in FuncInfo for arguments that look 9149 /// like copies into a local alloca. Record any copied arguments in 9150 /// ArgCopyElisionCandidates. 9151 static void 9152 findArgumentCopyElisionCandidates(const DataLayout &DL, 9153 FunctionLoweringInfo *FuncInfo, 9154 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 9155 // Record the state of every static alloca used in the entry block. Argument 9156 // allocas are all used in the entry block, so we need approximately as many 9157 // entries as we have arguments. 9158 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 9159 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 9160 unsigned NumArgs = FuncInfo->Fn->arg_size(); 9161 StaticAllocas.reserve(NumArgs * 2); 9162 9163 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 9164 if (!V) 9165 return nullptr; 9166 V = V->stripPointerCasts(); 9167 const auto *AI = dyn_cast<AllocaInst>(V); 9168 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 9169 return nullptr; 9170 auto Iter = StaticAllocas.insert({AI, Unknown}); 9171 return &Iter.first->second; 9172 }; 9173 9174 // Look for stores of arguments to static allocas. Look through bitcasts and 9175 // GEPs to handle type coercions, as long as the alloca is fully initialized 9176 // by the store. Any non-store use of an alloca escapes it and any subsequent 9177 // unanalyzed store might write it. 9178 // FIXME: Handle structs initialized with multiple stores. 9179 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 9180 // Look for stores, and handle non-store uses conservatively. 9181 const auto *SI = dyn_cast<StoreInst>(&I); 9182 if (!SI) { 9183 // We will look through cast uses, so ignore them completely. 9184 if (I.isCast()) 9185 continue; 9186 // Ignore debug info intrinsics, they don't escape or store to allocas. 9187 if (isa<DbgInfoIntrinsic>(I)) 9188 continue; 9189 // This is an unknown instruction. Assume it escapes or writes to all 9190 // static alloca operands. 9191 for (const Use &U : I.operands()) { 9192 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 9193 *Info = StaticAllocaInfo::Clobbered; 9194 } 9195 continue; 9196 } 9197 9198 // If the stored value is a static alloca, mark it as escaped. 9199 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 9200 *Info = StaticAllocaInfo::Clobbered; 9201 9202 // Check if the destination is a static alloca. 9203 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 9204 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 9205 if (!Info) 9206 continue; 9207 const AllocaInst *AI = cast<AllocaInst>(Dst); 9208 9209 // Skip allocas that have been initialized or clobbered. 9210 if (*Info != StaticAllocaInfo::Unknown) 9211 continue; 9212 9213 // Check if the stored value is an argument, and that this store fully 9214 // initializes the alloca. Don't elide copies from the same argument twice. 9215 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 9216 const auto *Arg = dyn_cast<Argument>(Val); 9217 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 9218 Arg->getType()->isEmptyTy() || 9219 DL.getTypeStoreSize(Arg->getType()) != 9220 DL.getTypeAllocSize(AI->getAllocatedType()) || 9221 ArgCopyElisionCandidates.count(Arg)) { 9222 *Info = StaticAllocaInfo::Clobbered; 9223 continue; 9224 } 9225 9226 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 9227 << '\n'); 9228 9229 // Mark this alloca and store for argument copy elision. 9230 *Info = StaticAllocaInfo::Elidable; 9231 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 9232 9233 // Stop scanning if we've seen all arguments. This will happen early in -O0 9234 // builds, which is useful, because -O0 builds have large entry blocks and 9235 // many allocas. 9236 if (ArgCopyElisionCandidates.size() == NumArgs) 9237 break; 9238 } 9239 } 9240 9241 /// Try to elide argument copies from memory into a local alloca. Succeeds if 9242 /// ArgVal is a load from a suitable fixed stack object. 9243 static void tryToElideArgumentCopy( 9244 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 9245 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 9246 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 9247 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 9248 SDValue ArgVal, bool &ArgHasUses) { 9249 // Check if this is a load from a fixed stack object. 9250 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 9251 if (!LNode) 9252 return; 9253 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 9254 if (!FINode) 9255 return; 9256 9257 // Check that the fixed stack object is the right size and alignment. 9258 // Look at the alignment that the user wrote on the alloca instead of looking 9259 // at the stack object. 9260 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 9261 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 9262 const AllocaInst *AI = ArgCopyIter->second.first; 9263 int FixedIndex = FINode->getIndex(); 9264 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 9265 int OldIndex = AllocaIndex; 9266 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 9267 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 9268 LLVM_DEBUG( 9269 dbgs() << " argument copy elision failed due to bad fixed stack " 9270 "object size\n"); 9271 return; 9272 } 9273 unsigned RequiredAlignment = AI->getAlignment(); 9274 if (!RequiredAlignment) { 9275 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 9276 AI->getAllocatedType()); 9277 } 9278 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 9279 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 9280 "greater than stack argument alignment (" 9281 << RequiredAlignment << " vs " 9282 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 9283 return; 9284 } 9285 9286 // Perform the elision. Delete the old stack object and replace its only use 9287 // in the variable info map. Mark the stack object as mutable. 9288 LLVM_DEBUG({ 9289 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 9290 << " Replacing frame index " << OldIndex << " with " << FixedIndex 9291 << '\n'; 9292 }); 9293 MFI.RemoveStackObject(OldIndex); 9294 MFI.setIsImmutableObjectIndex(FixedIndex, false); 9295 AllocaIndex = FixedIndex; 9296 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 9297 Chains.push_back(ArgVal.getValue(1)); 9298 9299 // Avoid emitting code for the store implementing the copy. 9300 const StoreInst *SI = ArgCopyIter->second.second; 9301 ElidedArgCopyInstrs.insert(SI); 9302 9303 // Check for uses of the argument again so that we can avoid exporting ArgVal 9304 // if it is't used by anything other than the store. 9305 for (const Value *U : Arg.users()) { 9306 if (U != SI) { 9307 ArgHasUses = true; 9308 break; 9309 } 9310 } 9311 } 9312 9313 void SelectionDAGISel::LowerArguments(const Function &F) { 9314 SelectionDAG &DAG = SDB->DAG; 9315 SDLoc dl = SDB->getCurSDLoc(); 9316 const DataLayout &DL = DAG.getDataLayout(); 9317 SmallVector<ISD::InputArg, 16> Ins; 9318 9319 if (!FuncInfo->CanLowerReturn) { 9320 // Put in an sret pointer parameter before all the other parameters. 9321 SmallVector<EVT, 1> ValueVTs; 9322 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9323 F.getReturnType()->getPointerTo( 9324 DAG.getDataLayout().getAllocaAddrSpace()), 9325 ValueVTs); 9326 9327 // NOTE: Assuming that a pointer will never break down to more than one VT 9328 // or one register. 9329 ISD::ArgFlagsTy Flags; 9330 Flags.setSRet(); 9331 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 9332 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 9333 ISD::InputArg::NoArgIndex, 0); 9334 Ins.push_back(RetArg); 9335 } 9336 9337 // Look for stores of arguments to static allocas. Mark such arguments with a 9338 // flag to ask the target to give us the memory location of that argument if 9339 // available. 9340 ArgCopyElisionMapTy ArgCopyElisionCandidates; 9341 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 9342 9343 // Set up the incoming argument description vector. 9344 for (const Argument &Arg : F.args()) { 9345 unsigned ArgNo = Arg.getArgNo(); 9346 SmallVector<EVT, 4> ValueVTs; 9347 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9348 bool isArgValueUsed = !Arg.use_empty(); 9349 unsigned PartBase = 0; 9350 Type *FinalType = Arg.getType(); 9351 if (Arg.hasAttribute(Attribute::ByVal)) 9352 FinalType = cast<PointerType>(FinalType)->getElementType(); 9353 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9354 FinalType, F.getCallingConv(), F.isVarArg()); 9355 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9356 Value != NumValues; ++Value) { 9357 EVT VT = ValueVTs[Value]; 9358 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9359 ISD::ArgFlagsTy Flags; 9360 9361 // Certain targets (such as MIPS), may have a different ABI alignment 9362 // for a type depending on the context. Give the target a chance to 9363 // specify the alignment it wants. 9364 unsigned OriginalAlignment = 9365 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9366 9367 if (Arg.hasAttribute(Attribute::ZExt)) 9368 Flags.setZExt(); 9369 if (Arg.hasAttribute(Attribute::SExt)) 9370 Flags.setSExt(); 9371 if (Arg.hasAttribute(Attribute::InReg)) { 9372 // If we are using vectorcall calling convention, a structure that is 9373 // passed InReg - is surely an HVA 9374 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9375 isa<StructType>(Arg.getType())) { 9376 // The first value of a structure is marked 9377 if (0 == Value) 9378 Flags.setHvaStart(); 9379 Flags.setHva(); 9380 } 9381 // Set InReg Flag 9382 Flags.setInReg(); 9383 } 9384 if (Arg.hasAttribute(Attribute::StructRet)) 9385 Flags.setSRet(); 9386 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9387 Flags.setSwiftSelf(); 9388 if (Arg.hasAttribute(Attribute::SwiftError)) 9389 Flags.setSwiftError(); 9390 if (Arg.hasAttribute(Attribute::ByVal)) 9391 Flags.setByVal(); 9392 if (Arg.hasAttribute(Attribute::InAlloca)) { 9393 Flags.setInAlloca(); 9394 // Set the byval flag for CCAssignFn callbacks that don't know about 9395 // inalloca. This way we can know how many bytes we should've allocated 9396 // and how many bytes a callee cleanup function will pop. If we port 9397 // inalloca to more targets, we'll have to add custom inalloca handling 9398 // in the various CC lowering callbacks. 9399 Flags.setByVal(); 9400 } 9401 if (F.getCallingConv() == CallingConv::X86_INTR) { 9402 // IA Interrupt passes frame (1st parameter) by value in the stack. 9403 if (ArgNo == 0) 9404 Flags.setByVal(); 9405 } 9406 if (Flags.isByVal() || Flags.isInAlloca()) { 9407 PointerType *Ty = cast<PointerType>(Arg.getType()); 9408 Type *ElementTy = Ty->getElementType(); 9409 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9410 // For ByVal, alignment should be passed from FE. BE will guess if 9411 // this info is not there but there are cases it cannot get right. 9412 unsigned FrameAlign; 9413 if (Arg.getParamAlignment()) 9414 FrameAlign = Arg.getParamAlignment(); 9415 else 9416 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9417 Flags.setByValAlign(FrameAlign); 9418 } 9419 if (Arg.hasAttribute(Attribute::Nest)) 9420 Flags.setNest(); 9421 if (NeedsRegBlock) 9422 Flags.setInConsecutiveRegs(); 9423 Flags.setOrigAlign(OriginalAlignment); 9424 if (ArgCopyElisionCandidates.count(&Arg)) 9425 Flags.setCopyElisionCandidate(); 9426 9427 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9428 *CurDAG->getContext(), F.getCallingConv(), VT); 9429 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9430 *CurDAG->getContext(), F.getCallingConv(), VT); 9431 for (unsigned i = 0; i != NumRegs; ++i) { 9432 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9433 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9434 if (NumRegs > 1 && i == 0) 9435 MyFlags.Flags.setSplit(); 9436 // if it isn't first piece, alignment must be 1 9437 else if (i > 0) { 9438 MyFlags.Flags.setOrigAlign(1); 9439 if (i == NumRegs - 1) 9440 MyFlags.Flags.setSplitEnd(); 9441 } 9442 Ins.push_back(MyFlags); 9443 } 9444 if (NeedsRegBlock && Value == NumValues - 1) 9445 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9446 PartBase += VT.getStoreSize(); 9447 } 9448 } 9449 9450 // Call the target to set up the argument values. 9451 SmallVector<SDValue, 8> InVals; 9452 SDValue NewRoot = TLI->LowerFormalArguments( 9453 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9454 9455 // Verify that the target's LowerFormalArguments behaved as expected. 9456 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9457 "LowerFormalArguments didn't return a valid chain!"); 9458 assert(InVals.size() == Ins.size() && 9459 "LowerFormalArguments didn't emit the correct number of values!"); 9460 LLVM_DEBUG({ 9461 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9462 assert(InVals[i].getNode() && 9463 "LowerFormalArguments emitted a null value!"); 9464 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9465 "LowerFormalArguments emitted a value with the wrong type!"); 9466 } 9467 }); 9468 9469 // Update the DAG with the new chain value resulting from argument lowering. 9470 DAG.setRoot(NewRoot); 9471 9472 // Set up the argument values. 9473 unsigned i = 0; 9474 if (!FuncInfo->CanLowerReturn) { 9475 // Create a virtual register for the sret pointer, and put in a copy 9476 // from the sret argument into it. 9477 SmallVector<EVT, 1> ValueVTs; 9478 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9479 F.getReturnType()->getPointerTo( 9480 DAG.getDataLayout().getAllocaAddrSpace()), 9481 ValueVTs); 9482 MVT VT = ValueVTs[0].getSimpleVT(); 9483 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9484 Optional<ISD::NodeType> AssertOp = None; 9485 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9486 nullptr, F.getCallingConv(), AssertOp); 9487 9488 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9489 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9490 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9491 FuncInfo->DemoteRegister = SRetReg; 9492 NewRoot = 9493 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9494 DAG.setRoot(NewRoot); 9495 9496 // i indexes lowered arguments. Bump it past the hidden sret argument. 9497 ++i; 9498 } 9499 9500 SmallVector<SDValue, 4> Chains; 9501 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9502 for (const Argument &Arg : F.args()) { 9503 SmallVector<SDValue, 4> ArgValues; 9504 SmallVector<EVT, 4> ValueVTs; 9505 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9506 unsigned NumValues = ValueVTs.size(); 9507 if (NumValues == 0) 9508 continue; 9509 9510 bool ArgHasUses = !Arg.use_empty(); 9511 9512 // Elide the copying store if the target loaded this argument from a 9513 // suitable fixed stack object. 9514 if (Ins[i].Flags.isCopyElisionCandidate()) { 9515 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9516 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9517 InVals[i], ArgHasUses); 9518 } 9519 9520 // If this argument is unused then remember its value. It is used to generate 9521 // debugging information. 9522 bool isSwiftErrorArg = 9523 TLI->supportSwiftError() && 9524 Arg.hasAttribute(Attribute::SwiftError); 9525 if (!ArgHasUses && !isSwiftErrorArg) { 9526 SDB->setUnusedArgValue(&Arg, InVals[i]); 9527 9528 // Also remember any frame index for use in FastISel. 9529 if (FrameIndexSDNode *FI = 9530 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9531 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9532 } 9533 9534 for (unsigned Val = 0; Val != NumValues; ++Val) { 9535 EVT VT = ValueVTs[Val]; 9536 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9537 F.getCallingConv(), VT); 9538 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9539 *CurDAG->getContext(), F.getCallingConv(), VT); 9540 9541 // Even an apparant 'unused' swifterror argument needs to be returned. So 9542 // we do generate a copy for it that can be used on return from the 9543 // function. 9544 if (ArgHasUses || isSwiftErrorArg) { 9545 Optional<ISD::NodeType> AssertOp; 9546 if (Arg.hasAttribute(Attribute::SExt)) 9547 AssertOp = ISD::AssertSext; 9548 else if (Arg.hasAttribute(Attribute::ZExt)) 9549 AssertOp = ISD::AssertZext; 9550 9551 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9552 PartVT, VT, nullptr, 9553 F.getCallingConv(), AssertOp)); 9554 } 9555 9556 i += NumParts; 9557 } 9558 9559 // We don't need to do anything else for unused arguments. 9560 if (ArgValues.empty()) 9561 continue; 9562 9563 // Note down frame index. 9564 if (FrameIndexSDNode *FI = 9565 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9566 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9567 9568 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9569 SDB->getCurSDLoc()); 9570 9571 SDB->setValue(&Arg, Res); 9572 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9573 // We want to associate the argument with the frame index, among 9574 // involved operands, that correspond to the lowest address. The 9575 // getCopyFromParts function, called earlier, is swapping the order of 9576 // the operands to BUILD_PAIR depending on endianness. The result of 9577 // that swapping is that the least significant bits of the argument will 9578 // be in the first operand of the BUILD_PAIR node, and the most 9579 // significant bits will be in the second operand. 9580 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9581 if (LoadSDNode *LNode = 9582 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9583 if (FrameIndexSDNode *FI = 9584 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9585 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9586 } 9587 9588 // Update the SwiftErrorVRegDefMap. 9589 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9590 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9591 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9592 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9593 FuncInfo->SwiftErrorArg, Reg); 9594 } 9595 9596 // If this argument is live outside of the entry block, insert a copy from 9597 // wherever we got it to the vreg that other BB's will reference it as. 9598 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9599 // If we can, though, try to skip creating an unnecessary vreg. 9600 // FIXME: This isn't very clean... it would be nice to make this more 9601 // general. It's also subtly incompatible with the hacks FastISel 9602 // uses with vregs. 9603 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9604 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9605 FuncInfo->ValueMap[&Arg] = Reg; 9606 continue; 9607 } 9608 } 9609 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9610 FuncInfo->InitializeRegForValue(&Arg); 9611 SDB->CopyToExportRegsIfNeeded(&Arg); 9612 } 9613 } 9614 9615 if (!Chains.empty()) { 9616 Chains.push_back(NewRoot); 9617 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9618 } 9619 9620 DAG.setRoot(NewRoot); 9621 9622 assert(i == InVals.size() && "Argument register count mismatch!"); 9623 9624 // If any argument copy elisions occurred and we have debug info, update the 9625 // stale frame indices used in the dbg.declare variable info table. 9626 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9627 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9628 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9629 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9630 if (I != ArgCopyElisionFrameIndexMap.end()) 9631 VI.Slot = I->second; 9632 } 9633 } 9634 9635 // Finally, if the target has anything special to do, allow it to do so. 9636 EmitFunctionEntryCode(); 9637 } 9638 9639 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9640 /// ensure constants are generated when needed. Remember the virtual registers 9641 /// that need to be added to the Machine PHI nodes as input. We cannot just 9642 /// directly add them, because expansion might result in multiple MBB's for one 9643 /// BB. As such, the start of the BB might correspond to a different MBB than 9644 /// the end. 9645 void 9646 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9647 const Instruction *TI = LLVMBB->getTerminator(); 9648 9649 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9650 9651 // Check PHI nodes in successors that expect a value to be available from this 9652 // block. 9653 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9654 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9655 if (!isa<PHINode>(SuccBB->begin())) continue; 9656 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9657 9658 // If this terminator has multiple identical successors (common for 9659 // switches), only handle each succ once. 9660 if (!SuccsHandled.insert(SuccMBB).second) 9661 continue; 9662 9663 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9664 9665 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9666 // nodes and Machine PHI nodes, but the incoming operands have not been 9667 // emitted yet. 9668 for (const PHINode &PN : SuccBB->phis()) { 9669 // Ignore dead phi's. 9670 if (PN.use_empty()) 9671 continue; 9672 9673 // Skip empty types 9674 if (PN.getType()->isEmptyTy()) 9675 continue; 9676 9677 unsigned Reg; 9678 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9679 9680 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9681 unsigned &RegOut = ConstantsOut[C]; 9682 if (RegOut == 0) { 9683 RegOut = FuncInfo.CreateRegs(C->getType()); 9684 CopyValueToVirtualRegister(C, RegOut); 9685 } 9686 Reg = RegOut; 9687 } else { 9688 DenseMap<const Value *, unsigned>::iterator I = 9689 FuncInfo.ValueMap.find(PHIOp); 9690 if (I != FuncInfo.ValueMap.end()) 9691 Reg = I->second; 9692 else { 9693 assert(isa<AllocaInst>(PHIOp) && 9694 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9695 "Didn't codegen value into a register!??"); 9696 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9697 CopyValueToVirtualRegister(PHIOp, Reg); 9698 } 9699 } 9700 9701 // Remember that this register needs to added to the machine PHI node as 9702 // the input for this MBB. 9703 SmallVector<EVT, 4> ValueVTs; 9704 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9705 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9706 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9707 EVT VT = ValueVTs[vti]; 9708 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9709 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9710 FuncInfo.PHINodesToUpdate.push_back( 9711 std::make_pair(&*MBBI++, Reg + i)); 9712 Reg += NumRegisters; 9713 } 9714 } 9715 } 9716 9717 ConstantsOut.clear(); 9718 } 9719 9720 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9721 /// is 0. 9722 MachineBasicBlock * 9723 SelectionDAGBuilder::StackProtectorDescriptor:: 9724 AddSuccessorMBB(const BasicBlock *BB, 9725 MachineBasicBlock *ParentMBB, 9726 bool IsLikely, 9727 MachineBasicBlock *SuccMBB) { 9728 // If SuccBB has not been created yet, create it. 9729 if (!SuccMBB) { 9730 MachineFunction *MF = ParentMBB->getParent(); 9731 MachineFunction::iterator BBI(ParentMBB); 9732 SuccMBB = MF->CreateMachineBasicBlock(BB); 9733 MF->insert(++BBI, SuccMBB); 9734 } 9735 // Add it as a successor of ParentMBB. 9736 ParentMBB->addSuccessor( 9737 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9738 return SuccMBB; 9739 } 9740 9741 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9742 MachineFunction::iterator I(MBB); 9743 if (++I == FuncInfo.MF->end()) 9744 return nullptr; 9745 return &*I; 9746 } 9747 9748 /// During lowering new call nodes can be created (such as memset, etc.). 9749 /// Those will become new roots of the current DAG, but complications arise 9750 /// when they are tail calls. In such cases, the call lowering will update 9751 /// the root, but the builder still needs to know that a tail call has been 9752 /// lowered in order to avoid generating an additional return. 9753 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9754 // If the node is null, we do have a tail call. 9755 if (MaybeTC.getNode() != nullptr) 9756 DAG.setRoot(MaybeTC); 9757 else 9758 HasTailCall = true; 9759 } 9760 9761 uint64_t 9762 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9763 unsigned First, unsigned Last) const { 9764 assert(Last >= First); 9765 const APInt &LowCase = Clusters[First].Low->getValue(); 9766 const APInt &HighCase = Clusters[Last].High->getValue(); 9767 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9768 9769 // FIXME: A range of consecutive cases has 100% density, but only requires one 9770 // comparison to lower. We should discriminate against such consecutive ranges 9771 // in jump tables. 9772 9773 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9774 } 9775 9776 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9777 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9778 unsigned Last) const { 9779 assert(Last >= First); 9780 assert(TotalCases[Last] >= TotalCases[First]); 9781 uint64_t NumCases = 9782 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9783 return NumCases; 9784 } 9785 9786 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9787 unsigned First, unsigned Last, 9788 const SwitchInst *SI, 9789 MachineBasicBlock *DefaultMBB, 9790 CaseCluster &JTCluster) { 9791 assert(First <= Last); 9792 9793 auto Prob = BranchProbability::getZero(); 9794 unsigned NumCmps = 0; 9795 std::vector<MachineBasicBlock*> Table; 9796 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9797 9798 // Initialize probabilities in JTProbs. 9799 for (unsigned I = First; I <= Last; ++I) 9800 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9801 9802 for (unsigned I = First; I <= Last; ++I) { 9803 assert(Clusters[I].Kind == CC_Range); 9804 Prob += Clusters[I].Prob; 9805 const APInt &Low = Clusters[I].Low->getValue(); 9806 const APInt &High = Clusters[I].High->getValue(); 9807 NumCmps += (Low == High) ? 1 : 2; 9808 if (I != First) { 9809 // Fill the gap between this and the previous cluster. 9810 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9811 assert(PreviousHigh.slt(Low)); 9812 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9813 for (uint64_t J = 0; J < Gap; J++) 9814 Table.push_back(DefaultMBB); 9815 } 9816 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9817 for (uint64_t J = 0; J < ClusterSize; ++J) 9818 Table.push_back(Clusters[I].MBB); 9819 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9820 } 9821 9822 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9823 unsigned NumDests = JTProbs.size(); 9824 if (TLI.isSuitableForBitTests( 9825 NumDests, NumCmps, Clusters[First].Low->getValue(), 9826 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9827 // Clusters[First..Last] should be lowered as bit tests instead. 9828 return false; 9829 } 9830 9831 // Create the MBB that will load from and jump through the table. 9832 // Note: We create it here, but it's not inserted into the function yet. 9833 MachineFunction *CurMF = FuncInfo.MF; 9834 MachineBasicBlock *JumpTableMBB = 9835 CurMF->CreateMachineBasicBlock(SI->getParent()); 9836 9837 // Add successors. Note: use table order for determinism. 9838 SmallPtrSet<MachineBasicBlock *, 8> Done; 9839 for (MachineBasicBlock *Succ : Table) { 9840 if (Done.count(Succ)) 9841 continue; 9842 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9843 Done.insert(Succ); 9844 } 9845 JumpTableMBB->normalizeSuccProbs(); 9846 9847 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9848 ->createJumpTableIndex(Table); 9849 9850 // Set up the jump table info. 9851 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9852 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9853 Clusters[Last].High->getValue(), SI->getCondition(), 9854 nullptr, false); 9855 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9856 9857 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9858 JTCases.size() - 1, Prob); 9859 return true; 9860 } 9861 9862 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9863 const SwitchInst *SI, 9864 MachineBasicBlock *DefaultMBB) { 9865 #ifndef NDEBUG 9866 // Clusters must be non-empty, sorted, and only contain Range clusters. 9867 assert(!Clusters.empty()); 9868 for (CaseCluster &C : Clusters) 9869 assert(C.Kind == CC_Range); 9870 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9871 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9872 #endif 9873 9874 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9875 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9876 return; 9877 9878 const int64_t N = Clusters.size(); 9879 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9880 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9881 9882 if (N < 2 || N < MinJumpTableEntries) 9883 return; 9884 9885 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9886 SmallVector<unsigned, 8> TotalCases(N); 9887 for (unsigned i = 0; i < N; ++i) { 9888 const APInt &Hi = Clusters[i].High->getValue(); 9889 const APInt &Lo = Clusters[i].Low->getValue(); 9890 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9891 if (i != 0) 9892 TotalCases[i] += TotalCases[i - 1]; 9893 } 9894 9895 // Cheap case: the whole range may be suitable for jump table. 9896 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9897 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9898 assert(NumCases < UINT64_MAX / 100); 9899 assert(Range >= NumCases); 9900 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9901 CaseCluster JTCluster; 9902 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9903 Clusters[0] = JTCluster; 9904 Clusters.resize(1); 9905 return; 9906 } 9907 } 9908 9909 // The algorithm below is not suitable for -O0. 9910 if (TM.getOptLevel() == CodeGenOpt::None) 9911 return; 9912 9913 // Split Clusters into minimum number of dense partitions. The algorithm uses 9914 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9915 // for the Case Statement'" (1994), but builds the MinPartitions array in 9916 // reverse order to make it easier to reconstruct the partitions in ascending 9917 // order. In the choice between two optimal partitionings, it picks the one 9918 // which yields more jump tables. 9919 9920 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9921 SmallVector<unsigned, 8> MinPartitions(N); 9922 // LastElement[i] is the last element of the partition starting at i. 9923 SmallVector<unsigned, 8> LastElement(N); 9924 // PartitionsScore[i] is used to break ties when choosing between two 9925 // partitionings resulting in the same number of partitions. 9926 SmallVector<unsigned, 8> PartitionsScore(N); 9927 // For PartitionsScore, a small number of comparisons is considered as good as 9928 // a jump table and a single comparison is considered better than a jump 9929 // table. 9930 enum PartitionScores : unsigned { 9931 NoTable = 0, 9932 Table = 1, 9933 FewCases = 1, 9934 SingleCase = 2 9935 }; 9936 9937 // Base case: There is only one way to partition Clusters[N-1]. 9938 MinPartitions[N - 1] = 1; 9939 LastElement[N - 1] = N - 1; 9940 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9941 9942 // Note: loop indexes are signed to avoid underflow. 9943 for (int64_t i = N - 2; i >= 0; i--) { 9944 // Find optimal partitioning of Clusters[i..N-1]. 9945 // Baseline: Put Clusters[i] into a partition on its own. 9946 MinPartitions[i] = MinPartitions[i + 1] + 1; 9947 LastElement[i] = i; 9948 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9949 9950 // Search for a solution that results in fewer partitions. 9951 for (int64_t j = N - 1; j > i; j--) { 9952 // Try building a partition from Clusters[i..j]. 9953 uint64_t Range = getJumpTableRange(Clusters, i, j); 9954 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9955 assert(NumCases < UINT64_MAX / 100); 9956 assert(Range >= NumCases); 9957 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9958 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9959 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9960 int64_t NumEntries = j - i + 1; 9961 9962 if (NumEntries == 1) 9963 Score += PartitionScores::SingleCase; 9964 else if (NumEntries <= SmallNumberOfEntries) 9965 Score += PartitionScores::FewCases; 9966 else if (NumEntries >= MinJumpTableEntries) 9967 Score += PartitionScores::Table; 9968 9969 // If this leads to fewer partitions, or to the same number of 9970 // partitions with better score, it is a better partitioning. 9971 if (NumPartitions < MinPartitions[i] || 9972 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9973 MinPartitions[i] = NumPartitions; 9974 LastElement[i] = j; 9975 PartitionsScore[i] = Score; 9976 } 9977 } 9978 } 9979 } 9980 9981 // Iterate over the partitions, replacing some with jump tables in-place. 9982 unsigned DstIndex = 0; 9983 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9984 Last = LastElement[First]; 9985 assert(Last >= First); 9986 assert(DstIndex <= First); 9987 unsigned NumClusters = Last - First + 1; 9988 9989 CaseCluster JTCluster; 9990 if (NumClusters >= MinJumpTableEntries && 9991 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9992 Clusters[DstIndex++] = JTCluster; 9993 } else { 9994 for (unsigned I = First; I <= Last; ++I) 9995 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9996 } 9997 } 9998 Clusters.resize(DstIndex); 9999 } 10000 10001 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 10002 unsigned First, unsigned Last, 10003 const SwitchInst *SI, 10004 CaseCluster &BTCluster) { 10005 assert(First <= Last); 10006 if (First == Last) 10007 return false; 10008 10009 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10010 unsigned NumCmps = 0; 10011 for (int64_t I = First; I <= Last; ++I) { 10012 assert(Clusters[I].Kind == CC_Range); 10013 Dests.set(Clusters[I].MBB->getNumber()); 10014 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 10015 } 10016 unsigned NumDests = Dests.count(); 10017 10018 APInt Low = Clusters[First].Low->getValue(); 10019 APInt High = Clusters[Last].High->getValue(); 10020 assert(Low.slt(High)); 10021 10022 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10023 const DataLayout &DL = DAG.getDataLayout(); 10024 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 10025 return false; 10026 10027 APInt LowBound; 10028 APInt CmpRange; 10029 10030 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 10031 assert(TLI.rangeFitsInWord(Low, High, DL) && 10032 "Case range must fit in bit mask!"); 10033 10034 // Check if the clusters cover a contiguous range such that no value in the 10035 // range will jump to the default statement. 10036 bool ContiguousRange = true; 10037 for (int64_t I = First + 1; I <= Last; ++I) { 10038 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 10039 ContiguousRange = false; 10040 break; 10041 } 10042 } 10043 10044 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 10045 // Optimize the case where all the case values fit in a word without having 10046 // to subtract minValue. In this case, we can optimize away the subtraction. 10047 LowBound = APInt::getNullValue(Low.getBitWidth()); 10048 CmpRange = High; 10049 ContiguousRange = false; 10050 } else { 10051 LowBound = Low; 10052 CmpRange = High - Low; 10053 } 10054 10055 CaseBitsVector CBV; 10056 auto TotalProb = BranchProbability::getZero(); 10057 for (unsigned i = First; i <= Last; ++i) { 10058 // Find the CaseBits for this destination. 10059 unsigned j; 10060 for (j = 0; j < CBV.size(); ++j) 10061 if (CBV[j].BB == Clusters[i].MBB) 10062 break; 10063 if (j == CBV.size()) 10064 CBV.push_back( 10065 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 10066 CaseBits *CB = &CBV[j]; 10067 10068 // Update Mask, Bits and ExtraProb. 10069 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 10070 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 10071 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 10072 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 10073 CB->Bits += Hi - Lo + 1; 10074 CB->ExtraProb += Clusters[i].Prob; 10075 TotalProb += Clusters[i].Prob; 10076 } 10077 10078 BitTestInfo BTI; 10079 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 10080 // Sort by probability first, number of bits second, bit mask third. 10081 if (a.ExtraProb != b.ExtraProb) 10082 return a.ExtraProb > b.ExtraProb; 10083 if (a.Bits != b.Bits) 10084 return a.Bits > b.Bits; 10085 return a.Mask < b.Mask; 10086 }); 10087 10088 for (auto &CB : CBV) { 10089 MachineBasicBlock *BitTestBB = 10090 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 10091 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 10092 } 10093 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 10094 SI->getCondition(), -1U, MVT::Other, false, 10095 ContiguousRange, nullptr, nullptr, std::move(BTI), 10096 TotalProb); 10097 10098 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 10099 BitTestCases.size() - 1, TotalProb); 10100 return true; 10101 } 10102 10103 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 10104 const SwitchInst *SI) { 10105 // Partition Clusters into as few subsets as possible, where each subset has a 10106 // range that fits in a machine word and has <= 3 unique destinations. 10107 10108 #ifndef NDEBUG 10109 // Clusters must be sorted and contain Range or JumpTable clusters. 10110 assert(!Clusters.empty()); 10111 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 10112 for (const CaseCluster &C : Clusters) 10113 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 10114 for (unsigned i = 1; i < Clusters.size(); ++i) 10115 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 10116 #endif 10117 10118 // The algorithm below is not suitable for -O0. 10119 if (TM.getOptLevel() == CodeGenOpt::None) 10120 return; 10121 10122 // If target does not have legal shift left, do not emit bit tests at all. 10123 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10124 const DataLayout &DL = DAG.getDataLayout(); 10125 10126 EVT PTy = TLI.getPointerTy(DL); 10127 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 10128 return; 10129 10130 int BitWidth = PTy.getSizeInBits(); 10131 const int64_t N = Clusters.size(); 10132 10133 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 10134 SmallVector<unsigned, 8> MinPartitions(N); 10135 // LastElement[i] is the last element of the partition starting at i. 10136 SmallVector<unsigned, 8> LastElement(N); 10137 10138 // FIXME: This might not be the best algorithm for finding bit test clusters. 10139 10140 // Base case: There is only one way to partition Clusters[N-1]. 10141 MinPartitions[N - 1] = 1; 10142 LastElement[N - 1] = N - 1; 10143 10144 // Note: loop indexes are signed to avoid underflow. 10145 for (int64_t i = N - 2; i >= 0; --i) { 10146 // Find optimal partitioning of Clusters[i..N-1]. 10147 // Baseline: Put Clusters[i] into a partition on its own. 10148 MinPartitions[i] = MinPartitions[i + 1] + 1; 10149 LastElement[i] = i; 10150 10151 // Search for a solution that results in fewer partitions. 10152 // Note: the search is limited by BitWidth, reducing time complexity. 10153 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 10154 // Try building a partition from Clusters[i..j]. 10155 10156 // Check the range. 10157 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 10158 Clusters[j].High->getValue(), DL)) 10159 continue; 10160 10161 // Check nbr of destinations and cluster types. 10162 // FIXME: This works, but doesn't seem very efficient. 10163 bool RangesOnly = true; 10164 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 10165 for (int64_t k = i; k <= j; k++) { 10166 if (Clusters[k].Kind != CC_Range) { 10167 RangesOnly = false; 10168 break; 10169 } 10170 Dests.set(Clusters[k].MBB->getNumber()); 10171 } 10172 if (!RangesOnly || Dests.count() > 3) 10173 break; 10174 10175 // Check if it's a better partition. 10176 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 10177 if (NumPartitions < MinPartitions[i]) { 10178 // Found a better partition. 10179 MinPartitions[i] = NumPartitions; 10180 LastElement[i] = j; 10181 } 10182 } 10183 } 10184 10185 // Iterate over the partitions, replacing with bit-test clusters in-place. 10186 unsigned DstIndex = 0; 10187 for (unsigned First = 0, Last; First < N; First = Last + 1) { 10188 Last = LastElement[First]; 10189 assert(First <= Last); 10190 assert(DstIndex <= First); 10191 10192 CaseCluster BitTestCluster; 10193 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 10194 Clusters[DstIndex++] = BitTestCluster; 10195 } else { 10196 size_t NumClusters = Last - First + 1; 10197 std::memmove(&Clusters[DstIndex], &Clusters[First], 10198 sizeof(Clusters[0]) * NumClusters); 10199 DstIndex += NumClusters; 10200 } 10201 } 10202 Clusters.resize(DstIndex); 10203 } 10204 10205 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 10206 MachineBasicBlock *SwitchMBB, 10207 MachineBasicBlock *DefaultMBB) { 10208 MachineFunction *CurMF = FuncInfo.MF; 10209 MachineBasicBlock *NextMBB = nullptr; 10210 MachineFunction::iterator BBI(W.MBB); 10211 if (++BBI != FuncInfo.MF->end()) 10212 NextMBB = &*BBI; 10213 10214 unsigned Size = W.LastCluster - W.FirstCluster + 1; 10215 10216 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10217 10218 if (Size == 2 && W.MBB == SwitchMBB) { 10219 // If any two of the cases has the same destination, and if one value 10220 // is the same as the other, but has one bit unset that the other has set, 10221 // use bit manipulation to do two compares at once. For example: 10222 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 10223 // TODO: This could be extended to merge any 2 cases in switches with 3 10224 // cases. 10225 // TODO: Handle cases where W.CaseBB != SwitchBB. 10226 CaseCluster &Small = *W.FirstCluster; 10227 CaseCluster &Big = *W.LastCluster; 10228 10229 if (Small.Low == Small.High && Big.Low == Big.High && 10230 Small.MBB == Big.MBB) { 10231 const APInt &SmallValue = Small.Low->getValue(); 10232 const APInt &BigValue = Big.Low->getValue(); 10233 10234 // Check that there is only one bit different. 10235 APInt CommonBit = BigValue ^ SmallValue; 10236 if (CommonBit.isPowerOf2()) { 10237 SDValue CondLHS = getValue(Cond); 10238 EVT VT = CondLHS.getValueType(); 10239 SDLoc DL = getCurSDLoc(); 10240 10241 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 10242 DAG.getConstant(CommonBit, DL, VT)); 10243 SDValue Cond = DAG.getSetCC( 10244 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 10245 ISD::SETEQ); 10246 10247 // Update successor info. 10248 // Both Small and Big will jump to Small.BB, so we sum up the 10249 // probabilities. 10250 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 10251 if (BPI) 10252 addSuccessorWithProb( 10253 SwitchMBB, DefaultMBB, 10254 // The default destination is the first successor in IR. 10255 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 10256 else 10257 addSuccessorWithProb(SwitchMBB, DefaultMBB); 10258 10259 // Insert the true branch. 10260 SDValue BrCond = 10261 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 10262 DAG.getBasicBlock(Small.MBB)); 10263 // Insert the false branch. 10264 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 10265 DAG.getBasicBlock(DefaultMBB)); 10266 10267 DAG.setRoot(BrCond); 10268 return; 10269 } 10270 } 10271 } 10272 10273 if (TM.getOptLevel() != CodeGenOpt::None) { 10274 // Here, we order cases by probability so the most likely case will be 10275 // checked first. However, two clusters can have the same probability in 10276 // which case their relative ordering is non-deterministic. So we use Low 10277 // as a tie-breaker as clusters are guaranteed to never overlap. 10278 llvm::sort(W.FirstCluster, W.LastCluster + 1, 10279 [](const CaseCluster &a, const CaseCluster &b) { 10280 return a.Prob != b.Prob ? 10281 a.Prob > b.Prob : 10282 a.Low->getValue().slt(b.Low->getValue()); 10283 }); 10284 10285 // Rearrange the case blocks so that the last one falls through if possible 10286 // without changing the order of probabilities. 10287 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 10288 --I; 10289 if (I->Prob > W.LastCluster->Prob) 10290 break; 10291 if (I->Kind == CC_Range && I->MBB == NextMBB) { 10292 std::swap(*I, *W.LastCluster); 10293 break; 10294 } 10295 } 10296 } 10297 10298 // Compute total probability. 10299 BranchProbability DefaultProb = W.DefaultProb; 10300 BranchProbability UnhandledProbs = DefaultProb; 10301 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 10302 UnhandledProbs += I->Prob; 10303 10304 MachineBasicBlock *CurMBB = W.MBB; 10305 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 10306 MachineBasicBlock *Fallthrough; 10307 if (I == W.LastCluster) { 10308 // For the last cluster, fall through to the default destination. 10309 Fallthrough = DefaultMBB; 10310 } else { 10311 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 10312 CurMF->insert(BBI, Fallthrough); 10313 // Put Cond in a virtual register to make it available from the new blocks. 10314 ExportFromCurrentBlock(Cond); 10315 } 10316 UnhandledProbs -= I->Prob; 10317 10318 switch (I->Kind) { 10319 case CC_JumpTable: { 10320 // FIXME: Optimize away range check based on pivot comparisons. 10321 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 10322 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 10323 10324 // The jump block hasn't been inserted yet; insert it here. 10325 MachineBasicBlock *JumpMBB = JT->MBB; 10326 CurMF->insert(BBI, JumpMBB); 10327 10328 auto JumpProb = I->Prob; 10329 auto FallthroughProb = UnhandledProbs; 10330 10331 // If the default statement is a target of the jump table, we evenly 10332 // distribute the default probability to successors of CurMBB. Also 10333 // update the probability on the edge from JumpMBB to Fallthrough. 10334 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 10335 SE = JumpMBB->succ_end(); 10336 SI != SE; ++SI) { 10337 if (*SI == DefaultMBB) { 10338 JumpProb += DefaultProb / 2; 10339 FallthroughProb -= DefaultProb / 2; 10340 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 10341 JumpMBB->normalizeSuccProbs(); 10342 break; 10343 } 10344 } 10345 10346 if (Fallthrough == DefaultMBB && 10347 isa<UnreachableInst>( 10348 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg())) { 10349 // Skip the range check if the fallthrough block is unreachable. 10350 JTH->OmitRangeCheck = true; 10351 } 10352 10353 if (!JTH->OmitRangeCheck) 10354 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 10355 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 10356 CurMBB->normalizeSuccProbs(); 10357 10358 // The jump table header will be inserted in our current block, do the 10359 // range check, and fall through to our fallthrough block. 10360 JTH->HeaderBB = CurMBB; 10361 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10362 10363 // If we're in the right place, emit the jump table header right now. 10364 if (CurMBB == SwitchMBB) { 10365 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10366 JTH->Emitted = true; 10367 } 10368 break; 10369 } 10370 case CC_BitTests: { 10371 // FIXME: Optimize away range check based on pivot comparisons. 10372 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10373 10374 // The bit test blocks haven't been inserted yet; insert them here. 10375 for (BitTestCase &BTC : BTB->Cases) 10376 CurMF->insert(BBI, BTC.ThisBB); 10377 10378 // Fill in fields of the BitTestBlock. 10379 BTB->Parent = CurMBB; 10380 BTB->Default = Fallthrough; 10381 10382 BTB->DefaultProb = UnhandledProbs; 10383 // If the cases in bit test don't form a contiguous range, we evenly 10384 // distribute the probability on the edge to Fallthrough to two 10385 // successors of CurMBB. 10386 if (!BTB->ContiguousRange) { 10387 BTB->Prob += DefaultProb / 2; 10388 BTB->DefaultProb -= DefaultProb / 2; 10389 } 10390 10391 // If we're in the right place, emit the bit test header right now. 10392 if (CurMBB == SwitchMBB) { 10393 visitBitTestHeader(*BTB, SwitchMBB); 10394 BTB->Emitted = true; 10395 } 10396 break; 10397 } 10398 case CC_Range: { 10399 const Value *RHS, *LHS, *MHS; 10400 ISD::CondCode CC; 10401 if (I->Low == I->High) { 10402 // Check Cond == I->Low. 10403 CC = ISD::SETEQ; 10404 LHS = Cond; 10405 RHS=I->Low; 10406 MHS = nullptr; 10407 } else { 10408 // Check I->Low <= Cond <= I->High. 10409 CC = ISD::SETLE; 10410 LHS = I->Low; 10411 MHS = Cond; 10412 RHS = I->High; 10413 } 10414 10415 // The false probability is the sum of all unhandled cases. 10416 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10417 getCurSDLoc(), I->Prob, UnhandledProbs); 10418 10419 if (CurMBB == SwitchMBB) 10420 visitSwitchCase(CB, SwitchMBB); 10421 else 10422 SwitchCases.push_back(CB); 10423 10424 break; 10425 } 10426 } 10427 CurMBB = Fallthrough; 10428 } 10429 } 10430 10431 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10432 CaseClusterIt First, 10433 CaseClusterIt Last) { 10434 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10435 if (X.Prob != CC.Prob) 10436 return X.Prob > CC.Prob; 10437 10438 // Ties are broken by comparing the case value. 10439 return X.Low->getValue().slt(CC.Low->getValue()); 10440 }); 10441 } 10442 10443 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10444 const SwitchWorkListItem &W, 10445 Value *Cond, 10446 MachineBasicBlock *SwitchMBB) { 10447 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10448 "Clusters not sorted?"); 10449 10450 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10451 10452 // Balance the tree based on branch probabilities to create a near-optimal (in 10453 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10454 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10455 CaseClusterIt LastLeft = W.FirstCluster; 10456 CaseClusterIt FirstRight = W.LastCluster; 10457 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10458 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10459 10460 // Move LastLeft and FirstRight towards each other from opposite directions to 10461 // find a partitioning of the clusters which balances the probability on both 10462 // sides. If LeftProb and RightProb are equal, alternate which side is 10463 // taken to ensure 0-probability nodes are distributed evenly. 10464 unsigned I = 0; 10465 while (LastLeft + 1 < FirstRight) { 10466 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10467 LeftProb += (++LastLeft)->Prob; 10468 else 10469 RightProb += (--FirstRight)->Prob; 10470 I++; 10471 } 10472 10473 while (true) { 10474 // Our binary search tree differs from a typical BST in that ours can have up 10475 // to three values in each leaf. The pivot selection above doesn't take that 10476 // into account, which means the tree might require more nodes and be less 10477 // efficient. We compensate for this here. 10478 10479 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10480 unsigned NumRight = W.LastCluster - FirstRight + 1; 10481 10482 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10483 // If one side has less than 3 clusters, and the other has more than 3, 10484 // consider taking a cluster from the other side. 10485 10486 if (NumLeft < NumRight) { 10487 // Consider moving the first cluster on the right to the left side. 10488 CaseCluster &CC = *FirstRight; 10489 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10490 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10491 if (LeftSideRank <= RightSideRank) { 10492 // Moving the cluster to the left does not demote it. 10493 ++LastLeft; 10494 ++FirstRight; 10495 continue; 10496 } 10497 } else { 10498 assert(NumRight < NumLeft); 10499 // Consider moving the last element on the left to the right side. 10500 CaseCluster &CC = *LastLeft; 10501 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10502 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10503 if (RightSideRank <= LeftSideRank) { 10504 // Moving the cluster to the right does not demot it. 10505 --LastLeft; 10506 --FirstRight; 10507 continue; 10508 } 10509 } 10510 } 10511 break; 10512 } 10513 10514 assert(LastLeft + 1 == FirstRight); 10515 assert(LastLeft >= W.FirstCluster); 10516 assert(FirstRight <= W.LastCluster); 10517 10518 // Use the first element on the right as pivot since we will make less-than 10519 // comparisons against it. 10520 CaseClusterIt PivotCluster = FirstRight; 10521 assert(PivotCluster > W.FirstCluster); 10522 assert(PivotCluster <= W.LastCluster); 10523 10524 CaseClusterIt FirstLeft = W.FirstCluster; 10525 CaseClusterIt LastRight = W.LastCluster; 10526 10527 const ConstantInt *Pivot = PivotCluster->Low; 10528 10529 // New blocks will be inserted immediately after the current one. 10530 MachineFunction::iterator BBI(W.MBB); 10531 ++BBI; 10532 10533 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10534 // we can branch to its destination directly if it's squeezed exactly in 10535 // between the known lower bound and Pivot - 1. 10536 MachineBasicBlock *LeftMBB; 10537 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10538 FirstLeft->Low == W.GE && 10539 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10540 LeftMBB = FirstLeft->MBB; 10541 } else { 10542 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10543 FuncInfo.MF->insert(BBI, LeftMBB); 10544 WorkList.push_back( 10545 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10546 // Put Cond in a virtual register to make it available from the new blocks. 10547 ExportFromCurrentBlock(Cond); 10548 } 10549 10550 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10551 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10552 // directly if RHS.High equals the current upper bound. 10553 MachineBasicBlock *RightMBB; 10554 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10555 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10556 RightMBB = FirstRight->MBB; 10557 } else { 10558 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10559 FuncInfo.MF->insert(BBI, RightMBB); 10560 WorkList.push_back( 10561 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10562 // Put Cond in a virtual register to make it available from the new blocks. 10563 ExportFromCurrentBlock(Cond); 10564 } 10565 10566 // Create the CaseBlock record that will be used to lower the branch. 10567 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10568 getCurSDLoc(), LeftProb, RightProb); 10569 10570 if (W.MBB == SwitchMBB) 10571 visitSwitchCase(CB, SwitchMBB); 10572 else 10573 SwitchCases.push_back(CB); 10574 } 10575 10576 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10577 // from the swith statement. 10578 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10579 BranchProbability PeeledCaseProb) { 10580 if (PeeledCaseProb == BranchProbability::getOne()) 10581 return BranchProbability::getZero(); 10582 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10583 10584 uint32_t Numerator = CaseProb.getNumerator(); 10585 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10586 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10587 } 10588 10589 // Try to peel the top probability case if it exceeds the threshold. 10590 // Return current MachineBasicBlock for the switch statement if the peeling 10591 // does not occur. 10592 // If the peeling is performed, return the newly created MachineBasicBlock 10593 // for the peeled switch statement. Also update Clusters to remove the peeled 10594 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10595 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10596 const SwitchInst &SI, CaseClusterVector &Clusters, 10597 BranchProbability &PeeledCaseProb) { 10598 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10599 // Don't perform if there is only one cluster or optimizing for size. 10600 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10601 TM.getOptLevel() == CodeGenOpt::None || 10602 SwitchMBB->getParent()->getFunction().optForMinSize()) 10603 return SwitchMBB; 10604 10605 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10606 unsigned PeeledCaseIndex = 0; 10607 bool SwitchPeeled = false; 10608 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10609 CaseCluster &CC = Clusters[Index]; 10610 if (CC.Prob < TopCaseProb) 10611 continue; 10612 TopCaseProb = CC.Prob; 10613 PeeledCaseIndex = Index; 10614 SwitchPeeled = true; 10615 } 10616 if (!SwitchPeeled) 10617 return SwitchMBB; 10618 10619 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10620 << TopCaseProb << "\n"); 10621 10622 // Record the MBB for the peeled switch statement. 10623 MachineFunction::iterator BBI(SwitchMBB); 10624 ++BBI; 10625 MachineBasicBlock *PeeledSwitchMBB = 10626 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10627 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10628 10629 ExportFromCurrentBlock(SI.getCondition()); 10630 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10631 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10632 nullptr, nullptr, TopCaseProb.getCompl()}; 10633 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10634 10635 Clusters.erase(PeeledCaseIt); 10636 for (CaseCluster &CC : Clusters) { 10637 LLVM_DEBUG( 10638 dbgs() << "Scale the probablity for one cluster, before scaling: " 10639 << CC.Prob << "\n"); 10640 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10641 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10642 } 10643 PeeledCaseProb = TopCaseProb; 10644 return PeeledSwitchMBB; 10645 } 10646 10647 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10648 // Extract cases from the switch. 10649 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10650 CaseClusterVector Clusters; 10651 Clusters.reserve(SI.getNumCases()); 10652 for (auto I : SI.cases()) { 10653 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10654 const ConstantInt *CaseVal = I.getCaseValue(); 10655 BranchProbability Prob = 10656 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10657 : BranchProbability(1, SI.getNumCases() + 1); 10658 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10659 } 10660 10661 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10662 10663 // Cluster adjacent cases with the same destination. We do this at all 10664 // optimization levels because it's cheap to do and will make codegen faster 10665 // if there are many clusters. 10666 sortAndRangeify(Clusters); 10667 10668 // The branch probablity of the peeled case. 10669 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10670 MachineBasicBlock *PeeledSwitchMBB = 10671 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10672 10673 // If there is only the default destination, jump there directly. 10674 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10675 if (Clusters.empty()) { 10676 assert(PeeledSwitchMBB == SwitchMBB); 10677 SwitchMBB->addSuccessor(DefaultMBB); 10678 if (DefaultMBB != NextBlock(SwitchMBB)) { 10679 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10680 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10681 } 10682 return; 10683 } 10684 10685 findJumpTables(Clusters, &SI, DefaultMBB); 10686 findBitTestClusters(Clusters, &SI); 10687 10688 LLVM_DEBUG({ 10689 dbgs() << "Case clusters: "; 10690 for (const CaseCluster &C : Clusters) { 10691 if (C.Kind == CC_JumpTable) 10692 dbgs() << "JT:"; 10693 if (C.Kind == CC_BitTests) 10694 dbgs() << "BT:"; 10695 10696 C.Low->getValue().print(dbgs(), true); 10697 if (C.Low != C.High) { 10698 dbgs() << '-'; 10699 C.High->getValue().print(dbgs(), true); 10700 } 10701 dbgs() << ' '; 10702 } 10703 dbgs() << '\n'; 10704 }); 10705 10706 assert(!Clusters.empty()); 10707 SwitchWorkList WorkList; 10708 CaseClusterIt First = Clusters.begin(); 10709 CaseClusterIt Last = Clusters.end() - 1; 10710 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10711 // Scale the branchprobability for DefaultMBB if the peel occurs and 10712 // DefaultMBB is not replaced. 10713 if (PeeledCaseProb != BranchProbability::getZero() && 10714 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10715 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10716 WorkList.push_back( 10717 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10718 10719 while (!WorkList.empty()) { 10720 SwitchWorkListItem W = WorkList.back(); 10721 WorkList.pop_back(); 10722 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10723 10724 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10725 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10726 // For optimized builds, lower large range as a balanced binary tree. 10727 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10728 continue; 10729 } 10730 10731 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10732 } 10733 } 10734