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