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 <algorithm> 112 #include <cassert> 113 #include <cstddef> 114 #include <cstdint> 115 #include <cstring> 116 #include <iterator> 117 #include <limits> 118 #include <numeric> 119 #include <tuple> 120 #include <utility> 121 #include <vector> 122 123 using namespace llvm; 124 using namespace PatternMatch; 125 126 #define DEBUG_TYPE "isel" 127 128 /// LimitFloatPrecision - Generate low-precision inline sequences for 129 /// some float libcalls (6, 8 or 12 bits). 130 static unsigned LimitFloatPrecision; 131 132 static cl::opt<unsigned, true> 133 LimitFPPrecision("limit-float-precision", 134 cl::desc("Generate low-precision inline sequences " 135 "for some float libcalls"), 136 cl::location(LimitFloatPrecision), cl::Hidden, 137 cl::init(0)); 138 139 static cl::opt<unsigned> SwitchPeelThreshold( 140 "switch-peel-threshold", cl::Hidden, cl::init(66), 141 cl::desc("Set the case probability threshold for peeling the case from a " 142 "switch statement. A value greater than 100 will void this " 143 "optimization")); 144 145 // Limit the width of DAG chains. This is important in general to prevent 146 // DAG-based analysis from blowing up. For example, alias analysis and 147 // load clustering may not complete in reasonable time. It is difficult to 148 // recognize and avoid this situation within each individual analysis, and 149 // future analyses are likely to have the same behavior. Limiting DAG width is 150 // the safe approach and will be especially important with global DAGs. 151 // 152 // MaxParallelChains default is arbitrarily high to avoid affecting 153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 154 // sequence over this should have been converted to llvm.memcpy by the 155 // frontend. It is easy to induce this behavior with .ll code such as: 156 // %buffer = alloca [4096 x i8] 157 // %data = load [4096 x i8]* %argPtr 158 // store [4096 x i8] %data, [4096 x i8]* %buffer 159 static const unsigned MaxParallelChains = 64; 160 161 // Return the calling convention if the Value passed requires ABI mangling as it 162 // is a parameter to a function or a return value from a function which is not 163 // an intrinsic. 164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) { 165 if (auto *R = dyn_cast<ReturnInst>(V)) 166 return R->getParent()->getParent()->getCallingConv(); 167 168 if (auto *CI = dyn_cast<CallInst>(V)) { 169 const bool IsInlineAsm = CI->isInlineAsm(); 170 const bool IsIndirectFunctionCall = 171 !IsInlineAsm && !CI->getCalledFunction(); 172 173 // It is possible that the call instruction is an inline asm statement or an 174 // indirect function call in which case the return value of 175 // getCalledFunction() would be nullptr. 176 const bool IsInstrinsicCall = 177 !IsInlineAsm && !IsIndirectFunctionCall && 178 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic; 179 180 if (!IsInlineAsm && !IsInstrinsicCall) 181 return CI->getCallingConv(); 182 } 183 184 return None; 185 } 186 187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 188 const SDValue *Parts, unsigned NumParts, 189 MVT PartVT, EVT ValueVT, const Value *V, 190 Optional<CallingConv::ID> CC); 191 192 /// getCopyFromParts - Create a value that contains the specified legal parts 193 /// combined into the value they represent. If the parts combine to a type 194 /// larger than ValueVT then AssertOp can be used to specify whether the extra 195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 196 /// (ISD::AssertSext). 197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 198 const SDValue *Parts, unsigned NumParts, 199 MVT PartVT, EVT ValueVT, const Value *V, 200 Optional<CallingConv::ID> CC = None, 201 Optional<ISD::NodeType> AssertOp = None) { 202 if (ValueVT.isVector()) 203 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V, 204 CC); 205 206 assert(NumParts > 0 && "No parts to assemble!"); 207 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 208 SDValue Val = Parts[0]; 209 210 if (NumParts > 1) { 211 // Assemble the value from multiple parts. 212 if (ValueVT.isInteger()) { 213 unsigned PartBits = PartVT.getSizeInBits(); 214 unsigned ValueBits = ValueVT.getSizeInBits(); 215 216 // Assemble the power of 2 part. 217 unsigned RoundParts = NumParts & (NumParts - 1) ? 218 1 << Log2_32(NumParts) : NumParts; 219 unsigned RoundBits = PartBits * RoundParts; 220 EVT RoundVT = RoundBits == ValueBits ? 221 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 222 SDValue Lo, Hi; 223 224 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 225 226 if (RoundParts > 2) { 227 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 228 PartVT, HalfVT, V); 229 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 230 RoundParts / 2, PartVT, HalfVT, V); 231 } else { 232 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 233 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 234 } 235 236 if (DAG.getDataLayout().isBigEndian()) 237 std::swap(Lo, Hi); 238 239 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 240 241 if (RoundParts < NumParts) { 242 // Assemble the trailing non-power-of-2 part. 243 unsigned OddParts = NumParts - RoundParts; 244 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 245 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT, 246 OddVT, V, CC); 247 248 // Combine the round and odd parts. 249 Lo = Val; 250 if (DAG.getDataLayout().isBigEndian()) 251 std::swap(Lo, Hi); 252 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 253 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 254 Hi = 255 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 256 DAG.getConstant(Lo.getValueSizeInBits(), DL, 257 TLI.getPointerTy(DAG.getDataLayout()))); 258 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 259 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 260 } 261 } else if (PartVT.isFloatingPoint()) { 262 // FP split into multiple FP parts (for ppcf128) 263 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 264 "Unexpected split"); 265 SDValue Lo, Hi; 266 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 267 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 268 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 269 std::swap(Lo, Hi); 270 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 271 } else { 272 // FP split into integer parts (soft fp) 273 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 274 !PartVT.isVector() && "Unexpected split"); 275 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 276 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC); 277 } 278 } 279 280 // There is now one part, held in Val. Correct it to match ValueVT. 281 // PartEVT is the type of the register class that holds the value. 282 // ValueVT is the type of the inline asm operation. 283 EVT PartEVT = Val.getValueType(); 284 285 if (PartEVT == ValueVT) 286 return Val; 287 288 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 289 ValueVT.bitsLT(PartEVT)) { 290 // For an FP value in an integer part, we need to truncate to the right 291 // width first. 292 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 293 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 294 } 295 296 // Handle types that have the same size. 297 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 298 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 299 300 // Handle types with different sizes. 301 if (PartEVT.isInteger() && ValueVT.isInteger()) { 302 if (ValueVT.bitsLT(PartEVT)) { 303 // For a truncate, see if we have any information to 304 // indicate whether the truncated bits will always be 305 // zero or sign-extension. 306 if (AssertOp.hasValue()) 307 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 308 DAG.getValueType(ValueVT)); 309 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 310 } 311 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 312 } 313 314 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 315 // FP_ROUND's are always exact here. 316 if (ValueVT.bitsLT(Val.getValueType())) 317 return DAG.getNode( 318 ISD::FP_ROUND, DL, ValueVT, Val, 319 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 320 321 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 322 } 323 324 llvm_unreachable("Unknown mismatch!"); 325 } 326 327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 328 const Twine &ErrMsg) { 329 const Instruction *I = dyn_cast_or_null<Instruction>(V); 330 if (!V) 331 return Ctx.emitError(ErrMsg); 332 333 const char *AsmError = ", possible invalid constraint for vector type"; 334 if (const CallInst *CI = dyn_cast<CallInst>(I)) 335 if (isa<InlineAsm>(CI->getCalledValue())) 336 return Ctx.emitError(I, ErrMsg + AsmError); 337 338 return Ctx.emitError(I, ErrMsg); 339 } 340 341 /// getCopyFromPartsVector - Create a value that contains the specified legal 342 /// parts combined into the value they represent. If the parts combine to a 343 /// type larger than ValueVT then AssertOp can be used to specify whether the 344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 345 /// ValueVT (ISD::AssertSext). 346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 347 const SDValue *Parts, unsigned NumParts, 348 MVT PartVT, EVT ValueVT, const Value *V, 349 Optional<CallingConv::ID> CallConv) { 350 assert(ValueVT.isVector() && "Not a vector value"); 351 assert(NumParts > 0 && "No parts to assemble!"); 352 const bool IsABIRegCopy = CallConv.hasValue(); 353 354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 355 SDValue Val = Parts[0]; 356 357 // Handle a multi-element vector. 358 if (NumParts > 1) { 359 EVT IntermediateVT; 360 MVT RegisterVT; 361 unsigned NumIntermediates; 362 unsigned NumRegs; 363 364 if (IsABIRegCopy) { 365 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 366 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 367 NumIntermediates, RegisterVT); 368 } else { 369 NumRegs = 370 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 371 NumIntermediates, RegisterVT); 372 } 373 374 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 375 NumParts = NumRegs; // Silence a compiler warning. 376 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 377 assert(RegisterVT.getSizeInBits() == 378 Parts[0].getSimpleValueType().getSizeInBits() && 379 "Part type sizes don't match!"); 380 381 // Assemble the parts into intermediate operands. 382 SmallVector<SDValue, 8> Ops(NumIntermediates); 383 if (NumIntermediates == NumParts) { 384 // If the register was not expanded, truncate or copy the value, 385 // as appropriate. 386 for (unsigned i = 0; i != NumParts; ++i) 387 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 388 PartVT, IntermediateVT, V); 389 } else if (NumParts > 0) { 390 // If the intermediate type was expanded, build the intermediate 391 // operands from the parts. 392 assert(NumParts % NumIntermediates == 0 && 393 "Must expand into a divisible number of parts!"); 394 unsigned Factor = NumParts / NumIntermediates; 395 for (unsigned i = 0; i != NumIntermediates; ++i) 396 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 397 PartVT, IntermediateVT, V); 398 } 399 400 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 401 // intermediate operands. 402 EVT BuiltVectorTy = 403 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 404 (IntermediateVT.isVector() 405 ? IntermediateVT.getVectorNumElements() * NumParts 406 : NumIntermediates)); 407 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 408 : ISD::BUILD_VECTOR, 409 DL, BuiltVectorTy, Ops); 410 } 411 412 // There is now one part, held in Val. Correct it to match ValueVT. 413 EVT PartEVT = Val.getValueType(); 414 415 if (PartEVT == ValueVT) 416 return Val; 417 418 if (PartEVT.isVector()) { 419 // If the element type of the source/dest vectors are the same, but the 420 // parts vector has more elements than the value vector, then we have a 421 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 422 // elements we want. 423 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 424 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 425 "Cannot narrow, it would be a lossy transformation"); 426 return DAG.getNode( 427 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 428 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 429 } 430 431 // Vector/Vector bitcast. 432 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 433 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 434 435 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 436 "Cannot handle this kind of promotion"); 437 // Promoted vector extract 438 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 439 440 } 441 442 // Trivial bitcast if the types are the same size and the destination 443 // vector type is legal. 444 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 445 TLI.isTypeLegal(ValueVT)) 446 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 447 448 if (ValueVT.getVectorNumElements() != 1) { 449 // Certain ABIs require that vectors are passed as integers. For vectors 450 // are the same size, this is an obvious bitcast. 451 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 452 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 453 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 454 // Bitcast Val back the original type and extract the corresponding 455 // vector we want. 456 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 457 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 458 ValueVT.getVectorElementType(), Elts); 459 Val = DAG.getBitcast(WiderVecType, Val); 460 return DAG.getNode( 461 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 462 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 463 } 464 465 diagnosePossiblyInvalidConstraint( 466 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 467 return DAG.getUNDEF(ValueVT); 468 } 469 470 // Handle cases such as i8 -> <1 x i1> 471 EVT ValueSVT = ValueVT.getVectorElementType(); 472 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 473 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 474 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 475 476 return DAG.getBuildVector(ValueVT, DL, Val); 477 } 478 479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 480 SDValue Val, SDValue *Parts, unsigned NumParts, 481 MVT PartVT, const Value *V, 482 Optional<CallingConv::ID> CallConv); 483 484 /// getCopyToParts - Create a series of nodes that contain the specified value 485 /// split into legal parts. If the parts contain more bits than Val, then, for 486 /// integers, ExtendKind can be used to specify how to generate the extra bits. 487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 488 SDValue *Parts, unsigned NumParts, MVT PartVT, 489 const Value *V, 490 Optional<CallingConv::ID> CallConv = None, 491 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 492 EVT ValueVT = Val.getValueType(); 493 494 // Handle the vector case separately. 495 if (ValueVT.isVector()) 496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 497 CallConv); 498 499 unsigned PartBits = PartVT.getSizeInBits(); 500 unsigned OrigNumParts = NumParts; 501 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 502 "Copying to an illegal type!"); 503 504 if (NumParts == 0) 505 return; 506 507 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 508 EVT PartEVT = PartVT; 509 if (PartEVT == ValueVT) { 510 assert(NumParts == 1 && "No-op copy with multiple parts!"); 511 Parts[0] = Val; 512 return; 513 } 514 515 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 516 // If the parts cover more bits than the value has, promote the value. 517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 518 assert(NumParts == 1 && "Do not know what to promote to!"); 519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 520 } else { 521 if (ValueVT.isFloatingPoint()) { 522 // FP values need to be bitcast, then extended if they are being put 523 // into a larger container. 524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 526 } 527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 528 ValueVT.isInteger() && 529 "Unknown mismatch!"); 530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 532 if (PartVT == MVT::x86mmx) 533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 534 } 535 } else if (PartBits == ValueVT.getSizeInBits()) { 536 // Different types of the same size. 537 assert(NumParts == 1 && PartEVT != ValueVT); 538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 540 // If the parts cover less bits than value has, truncate the value. 541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 542 ValueVT.isInteger() && 543 "Unknown mismatch!"); 544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 546 if (PartVT == MVT::x86mmx) 547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 548 } 549 550 // The value may have changed - recompute ValueVT. 551 ValueVT = Val.getValueType(); 552 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 553 "Failed to tile the value with PartVT!"); 554 555 if (NumParts == 1) { 556 if (PartEVT != ValueVT) { 557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 558 "scalar-to-vector conversion failed"); 559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 560 } 561 562 Parts[0] = Val; 563 return; 564 } 565 566 // Expand the value into multiple parts. 567 if (NumParts & (NumParts - 1)) { 568 // The number of parts is not a power of 2. Split off and copy the tail. 569 assert(PartVT.isInteger() && ValueVT.isInteger() && 570 "Do not know what to expand to!"); 571 unsigned RoundParts = 1 << Log2_32(NumParts); 572 unsigned RoundBits = RoundParts * PartBits; 573 unsigned OddParts = NumParts - RoundParts; 574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 575 DAG.getIntPtrConstant(RoundBits, DL)); 576 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V, 577 CallConv); 578 579 if (DAG.getDataLayout().isBigEndian()) 580 // The odd parts were reversed by getCopyToParts - unreverse them. 581 std::reverse(Parts + RoundParts, Parts + NumParts); 582 583 NumParts = RoundParts; 584 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 586 } 587 588 // The number of parts is a power of 2. Repeatedly bisect the value using 589 // EXTRACT_ELEMENT. 590 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 591 EVT::getIntegerVT(*DAG.getContext(), 592 ValueVT.getSizeInBits()), 593 Val); 594 595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 596 for (unsigned i = 0; i < NumParts; i += StepSize) { 597 unsigned ThisBits = StepSize * PartBits / 2; 598 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 599 SDValue &Part0 = Parts[i]; 600 SDValue &Part1 = Parts[i+StepSize/2]; 601 602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 603 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 605 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 606 607 if (ThisBits == PartBits && ThisVT != PartVT) { 608 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 609 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 610 } 611 } 612 } 613 614 if (DAG.getDataLayout().isBigEndian()) 615 std::reverse(Parts, Parts + OrigNumParts); 616 } 617 618 static SDValue widenVectorToPartType(SelectionDAG &DAG, 619 SDValue Val, const SDLoc &DL, EVT PartVT) { 620 if (!PartVT.isVector()) 621 return SDValue(); 622 623 EVT ValueVT = Val.getValueType(); 624 unsigned PartNumElts = PartVT.getVectorNumElements(); 625 unsigned ValueNumElts = ValueVT.getVectorNumElements(); 626 if (PartNumElts > ValueNumElts && 627 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) { 628 EVT ElementVT = PartVT.getVectorElementType(); 629 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 630 // undef elements. 631 SmallVector<SDValue, 16> Ops; 632 DAG.ExtractVectorElements(Val, Ops); 633 SDValue EltUndef = DAG.getUNDEF(ElementVT); 634 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i) 635 Ops.push_back(EltUndef); 636 637 // FIXME: Use CONCAT for 2x -> 4x. 638 return DAG.getBuildVector(PartVT, DL, Ops); 639 } 640 641 return SDValue(); 642 } 643 644 /// getCopyToPartsVector - Create a series of nodes that contain the specified 645 /// value split into legal parts. 646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 647 SDValue Val, SDValue *Parts, unsigned NumParts, 648 MVT PartVT, const Value *V, 649 Optional<CallingConv::ID> CallConv) { 650 EVT ValueVT = Val.getValueType(); 651 assert(ValueVT.isVector() && "Not a vector"); 652 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 653 const bool IsABIRegCopy = CallConv.hasValue(); 654 655 if (NumParts == 1) { 656 EVT PartEVT = PartVT; 657 if (PartEVT == ValueVT) { 658 // Nothing to do. 659 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 660 // Bitconvert vector->vector case. 661 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 662 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) { 663 Val = Widened; 664 } else if (PartVT.isVector() && 665 PartEVT.getVectorElementType().bitsGE( 666 ValueVT.getVectorElementType()) && 667 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 668 669 // Promoted vector extract 670 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 671 } else { 672 if (ValueVT.getVectorNumElements() == 1) { 673 Val = DAG.getNode( 674 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 675 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 676 } else { 677 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 678 "lossy conversion of vector to scalar type"); 679 EVT IntermediateType = 680 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 681 Val = DAG.getBitcast(IntermediateType, Val); 682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 683 } 684 } 685 686 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 687 Parts[0] = Val; 688 return; 689 } 690 691 // Handle a multi-element vector. 692 EVT IntermediateVT; 693 MVT RegisterVT; 694 unsigned NumIntermediates; 695 unsigned NumRegs; 696 if (IsABIRegCopy) { 697 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 698 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT, 699 NumIntermediates, RegisterVT); 700 } else { 701 NumRegs = 702 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 703 NumIntermediates, RegisterVT); 704 } 705 706 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 707 NumParts = NumRegs; // Silence a compiler warning. 708 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 709 710 unsigned IntermediateNumElts = IntermediateVT.isVector() ? 711 IntermediateVT.getVectorNumElements() : 1; 712 713 // Convert the vector to the appropiate type if necessary. 714 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts; 715 716 EVT BuiltVectorTy = EVT::getVectorVT( 717 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 718 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 719 if (ValueVT != BuiltVectorTy) { 720 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) 721 Val = Widened; 722 723 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 724 } 725 726 // Split the vector into intermediate operands. 727 SmallVector<SDValue, 8> Ops(NumIntermediates); 728 for (unsigned i = 0; i != NumIntermediates; ++i) { 729 if (IntermediateVT.isVector()) { 730 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 731 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT)); 732 } else { 733 Ops[i] = DAG.getNode( 734 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 735 DAG.getConstant(i, DL, IdxVT)); 736 } 737 } 738 739 // Split the intermediate operands into legal parts. 740 if (NumParts == NumIntermediates) { 741 // If the register was not expanded, promote or copy the value, 742 // as appropriate. 743 for (unsigned i = 0; i != NumParts; ++i) 744 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv); 745 } else if (NumParts > 0) { 746 // If the intermediate type was expanded, split each the value into 747 // legal parts. 748 assert(NumIntermediates != 0 && "division by zero"); 749 assert(NumParts % NumIntermediates == 0 && 750 "Must expand into a divisible number of parts!"); 751 unsigned Factor = NumParts / NumIntermediates; 752 for (unsigned i = 0; i != NumIntermediates; ++i) 753 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V, 754 CallConv); 755 } 756 } 757 758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 759 EVT valuevt, Optional<CallingConv::ID> CC) 760 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 761 RegCount(1, regs.size()), CallConv(CC) {} 762 763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 764 const DataLayout &DL, unsigned Reg, Type *Ty, 765 Optional<CallingConv::ID> CC) { 766 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 767 768 CallConv = CC; 769 770 for (EVT ValueVT : ValueVTs) { 771 unsigned NumRegs = 772 isABIMangled() 773 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT) 774 : TLI.getNumRegisters(Context, ValueVT); 775 MVT RegisterVT = 776 isABIMangled() 777 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT) 778 : TLI.getRegisterType(Context, ValueVT); 779 for (unsigned i = 0; i != NumRegs; ++i) 780 Regs.push_back(Reg + i); 781 RegVTs.push_back(RegisterVT); 782 RegCount.push_back(NumRegs); 783 Reg += NumRegs; 784 } 785 } 786 787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 788 FunctionLoweringInfo &FuncInfo, 789 const SDLoc &dl, SDValue &Chain, 790 SDValue *Flag, const Value *V) const { 791 // A Value with type {} or [0 x %t] needs no registers. 792 if (ValueVTs.empty()) 793 return SDValue(); 794 795 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 796 797 // Assemble the legal parts into the final values. 798 SmallVector<SDValue, 4> Values(ValueVTs.size()); 799 SmallVector<SDValue, 8> Parts; 800 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 801 // Copy the legal parts from the registers. 802 EVT ValueVT = ValueVTs[Value]; 803 unsigned NumRegs = RegCount[Value]; 804 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 805 *DAG.getContext(), 806 CallConv.getValue(), RegVTs[Value]) 807 : RegVTs[Value]; 808 809 Parts.resize(NumRegs); 810 for (unsigned i = 0; i != NumRegs; ++i) { 811 SDValue P; 812 if (!Flag) { 813 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 814 } else { 815 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 816 *Flag = P.getValue(2); 817 } 818 819 Chain = P.getValue(1); 820 Parts[i] = P; 821 822 // If the source register was virtual and if we know something about it, 823 // add an assert node. 824 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 825 !RegisterVT.isInteger()) 826 continue; 827 828 const FunctionLoweringInfo::LiveOutInfo *LOI = 829 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 830 if (!LOI) 831 continue; 832 833 unsigned RegSize = RegisterVT.getScalarSizeInBits(); 834 unsigned NumSignBits = LOI->NumSignBits; 835 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 836 837 if (NumZeroBits == RegSize) { 838 // The current value is a zero. 839 // Explicitly express that as it would be easier for 840 // optimizations to kick in. 841 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 842 continue; 843 } 844 845 // FIXME: We capture more information than the dag can represent. For 846 // now, just use the tightest assertzext/assertsext possible. 847 bool isSExt; 848 EVT FromVT(MVT::Other); 849 if (NumZeroBits) { 850 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits); 851 isSExt = false; 852 } else if (NumSignBits > 1) { 853 FromVT = 854 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1); 855 isSExt = true; 856 } else { 857 continue; 858 } 859 // Add an assertion node. 860 assert(FromVT != MVT::Other); 861 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 862 RegisterVT, P, DAG.getValueType(FromVT)); 863 } 864 865 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs, 866 RegisterVT, ValueVT, V, CallConv); 867 Part += NumRegs; 868 Parts.clear(); 869 } 870 871 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 872 } 873 874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 875 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 876 const Value *V, 877 ISD::NodeType PreferredExtendType) const { 878 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 879 ISD::NodeType ExtendKind = PreferredExtendType; 880 881 // Get the list of the values's legal parts. 882 unsigned NumRegs = Regs.size(); 883 SmallVector<SDValue, 8> Parts(NumRegs); 884 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 885 unsigned NumParts = RegCount[Value]; 886 887 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv( 888 *DAG.getContext(), 889 CallConv.getValue(), RegVTs[Value]) 890 : RegVTs[Value]; 891 892 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 893 ExtendKind = ISD::ZERO_EXTEND; 894 895 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part], 896 NumParts, RegisterVT, V, CallConv, ExtendKind); 897 Part += NumParts; 898 } 899 900 // Copy the parts into the registers. 901 SmallVector<SDValue, 8> Chains(NumRegs); 902 for (unsigned i = 0; i != NumRegs; ++i) { 903 SDValue Part; 904 if (!Flag) { 905 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 906 } else { 907 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 908 *Flag = Part.getValue(1); 909 } 910 911 Chains[i] = Part.getValue(0); 912 } 913 914 if (NumRegs == 1 || Flag) 915 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 916 // flagged to it. That is the CopyToReg nodes and the user are considered 917 // a single scheduling unit. If we create a TokenFactor and return it as 918 // chain, then the TokenFactor is both a predecessor (operand) of the 919 // user as well as a successor (the TF operands are flagged to the user). 920 // c1, f1 = CopyToReg 921 // c2, f2 = CopyToReg 922 // c3 = TokenFactor c1, c2 923 // ... 924 // = op c3, ..., f2 925 Chain = Chains[NumRegs-1]; 926 else 927 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 928 } 929 930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 931 unsigned MatchingIdx, const SDLoc &dl, 932 SelectionDAG &DAG, 933 std::vector<SDValue> &Ops) const { 934 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 935 936 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 937 if (HasMatching) 938 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 939 else if (!Regs.empty() && 940 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 941 // Put the register class of the virtual registers in the flag word. That 942 // way, later passes can recompute register class constraints for inline 943 // assembly as well as normal instructions. 944 // Don't do this for tied operands that can use the regclass information 945 // from the def. 946 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 947 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 948 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 949 } 950 951 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 952 Ops.push_back(Res); 953 954 if (Code == InlineAsm::Kind_Clobber) { 955 // Clobbers should always have a 1:1 mapping with registers, and may 956 // reference registers that have illegal (e.g. vector) types. Hence, we 957 // shouldn't try to apply any sort of splitting logic to them. 958 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 959 "No 1:1 mapping from clobbers to regs?"); 960 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 961 (void)SP; 962 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 963 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 964 assert( 965 (Regs[I] != SP || 966 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 967 "If we clobbered the stack pointer, MFI should know about it."); 968 } 969 return; 970 } 971 972 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 973 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 974 MVT RegisterVT = RegVTs[Value]; 975 for (unsigned i = 0; i != NumRegs; ++i) { 976 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 977 unsigned TheReg = Regs[Reg++]; 978 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 979 } 980 } 981 } 982 983 SmallVector<std::pair<unsigned, unsigned>, 4> 984 RegsForValue::getRegsAndSizes() const { 985 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec; 986 unsigned I = 0; 987 for (auto CountAndVT : zip_first(RegCount, RegVTs)) { 988 unsigned RegCount = std::get<0>(CountAndVT); 989 MVT RegisterVT = std::get<1>(CountAndVT); 990 unsigned RegisterSize = RegisterVT.getSizeInBits(); 991 for (unsigned E = I + RegCount; I != E; ++I) 992 OutVec.push_back(std::make_pair(Regs[I], RegisterSize)); 993 } 994 return OutVec; 995 } 996 997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 998 const TargetLibraryInfo *li) { 999 AA = aa; 1000 GFI = gfi; 1001 LibInfo = li; 1002 DL = &DAG.getDataLayout(); 1003 Context = DAG.getContext(); 1004 LPadToCallSiteMap.clear(); 1005 } 1006 1007 void SelectionDAGBuilder::clear() { 1008 NodeMap.clear(); 1009 UnusedArgNodeMap.clear(); 1010 PendingLoads.clear(); 1011 PendingExports.clear(); 1012 CurInst = nullptr; 1013 HasTailCall = false; 1014 SDNodeOrder = LowestSDNodeOrder; 1015 StatepointLowering.clear(); 1016 } 1017 1018 void SelectionDAGBuilder::clearDanglingDebugInfo() { 1019 DanglingDebugInfoMap.clear(); 1020 } 1021 1022 SDValue SelectionDAGBuilder::getRoot() { 1023 if (PendingLoads.empty()) 1024 return DAG.getRoot(); 1025 1026 if (PendingLoads.size() == 1) { 1027 SDValue Root = PendingLoads[0]; 1028 DAG.setRoot(Root); 1029 PendingLoads.clear(); 1030 return Root; 1031 } 1032 1033 // Otherwise, we have to make a token factor node. 1034 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads); 1035 PendingLoads.clear(); 1036 DAG.setRoot(Root); 1037 return Root; 1038 } 1039 1040 SDValue SelectionDAGBuilder::getControlRoot() { 1041 SDValue Root = DAG.getRoot(); 1042 1043 if (PendingExports.empty()) 1044 return Root; 1045 1046 // Turn all of the CopyToReg chains into one factored node. 1047 if (Root.getOpcode() != ISD::EntryToken) { 1048 unsigned i = 0, e = PendingExports.size(); 1049 for (; i != e; ++i) { 1050 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1051 if (PendingExports[i].getNode()->getOperand(0) == Root) 1052 break; // Don't add the root if we already indirectly depend on it. 1053 } 1054 1055 if (i == e) 1056 PendingExports.push_back(Root); 1057 } 1058 1059 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1060 PendingExports); 1061 PendingExports.clear(); 1062 DAG.setRoot(Root); 1063 return Root; 1064 } 1065 1066 void SelectionDAGBuilder::visit(const Instruction &I) { 1067 // Set up outgoing PHI node register values before emitting the terminator. 1068 if (I.isTerminator()) { 1069 HandlePHINodesInSuccessorBlocks(I.getParent()); 1070 } 1071 1072 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1073 if (!isa<DbgInfoIntrinsic>(I)) 1074 ++SDNodeOrder; 1075 1076 CurInst = &I; 1077 1078 visit(I.getOpcode(), I); 1079 1080 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) { 1081 // Propagate the fast-math-flags of this IR instruction to the DAG node that 1082 // maps to this instruction. 1083 // TODO: We could handle all flags (nsw, etc) here. 1084 // TODO: If an IR instruction maps to >1 node, only the final node will have 1085 // flags set. 1086 if (SDNode *Node = getNodeForIRValue(&I)) { 1087 SDNodeFlags IncomingFlags; 1088 IncomingFlags.copyFMF(*FPMO); 1089 if (!Node->getFlags().isDefined()) 1090 Node->setFlags(IncomingFlags); 1091 else 1092 Node->intersectFlagsWith(IncomingFlags); 1093 } 1094 } 1095 1096 if (!I.isTerminator() && !HasTailCall && 1097 !isStatepoint(&I)) // statepoints handle their exports internally 1098 CopyToExportRegsIfNeeded(&I); 1099 1100 CurInst = nullptr; 1101 } 1102 1103 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1104 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1105 } 1106 1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1108 // Note: this doesn't use InstVisitor, because it has to work with 1109 // ConstantExpr's in addition to instructions. 1110 switch (Opcode) { 1111 default: llvm_unreachable("Unknown instruction type encountered!"); 1112 // Build the switch statement using the Instruction.def file. 1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1114 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1115 #include "llvm/IR/Instruction.def" 1116 } 1117 } 1118 1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable, 1120 const DIExpression *Expr) { 1121 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) { 1122 const DbgValueInst *DI = DDI.getDI(); 1123 DIVariable *DanglingVariable = DI->getVariable(); 1124 DIExpression *DanglingExpr = DI->getExpression(); 1125 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) { 1126 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n"); 1127 return true; 1128 } 1129 return false; 1130 }; 1131 1132 for (auto &DDIMI : DanglingDebugInfoMap) { 1133 DanglingDebugInfoVector &DDIV = DDIMI.second; 1134 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end()); 1135 } 1136 } 1137 1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1139 // generate the debug data structures now that we've seen its definition. 1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1141 SDValue Val) { 1142 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V); 1143 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end()) 1144 return; 1145 1146 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second; 1147 for (auto &DDI : DDIV) { 1148 const DbgValueInst *DI = DDI.getDI(); 1149 assert(DI && "Ill-formed DanglingDebugInfo"); 1150 DebugLoc dl = DDI.getdl(); 1151 unsigned ValSDNodeOrder = Val.getNode()->getIROrder(); 1152 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1153 DILocalVariable *Variable = DI->getVariable(); 1154 DIExpression *Expr = DI->getExpression(); 1155 assert(Variable->isValidLocationForIntrinsic(dl) && 1156 "Expected inlined-at fields to agree"); 1157 SDDbgValue *SDV; 1158 if (Val.getNode()) { 1159 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1160 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order=" 1161 << DbgSDNodeOrder << "] for:\n " << *DI << "\n"); 1162 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump()); 1163 // Increase the SDNodeOrder for the DbgValue here to make sure it is 1164 // inserted after the definition of Val when emitting the instructions 1165 // after ISel. An alternative could be to teach 1166 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly. 1167 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() 1168 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to " 1169 << ValSDNodeOrder << "\n"); 1170 SDV = getDbgValue(Val, Variable, Expr, dl, 1171 std::max(DbgSDNodeOrder, ValSDNodeOrder)); 1172 DAG.AddDbgValue(SDV, Val.getNode(), false); 1173 } else 1174 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI 1175 << "in EmitFuncArgumentDbgValue\n"); 1176 } else 1177 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1178 } 1179 DDIV.clear(); 1180 } 1181 1182 /// getCopyFromRegs - If there was virtual register allocated for the value V 1183 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1184 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1185 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1186 SDValue Result; 1187 1188 if (It != FuncInfo.ValueMap.end()) { 1189 unsigned InReg = It->second; 1190 1191 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1192 DAG.getDataLayout(), InReg, Ty, 1193 None); // This is not an ABI copy. 1194 SDValue Chain = DAG.getEntryNode(); 1195 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1196 V); 1197 resolveDanglingDebugInfo(V, Result); 1198 } 1199 1200 return Result; 1201 } 1202 1203 /// getValue - Return an SDValue for the given Value. 1204 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1205 // If we already have an SDValue for this value, use it. It's important 1206 // to do this first, so that we don't create a CopyFromReg if we already 1207 // have a regular SDValue. 1208 SDValue &N = NodeMap[V]; 1209 if (N.getNode()) return N; 1210 1211 // If there's a virtual register allocated and initialized for this 1212 // value, use it. 1213 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1214 return copyFromReg; 1215 1216 // Otherwise create a new SDValue and remember it. 1217 SDValue Val = getValueImpl(V); 1218 NodeMap[V] = Val; 1219 resolveDanglingDebugInfo(V, Val); 1220 return Val; 1221 } 1222 1223 // Return true if SDValue exists for the given Value 1224 bool SelectionDAGBuilder::findValue(const Value *V) const { 1225 return (NodeMap.find(V) != NodeMap.end()) || 1226 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1227 } 1228 1229 /// getNonRegisterValue - Return an SDValue for the given Value, but 1230 /// don't look in FuncInfo.ValueMap for a virtual register. 1231 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1232 // If we already have an SDValue for this value, use it. 1233 SDValue &N = NodeMap[V]; 1234 if (N.getNode()) { 1235 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1236 // Remove the debug location from the node as the node is about to be used 1237 // in a location which may differ from the original debug location. This 1238 // is relevant to Constant and ConstantFP nodes because they can appear 1239 // as constant expressions inside PHI nodes. 1240 N->setDebugLoc(DebugLoc()); 1241 } 1242 return N; 1243 } 1244 1245 // Otherwise create a new SDValue and remember it. 1246 SDValue Val = getValueImpl(V); 1247 NodeMap[V] = Val; 1248 resolveDanglingDebugInfo(V, Val); 1249 return Val; 1250 } 1251 1252 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1253 /// Create an SDValue for the given value. 1254 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1255 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1256 1257 if (const Constant *C = dyn_cast<Constant>(V)) { 1258 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1259 1260 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1261 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1262 1263 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1264 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1265 1266 if (isa<ConstantPointerNull>(C)) { 1267 unsigned AS = V->getType()->getPointerAddressSpace(); 1268 return DAG.getConstant(0, getCurSDLoc(), 1269 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1270 } 1271 1272 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1273 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1274 1275 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1276 return DAG.getUNDEF(VT); 1277 1278 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1279 visit(CE->getOpcode(), *CE); 1280 SDValue N1 = NodeMap[V]; 1281 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1282 return N1; 1283 } 1284 1285 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1286 SmallVector<SDValue, 4> Constants; 1287 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1288 OI != OE; ++OI) { 1289 SDNode *Val = getValue(*OI).getNode(); 1290 // If the operand is an empty aggregate, there are no values. 1291 if (!Val) continue; 1292 // Add each leaf value from the operand to the Constants list 1293 // to form a flattened list of all the values. 1294 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1295 Constants.push_back(SDValue(Val, i)); 1296 } 1297 1298 return DAG.getMergeValues(Constants, getCurSDLoc()); 1299 } 1300 1301 if (const ConstantDataSequential *CDS = 1302 dyn_cast<ConstantDataSequential>(C)) { 1303 SmallVector<SDValue, 4> Ops; 1304 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1305 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1306 // Add each leaf value from the operand to the Constants list 1307 // to form a flattened list of all the values. 1308 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1309 Ops.push_back(SDValue(Val, i)); 1310 } 1311 1312 if (isa<ArrayType>(CDS->getType())) 1313 return DAG.getMergeValues(Ops, getCurSDLoc()); 1314 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1315 } 1316 1317 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1318 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1319 "Unknown struct or array constant!"); 1320 1321 SmallVector<EVT, 4> ValueVTs; 1322 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1323 unsigned NumElts = ValueVTs.size(); 1324 if (NumElts == 0) 1325 return SDValue(); // empty struct 1326 SmallVector<SDValue, 4> Constants(NumElts); 1327 for (unsigned i = 0; i != NumElts; ++i) { 1328 EVT EltVT = ValueVTs[i]; 1329 if (isa<UndefValue>(C)) 1330 Constants[i] = DAG.getUNDEF(EltVT); 1331 else if (EltVT.isFloatingPoint()) 1332 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1333 else 1334 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1335 } 1336 1337 return DAG.getMergeValues(Constants, getCurSDLoc()); 1338 } 1339 1340 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1341 return DAG.getBlockAddress(BA, VT); 1342 1343 VectorType *VecTy = cast<VectorType>(V->getType()); 1344 unsigned NumElements = VecTy->getNumElements(); 1345 1346 // Now that we know the number and type of the elements, get that number of 1347 // elements into the Ops array based on what kind of constant it is. 1348 SmallVector<SDValue, 16> Ops; 1349 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1350 for (unsigned i = 0; i != NumElements; ++i) 1351 Ops.push_back(getValue(CV->getOperand(i))); 1352 } else { 1353 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1354 EVT EltVT = 1355 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1356 1357 SDValue Op; 1358 if (EltVT.isFloatingPoint()) 1359 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1360 else 1361 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1362 Ops.assign(NumElements, Op); 1363 } 1364 1365 // Create a BUILD_VECTOR node. 1366 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1367 } 1368 1369 // If this is a static alloca, generate it as the frameindex instead of 1370 // computation. 1371 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1372 DenseMap<const AllocaInst*, int>::iterator SI = 1373 FuncInfo.StaticAllocaMap.find(AI); 1374 if (SI != FuncInfo.StaticAllocaMap.end()) 1375 return DAG.getFrameIndex(SI->second, 1376 TLI.getFrameIndexTy(DAG.getDataLayout())); 1377 } 1378 1379 // If this is an instruction which fast-isel has deferred, select it now. 1380 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1381 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1382 1383 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1384 Inst->getType(), getABIRegCopyCC(V)); 1385 SDValue Chain = DAG.getEntryNode(); 1386 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1387 } 1388 1389 llvm_unreachable("Can't get register for value!"); 1390 } 1391 1392 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1393 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1394 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1395 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1396 bool IsSEH = isAsynchronousEHPersonality(Pers); 1397 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX; 1398 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1399 if (!IsSEH) 1400 CatchPadMBB->setIsEHScopeEntry(); 1401 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1402 if (IsMSVCCXX || IsCoreCLR) 1403 CatchPadMBB->setIsEHFuncletEntry(); 1404 // Wasm does not need catchpads anymore 1405 if (!IsWasmCXX) 1406 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, 1407 getControlRoot())); 1408 } 1409 1410 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1411 // Update machine-CFG edge. 1412 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1413 FuncInfo.MBB->addSuccessor(TargetMBB); 1414 1415 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1416 bool IsSEH = isAsynchronousEHPersonality(Pers); 1417 if (IsSEH) { 1418 // If this is not a fall-through branch or optimizations are switched off, 1419 // emit the branch. 1420 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1421 TM.getOptLevel() == CodeGenOpt::None) 1422 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1423 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1424 return; 1425 } 1426 1427 // Figure out the funclet membership for the catchret's successor. 1428 // This will be used by the FuncletLayout pass to determine how to order the 1429 // BB's. 1430 // A 'catchret' returns to the outer scope's color. 1431 Value *ParentPad = I.getCatchSwitchParentPad(); 1432 const BasicBlock *SuccessorColor; 1433 if (isa<ConstantTokenNone>(ParentPad)) 1434 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1435 else 1436 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1437 assert(SuccessorColor && "No parent funclet for catchret!"); 1438 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1439 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1440 1441 // Create the terminator node. 1442 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1443 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1444 DAG.getBasicBlock(SuccessorColorMBB)); 1445 DAG.setRoot(Ret); 1446 } 1447 1448 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1449 // Don't emit any special code for the cleanuppad instruction. It just marks 1450 // the start of an EH scope/funclet. 1451 FuncInfo.MBB->setIsEHScopeEntry(); 1452 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1453 if (Pers != EHPersonality::Wasm_CXX) { 1454 FuncInfo.MBB->setIsEHFuncletEntry(); 1455 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1456 } 1457 } 1458 1459 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1460 /// many places it could ultimately go. In the IR, we have a single unwind 1461 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1462 /// This function skips over imaginary basic blocks that hold catchswitch 1463 /// instructions, and finds all the "real" machine 1464 /// basic block destinations. As those destinations may not be successors of 1465 /// EHPadBB, here we also calculate the edge probability to those destinations. 1466 /// The passed-in Prob is the edge probability to EHPadBB. 1467 static void findUnwindDestinations( 1468 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1469 BranchProbability Prob, 1470 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1471 &UnwindDests) { 1472 EHPersonality Personality = 1473 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1474 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1475 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1476 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 1477 bool IsSEH = isAsynchronousEHPersonality(Personality); 1478 1479 while (EHPadBB) { 1480 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1481 BasicBlock *NewEHPadBB = nullptr; 1482 if (isa<LandingPadInst>(Pad)) { 1483 // Stop on landingpads. They are not funclets. 1484 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1485 break; 1486 } else if (isa<CleanupPadInst>(Pad)) { 1487 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1488 // personalities. 1489 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1490 UnwindDests.back().first->setIsEHScopeEntry(); 1491 if (!IsWasmCXX) 1492 UnwindDests.back().first->setIsEHFuncletEntry(); 1493 break; 1494 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1495 // Add the catchpad handlers to the possible destinations. 1496 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1497 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1498 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1499 if (IsMSVCCXX || IsCoreCLR) 1500 UnwindDests.back().first->setIsEHFuncletEntry(); 1501 if (!IsSEH) 1502 UnwindDests.back().first->setIsEHScopeEntry(); 1503 } 1504 NewEHPadBB = CatchSwitch->getUnwindDest(); 1505 } else { 1506 continue; 1507 } 1508 1509 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1510 if (BPI && NewEHPadBB) 1511 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1512 EHPadBB = NewEHPadBB; 1513 } 1514 } 1515 1516 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1517 // Update successor info. 1518 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1519 auto UnwindDest = I.getUnwindDest(); 1520 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1521 BranchProbability UnwindDestProb = 1522 (BPI && UnwindDest) 1523 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1524 : BranchProbability::getZero(); 1525 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1526 for (auto &UnwindDest : UnwindDests) { 1527 UnwindDest.first->setIsEHPad(); 1528 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1529 } 1530 FuncInfo.MBB->normalizeSuccProbs(); 1531 1532 // Create the terminator node. 1533 SDValue Ret = 1534 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1535 DAG.setRoot(Ret); 1536 } 1537 1538 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1539 report_fatal_error("visitCatchSwitch not yet implemented!"); 1540 } 1541 1542 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1543 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1544 auto &DL = DAG.getDataLayout(); 1545 SDValue Chain = getControlRoot(); 1546 SmallVector<ISD::OutputArg, 8> Outs; 1547 SmallVector<SDValue, 8> OutVals; 1548 1549 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1550 // lower 1551 // 1552 // %val = call <ty> @llvm.experimental.deoptimize() 1553 // ret <ty> %val 1554 // 1555 // differently. 1556 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1557 LowerDeoptimizingReturn(); 1558 return; 1559 } 1560 1561 if (!FuncInfo.CanLowerReturn) { 1562 unsigned DemoteReg = FuncInfo.DemoteRegister; 1563 const Function *F = I.getParent()->getParent(); 1564 1565 // Emit a store of the return value through the virtual register. 1566 // Leave Outs empty so that LowerReturn won't try to load return 1567 // registers the usual way. 1568 SmallVector<EVT, 1> PtrValueVTs; 1569 ComputeValueVTs(TLI, DL, 1570 F->getReturnType()->getPointerTo( 1571 DAG.getDataLayout().getAllocaAddrSpace()), 1572 PtrValueVTs); 1573 1574 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1575 DemoteReg, PtrValueVTs[0]); 1576 SDValue RetOp = getValue(I.getOperand(0)); 1577 1578 SmallVector<EVT, 4> ValueVTs; 1579 SmallVector<uint64_t, 4> Offsets; 1580 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1581 unsigned NumValues = ValueVTs.size(); 1582 1583 SmallVector<SDValue, 4> Chains(NumValues); 1584 for (unsigned i = 0; i != NumValues; ++i) { 1585 // An aggregate return value cannot wrap around the address space, so 1586 // offsets to its parts don't wrap either. 1587 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1588 Chains[i] = DAG.getStore( 1589 Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1590 // FIXME: better loc info would be nice. 1591 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction())); 1592 } 1593 1594 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1595 MVT::Other, Chains); 1596 } else if (I.getNumOperands() != 0) { 1597 SmallVector<EVT, 4> ValueVTs; 1598 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1599 unsigned NumValues = ValueVTs.size(); 1600 if (NumValues) { 1601 SDValue RetOp = getValue(I.getOperand(0)); 1602 1603 const Function *F = I.getParent()->getParent(); 1604 1605 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1606 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1607 Attribute::SExt)) 1608 ExtendKind = ISD::SIGN_EXTEND; 1609 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1610 Attribute::ZExt)) 1611 ExtendKind = ISD::ZERO_EXTEND; 1612 1613 LLVMContext &Context = F->getContext(); 1614 bool RetInReg = F->getAttributes().hasAttribute( 1615 AttributeList::ReturnIndex, Attribute::InReg); 1616 1617 for (unsigned j = 0; j != NumValues; ++j) { 1618 EVT VT = ValueVTs[j]; 1619 1620 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1621 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1622 1623 CallingConv::ID CC = F->getCallingConv(); 1624 1625 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT); 1626 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT); 1627 SmallVector<SDValue, 4> Parts(NumParts); 1628 getCopyToParts(DAG, getCurSDLoc(), 1629 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1630 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind); 1631 1632 // 'inreg' on function refers to return value 1633 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1634 if (RetInReg) 1635 Flags.setInReg(); 1636 1637 // Propagate extension type if any 1638 if (ExtendKind == ISD::SIGN_EXTEND) 1639 Flags.setSExt(); 1640 else if (ExtendKind == ISD::ZERO_EXTEND) 1641 Flags.setZExt(); 1642 1643 for (unsigned i = 0; i < NumParts; ++i) { 1644 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1645 VT, /*isfixed=*/true, 0, 0)); 1646 OutVals.push_back(Parts[i]); 1647 } 1648 } 1649 } 1650 } 1651 1652 // Push in swifterror virtual register as the last element of Outs. This makes 1653 // sure swifterror virtual register will be returned in the swifterror 1654 // physical register. 1655 const Function *F = I.getParent()->getParent(); 1656 if (TLI.supportSwiftError() && 1657 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1658 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1659 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1660 Flags.setSwiftError(); 1661 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1662 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1663 true /*isfixed*/, 1 /*origidx*/, 1664 0 /*partOffs*/)); 1665 // Create SDNode for the swifterror virtual register. 1666 OutVals.push_back( 1667 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1668 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1669 EVT(TLI.getPointerTy(DL)))); 1670 } 1671 1672 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg(); 1673 CallingConv::ID CallConv = 1674 DAG.getMachineFunction().getFunction().getCallingConv(); 1675 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1676 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1677 1678 // Verify that the target's LowerReturn behaved as expected. 1679 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1680 "LowerReturn didn't return a valid chain!"); 1681 1682 // Update the DAG with the new chain value resulting from return lowering. 1683 DAG.setRoot(Chain); 1684 } 1685 1686 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1687 /// created for it, emit nodes to copy the value into the virtual 1688 /// registers. 1689 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1690 // Skip empty types 1691 if (V->getType()->isEmptyTy()) 1692 return; 1693 1694 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1695 if (VMI != FuncInfo.ValueMap.end()) { 1696 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1697 CopyValueToVirtualRegister(V, VMI->second); 1698 } 1699 } 1700 1701 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1702 /// the current basic block, add it to ValueMap now so that we'll get a 1703 /// CopyTo/FromReg. 1704 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1705 // No need to export constants. 1706 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1707 1708 // Already exported? 1709 if (FuncInfo.isExportedInst(V)) return; 1710 1711 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1712 CopyValueToVirtualRegister(V, Reg); 1713 } 1714 1715 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1716 const BasicBlock *FromBB) { 1717 // The operands of the setcc have to be in this block. We don't know 1718 // how to export them from some other block. 1719 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1720 // Can export from current BB. 1721 if (VI->getParent() == FromBB) 1722 return true; 1723 1724 // Is already exported, noop. 1725 return FuncInfo.isExportedInst(V); 1726 } 1727 1728 // If this is an argument, we can export it if the BB is the entry block or 1729 // if it is already exported. 1730 if (isa<Argument>(V)) { 1731 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1732 return true; 1733 1734 // Otherwise, can only export this if it is already exported. 1735 return FuncInfo.isExportedInst(V); 1736 } 1737 1738 // Otherwise, constants can always be exported. 1739 return true; 1740 } 1741 1742 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1743 BranchProbability 1744 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1745 const MachineBasicBlock *Dst) const { 1746 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1747 const BasicBlock *SrcBB = Src->getBasicBlock(); 1748 const BasicBlock *DstBB = Dst->getBasicBlock(); 1749 if (!BPI) { 1750 // If BPI is not available, set the default probability as 1 / N, where N is 1751 // the number of successors. 1752 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 1753 return BranchProbability(1, SuccSize); 1754 } 1755 return BPI->getEdgeProbability(SrcBB, DstBB); 1756 } 1757 1758 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1759 MachineBasicBlock *Dst, 1760 BranchProbability Prob) { 1761 if (!FuncInfo.BPI) 1762 Src->addSuccessorWithoutProb(Dst); 1763 else { 1764 if (Prob.isUnknown()) 1765 Prob = getEdgeProbability(Src, Dst); 1766 Src->addSuccessor(Dst, Prob); 1767 } 1768 } 1769 1770 static bool InBlock(const Value *V, const BasicBlock *BB) { 1771 if (const Instruction *I = dyn_cast<Instruction>(V)) 1772 return I->getParent() == BB; 1773 return true; 1774 } 1775 1776 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1777 /// This function emits a branch and is used at the leaves of an OR or an 1778 /// AND operator tree. 1779 void 1780 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1781 MachineBasicBlock *TBB, 1782 MachineBasicBlock *FBB, 1783 MachineBasicBlock *CurBB, 1784 MachineBasicBlock *SwitchBB, 1785 BranchProbability TProb, 1786 BranchProbability FProb, 1787 bool InvertCond) { 1788 const BasicBlock *BB = CurBB->getBasicBlock(); 1789 1790 // If the leaf of the tree is a comparison, merge the condition into 1791 // the caseblock. 1792 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1793 // The operands of the cmp have to be in this block. We don't know 1794 // how to export them from some other block. If this is the first block 1795 // of the sequence, no exporting is needed. 1796 if (CurBB == SwitchBB || 1797 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1798 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1799 ISD::CondCode Condition; 1800 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1801 ICmpInst::Predicate Pred = 1802 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1803 Condition = getICmpCondCode(Pred); 1804 } else { 1805 const FCmpInst *FC = cast<FCmpInst>(Cond); 1806 FCmpInst::Predicate Pred = 1807 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1808 Condition = getFCmpCondCode(Pred); 1809 if (TM.Options.NoNaNsFPMath) 1810 Condition = getFCmpCodeWithoutNaN(Condition); 1811 } 1812 1813 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1814 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1815 SwitchCases.push_back(CB); 1816 return; 1817 } 1818 } 1819 1820 // Create a CaseBlock record representing this branch. 1821 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1822 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1823 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1824 SwitchCases.push_back(CB); 1825 } 1826 1827 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1828 MachineBasicBlock *TBB, 1829 MachineBasicBlock *FBB, 1830 MachineBasicBlock *CurBB, 1831 MachineBasicBlock *SwitchBB, 1832 Instruction::BinaryOps Opc, 1833 BranchProbability TProb, 1834 BranchProbability FProb, 1835 bool InvertCond) { 1836 // Skip over not part of the tree and remember to invert op and operands at 1837 // next level. 1838 Value *NotCond; 1839 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 1840 InBlock(NotCond, CurBB->getBasicBlock())) { 1841 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1842 !InvertCond); 1843 return; 1844 } 1845 1846 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1847 // Compute the effective opcode for Cond, taking into account whether it needs 1848 // to be inverted, e.g. 1849 // and (not (or A, B)), C 1850 // gets lowered as 1851 // and (and (not A, not B), C) 1852 unsigned BOpc = 0; 1853 if (BOp) { 1854 BOpc = BOp->getOpcode(); 1855 if (InvertCond) { 1856 if (BOpc == Instruction::And) 1857 BOpc = Instruction::Or; 1858 else if (BOpc == Instruction::Or) 1859 BOpc = Instruction::And; 1860 } 1861 } 1862 1863 // If this node is not part of the or/and tree, emit it as a branch. 1864 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1865 BOpc != unsigned(Opc) || !BOp->hasOneUse() || 1866 BOp->getParent() != CurBB->getBasicBlock() || 1867 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1868 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1869 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1870 TProb, FProb, InvertCond); 1871 return; 1872 } 1873 1874 // Create TmpBB after CurBB. 1875 MachineFunction::iterator BBI(CurBB); 1876 MachineFunction &MF = DAG.getMachineFunction(); 1877 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1878 CurBB->getParent()->insert(++BBI, TmpBB); 1879 1880 if (Opc == Instruction::Or) { 1881 // Codegen X | Y as: 1882 // BB1: 1883 // jmp_if_X TBB 1884 // jmp TmpBB 1885 // TmpBB: 1886 // jmp_if_Y TBB 1887 // jmp FBB 1888 // 1889 1890 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1891 // The requirement is that 1892 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1893 // = TrueProb for original BB. 1894 // Assuming the original probabilities are A and B, one choice is to set 1895 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1896 // A/(1+B) and 2B/(1+B). This choice assumes that 1897 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1898 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1899 // TmpBB, but the math is more complicated. 1900 1901 auto NewTrueProb = TProb / 2; 1902 auto NewFalseProb = TProb / 2 + FProb; 1903 // Emit the LHS condition. 1904 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1905 NewTrueProb, NewFalseProb, InvertCond); 1906 1907 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1908 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1909 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1910 // Emit the RHS condition into TmpBB. 1911 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1912 Probs[0], Probs[1], InvertCond); 1913 } else { 1914 assert(Opc == Instruction::And && "Unknown merge op!"); 1915 // Codegen X & Y as: 1916 // BB1: 1917 // jmp_if_X TmpBB 1918 // jmp FBB 1919 // TmpBB: 1920 // jmp_if_Y TBB 1921 // jmp FBB 1922 // 1923 // This requires creation of TmpBB after CurBB. 1924 1925 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1926 // The requirement is that 1927 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1928 // = FalseProb for original BB. 1929 // Assuming the original probabilities are A and B, one choice is to set 1930 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1931 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1932 // TrueProb for BB1 * FalseProb for TmpBB. 1933 1934 auto NewTrueProb = TProb + FProb / 2; 1935 auto NewFalseProb = FProb / 2; 1936 // Emit the LHS condition. 1937 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1938 NewTrueProb, NewFalseProb, InvertCond); 1939 1940 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1941 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1942 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1943 // Emit the RHS condition into TmpBB. 1944 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1945 Probs[0], Probs[1], InvertCond); 1946 } 1947 } 1948 1949 /// If the set of cases should be emitted as a series of branches, return true. 1950 /// If we should emit this as a bunch of and/or'd together conditions, return 1951 /// false. 1952 bool 1953 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1954 if (Cases.size() != 2) return true; 1955 1956 // If this is two comparisons of the same values or'd or and'd together, they 1957 // will get folded into a single comparison, so don't emit two blocks. 1958 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1959 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1960 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1961 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1962 return false; 1963 } 1964 1965 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1966 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1967 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1968 Cases[0].CC == Cases[1].CC && 1969 isa<Constant>(Cases[0].CmpRHS) && 1970 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1971 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1972 return false; 1973 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1974 return false; 1975 } 1976 1977 return true; 1978 } 1979 1980 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1981 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1982 1983 // Update machine-CFG edges. 1984 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1985 1986 if (I.isUnconditional()) { 1987 // Update machine-CFG edges. 1988 BrMBB->addSuccessor(Succ0MBB); 1989 1990 // If this is not a fall-through branch or optimizations are switched off, 1991 // emit the branch. 1992 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1993 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1994 MVT::Other, getControlRoot(), 1995 DAG.getBasicBlock(Succ0MBB))); 1996 1997 return; 1998 } 1999 2000 // If this condition is one of the special cases we handle, do special stuff 2001 // now. 2002 const Value *CondVal = I.getCondition(); 2003 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 2004 2005 // If this is a series of conditions that are or'd or and'd together, emit 2006 // this as a sequence of branches instead of setcc's with and/or operations. 2007 // As long as jumps are not expensive, this should improve performance. 2008 // For example, instead of something like: 2009 // cmp A, B 2010 // C = seteq 2011 // cmp D, E 2012 // F = setle 2013 // or C, F 2014 // jnz foo 2015 // Emit: 2016 // cmp A, B 2017 // je foo 2018 // cmp D, E 2019 // jle foo 2020 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 2021 Instruction::BinaryOps Opcode = BOp->getOpcode(); 2022 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 2023 !I.getMetadata(LLVMContext::MD_unpredictable) && 2024 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 2025 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 2026 Opcode, 2027 getEdgeProbability(BrMBB, Succ0MBB), 2028 getEdgeProbability(BrMBB, Succ1MBB), 2029 /*InvertCond=*/false); 2030 // If the compares in later blocks need to use values not currently 2031 // exported from this block, export them now. This block should always 2032 // be the first entry. 2033 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 2034 2035 // Allow some cases to be rejected. 2036 if (ShouldEmitAsBranches(SwitchCases)) { 2037 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 2038 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 2039 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 2040 } 2041 2042 // Emit the branch for this block. 2043 visitSwitchCase(SwitchCases[0], BrMBB); 2044 SwitchCases.erase(SwitchCases.begin()); 2045 return; 2046 } 2047 2048 // Okay, we decided not to do this, remove any inserted MBB's and clear 2049 // SwitchCases. 2050 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 2051 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 2052 2053 SwitchCases.clear(); 2054 } 2055 } 2056 2057 // Create a CaseBlock record representing this branch. 2058 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 2059 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 2060 2061 // Use visitSwitchCase to actually insert the fast branch sequence for this 2062 // cond branch. 2063 visitSwitchCase(CB, BrMBB); 2064 } 2065 2066 /// visitSwitchCase - Emits the necessary code to represent a single node in 2067 /// the binary search tree resulting from lowering a switch instruction. 2068 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 2069 MachineBasicBlock *SwitchBB) { 2070 SDValue Cond; 2071 SDValue CondLHS = getValue(CB.CmpLHS); 2072 SDLoc dl = CB.DL; 2073 2074 // Build the setcc now. 2075 if (!CB.CmpMHS) { 2076 // Fold "(X == true)" to X and "(X == false)" to !X to 2077 // handle common cases produced by branch lowering. 2078 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 2079 CB.CC == ISD::SETEQ) 2080 Cond = CondLHS; 2081 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 2082 CB.CC == ISD::SETEQ) { 2083 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 2084 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 2085 } else 2086 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 2087 } else { 2088 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 2089 2090 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 2091 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 2092 2093 SDValue CmpOp = getValue(CB.CmpMHS); 2094 EVT VT = CmpOp.getValueType(); 2095 2096 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2097 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2098 ISD::SETLE); 2099 } else { 2100 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2101 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2102 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2103 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2104 } 2105 } 2106 2107 // Update successor info 2108 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2109 // TrueBB and FalseBB are always different unless the incoming IR is 2110 // degenerate. This only happens when running llc on weird IR. 2111 if (CB.TrueBB != CB.FalseBB) 2112 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2113 SwitchBB->normalizeSuccProbs(); 2114 2115 // If the lhs block is the next block, invert the condition so that we can 2116 // fall through to the lhs instead of the rhs block. 2117 if (CB.TrueBB == NextBlock(SwitchBB)) { 2118 std::swap(CB.TrueBB, CB.FalseBB); 2119 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2120 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2121 } 2122 2123 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2124 MVT::Other, getControlRoot(), Cond, 2125 DAG.getBasicBlock(CB.TrueBB)); 2126 2127 // Insert the false branch. Do this even if it's a fall through branch, 2128 // this makes it easier to do DAG optimizations which require inverting 2129 // the branch condition. 2130 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2131 DAG.getBasicBlock(CB.FalseBB)); 2132 2133 DAG.setRoot(BrCond); 2134 } 2135 2136 /// visitJumpTable - Emit JumpTable node in the current MBB 2137 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2138 // Emit the code for the jump table 2139 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2140 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2141 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2142 JT.Reg, PTy); 2143 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2144 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2145 MVT::Other, Index.getValue(1), 2146 Table, Index); 2147 DAG.setRoot(BrJumpTable); 2148 } 2149 2150 /// visitJumpTableHeader - This function emits necessary code to produce index 2151 /// in the JumpTable from switch case. 2152 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2153 JumpTableHeader &JTH, 2154 MachineBasicBlock *SwitchBB) { 2155 SDLoc dl = getCurSDLoc(); 2156 2157 // Subtract the lowest switch case value from the value being switched on and 2158 // conditional branch to default mbb if the result is greater than the 2159 // difference between smallest and largest cases. 2160 SDValue SwitchOp = getValue(JTH.SValue); 2161 EVT VT = SwitchOp.getValueType(); 2162 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2163 DAG.getConstant(JTH.First, dl, VT)); 2164 2165 // The SDNode we just created, which holds the value being switched on minus 2166 // the smallest case value, needs to be copied to a virtual register so it 2167 // can be used as an index into the jump table in a subsequent basic block. 2168 // This value may be smaller or larger than the target's pointer type, and 2169 // therefore require extension or truncating. 2170 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2171 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2172 2173 unsigned JumpTableReg = 2174 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2175 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2176 JumpTableReg, SwitchOp); 2177 JT.Reg = JumpTableReg; 2178 2179 // Emit the range check for the jump table, and branch to the default block 2180 // for the switch statement if the value being switched on exceeds the largest 2181 // case in the switch. 2182 SDValue CMP = DAG.getSetCC( 2183 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2184 Sub.getValueType()), 2185 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2186 2187 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2188 MVT::Other, CopyTo, CMP, 2189 DAG.getBasicBlock(JT.Default)); 2190 2191 // Avoid emitting unnecessary branches to the next block. 2192 if (JT.MBB != NextBlock(SwitchBB)) 2193 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2194 DAG.getBasicBlock(JT.MBB)); 2195 2196 DAG.setRoot(BrCond); 2197 } 2198 2199 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2200 /// variable if there exists one. 2201 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2202 SDValue &Chain) { 2203 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2204 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2205 MachineFunction &MF = DAG.getMachineFunction(); 2206 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent()); 2207 MachineSDNode *Node = 2208 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2209 if (Global) { 2210 MachinePointerInfo MPInfo(Global); 2211 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2212 MachineMemOperand::MODereferenceable; 2213 MachineMemOperand *MemRef = MF.getMachineMemOperand( 2214 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy)); 2215 DAG.setNodeMemRefs(Node, {MemRef}); 2216 } 2217 return SDValue(Node, 0); 2218 } 2219 2220 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2221 /// tail spliced into a stack protector check success bb. 2222 /// 2223 /// For a high level explanation of how this fits into the stack protector 2224 /// generation see the comment on the declaration of class 2225 /// StackProtectorDescriptor. 2226 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2227 MachineBasicBlock *ParentBB) { 2228 2229 // First create the loads to the guard/stack slot for the comparison. 2230 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2231 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2232 2233 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2234 int FI = MFI.getStackProtectorIndex(); 2235 2236 SDValue Guard; 2237 SDLoc dl = getCurSDLoc(); 2238 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2239 const Module &M = *ParentBB->getParent()->getFunction().getParent(); 2240 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2241 2242 // Generate code to load the content of the guard slot. 2243 SDValue GuardVal = DAG.getLoad( 2244 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2245 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2246 MachineMemOperand::MOVolatile); 2247 2248 if (TLI.useStackGuardXorFP()) 2249 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl); 2250 2251 // Retrieve guard check function, nullptr if instrumentation is inlined. 2252 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2253 // The target provides a guard check function to validate the guard value. 2254 // Generate a call to that function with the content of the guard slot as 2255 // argument. 2256 auto *Fn = cast<Function>(GuardCheck); 2257 FunctionType *FnTy = Fn->getFunctionType(); 2258 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2259 2260 TargetLowering::ArgListTy Args; 2261 TargetLowering::ArgListEntry Entry; 2262 Entry.Node = GuardVal; 2263 Entry.Ty = FnTy->getParamType(0); 2264 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2265 Entry.IsInReg = true; 2266 Args.push_back(Entry); 2267 2268 TargetLowering::CallLoweringInfo CLI(DAG); 2269 CLI.setDebugLoc(getCurSDLoc()) 2270 .setChain(DAG.getEntryNode()) 2271 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2272 getValue(GuardCheck), std::move(Args)); 2273 2274 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2275 DAG.setRoot(Result.second); 2276 return; 2277 } 2278 2279 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2280 // Otherwise, emit a volatile load to retrieve the stack guard value. 2281 SDValue Chain = DAG.getEntryNode(); 2282 if (TLI.useLoadStackGuardNode()) { 2283 Guard = getLoadStackGuard(DAG, dl, Chain); 2284 } else { 2285 const Value *IRGuard = TLI.getSDagStackGuard(M); 2286 SDValue GuardPtr = getValue(IRGuard); 2287 2288 Guard = 2289 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2290 Align, MachineMemOperand::MOVolatile); 2291 } 2292 2293 // Perform the comparison via a subtract/getsetcc. 2294 EVT VT = Guard.getValueType(); 2295 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal); 2296 2297 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2298 *DAG.getContext(), 2299 Sub.getValueType()), 2300 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2301 2302 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2303 // branch to failure MBB. 2304 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2305 MVT::Other, GuardVal.getOperand(0), 2306 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2307 // Otherwise branch to success MBB. 2308 SDValue Br = DAG.getNode(ISD::BR, dl, 2309 MVT::Other, BrCond, 2310 DAG.getBasicBlock(SPD.getSuccessMBB())); 2311 2312 DAG.setRoot(Br); 2313 } 2314 2315 /// Codegen the failure basic block for a stack protector check. 2316 /// 2317 /// A failure stack protector machine basic block consists simply of a call to 2318 /// __stack_chk_fail(). 2319 /// 2320 /// For a high level explanation of how this fits into the stack protector 2321 /// generation see the comment on the declaration of class 2322 /// StackProtectorDescriptor. 2323 void 2324 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2325 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2326 SDValue Chain = 2327 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2328 None, false, getCurSDLoc(), false, false).second; 2329 DAG.setRoot(Chain); 2330 } 2331 2332 /// visitBitTestHeader - This function emits necessary code to produce value 2333 /// suitable for "bit tests" 2334 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2335 MachineBasicBlock *SwitchBB) { 2336 SDLoc dl = getCurSDLoc(); 2337 2338 // Subtract the minimum value 2339 SDValue SwitchOp = getValue(B.SValue); 2340 EVT VT = SwitchOp.getValueType(); 2341 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2342 DAG.getConstant(B.First, dl, VT)); 2343 2344 // Check range 2345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2346 SDValue RangeCmp = DAG.getSetCC( 2347 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2348 Sub.getValueType()), 2349 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2350 2351 // Determine the type of the test operands. 2352 bool UsePtrType = false; 2353 if (!TLI.isTypeLegal(VT)) 2354 UsePtrType = true; 2355 else { 2356 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2357 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2358 // Switch table case range are encoded into series of masks. 2359 // Just use pointer type, it's guaranteed to fit. 2360 UsePtrType = true; 2361 break; 2362 } 2363 } 2364 if (UsePtrType) { 2365 VT = TLI.getPointerTy(DAG.getDataLayout()); 2366 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2367 } 2368 2369 B.RegVT = VT.getSimpleVT(); 2370 B.Reg = FuncInfo.CreateReg(B.RegVT); 2371 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2372 2373 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2374 2375 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2376 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2377 SwitchBB->normalizeSuccProbs(); 2378 2379 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2380 MVT::Other, CopyTo, RangeCmp, 2381 DAG.getBasicBlock(B.Default)); 2382 2383 // Avoid emitting unnecessary branches to the next block. 2384 if (MBB != NextBlock(SwitchBB)) 2385 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2386 DAG.getBasicBlock(MBB)); 2387 2388 DAG.setRoot(BrRange); 2389 } 2390 2391 /// visitBitTestCase - this function produces one "bit test" 2392 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2393 MachineBasicBlock* NextMBB, 2394 BranchProbability BranchProbToNext, 2395 unsigned Reg, 2396 BitTestCase &B, 2397 MachineBasicBlock *SwitchBB) { 2398 SDLoc dl = getCurSDLoc(); 2399 MVT VT = BB.RegVT; 2400 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2401 SDValue Cmp; 2402 unsigned PopCount = countPopulation(B.Mask); 2403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2404 if (PopCount == 1) { 2405 // Testing for a single bit; just compare the shift count with what it 2406 // would need to be to shift a 1 bit in that position. 2407 Cmp = DAG.getSetCC( 2408 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2409 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2410 ISD::SETEQ); 2411 } else if (PopCount == BB.Range) { 2412 // There is only one zero bit in the range, test for it directly. 2413 Cmp = DAG.getSetCC( 2414 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2415 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2416 ISD::SETNE); 2417 } else { 2418 // Make desired shift 2419 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2420 DAG.getConstant(1, dl, VT), ShiftOp); 2421 2422 // Emit bit tests and jumps 2423 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2424 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2425 Cmp = DAG.getSetCC( 2426 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2427 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2428 } 2429 2430 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2431 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2432 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2433 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2434 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2435 // one as they are relative probabilities (and thus work more like weights), 2436 // and hence we need to normalize them to let the sum of them become one. 2437 SwitchBB->normalizeSuccProbs(); 2438 2439 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2440 MVT::Other, getControlRoot(), 2441 Cmp, DAG.getBasicBlock(B.TargetBB)); 2442 2443 // Avoid emitting unnecessary branches to the next block. 2444 if (NextMBB != NextBlock(SwitchBB)) 2445 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2446 DAG.getBasicBlock(NextMBB)); 2447 2448 DAG.setRoot(BrAnd); 2449 } 2450 2451 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2452 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2453 2454 // Retrieve successors. Look through artificial IR level blocks like 2455 // catchswitch for successors. 2456 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2457 const BasicBlock *EHPadBB = I.getSuccessor(1); 2458 2459 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2460 // have to do anything here to lower funclet bundles. 2461 assert(!I.hasOperandBundlesOtherThan( 2462 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2463 "Cannot lower invokes with arbitrary operand bundles yet!"); 2464 2465 const Value *Callee(I.getCalledValue()); 2466 const Function *Fn = dyn_cast<Function>(Callee); 2467 if (isa<InlineAsm>(Callee)) 2468 visitInlineAsm(&I); 2469 else if (Fn && Fn->isIntrinsic()) { 2470 switch (Fn->getIntrinsicID()) { 2471 default: 2472 llvm_unreachable("Cannot invoke this intrinsic"); 2473 case Intrinsic::donothing: 2474 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2475 break; 2476 case Intrinsic::experimental_patchpoint_void: 2477 case Intrinsic::experimental_patchpoint_i64: 2478 visitPatchpoint(&I, EHPadBB); 2479 break; 2480 case Intrinsic::experimental_gc_statepoint: 2481 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2482 break; 2483 } 2484 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2485 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2486 // Eventually we will support lowering the @llvm.experimental.deoptimize 2487 // intrinsic, and right now there are no plans to support other intrinsics 2488 // with deopt state. 2489 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2490 } else { 2491 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2492 } 2493 2494 // If the value of the invoke is used outside of its defining block, make it 2495 // available as a virtual register. 2496 // We already took care of the exported value for the statepoint instruction 2497 // during call to the LowerStatepoint. 2498 if (!isStatepoint(I)) { 2499 CopyToExportRegsIfNeeded(&I); 2500 } 2501 2502 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2503 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2504 BranchProbability EHPadBBProb = 2505 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2506 : BranchProbability::getZero(); 2507 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2508 2509 // Update successor info. 2510 addSuccessorWithProb(InvokeMBB, Return); 2511 for (auto &UnwindDest : UnwindDests) { 2512 UnwindDest.first->setIsEHPad(); 2513 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2514 } 2515 InvokeMBB->normalizeSuccProbs(); 2516 2517 // Drop into normal successor. 2518 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2519 MVT::Other, getControlRoot(), 2520 DAG.getBasicBlock(Return))); 2521 } 2522 2523 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2524 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2525 } 2526 2527 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2528 assert(FuncInfo.MBB->isEHPad() && 2529 "Call to landingpad not in landing pad!"); 2530 2531 // If there aren't registers to copy the values into (e.g., during SjLj 2532 // exceptions), then don't bother to create these DAG nodes. 2533 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2534 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2535 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2536 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2537 return; 2538 2539 // If landingpad's return type is token type, we don't create DAG nodes 2540 // for its exception pointer and selector value. The extraction of exception 2541 // pointer or selector value from token type landingpads is not currently 2542 // supported. 2543 if (LP.getType()->isTokenTy()) 2544 return; 2545 2546 SmallVector<EVT, 2> ValueVTs; 2547 SDLoc dl = getCurSDLoc(); 2548 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2549 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2550 2551 // Get the two live-in registers as SDValues. The physregs have already been 2552 // copied into virtual registers. 2553 SDValue Ops[2]; 2554 if (FuncInfo.ExceptionPointerVirtReg) { 2555 Ops[0] = DAG.getZExtOrTrunc( 2556 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2557 FuncInfo.ExceptionPointerVirtReg, 2558 TLI.getPointerTy(DAG.getDataLayout())), 2559 dl, ValueVTs[0]); 2560 } else { 2561 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2562 } 2563 Ops[1] = DAG.getZExtOrTrunc( 2564 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2565 FuncInfo.ExceptionSelectorVirtReg, 2566 TLI.getPointerTy(DAG.getDataLayout())), 2567 dl, ValueVTs[1]); 2568 2569 // Merge into one. 2570 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2571 DAG.getVTList(ValueVTs), Ops); 2572 setValue(&LP, Res); 2573 } 2574 2575 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2576 #ifndef NDEBUG 2577 for (const CaseCluster &CC : Clusters) 2578 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2579 #endif 2580 2581 llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 2582 return a.Low->getValue().slt(b.Low->getValue()); 2583 }); 2584 2585 // Merge adjacent clusters with the same destination. 2586 const unsigned N = Clusters.size(); 2587 unsigned DstIndex = 0; 2588 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2589 CaseCluster &CC = Clusters[SrcIndex]; 2590 const ConstantInt *CaseVal = CC.Low; 2591 MachineBasicBlock *Succ = CC.MBB; 2592 2593 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2594 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2595 // If this case has the same successor and is a neighbour, merge it into 2596 // the previous cluster. 2597 Clusters[DstIndex - 1].High = CaseVal; 2598 Clusters[DstIndex - 1].Prob += CC.Prob; 2599 } else { 2600 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2601 sizeof(Clusters[SrcIndex])); 2602 } 2603 } 2604 Clusters.resize(DstIndex); 2605 } 2606 2607 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2608 MachineBasicBlock *Last) { 2609 // Update JTCases. 2610 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2611 if (JTCases[i].first.HeaderBB == First) 2612 JTCases[i].first.HeaderBB = Last; 2613 2614 // Update BitTestCases. 2615 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2616 if (BitTestCases[i].Parent == First) 2617 BitTestCases[i].Parent = Last; 2618 } 2619 2620 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2621 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2622 2623 // Update machine-CFG edges with unique successors. 2624 SmallSet<BasicBlock*, 32> Done; 2625 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2626 BasicBlock *BB = I.getSuccessor(i); 2627 bool Inserted = Done.insert(BB).second; 2628 if (!Inserted) 2629 continue; 2630 2631 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2632 addSuccessorWithProb(IndirectBrMBB, Succ); 2633 } 2634 IndirectBrMBB->normalizeSuccProbs(); 2635 2636 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2637 MVT::Other, getControlRoot(), 2638 getValue(I.getAddress()))); 2639 } 2640 2641 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2642 if (!DAG.getTarget().Options.TrapUnreachable) 2643 return; 2644 2645 // We may be able to ignore unreachable behind a noreturn call. 2646 if (DAG.getTarget().Options.NoTrapAfterNoreturn) { 2647 const BasicBlock &BB = *I.getParent(); 2648 if (&I != &BB.front()) { 2649 BasicBlock::const_iterator PredI = 2650 std::prev(BasicBlock::const_iterator(&I)); 2651 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) { 2652 if (Call->doesNotReturn()) 2653 return; 2654 } 2655 } 2656 } 2657 2658 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2659 } 2660 2661 void SelectionDAGBuilder::visitFSub(const User &I) { 2662 // -0.0 - X --> fneg 2663 Type *Ty = I.getType(); 2664 if (isa<Constant>(I.getOperand(0)) && 2665 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2666 SDValue Op2 = getValue(I.getOperand(1)); 2667 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2668 Op2.getValueType(), Op2)); 2669 return; 2670 } 2671 2672 visitBinary(I, ISD::FSUB); 2673 } 2674 2675 /// Checks if the given instruction performs a vector reduction, in which case 2676 /// we have the freedom to alter the elements in the result as long as the 2677 /// reduction of them stays unchanged. 2678 static bool isVectorReductionOp(const User *I) { 2679 const Instruction *Inst = dyn_cast<Instruction>(I); 2680 if (!Inst || !Inst->getType()->isVectorTy()) 2681 return false; 2682 2683 auto OpCode = Inst->getOpcode(); 2684 switch (OpCode) { 2685 case Instruction::Add: 2686 case Instruction::Mul: 2687 case Instruction::And: 2688 case Instruction::Or: 2689 case Instruction::Xor: 2690 break; 2691 case Instruction::FAdd: 2692 case Instruction::FMul: 2693 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2694 if (FPOp->getFastMathFlags().isFast()) 2695 break; 2696 LLVM_FALLTHROUGH; 2697 default: 2698 return false; 2699 } 2700 2701 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2702 // Ensure the reduction size is a power of 2. 2703 if (!isPowerOf2_32(ElemNum)) 2704 return false; 2705 2706 unsigned ElemNumToReduce = ElemNum; 2707 2708 // Do DFS search on the def-use chain from the given instruction. We only 2709 // allow four kinds of operations during the search until we reach the 2710 // instruction that extracts the first element from the vector: 2711 // 2712 // 1. The reduction operation of the same opcode as the given instruction. 2713 // 2714 // 2. PHI node. 2715 // 2716 // 3. ShuffleVector instruction together with a reduction operation that 2717 // does a partial reduction. 2718 // 2719 // 4. ExtractElement that extracts the first element from the vector, and we 2720 // stop searching the def-use chain here. 2721 // 2722 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2723 // from 1-3 to the stack to continue the DFS. The given instruction is not 2724 // a reduction operation if we meet any other instructions other than those 2725 // listed above. 2726 2727 SmallVector<const User *, 16> UsersToVisit{Inst}; 2728 SmallPtrSet<const User *, 16> Visited; 2729 bool ReduxExtracted = false; 2730 2731 while (!UsersToVisit.empty()) { 2732 auto User = UsersToVisit.back(); 2733 UsersToVisit.pop_back(); 2734 if (!Visited.insert(User).second) 2735 continue; 2736 2737 for (const auto &U : User->users()) { 2738 auto Inst = dyn_cast<Instruction>(U); 2739 if (!Inst) 2740 return false; 2741 2742 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2743 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2744 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2745 return false; 2746 UsersToVisit.push_back(U); 2747 } else if (const ShuffleVectorInst *ShufInst = 2748 dyn_cast<ShuffleVectorInst>(U)) { 2749 // Detect the following pattern: A ShuffleVector instruction together 2750 // with a reduction that do partial reduction on the first and second 2751 // ElemNumToReduce / 2 elements, and store the result in 2752 // ElemNumToReduce / 2 elements in another vector. 2753 2754 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2755 if (ResultElements < ElemNum) 2756 return false; 2757 2758 if (ElemNumToReduce == 1) 2759 return false; 2760 if (!isa<UndefValue>(U->getOperand(1))) 2761 return false; 2762 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2763 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2764 return false; 2765 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2766 if (ShufInst->getMaskValue(i) != -1) 2767 return false; 2768 2769 // There is only one user of this ShuffleVector instruction, which 2770 // must be a reduction operation. 2771 if (!U->hasOneUse()) 2772 return false; 2773 2774 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2775 if (!U2 || U2->getOpcode() != OpCode) 2776 return false; 2777 2778 // Check operands of the reduction operation. 2779 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2780 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2781 UsersToVisit.push_back(U2); 2782 ElemNumToReduce /= 2; 2783 } else 2784 return false; 2785 } else if (isa<ExtractElementInst>(U)) { 2786 // At this moment we should have reduced all elements in the vector. 2787 if (ElemNumToReduce != 1) 2788 return false; 2789 2790 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2791 if (!Val || !Val->isZero()) 2792 return false; 2793 2794 ReduxExtracted = true; 2795 } else 2796 return false; 2797 } 2798 } 2799 return ReduxExtracted; 2800 } 2801 2802 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) { 2803 SDNodeFlags Flags; 2804 2805 SDValue Op = getValue(I.getOperand(0)); 2806 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(), 2807 Op, Flags); 2808 setValue(&I, UnNodeValue); 2809 } 2810 2811 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) { 2812 SDNodeFlags Flags; 2813 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) { 2814 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap()); 2815 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap()); 2816 } 2817 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) { 2818 Flags.setExact(ExactOp->isExact()); 2819 } 2820 if (isVectorReductionOp(&I)) { 2821 Flags.setVectorReduction(true); 2822 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2823 } 2824 2825 SDValue Op1 = getValue(I.getOperand(0)); 2826 SDValue Op2 = getValue(I.getOperand(1)); 2827 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), 2828 Op1, Op2, Flags); 2829 setValue(&I, BinNodeValue); 2830 } 2831 2832 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2833 SDValue Op1 = getValue(I.getOperand(0)); 2834 SDValue Op2 = getValue(I.getOperand(1)); 2835 2836 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2837 Op1.getValueType(), DAG.getDataLayout()); 2838 2839 // Coerce the shift amount to the right type if we can. 2840 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2841 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2842 unsigned Op2Size = Op2.getValueSizeInBits(); 2843 SDLoc DL = getCurSDLoc(); 2844 2845 // If the operand is smaller than the shift count type, promote it. 2846 if (ShiftSize > Op2Size) 2847 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2848 2849 // If the operand is larger than the shift count type but the shift 2850 // count type has enough bits to represent any shift value, truncate 2851 // it now. This is a common case and it exposes the truncate to 2852 // optimization early. 2853 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2854 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2855 // Otherwise we'll need to temporarily settle for some other convenient 2856 // type. Type legalization will make adjustments once the shiftee is split. 2857 else 2858 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2859 } 2860 2861 bool nuw = false; 2862 bool nsw = false; 2863 bool exact = false; 2864 2865 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2866 2867 if (const OverflowingBinaryOperator *OFBinOp = 2868 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2869 nuw = OFBinOp->hasNoUnsignedWrap(); 2870 nsw = OFBinOp->hasNoSignedWrap(); 2871 } 2872 if (const PossiblyExactOperator *ExactOp = 2873 dyn_cast<const PossiblyExactOperator>(&I)) 2874 exact = ExactOp->isExact(); 2875 } 2876 SDNodeFlags Flags; 2877 Flags.setExact(exact); 2878 Flags.setNoSignedWrap(nsw); 2879 Flags.setNoUnsignedWrap(nuw); 2880 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2881 Flags); 2882 setValue(&I, Res); 2883 } 2884 2885 void SelectionDAGBuilder::visitSDiv(const User &I) { 2886 SDValue Op1 = getValue(I.getOperand(0)); 2887 SDValue Op2 = getValue(I.getOperand(1)); 2888 2889 SDNodeFlags Flags; 2890 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2891 cast<PossiblyExactOperator>(&I)->isExact()); 2892 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2893 Op2, Flags)); 2894 } 2895 2896 void SelectionDAGBuilder::visitICmp(const User &I) { 2897 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2898 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2899 predicate = IC->getPredicate(); 2900 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2901 predicate = ICmpInst::Predicate(IC->getPredicate()); 2902 SDValue Op1 = getValue(I.getOperand(0)); 2903 SDValue Op2 = getValue(I.getOperand(1)); 2904 ISD::CondCode Opcode = getICmpCondCode(predicate); 2905 2906 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2907 I.getType()); 2908 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2909 } 2910 2911 void SelectionDAGBuilder::visitFCmp(const User &I) { 2912 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2913 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2914 predicate = FC->getPredicate(); 2915 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2916 predicate = FCmpInst::Predicate(FC->getPredicate()); 2917 SDValue Op1 = getValue(I.getOperand(0)); 2918 SDValue Op2 = getValue(I.getOperand(1)); 2919 2920 ISD::CondCode Condition = getFCmpCondCode(predicate); 2921 auto *FPMO = dyn_cast<FPMathOperator>(&I); 2922 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath) 2923 Condition = getFCmpCodeWithoutNaN(Condition); 2924 2925 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2926 I.getType()); 2927 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2928 } 2929 2930 // Check if the condition of the select has one use or two users that are both 2931 // selects with the same condition. 2932 static bool hasOnlySelectUsers(const Value *Cond) { 2933 return llvm::all_of(Cond->users(), [](const Value *V) { 2934 return isa<SelectInst>(V); 2935 }); 2936 } 2937 2938 void SelectionDAGBuilder::visitSelect(const User &I) { 2939 SmallVector<EVT, 4> ValueVTs; 2940 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2941 ValueVTs); 2942 unsigned NumValues = ValueVTs.size(); 2943 if (NumValues == 0) return; 2944 2945 SmallVector<SDValue, 4> Values(NumValues); 2946 SDValue Cond = getValue(I.getOperand(0)); 2947 SDValue LHSVal = getValue(I.getOperand(1)); 2948 SDValue RHSVal = getValue(I.getOperand(2)); 2949 auto BaseOps = {Cond}; 2950 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2951 ISD::VSELECT : ISD::SELECT; 2952 2953 // Min/max matching is only viable if all output VTs are the same. 2954 if (is_splat(ValueVTs)) { 2955 EVT VT = ValueVTs[0]; 2956 LLVMContext &Ctx = *DAG.getContext(); 2957 auto &TLI = DAG.getTargetLoweringInfo(); 2958 2959 // We care about the legality of the operation after it has been type 2960 // legalized. 2961 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2962 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2963 VT = TLI.getTypeToTransformTo(Ctx, VT); 2964 2965 // If the vselect is legal, assume we want to leave this as a vector setcc + 2966 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2967 // min/max is legal on the scalar type. 2968 bool UseScalarMinMax = VT.isVector() && 2969 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2970 2971 Value *LHS, *RHS; 2972 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2973 ISD::NodeType Opc = ISD::DELETED_NODE; 2974 switch (SPR.Flavor) { 2975 case SPF_UMAX: Opc = ISD::UMAX; break; 2976 case SPF_UMIN: Opc = ISD::UMIN; break; 2977 case SPF_SMAX: Opc = ISD::SMAX; break; 2978 case SPF_SMIN: Opc = ISD::SMIN; break; 2979 case SPF_FMINNUM: 2980 switch (SPR.NaNBehavior) { 2981 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2982 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break; 2983 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2984 case SPNB_RETURNS_ANY: { 2985 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2986 Opc = ISD::FMINNUM; 2987 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)) 2988 Opc = ISD::FMINIMUM; 2989 else if (UseScalarMinMax) 2990 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2991 ISD::FMINNUM : ISD::FMINIMUM; 2992 break; 2993 } 2994 } 2995 break; 2996 case SPF_FMAXNUM: 2997 switch (SPR.NaNBehavior) { 2998 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2999 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break; 3000 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 3001 case SPNB_RETURNS_ANY: 3002 3003 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 3004 Opc = ISD::FMAXNUM; 3005 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)) 3006 Opc = ISD::FMAXIMUM; 3007 else if (UseScalarMinMax) 3008 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 3009 ISD::FMAXNUM : ISD::FMAXIMUM; 3010 break; 3011 } 3012 break; 3013 default: break; 3014 } 3015 3016 if (Opc != ISD::DELETED_NODE && 3017 (TLI.isOperationLegalOrCustom(Opc, VT) || 3018 (UseScalarMinMax && 3019 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 3020 // If the underlying comparison instruction is used by any other 3021 // instruction, the consumed instructions won't be destroyed, so it is 3022 // not profitable to convert to a min/max. 3023 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 3024 OpCode = Opc; 3025 LHSVal = getValue(LHS); 3026 RHSVal = getValue(RHS); 3027 BaseOps = {}; 3028 } 3029 } 3030 3031 for (unsigned i = 0; i != NumValues; ++i) { 3032 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 3033 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 3034 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 3035 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 3036 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 3037 Ops); 3038 } 3039 3040 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3041 DAG.getVTList(ValueVTs), Values)); 3042 } 3043 3044 void SelectionDAGBuilder::visitTrunc(const User &I) { 3045 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 3046 SDValue N = getValue(I.getOperand(0)); 3047 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3048 I.getType()); 3049 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 3050 } 3051 3052 void SelectionDAGBuilder::visitZExt(const User &I) { 3053 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3054 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 3055 SDValue N = getValue(I.getOperand(0)); 3056 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3057 I.getType()); 3058 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 3059 } 3060 3061 void SelectionDAGBuilder::visitSExt(const User &I) { 3062 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 3063 // SExt also can't be a cast to bool for same reason. So, nothing much to do 3064 SDValue N = getValue(I.getOperand(0)); 3065 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3066 I.getType()); 3067 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 3068 } 3069 3070 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 3071 // FPTrunc is never a no-op cast, no need to check 3072 SDValue N = getValue(I.getOperand(0)); 3073 SDLoc dl = getCurSDLoc(); 3074 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3075 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3076 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 3077 DAG.getTargetConstant( 3078 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 3079 } 3080 3081 void SelectionDAGBuilder::visitFPExt(const User &I) { 3082 // FPExt is never a no-op cast, no need to check 3083 SDValue N = getValue(I.getOperand(0)); 3084 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3085 I.getType()); 3086 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 3087 } 3088 3089 void SelectionDAGBuilder::visitFPToUI(const User &I) { 3090 // FPToUI is never a no-op cast, no need to check 3091 SDValue N = getValue(I.getOperand(0)); 3092 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3093 I.getType()); 3094 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 3095 } 3096 3097 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3098 // FPToSI is never a no-op cast, no need to check 3099 SDValue N = getValue(I.getOperand(0)); 3100 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3101 I.getType()); 3102 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3103 } 3104 3105 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3106 // UIToFP is never a no-op cast, no need to check 3107 SDValue N = getValue(I.getOperand(0)); 3108 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3109 I.getType()); 3110 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3111 } 3112 3113 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3114 // SIToFP is never a no-op cast, no need to check 3115 SDValue N = getValue(I.getOperand(0)); 3116 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3117 I.getType()); 3118 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3119 } 3120 3121 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3122 // What to do depends on the size of the integer and the size of the pointer. 3123 // We can either truncate, zero extend, or no-op, accordingly. 3124 SDValue N = getValue(I.getOperand(0)); 3125 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3126 I.getType()); 3127 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3128 } 3129 3130 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3131 // What to do depends on the size of the integer and the size of the pointer. 3132 // We can either truncate, zero extend, or no-op, accordingly. 3133 SDValue N = getValue(I.getOperand(0)); 3134 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3135 I.getType()); 3136 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3137 } 3138 3139 void SelectionDAGBuilder::visitBitCast(const User &I) { 3140 SDValue N = getValue(I.getOperand(0)); 3141 SDLoc dl = getCurSDLoc(); 3142 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3143 I.getType()); 3144 3145 // BitCast assures us that source and destination are the same size so this is 3146 // either a BITCAST or a no-op. 3147 if (DestVT != N.getValueType()) 3148 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3149 DestVT, N)); // convert types. 3150 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3151 // might fold any kind of constant expression to an integer constant and that 3152 // is not what we are looking for. Only recognize a bitcast of a genuine 3153 // constant integer as an opaque constant. 3154 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3155 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3156 /*isOpaque*/true)); 3157 else 3158 setValue(&I, N); // noop cast. 3159 } 3160 3161 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3162 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3163 const Value *SV = I.getOperand(0); 3164 SDValue N = getValue(SV); 3165 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3166 3167 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3168 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3169 3170 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3171 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3172 3173 setValue(&I, N); 3174 } 3175 3176 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3177 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3178 SDValue InVec = getValue(I.getOperand(0)); 3179 SDValue InVal = getValue(I.getOperand(1)); 3180 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3181 TLI.getVectorIdxTy(DAG.getDataLayout())); 3182 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3183 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3184 InVec, InVal, InIdx)); 3185 } 3186 3187 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3188 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3189 SDValue InVec = getValue(I.getOperand(0)); 3190 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3191 TLI.getVectorIdxTy(DAG.getDataLayout())); 3192 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3193 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3194 InVec, InIdx)); 3195 } 3196 3197 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3198 SDValue Src1 = getValue(I.getOperand(0)); 3199 SDValue Src2 = getValue(I.getOperand(1)); 3200 SDLoc DL = getCurSDLoc(); 3201 3202 SmallVector<int, 8> Mask; 3203 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3204 unsigned MaskNumElts = Mask.size(); 3205 3206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3207 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3208 EVT SrcVT = Src1.getValueType(); 3209 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3210 3211 if (SrcNumElts == MaskNumElts) { 3212 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3213 return; 3214 } 3215 3216 // Normalize the shuffle vector since mask and vector length don't match. 3217 if (SrcNumElts < MaskNumElts) { 3218 // Mask is longer than the source vectors. We can use concatenate vector to 3219 // make the mask and vectors lengths match. 3220 3221 if (MaskNumElts % SrcNumElts == 0) { 3222 // Mask length is a multiple of the source vector length. 3223 // Check if the shuffle is some kind of concatenation of the input 3224 // vectors. 3225 unsigned NumConcat = MaskNumElts / SrcNumElts; 3226 bool IsConcat = true; 3227 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3228 for (unsigned i = 0; i != MaskNumElts; ++i) { 3229 int Idx = Mask[i]; 3230 if (Idx < 0) 3231 continue; 3232 // Ensure the indices in each SrcVT sized piece are sequential and that 3233 // the same source is used for the whole piece. 3234 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3235 (ConcatSrcs[i / SrcNumElts] >= 0 && 3236 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3237 IsConcat = false; 3238 break; 3239 } 3240 // Remember which source this index came from. 3241 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3242 } 3243 3244 // The shuffle is concatenating multiple vectors together. Just emit 3245 // a CONCAT_VECTORS operation. 3246 if (IsConcat) { 3247 SmallVector<SDValue, 8> ConcatOps; 3248 for (auto Src : ConcatSrcs) { 3249 if (Src < 0) 3250 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3251 else if (Src == 0) 3252 ConcatOps.push_back(Src1); 3253 else 3254 ConcatOps.push_back(Src2); 3255 } 3256 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3257 return; 3258 } 3259 } 3260 3261 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3262 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3263 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3264 PaddedMaskNumElts); 3265 3266 // Pad both vectors with undefs to make them the same length as the mask. 3267 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3268 3269 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3270 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3271 MOps1[0] = Src1; 3272 MOps2[0] = Src2; 3273 3274 Src1 = Src1.isUndef() 3275 ? DAG.getUNDEF(PaddedVT) 3276 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3277 Src2 = Src2.isUndef() 3278 ? DAG.getUNDEF(PaddedVT) 3279 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3280 3281 // Readjust mask for new input vector length. 3282 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3283 for (unsigned i = 0; i != MaskNumElts; ++i) { 3284 int Idx = Mask[i]; 3285 if (Idx >= (int)SrcNumElts) 3286 Idx -= SrcNumElts - PaddedMaskNumElts; 3287 MappedOps[i] = Idx; 3288 } 3289 3290 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3291 3292 // If the concatenated vector was padded, extract a subvector with the 3293 // correct number of elements. 3294 if (MaskNumElts != PaddedMaskNumElts) 3295 Result = DAG.getNode( 3296 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3297 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3298 3299 setValue(&I, Result); 3300 return; 3301 } 3302 3303 if (SrcNumElts > MaskNumElts) { 3304 // Analyze the access pattern of the vector to see if we can extract 3305 // two subvectors and do the shuffle. 3306 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3307 bool CanExtract = true; 3308 for (int Idx : Mask) { 3309 unsigned Input = 0; 3310 if (Idx < 0) 3311 continue; 3312 3313 if (Idx >= (int)SrcNumElts) { 3314 Input = 1; 3315 Idx -= SrcNumElts; 3316 } 3317 3318 // If all the indices come from the same MaskNumElts sized portion of 3319 // the sources we can use extract. Also make sure the extract wouldn't 3320 // extract past the end of the source. 3321 int NewStartIdx = alignDown(Idx, MaskNumElts); 3322 if (NewStartIdx + MaskNumElts > SrcNumElts || 3323 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3324 CanExtract = false; 3325 // Make sure we always update StartIdx as we use it to track if all 3326 // elements are undef. 3327 StartIdx[Input] = NewStartIdx; 3328 } 3329 3330 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3331 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3332 return; 3333 } 3334 if (CanExtract) { 3335 // Extract appropriate subvector and generate a vector shuffle 3336 for (unsigned Input = 0; Input < 2; ++Input) { 3337 SDValue &Src = Input == 0 ? Src1 : Src2; 3338 if (StartIdx[Input] < 0) 3339 Src = DAG.getUNDEF(VT); 3340 else { 3341 Src = DAG.getNode( 3342 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3343 DAG.getConstant(StartIdx[Input], DL, 3344 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3345 } 3346 } 3347 3348 // Calculate new mask. 3349 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3350 for (int &Idx : MappedOps) { 3351 if (Idx >= (int)SrcNumElts) 3352 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3353 else if (Idx >= 0) 3354 Idx -= StartIdx[0]; 3355 } 3356 3357 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3358 return; 3359 } 3360 } 3361 3362 // We can't use either concat vectors or extract subvectors so fall back to 3363 // replacing the shuffle with extract and build vector. 3364 // to insert and build vector. 3365 EVT EltVT = VT.getVectorElementType(); 3366 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3367 SmallVector<SDValue,8> Ops; 3368 for (int Idx : Mask) { 3369 SDValue Res; 3370 3371 if (Idx < 0) { 3372 Res = DAG.getUNDEF(EltVT); 3373 } else { 3374 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3375 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3376 3377 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3378 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3379 } 3380 3381 Ops.push_back(Res); 3382 } 3383 3384 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3385 } 3386 3387 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3388 ArrayRef<unsigned> Indices; 3389 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3390 Indices = IV->getIndices(); 3391 else 3392 Indices = cast<ConstantExpr>(&I)->getIndices(); 3393 3394 const Value *Op0 = I.getOperand(0); 3395 const Value *Op1 = I.getOperand(1); 3396 Type *AggTy = I.getType(); 3397 Type *ValTy = Op1->getType(); 3398 bool IntoUndef = isa<UndefValue>(Op0); 3399 bool FromUndef = isa<UndefValue>(Op1); 3400 3401 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3402 3403 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3404 SmallVector<EVT, 4> AggValueVTs; 3405 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3406 SmallVector<EVT, 4> ValValueVTs; 3407 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3408 3409 unsigned NumAggValues = AggValueVTs.size(); 3410 unsigned NumValValues = ValValueVTs.size(); 3411 SmallVector<SDValue, 4> Values(NumAggValues); 3412 3413 // Ignore an insertvalue that produces an empty object 3414 if (!NumAggValues) { 3415 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3416 return; 3417 } 3418 3419 SDValue Agg = getValue(Op0); 3420 unsigned i = 0; 3421 // Copy the beginning value(s) from the original aggregate. 3422 for (; i != LinearIndex; ++i) 3423 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3424 SDValue(Agg.getNode(), Agg.getResNo() + i); 3425 // Copy values from the inserted value(s). 3426 if (NumValValues) { 3427 SDValue Val = getValue(Op1); 3428 for (; i != LinearIndex + NumValValues; ++i) 3429 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3430 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3431 } 3432 // Copy remaining value(s) from the original aggregate. 3433 for (; i != NumAggValues; ++i) 3434 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3435 SDValue(Agg.getNode(), Agg.getResNo() + i); 3436 3437 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3438 DAG.getVTList(AggValueVTs), Values)); 3439 } 3440 3441 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3442 ArrayRef<unsigned> Indices; 3443 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3444 Indices = EV->getIndices(); 3445 else 3446 Indices = cast<ConstantExpr>(&I)->getIndices(); 3447 3448 const Value *Op0 = I.getOperand(0); 3449 Type *AggTy = Op0->getType(); 3450 Type *ValTy = I.getType(); 3451 bool OutOfUndef = isa<UndefValue>(Op0); 3452 3453 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3454 3455 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3456 SmallVector<EVT, 4> ValValueVTs; 3457 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3458 3459 unsigned NumValValues = ValValueVTs.size(); 3460 3461 // Ignore a extractvalue that produces an empty object 3462 if (!NumValValues) { 3463 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3464 return; 3465 } 3466 3467 SmallVector<SDValue, 4> Values(NumValValues); 3468 3469 SDValue Agg = getValue(Op0); 3470 // Copy out the selected value(s). 3471 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3472 Values[i - LinearIndex] = 3473 OutOfUndef ? 3474 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3475 SDValue(Agg.getNode(), Agg.getResNo() + i); 3476 3477 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3478 DAG.getVTList(ValValueVTs), Values)); 3479 } 3480 3481 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3482 Value *Op0 = I.getOperand(0); 3483 // Note that the pointer operand may be a vector of pointers. Take the scalar 3484 // element which holds a pointer. 3485 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3486 SDValue N = getValue(Op0); 3487 SDLoc dl = getCurSDLoc(); 3488 3489 // Normalize Vector GEP - all scalar operands should be converted to the 3490 // splat vector. 3491 unsigned VectorWidth = I.getType()->isVectorTy() ? 3492 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3493 3494 if (VectorWidth && !N.getValueType().isVector()) { 3495 LLVMContext &Context = *DAG.getContext(); 3496 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3497 N = DAG.getSplatBuildVector(VT, dl, N); 3498 } 3499 3500 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3501 GTI != E; ++GTI) { 3502 const Value *Idx = GTI.getOperand(); 3503 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3504 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3505 if (Field) { 3506 // N = N + Offset 3507 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3508 3509 // In an inbounds GEP with an offset that is nonnegative even when 3510 // interpreted as signed, assume there is no unsigned overflow. 3511 SDNodeFlags Flags; 3512 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3513 Flags.setNoUnsignedWrap(true); 3514 3515 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3516 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3517 } 3518 } else { 3519 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS); 3520 MVT IdxTy = MVT::getIntegerVT(IdxSize); 3521 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3522 3523 // If this is a scalar constant or a splat vector of constants, 3524 // handle it quickly. 3525 const auto *CI = dyn_cast<ConstantInt>(Idx); 3526 if (!CI && isa<ConstantDataVector>(Idx) && 3527 cast<ConstantDataVector>(Idx)->getSplatValue()) 3528 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3529 3530 if (CI) { 3531 if (CI->isZero()) 3532 continue; 3533 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize); 3534 LLVMContext &Context = *DAG.getContext(); 3535 SDValue OffsVal = VectorWidth ? 3536 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) : 3537 DAG.getConstant(Offs, dl, IdxTy); 3538 3539 // In an inbouds GEP with an offset that is nonnegative even when 3540 // interpreted as signed, assume there is no unsigned overflow. 3541 SDNodeFlags Flags; 3542 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3543 Flags.setNoUnsignedWrap(true); 3544 3545 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3546 continue; 3547 } 3548 3549 // N = N + Idx * ElementSize; 3550 SDValue IdxN = getValue(Idx); 3551 3552 if (!IdxN.getValueType().isVector() && VectorWidth) { 3553 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3554 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3555 } 3556 3557 // If the index is smaller or larger than intptr_t, truncate or extend 3558 // it. 3559 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3560 3561 // If this is a multiply by a power of two, turn it into a shl 3562 // immediately. This is a very common case. 3563 if (ElementSize != 1) { 3564 if (ElementSize.isPowerOf2()) { 3565 unsigned Amt = ElementSize.logBase2(); 3566 IdxN = DAG.getNode(ISD::SHL, dl, 3567 N.getValueType(), IdxN, 3568 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3569 } else { 3570 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3571 IdxN = DAG.getNode(ISD::MUL, dl, 3572 N.getValueType(), IdxN, Scale); 3573 } 3574 } 3575 3576 N = DAG.getNode(ISD::ADD, dl, 3577 N.getValueType(), N, IdxN); 3578 } 3579 } 3580 3581 setValue(&I, N); 3582 } 3583 3584 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3585 // If this is a fixed sized alloca in the entry block of the function, 3586 // allocate it statically on the stack. 3587 if (FuncInfo.StaticAllocaMap.count(&I)) 3588 return; // getValue will auto-populate this. 3589 3590 SDLoc dl = getCurSDLoc(); 3591 Type *Ty = I.getAllocatedType(); 3592 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3593 auto &DL = DAG.getDataLayout(); 3594 uint64_t TySize = DL.getTypeAllocSize(Ty); 3595 unsigned Align = 3596 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3597 3598 SDValue AllocSize = getValue(I.getArraySize()); 3599 3600 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3601 if (AllocSize.getValueType() != IntPtr) 3602 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3603 3604 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3605 AllocSize, 3606 DAG.getConstant(TySize, dl, IntPtr)); 3607 3608 // Handle alignment. If the requested alignment is less than or equal to 3609 // the stack alignment, ignore it. If the size is greater than or equal to 3610 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3611 unsigned StackAlign = 3612 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3613 if (Align <= StackAlign) 3614 Align = 0; 3615 3616 // Round the size of the allocation up to the stack alignment size 3617 // by add SA-1 to the size. This doesn't overflow because we're computing 3618 // an address inside an alloca. 3619 SDNodeFlags Flags; 3620 Flags.setNoUnsignedWrap(true); 3621 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3622 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3623 3624 // Mask out the low bits for alignment purposes. 3625 AllocSize = 3626 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3627 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3628 3629 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3630 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3631 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3632 setValue(&I, DSA); 3633 DAG.setRoot(DSA.getValue(1)); 3634 3635 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3636 } 3637 3638 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3639 if (I.isAtomic()) 3640 return visitAtomicLoad(I); 3641 3642 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3643 const Value *SV = I.getOperand(0); 3644 if (TLI.supportSwiftError()) { 3645 // Swifterror values can come from either a function parameter with 3646 // swifterror attribute or an alloca with swifterror attribute. 3647 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3648 if (Arg->hasSwiftErrorAttr()) 3649 return visitLoadFromSwiftError(I); 3650 } 3651 3652 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3653 if (Alloca->isSwiftError()) 3654 return visitLoadFromSwiftError(I); 3655 } 3656 } 3657 3658 SDValue Ptr = getValue(SV); 3659 3660 Type *Ty = I.getType(); 3661 3662 bool isVolatile = I.isVolatile(); 3663 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3664 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3665 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3666 unsigned Alignment = I.getAlignment(); 3667 3668 AAMDNodes AAInfo; 3669 I.getAAMetadata(AAInfo); 3670 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3671 3672 SmallVector<EVT, 4> ValueVTs; 3673 SmallVector<uint64_t, 4> Offsets; 3674 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3675 unsigned NumValues = ValueVTs.size(); 3676 if (NumValues == 0) 3677 return; 3678 3679 SDValue Root; 3680 bool ConstantMemory = false; 3681 if (isVolatile || NumValues > MaxParallelChains) 3682 // Serialize volatile loads with other side effects. 3683 Root = getRoot(); 3684 else if (AA && 3685 AA->pointsToConstantMemory(MemoryLocation( 3686 SV, 3687 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3688 AAInfo))) { 3689 // Do not serialize (non-volatile) loads of constant memory with anything. 3690 Root = DAG.getEntryNode(); 3691 ConstantMemory = true; 3692 } else { 3693 // Do not serialize non-volatile loads against each other. 3694 Root = DAG.getRoot(); 3695 } 3696 3697 SDLoc dl = getCurSDLoc(); 3698 3699 if (isVolatile) 3700 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3701 3702 // An aggregate load cannot wrap around the address space, so offsets to its 3703 // parts don't wrap either. 3704 SDNodeFlags Flags; 3705 Flags.setNoUnsignedWrap(true); 3706 3707 SmallVector<SDValue, 4> Values(NumValues); 3708 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3709 EVT PtrVT = Ptr.getValueType(); 3710 unsigned ChainI = 0; 3711 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3712 // Serializing loads here may result in excessive register pressure, and 3713 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3714 // could recover a bit by hoisting nodes upward in the chain by recognizing 3715 // they are side-effect free or do not alias. The optimizer should really 3716 // avoid this case by converting large object/array copies to llvm.memcpy 3717 // (MaxParallelChains should always remain as failsafe). 3718 if (ChainI == MaxParallelChains) { 3719 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3720 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3721 makeArrayRef(Chains.data(), ChainI)); 3722 Root = Chain; 3723 ChainI = 0; 3724 } 3725 SDValue A = DAG.getNode(ISD::ADD, dl, 3726 PtrVT, Ptr, 3727 DAG.getConstant(Offsets[i], dl, PtrVT), 3728 Flags); 3729 auto MMOFlags = MachineMemOperand::MONone; 3730 if (isVolatile) 3731 MMOFlags |= MachineMemOperand::MOVolatile; 3732 if (isNonTemporal) 3733 MMOFlags |= MachineMemOperand::MONonTemporal; 3734 if (isInvariant) 3735 MMOFlags |= MachineMemOperand::MOInvariant; 3736 if (isDereferenceable) 3737 MMOFlags |= MachineMemOperand::MODereferenceable; 3738 MMOFlags |= TLI.getMMOFlags(I); 3739 3740 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3741 MachinePointerInfo(SV, Offsets[i]), Alignment, 3742 MMOFlags, AAInfo, Ranges); 3743 3744 Values[i] = L; 3745 Chains[ChainI] = L.getValue(1); 3746 } 3747 3748 if (!ConstantMemory) { 3749 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3750 makeArrayRef(Chains.data(), ChainI)); 3751 if (isVolatile) 3752 DAG.setRoot(Chain); 3753 else 3754 PendingLoads.push_back(Chain); 3755 } 3756 3757 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3758 DAG.getVTList(ValueVTs), Values)); 3759 } 3760 3761 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3762 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3763 "call visitStoreToSwiftError when backend supports swifterror"); 3764 3765 SmallVector<EVT, 4> ValueVTs; 3766 SmallVector<uint64_t, 4> Offsets; 3767 const Value *SrcV = I.getOperand(0); 3768 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3769 SrcV->getType(), ValueVTs, &Offsets); 3770 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3771 "expect a single EVT for swifterror"); 3772 3773 SDValue Src = getValue(SrcV); 3774 // Create a virtual register, then update the virtual register. 3775 unsigned VReg; bool CreatedVReg; 3776 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3777 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3778 // Chain can be getRoot or getControlRoot. 3779 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3780 SDValue(Src.getNode(), Src.getResNo())); 3781 DAG.setRoot(CopyNode); 3782 if (CreatedVReg) 3783 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3784 } 3785 3786 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3787 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3788 "call visitLoadFromSwiftError when backend supports swifterror"); 3789 3790 assert(!I.isVolatile() && 3791 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3792 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3793 "Support volatile, non temporal, invariant for load_from_swift_error"); 3794 3795 const Value *SV = I.getOperand(0); 3796 Type *Ty = I.getType(); 3797 AAMDNodes AAInfo; 3798 I.getAAMetadata(AAInfo); 3799 assert( 3800 (!AA || 3801 !AA->pointsToConstantMemory(MemoryLocation( 3802 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), 3803 AAInfo))) && 3804 "load_from_swift_error should not be constant memory"); 3805 3806 SmallVector<EVT, 4> ValueVTs; 3807 SmallVector<uint64_t, 4> Offsets; 3808 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3809 ValueVTs, &Offsets); 3810 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3811 "expect a single EVT for swifterror"); 3812 3813 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3814 SDValue L = DAG.getCopyFromReg( 3815 getRoot(), getCurSDLoc(), 3816 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3817 ValueVTs[0]); 3818 3819 setValue(&I, L); 3820 } 3821 3822 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3823 if (I.isAtomic()) 3824 return visitAtomicStore(I); 3825 3826 const Value *SrcV = I.getOperand(0); 3827 const Value *PtrV = I.getOperand(1); 3828 3829 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3830 if (TLI.supportSwiftError()) { 3831 // Swifterror values can come from either a function parameter with 3832 // swifterror attribute or an alloca with swifterror attribute. 3833 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3834 if (Arg->hasSwiftErrorAttr()) 3835 return visitStoreToSwiftError(I); 3836 } 3837 3838 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3839 if (Alloca->isSwiftError()) 3840 return visitStoreToSwiftError(I); 3841 } 3842 } 3843 3844 SmallVector<EVT, 4> ValueVTs; 3845 SmallVector<uint64_t, 4> Offsets; 3846 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3847 SrcV->getType(), ValueVTs, &Offsets); 3848 unsigned NumValues = ValueVTs.size(); 3849 if (NumValues == 0) 3850 return; 3851 3852 // Get the lowered operands. Note that we do this after 3853 // checking if NumResults is zero, because with zero results 3854 // the operands won't have values in the map. 3855 SDValue Src = getValue(SrcV); 3856 SDValue Ptr = getValue(PtrV); 3857 3858 SDValue Root = getRoot(); 3859 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3860 SDLoc dl = getCurSDLoc(); 3861 EVT PtrVT = Ptr.getValueType(); 3862 unsigned Alignment = I.getAlignment(); 3863 AAMDNodes AAInfo; 3864 I.getAAMetadata(AAInfo); 3865 3866 auto MMOFlags = MachineMemOperand::MONone; 3867 if (I.isVolatile()) 3868 MMOFlags |= MachineMemOperand::MOVolatile; 3869 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3870 MMOFlags |= MachineMemOperand::MONonTemporal; 3871 MMOFlags |= TLI.getMMOFlags(I); 3872 3873 // An aggregate load cannot wrap around the address space, so offsets to its 3874 // parts don't wrap either. 3875 SDNodeFlags Flags; 3876 Flags.setNoUnsignedWrap(true); 3877 3878 unsigned ChainI = 0; 3879 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3880 // See visitLoad comments. 3881 if (ChainI == MaxParallelChains) { 3882 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3883 makeArrayRef(Chains.data(), ChainI)); 3884 Root = Chain; 3885 ChainI = 0; 3886 } 3887 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3888 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3889 SDValue St = DAG.getStore( 3890 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3891 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3892 Chains[ChainI] = St; 3893 } 3894 3895 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3896 makeArrayRef(Chains.data(), ChainI)); 3897 DAG.setRoot(StoreNode); 3898 } 3899 3900 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3901 bool IsCompressing) { 3902 SDLoc sdl = getCurSDLoc(); 3903 3904 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3905 unsigned& Alignment) { 3906 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3907 Src0 = I.getArgOperand(0); 3908 Ptr = I.getArgOperand(1); 3909 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3910 Mask = I.getArgOperand(3); 3911 }; 3912 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3913 unsigned& Alignment) { 3914 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3915 Src0 = I.getArgOperand(0); 3916 Ptr = I.getArgOperand(1); 3917 Mask = I.getArgOperand(2); 3918 Alignment = 0; 3919 }; 3920 3921 Value *PtrOperand, *MaskOperand, *Src0Operand; 3922 unsigned Alignment; 3923 if (IsCompressing) 3924 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3925 else 3926 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3927 3928 SDValue Ptr = getValue(PtrOperand); 3929 SDValue Src0 = getValue(Src0Operand); 3930 SDValue Mask = getValue(MaskOperand); 3931 3932 EVT VT = Src0.getValueType(); 3933 if (!Alignment) 3934 Alignment = DAG.getEVTAlignment(VT); 3935 3936 AAMDNodes AAInfo; 3937 I.getAAMetadata(AAInfo); 3938 3939 MachineMemOperand *MMO = 3940 DAG.getMachineFunction(). 3941 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3942 MachineMemOperand::MOStore, VT.getStoreSize(), 3943 Alignment, AAInfo); 3944 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3945 MMO, false /* Truncating */, 3946 IsCompressing); 3947 DAG.setRoot(StoreNode); 3948 setValue(&I, StoreNode); 3949 } 3950 3951 // Get a uniform base for the Gather/Scatter intrinsic. 3952 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3953 // We try to represent it as a base pointer + vector of indices. 3954 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3955 // The first operand of the GEP may be a single pointer or a vector of pointers 3956 // Example: 3957 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3958 // or 3959 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3960 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3961 // 3962 // When the first GEP operand is a single pointer - it is the uniform base we 3963 // are looking for. If first operand of the GEP is a splat vector - we 3964 // extract the splat value and use it as a uniform base. 3965 // In all other cases the function returns 'false'. 3966 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3967 SDValue &Scale, SelectionDAGBuilder* SDB) { 3968 SelectionDAG& DAG = SDB->DAG; 3969 LLVMContext &Context = *DAG.getContext(); 3970 3971 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3972 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3973 if (!GEP) 3974 return false; 3975 3976 const Value *GEPPtr = GEP->getPointerOperand(); 3977 if (!GEPPtr->getType()->isVectorTy()) 3978 Ptr = GEPPtr; 3979 else if (!(Ptr = getSplatValue(GEPPtr))) 3980 return false; 3981 3982 unsigned FinalIndex = GEP->getNumOperands() - 1; 3983 Value *IndexVal = GEP->getOperand(FinalIndex); 3984 3985 // Ensure all the other indices are 0. 3986 for (unsigned i = 1; i < FinalIndex; ++i) { 3987 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3988 if (!C || !C->isZero()) 3989 return false; 3990 } 3991 3992 // The operands of the GEP may be defined in another basic block. 3993 // In this case we'll not find nodes for the operands. 3994 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3995 return false; 3996 3997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3998 const DataLayout &DL = DAG.getDataLayout(); 3999 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()), 4000 SDB->getCurSDLoc(), TLI.getPointerTy(DL)); 4001 Base = SDB->getValue(Ptr); 4002 Index = SDB->getValue(IndexVal); 4003 4004 if (!Index.getValueType().isVector()) { 4005 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 4006 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 4007 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 4008 } 4009 return true; 4010 } 4011 4012 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 4013 SDLoc sdl = getCurSDLoc(); 4014 4015 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 4016 const Value *Ptr = I.getArgOperand(1); 4017 SDValue Src0 = getValue(I.getArgOperand(0)); 4018 SDValue Mask = getValue(I.getArgOperand(3)); 4019 EVT VT = Src0.getValueType(); 4020 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 4021 if (!Alignment) 4022 Alignment = DAG.getEVTAlignment(VT); 4023 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4024 4025 AAMDNodes AAInfo; 4026 I.getAAMetadata(AAInfo); 4027 4028 SDValue Base; 4029 SDValue Index; 4030 SDValue Scale; 4031 const Value *BasePtr = Ptr; 4032 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4033 4034 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 4035 MachineMemOperand *MMO = DAG.getMachineFunction(). 4036 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 4037 MachineMemOperand::MOStore, VT.getStoreSize(), 4038 Alignment, AAInfo); 4039 if (!UniformBase) { 4040 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4041 Index = getValue(Ptr); 4042 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4043 } 4044 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale }; 4045 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 4046 Ops, MMO); 4047 DAG.setRoot(Scatter); 4048 setValue(&I, Scatter); 4049 } 4050 4051 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 4052 SDLoc sdl = getCurSDLoc(); 4053 4054 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4055 unsigned& Alignment) { 4056 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 4057 Ptr = I.getArgOperand(0); 4058 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 4059 Mask = I.getArgOperand(2); 4060 Src0 = I.getArgOperand(3); 4061 }; 4062 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 4063 unsigned& Alignment) { 4064 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 4065 Ptr = I.getArgOperand(0); 4066 Alignment = 0; 4067 Mask = I.getArgOperand(1); 4068 Src0 = I.getArgOperand(2); 4069 }; 4070 4071 Value *PtrOperand, *MaskOperand, *Src0Operand; 4072 unsigned Alignment; 4073 if (IsExpanding) 4074 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4075 else 4076 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 4077 4078 SDValue Ptr = getValue(PtrOperand); 4079 SDValue Src0 = getValue(Src0Operand); 4080 SDValue Mask = getValue(MaskOperand); 4081 4082 EVT VT = Src0.getValueType(); 4083 if (!Alignment) 4084 Alignment = DAG.getEVTAlignment(VT); 4085 4086 AAMDNodes AAInfo; 4087 I.getAAMetadata(AAInfo); 4088 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4089 4090 // Do not serialize masked loads of constant memory with anything. 4091 bool AddToChain = 4092 !AA || !AA->pointsToConstantMemory(MemoryLocation( 4093 PtrOperand, 4094 LocationSize::precise( 4095 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4096 AAInfo)); 4097 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 4098 4099 MachineMemOperand *MMO = 4100 DAG.getMachineFunction(). 4101 getMachineMemOperand(MachinePointerInfo(PtrOperand), 4102 MachineMemOperand::MOLoad, VT.getStoreSize(), 4103 Alignment, AAInfo, Ranges); 4104 4105 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 4106 ISD::NON_EXTLOAD, IsExpanding); 4107 if (AddToChain) 4108 PendingLoads.push_back(Load.getValue(1)); 4109 setValue(&I, Load); 4110 } 4111 4112 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4113 SDLoc sdl = getCurSDLoc(); 4114 4115 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4116 const Value *Ptr = I.getArgOperand(0); 4117 SDValue Src0 = getValue(I.getArgOperand(3)); 4118 SDValue Mask = getValue(I.getArgOperand(2)); 4119 4120 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4121 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4122 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4123 if (!Alignment) 4124 Alignment = DAG.getEVTAlignment(VT); 4125 4126 AAMDNodes AAInfo; 4127 I.getAAMetadata(AAInfo); 4128 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4129 4130 SDValue Root = DAG.getRoot(); 4131 SDValue Base; 4132 SDValue Index; 4133 SDValue Scale; 4134 const Value *BasePtr = Ptr; 4135 bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this); 4136 bool ConstantMemory = false; 4137 if (UniformBase && AA && 4138 AA->pointsToConstantMemory( 4139 MemoryLocation(BasePtr, 4140 LocationSize::precise( 4141 DAG.getDataLayout().getTypeStoreSize(I.getType())), 4142 AAInfo))) { 4143 // Do not serialize (non-volatile) loads of constant memory with anything. 4144 Root = DAG.getEntryNode(); 4145 ConstantMemory = true; 4146 } 4147 4148 MachineMemOperand *MMO = 4149 DAG.getMachineFunction(). 4150 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4151 MachineMemOperand::MOLoad, VT.getStoreSize(), 4152 Alignment, AAInfo, Ranges); 4153 4154 if (!UniformBase) { 4155 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4156 Index = getValue(Ptr); 4157 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4158 } 4159 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale }; 4160 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4161 Ops, MMO); 4162 4163 SDValue OutChain = Gather.getValue(1); 4164 if (!ConstantMemory) 4165 PendingLoads.push_back(OutChain); 4166 setValue(&I, Gather); 4167 } 4168 4169 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4170 SDLoc dl = getCurSDLoc(); 4171 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4172 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4173 SyncScope::ID SSID = I.getSyncScopeID(); 4174 4175 SDValue InChain = getRoot(); 4176 4177 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4178 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4179 SDValue L = DAG.getAtomicCmpSwap( 4180 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4181 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4182 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4183 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4184 4185 SDValue OutChain = L.getValue(2); 4186 4187 setValue(&I, L); 4188 DAG.setRoot(OutChain); 4189 } 4190 4191 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4192 SDLoc dl = getCurSDLoc(); 4193 ISD::NodeType NT; 4194 switch (I.getOperation()) { 4195 default: llvm_unreachable("Unknown atomicrmw operation"); 4196 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4197 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4198 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4199 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4200 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4201 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4202 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4203 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4204 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4205 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4206 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4207 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break; 4208 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break; 4209 } 4210 AtomicOrdering Order = I.getOrdering(); 4211 SyncScope::ID SSID = I.getSyncScopeID(); 4212 4213 SDValue InChain = getRoot(); 4214 4215 SDValue L = 4216 DAG.getAtomic(NT, dl, 4217 getValue(I.getValOperand()).getSimpleValueType(), 4218 InChain, 4219 getValue(I.getPointerOperand()), 4220 getValue(I.getValOperand()), 4221 I.getPointerOperand(), 4222 /* Alignment=*/ 0, Order, SSID); 4223 4224 SDValue OutChain = L.getValue(1); 4225 4226 setValue(&I, L); 4227 DAG.setRoot(OutChain); 4228 } 4229 4230 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4231 SDLoc dl = getCurSDLoc(); 4232 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4233 SDValue Ops[3]; 4234 Ops[0] = getRoot(); 4235 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4236 TLI.getFenceOperandTy(DAG.getDataLayout())); 4237 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4238 TLI.getFenceOperandTy(DAG.getDataLayout())); 4239 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4240 } 4241 4242 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4243 SDLoc dl = getCurSDLoc(); 4244 AtomicOrdering Order = I.getOrdering(); 4245 SyncScope::ID SSID = I.getSyncScopeID(); 4246 4247 SDValue InChain = getRoot(); 4248 4249 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4250 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4251 4252 if (!TLI.supportsUnalignedAtomics() && 4253 I.getAlignment() < VT.getStoreSize()) 4254 report_fatal_error("Cannot generate unaligned atomic load"); 4255 4256 MachineMemOperand *MMO = 4257 DAG.getMachineFunction(). 4258 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4259 MachineMemOperand::MOVolatile | 4260 MachineMemOperand::MOLoad, 4261 VT.getStoreSize(), 4262 I.getAlignment() ? I.getAlignment() : 4263 DAG.getEVTAlignment(VT), 4264 AAMDNodes(), nullptr, SSID, Order); 4265 4266 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4267 SDValue L = 4268 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4269 getValue(I.getPointerOperand()), MMO); 4270 4271 SDValue OutChain = L.getValue(1); 4272 4273 setValue(&I, L); 4274 DAG.setRoot(OutChain); 4275 } 4276 4277 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4278 SDLoc dl = getCurSDLoc(); 4279 4280 AtomicOrdering Order = I.getOrdering(); 4281 SyncScope::ID SSID = I.getSyncScopeID(); 4282 4283 SDValue InChain = getRoot(); 4284 4285 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4286 EVT VT = 4287 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4288 4289 if (I.getAlignment() < VT.getStoreSize()) 4290 report_fatal_error("Cannot generate unaligned atomic store"); 4291 4292 SDValue OutChain = 4293 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4294 InChain, 4295 getValue(I.getPointerOperand()), 4296 getValue(I.getValueOperand()), 4297 I.getPointerOperand(), I.getAlignment(), 4298 Order, SSID); 4299 4300 DAG.setRoot(OutChain); 4301 } 4302 4303 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4304 /// node. 4305 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4306 unsigned Intrinsic) { 4307 // Ignore the callsite's attributes. A specific call site may be marked with 4308 // readnone, but the lowering code will expect the chain based on the 4309 // definition. 4310 const Function *F = I.getCalledFunction(); 4311 bool HasChain = !F->doesNotAccessMemory(); 4312 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4313 4314 // Build the operand list. 4315 SmallVector<SDValue, 8> Ops; 4316 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4317 if (OnlyLoad) { 4318 // We don't need to serialize loads against other loads. 4319 Ops.push_back(DAG.getRoot()); 4320 } else { 4321 Ops.push_back(getRoot()); 4322 } 4323 } 4324 4325 // Info is set by getTgtMemInstrinsic 4326 TargetLowering::IntrinsicInfo Info; 4327 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4328 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, 4329 DAG.getMachineFunction(), 4330 Intrinsic); 4331 4332 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4333 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4334 Info.opc == ISD::INTRINSIC_W_CHAIN) 4335 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4336 TLI.getPointerTy(DAG.getDataLayout()))); 4337 4338 // Add all operands of the call to the operand list. 4339 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4340 SDValue Op = getValue(I.getArgOperand(i)); 4341 Ops.push_back(Op); 4342 } 4343 4344 SmallVector<EVT, 4> ValueVTs; 4345 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4346 4347 if (HasChain) 4348 ValueVTs.push_back(MVT::Other); 4349 4350 SDVTList VTs = DAG.getVTList(ValueVTs); 4351 4352 // Create the node. 4353 SDValue Result; 4354 if (IsTgtIntrinsic) { 4355 // This is target intrinsic that touches memory 4356 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, 4357 Ops, Info.memVT, 4358 MachinePointerInfo(Info.ptrVal, Info.offset), Info.align, 4359 Info.flags, Info.size); 4360 } else if (!HasChain) { 4361 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4362 } else if (!I.getType()->isVoidTy()) { 4363 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4364 } else { 4365 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4366 } 4367 4368 if (HasChain) { 4369 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4370 if (OnlyLoad) 4371 PendingLoads.push_back(Chain); 4372 else 4373 DAG.setRoot(Chain); 4374 } 4375 4376 if (!I.getType()->isVoidTy()) { 4377 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4378 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4379 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4380 } else 4381 Result = lowerRangeToAssertZExt(DAG, I, Result); 4382 4383 setValue(&I, Result); 4384 } 4385 } 4386 4387 /// GetSignificand - Get the significand and build it into a floating-point 4388 /// number with exponent of 1: 4389 /// 4390 /// Op = (Op & 0x007fffff) | 0x3f800000; 4391 /// 4392 /// where Op is the hexadecimal representation of floating point value. 4393 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4394 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4395 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4396 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4397 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4398 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4399 } 4400 4401 /// GetExponent - Get the exponent: 4402 /// 4403 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4404 /// 4405 /// where Op is the hexadecimal representation of floating point value. 4406 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4407 const TargetLowering &TLI, const SDLoc &dl) { 4408 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4409 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4410 SDValue t1 = DAG.getNode( 4411 ISD::SRL, dl, MVT::i32, t0, 4412 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4413 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4414 DAG.getConstant(127, dl, MVT::i32)); 4415 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4416 } 4417 4418 /// getF32Constant - Get 32-bit floating point constant. 4419 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4420 const SDLoc &dl) { 4421 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4422 MVT::f32); 4423 } 4424 4425 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4426 SelectionDAG &DAG) { 4427 // TODO: What fast-math-flags should be set on the floating-point nodes? 4428 4429 // IntegerPartOfX = ((int32_t)(t0); 4430 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4431 4432 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4433 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4434 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4435 4436 // IntegerPartOfX <<= 23; 4437 IntegerPartOfX = DAG.getNode( 4438 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4439 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4440 DAG.getDataLayout()))); 4441 4442 SDValue TwoToFractionalPartOfX; 4443 if (LimitFloatPrecision <= 6) { 4444 // For floating-point precision of 6: 4445 // 4446 // TwoToFractionalPartOfX = 4447 // 0.997535578f + 4448 // (0.735607626f + 0.252464424f * x) * x; 4449 // 4450 // error 0.0144103317, which is 6 bits 4451 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4452 getF32Constant(DAG, 0x3e814304, dl)); 4453 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4454 getF32Constant(DAG, 0x3f3c50c8, dl)); 4455 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4456 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4457 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4458 } else if (LimitFloatPrecision <= 12) { 4459 // For floating-point precision of 12: 4460 // 4461 // TwoToFractionalPartOfX = 4462 // 0.999892986f + 4463 // (0.696457318f + 4464 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4465 // 4466 // error 0.000107046256, which is 13 to 14 bits 4467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4468 getF32Constant(DAG, 0x3da235e3, dl)); 4469 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4470 getF32Constant(DAG, 0x3e65b8f3, dl)); 4471 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4472 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4473 getF32Constant(DAG, 0x3f324b07, dl)); 4474 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4475 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4476 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4477 } else { // LimitFloatPrecision <= 18 4478 // For floating-point precision of 18: 4479 // 4480 // TwoToFractionalPartOfX = 4481 // 0.999999982f + 4482 // (0.693148872f + 4483 // (0.240227044f + 4484 // (0.554906021e-1f + 4485 // (0.961591928e-2f + 4486 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4487 // error 2.47208000*10^(-7), which is better than 18 bits 4488 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4489 getF32Constant(DAG, 0x3924b03e, dl)); 4490 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4491 getF32Constant(DAG, 0x3ab24b87, dl)); 4492 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4493 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4494 getF32Constant(DAG, 0x3c1d8c17, dl)); 4495 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4496 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4497 getF32Constant(DAG, 0x3d634a1d, dl)); 4498 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4499 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4500 getF32Constant(DAG, 0x3e75fe14, dl)); 4501 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4502 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4503 getF32Constant(DAG, 0x3f317234, dl)); 4504 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4505 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4506 getF32Constant(DAG, 0x3f800000, dl)); 4507 } 4508 4509 // Add the exponent into the result in integer domain. 4510 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4511 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4512 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4513 } 4514 4515 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4516 /// limited-precision mode. 4517 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4518 const TargetLowering &TLI) { 4519 if (Op.getValueType() == MVT::f32 && 4520 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4521 4522 // Put the exponent in the right bit position for later addition to the 4523 // final result: 4524 // 4525 // #define LOG2OFe 1.4426950f 4526 // t0 = Op * LOG2OFe 4527 4528 // TODO: What fast-math-flags should be set here? 4529 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4530 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4531 return getLimitedPrecisionExp2(t0, dl, DAG); 4532 } 4533 4534 // No special expansion. 4535 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4536 } 4537 4538 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4539 /// limited-precision mode. 4540 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4541 const TargetLowering &TLI) { 4542 // TODO: What fast-math-flags should be set on the floating-point nodes? 4543 4544 if (Op.getValueType() == MVT::f32 && 4545 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4546 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4547 4548 // Scale the exponent by log(2) [0.69314718f]. 4549 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4550 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4551 getF32Constant(DAG, 0x3f317218, dl)); 4552 4553 // Get the significand and build it into a floating-point number with 4554 // exponent of 1. 4555 SDValue X = GetSignificand(DAG, Op1, dl); 4556 4557 SDValue LogOfMantissa; 4558 if (LimitFloatPrecision <= 6) { 4559 // For floating-point precision of 6: 4560 // 4561 // LogofMantissa = 4562 // -1.1609546f + 4563 // (1.4034025f - 0.23903021f * x) * x; 4564 // 4565 // error 0.0034276066, which is better than 8 bits 4566 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4567 getF32Constant(DAG, 0xbe74c456, dl)); 4568 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4569 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4570 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4571 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4572 getF32Constant(DAG, 0x3f949a29, dl)); 4573 } else if (LimitFloatPrecision <= 12) { 4574 // For floating-point precision of 12: 4575 // 4576 // LogOfMantissa = 4577 // -1.7417939f + 4578 // (2.8212026f + 4579 // (-1.4699568f + 4580 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4581 // 4582 // error 0.000061011436, which is 14 bits 4583 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4584 getF32Constant(DAG, 0xbd67b6d6, dl)); 4585 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4586 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4587 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4588 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4589 getF32Constant(DAG, 0x3fbc278b, dl)); 4590 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4591 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4592 getF32Constant(DAG, 0x40348e95, dl)); 4593 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4594 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4595 getF32Constant(DAG, 0x3fdef31a, dl)); 4596 } else { // LimitFloatPrecision <= 18 4597 // For floating-point precision of 18: 4598 // 4599 // LogOfMantissa = 4600 // -2.1072184f + 4601 // (4.2372794f + 4602 // (-3.7029485f + 4603 // (2.2781945f + 4604 // (-0.87823314f + 4605 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4606 // 4607 // error 0.0000023660568, which is better than 18 bits 4608 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4609 getF32Constant(DAG, 0xbc91e5ac, dl)); 4610 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4611 getF32Constant(DAG, 0x3e4350aa, dl)); 4612 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4613 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4614 getF32Constant(DAG, 0x3f60d3e3, dl)); 4615 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4616 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4617 getF32Constant(DAG, 0x4011cdf0, dl)); 4618 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4619 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4620 getF32Constant(DAG, 0x406cfd1c, dl)); 4621 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4622 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4623 getF32Constant(DAG, 0x408797cb, dl)); 4624 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4625 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4626 getF32Constant(DAG, 0x4006dcab, dl)); 4627 } 4628 4629 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4630 } 4631 4632 // No special expansion. 4633 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4634 } 4635 4636 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4637 /// limited-precision mode. 4638 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4639 const TargetLowering &TLI) { 4640 // TODO: What fast-math-flags should be set on the floating-point nodes? 4641 4642 if (Op.getValueType() == MVT::f32 && 4643 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4644 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4645 4646 // Get the exponent. 4647 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4648 4649 // Get the significand and build it into a floating-point number with 4650 // exponent of 1. 4651 SDValue X = GetSignificand(DAG, Op1, dl); 4652 4653 // Different possible minimax approximations of significand in 4654 // floating-point for various degrees of accuracy over [1,2]. 4655 SDValue Log2ofMantissa; 4656 if (LimitFloatPrecision <= 6) { 4657 // For floating-point precision of 6: 4658 // 4659 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4660 // 4661 // error 0.0049451742, which is more than 7 bits 4662 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4663 getF32Constant(DAG, 0xbeb08fe0, dl)); 4664 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4665 getF32Constant(DAG, 0x40019463, dl)); 4666 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4667 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4668 getF32Constant(DAG, 0x3fd6633d, dl)); 4669 } else if (LimitFloatPrecision <= 12) { 4670 // For floating-point precision of 12: 4671 // 4672 // Log2ofMantissa = 4673 // -2.51285454f + 4674 // (4.07009056f + 4675 // (-2.12067489f + 4676 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4677 // 4678 // error 0.0000876136000, which is better than 13 bits 4679 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4680 getF32Constant(DAG, 0xbda7262e, dl)); 4681 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4682 getF32Constant(DAG, 0x3f25280b, dl)); 4683 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4684 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4685 getF32Constant(DAG, 0x4007b923, dl)); 4686 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4687 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4688 getF32Constant(DAG, 0x40823e2f, dl)); 4689 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4690 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4691 getF32Constant(DAG, 0x4020d29c, dl)); 4692 } else { // LimitFloatPrecision <= 18 4693 // For floating-point precision of 18: 4694 // 4695 // Log2ofMantissa = 4696 // -3.0400495f + 4697 // (6.1129976f + 4698 // (-5.3420409f + 4699 // (3.2865683f + 4700 // (-1.2669343f + 4701 // (0.27515199f - 4702 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4703 // 4704 // error 0.0000018516, which is better than 18 bits 4705 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4706 getF32Constant(DAG, 0xbcd2769e, dl)); 4707 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4708 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4709 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4710 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4711 getF32Constant(DAG, 0x3fa22ae7, dl)); 4712 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4713 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4714 getF32Constant(DAG, 0x40525723, dl)); 4715 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4716 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4717 getF32Constant(DAG, 0x40aaf200, dl)); 4718 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4719 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4720 getF32Constant(DAG, 0x40c39dad, dl)); 4721 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4722 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4723 getF32Constant(DAG, 0x4042902c, dl)); 4724 } 4725 4726 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4727 } 4728 4729 // No special expansion. 4730 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4731 } 4732 4733 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4734 /// limited-precision mode. 4735 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4736 const TargetLowering &TLI) { 4737 // TODO: What fast-math-flags should be set on the floating-point nodes? 4738 4739 if (Op.getValueType() == MVT::f32 && 4740 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4741 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4742 4743 // Scale the exponent by log10(2) [0.30102999f]. 4744 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4745 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4746 getF32Constant(DAG, 0x3e9a209a, dl)); 4747 4748 // Get the significand and build it into a floating-point number with 4749 // exponent of 1. 4750 SDValue X = GetSignificand(DAG, Op1, dl); 4751 4752 SDValue Log10ofMantissa; 4753 if (LimitFloatPrecision <= 6) { 4754 // For floating-point precision of 6: 4755 // 4756 // Log10ofMantissa = 4757 // -0.50419619f + 4758 // (0.60948995f - 0.10380950f * x) * x; 4759 // 4760 // error 0.0014886165, which is 6 bits 4761 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4762 getF32Constant(DAG, 0xbdd49a13, dl)); 4763 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4764 getF32Constant(DAG, 0x3f1c0789, dl)); 4765 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4766 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4767 getF32Constant(DAG, 0x3f011300, dl)); 4768 } else if (LimitFloatPrecision <= 12) { 4769 // For floating-point precision of 12: 4770 // 4771 // Log10ofMantissa = 4772 // -0.64831180f + 4773 // (0.91751397f + 4774 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4775 // 4776 // error 0.00019228036, which is better than 12 bits 4777 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4778 getF32Constant(DAG, 0x3d431f31, dl)); 4779 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4780 getF32Constant(DAG, 0x3ea21fb2, dl)); 4781 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4782 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4783 getF32Constant(DAG, 0x3f6ae232, dl)); 4784 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4785 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4786 getF32Constant(DAG, 0x3f25f7c3, dl)); 4787 } else { // LimitFloatPrecision <= 18 4788 // For floating-point precision of 18: 4789 // 4790 // Log10ofMantissa = 4791 // -0.84299375f + 4792 // (1.5327582f + 4793 // (-1.0688956f + 4794 // (0.49102474f + 4795 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4796 // 4797 // error 0.0000037995730, which is better than 18 bits 4798 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4799 getF32Constant(DAG, 0x3c5d51ce, dl)); 4800 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4801 getF32Constant(DAG, 0x3e00685a, dl)); 4802 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4803 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4804 getF32Constant(DAG, 0x3efb6798, dl)); 4805 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4806 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4807 getF32Constant(DAG, 0x3f88d192, dl)); 4808 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4809 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4810 getF32Constant(DAG, 0x3fc4316c, dl)); 4811 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4812 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4813 getF32Constant(DAG, 0x3f57ce70, dl)); 4814 } 4815 4816 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4817 } 4818 4819 // No special expansion. 4820 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4821 } 4822 4823 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4824 /// limited-precision mode. 4825 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4826 const TargetLowering &TLI) { 4827 if (Op.getValueType() == MVT::f32 && 4828 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4829 return getLimitedPrecisionExp2(Op, dl, DAG); 4830 4831 // No special expansion. 4832 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4833 } 4834 4835 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4836 /// limited-precision mode with x == 10.0f. 4837 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4838 SelectionDAG &DAG, const TargetLowering &TLI) { 4839 bool IsExp10 = false; 4840 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4841 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4842 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4843 APFloat Ten(10.0f); 4844 IsExp10 = LHSC->isExactlyValue(Ten); 4845 } 4846 } 4847 4848 // TODO: What fast-math-flags should be set on the FMUL node? 4849 if (IsExp10) { 4850 // Put the exponent in the right bit position for later addition to the 4851 // final result: 4852 // 4853 // #define LOG2OF10 3.3219281f 4854 // t0 = Op * LOG2OF10; 4855 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4856 getF32Constant(DAG, 0x40549a78, dl)); 4857 return getLimitedPrecisionExp2(t0, dl, DAG); 4858 } 4859 4860 // No special expansion. 4861 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4862 } 4863 4864 /// ExpandPowI - Expand a llvm.powi intrinsic. 4865 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4866 SelectionDAG &DAG) { 4867 // If RHS is a constant, we can expand this out to a multiplication tree, 4868 // otherwise we end up lowering to a call to __powidf2 (for example). When 4869 // optimizing for size, we only want to do this if the expansion would produce 4870 // a small number of multiplies, otherwise we do the full expansion. 4871 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4872 // Get the exponent as a positive value. 4873 unsigned Val = RHSC->getSExtValue(); 4874 if ((int)Val < 0) Val = -Val; 4875 4876 // powi(x, 0) -> 1.0 4877 if (Val == 0) 4878 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4879 4880 const Function &F = DAG.getMachineFunction().getFunction(); 4881 if (!F.optForSize() || 4882 // If optimizing for size, don't insert too many multiplies. 4883 // This inserts up to 5 multiplies. 4884 countPopulation(Val) + Log2_32(Val) < 7) { 4885 // We use the simple binary decomposition method to generate the multiply 4886 // sequence. There are more optimal ways to do this (for example, 4887 // powi(x,15) generates one more multiply than it should), but this has 4888 // the benefit of being both really simple and much better than a libcall. 4889 SDValue Res; // Logically starts equal to 1.0 4890 SDValue CurSquare = LHS; 4891 // TODO: Intrinsics should have fast-math-flags that propagate to these 4892 // nodes. 4893 while (Val) { 4894 if (Val & 1) { 4895 if (Res.getNode()) 4896 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4897 else 4898 Res = CurSquare; // 1.0*CurSquare. 4899 } 4900 4901 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4902 CurSquare, CurSquare); 4903 Val >>= 1; 4904 } 4905 4906 // If the original was negative, invert the result, producing 1/(x*x*x). 4907 if (RHSC->getSExtValue() < 0) 4908 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4909 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4910 return Res; 4911 } 4912 } 4913 4914 // Otherwise, expand to a libcall. 4915 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4916 } 4917 4918 // getUnderlyingArgReg - Find underlying register used for a truncated or 4919 // bitcasted argument. 4920 static unsigned getUnderlyingArgReg(const SDValue &N) { 4921 switch (N.getOpcode()) { 4922 case ISD::CopyFromReg: 4923 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4924 case ISD::BITCAST: 4925 case ISD::AssertZext: 4926 case ISD::AssertSext: 4927 case ISD::TRUNCATE: 4928 return getUnderlyingArgReg(N.getOperand(0)); 4929 default: 4930 return 0; 4931 } 4932 } 4933 4934 /// If the DbgValueInst is a dbg_value of a function argument, create the 4935 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4936 /// instruction selection, they will be inserted to the entry BB. 4937 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4938 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4939 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4940 const Argument *Arg = dyn_cast<Argument>(V); 4941 if (!Arg) 4942 return false; 4943 4944 MachineFunction &MF = DAG.getMachineFunction(); 4945 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4946 4947 bool IsIndirect = false; 4948 Optional<MachineOperand> Op; 4949 // Some arguments' frame index is recorded during argument lowering. 4950 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4951 if (FI != std::numeric_limits<int>::max()) 4952 Op = MachineOperand::CreateFI(FI); 4953 4954 if (!Op && N.getNode()) { 4955 unsigned Reg = getUnderlyingArgReg(N); 4956 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4957 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4958 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4959 if (PR) 4960 Reg = PR; 4961 } 4962 if (Reg) { 4963 Op = MachineOperand::CreateReg(Reg, false); 4964 IsIndirect = IsDbgDeclare; 4965 } 4966 } 4967 4968 if (!Op && N.getNode()) 4969 // Check if frame index is available. 4970 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4971 if (FrameIndexSDNode *FINode = 4972 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4973 Op = MachineOperand::CreateFI(FINode->getIndex()); 4974 4975 if (!Op) { 4976 // Check if ValueMap has reg number. 4977 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4978 if (VMI != FuncInfo.ValueMap.end()) { 4979 const auto &TLI = DAG.getTargetLoweringInfo(); 4980 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4981 V->getType(), getABIRegCopyCC(V)); 4982 if (RFV.occupiesMultipleRegs()) { 4983 unsigned Offset = 0; 4984 for (auto RegAndSize : RFV.getRegsAndSizes()) { 4985 Op = MachineOperand::CreateReg(RegAndSize.first, false); 4986 auto FragmentExpr = DIExpression::createFragmentExpression( 4987 Expr, Offset, RegAndSize.second); 4988 if (!FragmentExpr) 4989 continue; 4990 FuncInfo.ArgDbgValues.push_back( 4991 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4992 Op->getReg(), Variable, *FragmentExpr)); 4993 Offset += RegAndSize.second; 4994 } 4995 return true; 4996 } 4997 Op = MachineOperand::CreateReg(VMI->second, false); 4998 IsIndirect = IsDbgDeclare; 4999 } 5000 } 5001 5002 if (!Op) 5003 return false; 5004 5005 assert(Variable->isValidLocationForIntrinsic(DL) && 5006 "Expected inlined-at fields to agree"); 5007 IsIndirect = (Op->isReg()) ? IsIndirect : true; 5008 FuncInfo.ArgDbgValues.push_back( 5009 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 5010 *Op, Variable, Expr)); 5011 5012 return true; 5013 } 5014 5015 /// Return the appropriate SDDbgValue based on N. 5016 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 5017 DILocalVariable *Variable, 5018 DIExpression *Expr, 5019 const DebugLoc &dl, 5020 unsigned DbgSDNodeOrder) { 5021 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 5022 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 5023 // stack slot locations. 5024 // 5025 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting 5026 // debug values here after optimization: 5027 // 5028 // dbg.value(i32* %px, !"int *px", !DIExpression()), and 5029 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref)) 5030 // 5031 // Both describe the direct values of their associated variables. 5032 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), 5033 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5034 } 5035 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), 5036 /*IsIndirect*/ false, dl, DbgSDNodeOrder); 5037 } 5038 5039 // VisualStudio defines setjmp as _setjmp 5040 #if defined(_MSC_VER) && defined(setjmp) && \ 5041 !defined(setjmp_undefined_for_msvc) 5042 # pragma push_macro("setjmp") 5043 # undef setjmp 5044 # define setjmp_undefined_for_msvc 5045 #endif 5046 5047 /// Lower the call to the specified intrinsic function. If we want to emit this 5048 /// as a call to a named external function, return the name. Otherwise, lower it 5049 /// and return null. 5050 const char * 5051 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 5052 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5053 SDLoc sdl = getCurSDLoc(); 5054 DebugLoc dl = getCurDebugLoc(); 5055 SDValue Res; 5056 5057 switch (Intrinsic) { 5058 default: 5059 // By default, turn this into a target intrinsic node. 5060 visitTargetIntrinsic(I, Intrinsic); 5061 return nullptr; 5062 case Intrinsic::vastart: visitVAStart(I); return nullptr; 5063 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 5064 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 5065 case Intrinsic::returnaddress: 5066 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 5067 TLI.getPointerTy(DAG.getDataLayout()), 5068 getValue(I.getArgOperand(0)))); 5069 return nullptr; 5070 case Intrinsic::addressofreturnaddress: 5071 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 5072 TLI.getPointerTy(DAG.getDataLayout()))); 5073 return nullptr; 5074 case Intrinsic::sponentry: 5075 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl, 5076 TLI.getPointerTy(DAG.getDataLayout()))); 5077 return nullptr; 5078 case Intrinsic::frameaddress: 5079 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 5080 TLI.getPointerTy(DAG.getDataLayout()), 5081 getValue(I.getArgOperand(0)))); 5082 return nullptr; 5083 case Intrinsic::read_register: { 5084 Value *Reg = I.getArgOperand(0); 5085 SDValue Chain = getRoot(); 5086 SDValue RegName = 5087 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5088 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5089 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 5090 DAG.getVTList(VT, MVT::Other), Chain, RegName); 5091 setValue(&I, Res); 5092 DAG.setRoot(Res.getValue(1)); 5093 return nullptr; 5094 } 5095 case Intrinsic::write_register: { 5096 Value *Reg = I.getArgOperand(0); 5097 Value *RegValue = I.getArgOperand(1); 5098 SDValue Chain = getRoot(); 5099 SDValue RegName = 5100 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 5101 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 5102 RegName, getValue(RegValue))); 5103 return nullptr; 5104 } 5105 case Intrinsic::setjmp: 5106 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 5107 case Intrinsic::longjmp: 5108 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 5109 case Intrinsic::memcpy: { 5110 const auto &MCI = cast<MemCpyInst>(I); 5111 SDValue Op1 = getValue(I.getArgOperand(0)); 5112 SDValue Op2 = getValue(I.getArgOperand(1)); 5113 SDValue Op3 = getValue(I.getArgOperand(2)); 5114 // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5115 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1); 5116 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1); 5117 unsigned Align = MinAlign(DstAlign, SrcAlign); 5118 bool isVol = MCI.isVolatile(); 5119 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5120 // FIXME: Support passing different dest/src alignments to the memcpy DAG 5121 // node. 5122 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5123 false, isTC, 5124 MachinePointerInfo(I.getArgOperand(0)), 5125 MachinePointerInfo(I.getArgOperand(1))); 5126 updateDAGForMaybeTailCall(MC); 5127 return nullptr; 5128 } 5129 case Intrinsic::memset: { 5130 const auto &MSI = cast<MemSetInst>(I); 5131 SDValue Op1 = getValue(I.getArgOperand(0)); 5132 SDValue Op2 = getValue(I.getArgOperand(1)); 5133 SDValue Op3 = getValue(I.getArgOperand(2)); 5134 // @llvm.memset defines 0 and 1 to both mean no alignment. 5135 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1); 5136 bool isVol = MSI.isVolatile(); 5137 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5138 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5139 isTC, MachinePointerInfo(I.getArgOperand(0))); 5140 updateDAGForMaybeTailCall(MS); 5141 return nullptr; 5142 } 5143 case Intrinsic::memmove: { 5144 const auto &MMI = cast<MemMoveInst>(I); 5145 SDValue Op1 = getValue(I.getArgOperand(0)); 5146 SDValue Op2 = getValue(I.getArgOperand(1)); 5147 SDValue Op3 = getValue(I.getArgOperand(2)); 5148 // @llvm.memmove defines 0 and 1 to both mean no alignment. 5149 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1); 5150 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1); 5151 unsigned Align = MinAlign(DstAlign, SrcAlign); 5152 bool isVol = MMI.isVolatile(); 5153 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5154 // FIXME: Support passing different dest/src alignments to the memmove DAG 5155 // node. 5156 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5157 isTC, MachinePointerInfo(I.getArgOperand(0)), 5158 MachinePointerInfo(I.getArgOperand(1))); 5159 updateDAGForMaybeTailCall(MM); 5160 return nullptr; 5161 } 5162 case Intrinsic::memcpy_element_unordered_atomic: { 5163 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5164 SDValue Dst = getValue(MI.getRawDest()); 5165 SDValue Src = getValue(MI.getRawSource()); 5166 SDValue Length = getValue(MI.getLength()); 5167 5168 unsigned DstAlign = MI.getDestAlignment(); 5169 unsigned SrcAlign = MI.getSourceAlignment(); 5170 Type *LengthTy = MI.getLength()->getType(); 5171 unsigned ElemSz = MI.getElementSizeInBytes(); 5172 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5173 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src, 5174 SrcAlign, Length, LengthTy, ElemSz, isTC, 5175 MachinePointerInfo(MI.getRawDest()), 5176 MachinePointerInfo(MI.getRawSource())); 5177 updateDAGForMaybeTailCall(MC); 5178 return nullptr; 5179 } 5180 case Intrinsic::memmove_element_unordered_atomic: { 5181 auto &MI = cast<AtomicMemMoveInst>(I); 5182 SDValue Dst = getValue(MI.getRawDest()); 5183 SDValue Src = getValue(MI.getRawSource()); 5184 SDValue Length = getValue(MI.getLength()); 5185 5186 unsigned DstAlign = MI.getDestAlignment(); 5187 unsigned SrcAlign = MI.getSourceAlignment(); 5188 Type *LengthTy = MI.getLength()->getType(); 5189 unsigned ElemSz = MI.getElementSizeInBytes(); 5190 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5191 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src, 5192 SrcAlign, Length, LengthTy, ElemSz, isTC, 5193 MachinePointerInfo(MI.getRawDest()), 5194 MachinePointerInfo(MI.getRawSource())); 5195 updateDAGForMaybeTailCall(MC); 5196 return nullptr; 5197 } 5198 case Intrinsic::memset_element_unordered_atomic: { 5199 auto &MI = cast<AtomicMemSetInst>(I); 5200 SDValue Dst = getValue(MI.getRawDest()); 5201 SDValue Val = getValue(MI.getValue()); 5202 SDValue Length = getValue(MI.getLength()); 5203 5204 unsigned DstAlign = MI.getDestAlignment(); 5205 Type *LengthTy = MI.getLength()->getType(); 5206 unsigned ElemSz = MI.getElementSizeInBytes(); 5207 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5208 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length, 5209 LengthTy, ElemSz, isTC, 5210 MachinePointerInfo(MI.getRawDest())); 5211 updateDAGForMaybeTailCall(MC); 5212 return nullptr; 5213 } 5214 case Intrinsic::dbg_addr: 5215 case Intrinsic::dbg_declare: { 5216 const auto &DI = cast<DbgVariableIntrinsic>(I); 5217 DILocalVariable *Variable = DI.getVariable(); 5218 DIExpression *Expression = DI.getExpression(); 5219 dropDanglingDebugInfo(Variable, Expression); 5220 assert(Variable && "Missing variable"); 5221 5222 // Check if address has undef value. 5223 const Value *Address = DI.getVariableLocation(); 5224 if (!Address || isa<UndefValue>(Address) || 5225 (Address->use_empty() && !isa<Argument>(Address))) { 5226 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5227 return nullptr; 5228 } 5229 5230 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5231 5232 // Check if this variable can be described by a frame index, typically 5233 // either as a static alloca or a byval parameter. 5234 int FI = std::numeric_limits<int>::max(); 5235 if (const auto *AI = 5236 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5237 if (AI->isStaticAlloca()) { 5238 auto I = FuncInfo.StaticAllocaMap.find(AI); 5239 if (I != FuncInfo.StaticAllocaMap.end()) 5240 FI = I->second; 5241 } 5242 } else if (const auto *Arg = dyn_cast<Argument>( 5243 Address->stripInBoundsConstantOffsets())) { 5244 FI = FuncInfo.getArgumentFrameIndex(Arg); 5245 } 5246 5247 // llvm.dbg.addr is control dependent and always generates indirect 5248 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5249 // the MachineFunction variable table. 5250 if (FI != std::numeric_limits<int>::max()) { 5251 if (Intrinsic == Intrinsic::dbg_addr) { 5252 SDDbgValue *SDV = DAG.getFrameIndexDbgValue( 5253 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder); 5254 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter); 5255 } 5256 return nullptr; 5257 } 5258 5259 SDValue &N = NodeMap[Address]; 5260 if (!N.getNode() && isa<Argument>(Address)) 5261 // Check unused arguments map. 5262 N = UnusedArgNodeMap[Address]; 5263 SDDbgValue *SDV; 5264 if (N.getNode()) { 5265 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5266 Address = BCI->getOperand(0); 5267 // Parameters are handled specially. 5268 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5269 if (isParameter && FINode) { 5270 // Byval parameter. We have a frame index at this point. 5271 SDV = 5272 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(), 5273 /*IsIndirect*/ true, dl, SDNodeOrder); 5274 } else if (isa<Argument>(Address)) { 5275 // Address is an argument, so try to emit its dbg value using 5276 // virtual register info from the FuncInfo.ValueMap. 5277 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5278 return nullptr; 5279 } else { 5280 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5281 true, dl, SDNodeOrder); 5282 } 5283 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5284 } else { 5285 // If Address is an argument then try to emit its dbg value using 5286 // virtual register info from the FuncInfo.ValueMap. 5287 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5288 N)) { 5289 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5290 } 5291 } 5292 return nullptr; 5293 } 5294 case Intrinsic::dbg_label: { 5295 const DbgLabelInst &DI = cast<DbgLabelInst>(I); 5296 DILabel *Label = DI.getLabel(); 5297 assert(Label && "Missing label"); 5298 5299 SDDbgLabel *SDV; 5300 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder); 5301 DAG.AddDbgLabel(SDV); 5302 return nullptr; 5303 } 5304 case Intrinsic::dbg_value: { 5305 const DbgValueInst &DI = cast<DbgValueInst>(I); 5306 assert(DI.getVariable() && "Missing variable"); 5307 5308 DILocalVariable *Variable = DI.getVariable(); 5309 DIExpression *Expression = DI.getExpression(); 5310 dropDanglingDebugInfo(Variable, Expression); 5311 const Value *V = DI.getValue(); 5312 if (!V) 5313 return nullptr; 5314 5315 SDDbgValue *SDV; 5316 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) || 5317 isa<ConstantPointerNull>(V)) { 5318 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5319 DAG.AddDbgValue(SDV, nullptr, false); 5320 return nullptr; 5321 } 5322 5323 // If the Value is a frame index, we can create a FrameIndex debug value 5324 // without relying on the DAG at all. 5325 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 5326 auto SI = FuncInfo.StaticAllocaMap.find(AI); 5327 if (SI != FuncInfo.StaticAllocaMap.end()) { 5328 auto SDV = 5329 DAG.getFrameIndexDbgValue(Variable, Expression, SI->second, 5330 /*IsIndirect*/ false, dl, SDNodeOrder); 5331 // Do not attach the SDNodeDbgValue to an SDNode: this variable location 5332 // is still available even if the SDNode gets optimized out. 5333 DAG.AddDbgValue(SDV, nullptr, false); 5334 return nullptr; 5335 } 5336 } 5337 5338 // Do not use getValue() in here; we don't want to generate code at 5339 // this point if it hasn't been done yet. 5340 SDValue N = NodeMap[V]; 5341 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5342 N = UnusedArgNodeMap[V]; 5343 if (N.getNode()) { 5344 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5345 return nullptr; 5346 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5347 DAG.AddDbgValue(SDV, N.getNode(), false); 5348 return nullptr; 5349 } 5350 5351 // The value is not used in this block yet (or it would have an SDNode). 5352 // We still want the value to appear for the user if possible -- if it has 5353 // an associated VReg, we can refer to that instead. 5354 if (!isa<Argument>(V)) { 5355 auto VMI = FuncInfo.ValueMap.find(V); 5356 if (VMI != FuncInfo.ValueMap.end()) { 5357 unsigned Reg = VMI->second; 5358 // If this is a PHI node, it may be split up into several MI PHI nodes 5359 // (in FunctionLoweringInfo::set). 5360 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 5361 V->getType(), None); 5362 if (RFV.occupiesMultipleRegs()) { 5363 unsigned Offset = 0; 5364 unsigned BitsToDescribe = 0; 5365 if (auto VarSize = Variable->getSizeInBits()) 5366 BitsToDescribe = *VarSize; 5367 if (auto Fragment = Expression->getFragmentInfo()) 5368 BitsToDescribe = Fragment->SizeInBits; 5369 for (auto RegAndSize : RFV.getRegsAndSizes()) { 5370 unsigned RegisterSize = RegAndSize.second; 5371 // Bail out if all bits are described already. 5372 if (Offset >= BitsToDescribe) 5373 break; 5374 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe) 5375 ? BitsToDescribe - Offset 5376 : RegisterSize; 5377 auto FragmentExpr = DIExpression::createFragmentExpression( 5378 Expression, Offset, FragmentSize); 5379 if (!FragmentExpr) 5380 continue; 5381 SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first, 5382 false, dl, SDNodeOrder); 5383 DAG.AddDbgValue(SDV, nullptr, false); 5384 Offset += RegisterSize; 5385 } 5386 } else { 5387 SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl, 5388 SDNodeOrder); 5389 DAG.AddDbgValue(SDV, nullptr, false); 5390 } 5391 return nullptr; 5392 } 5393 } 5394 5395 // TODO: When we get here we will either drop the dbg.value completely, or 5396 // we try to move it forward by letting it dangle for awhile. So we should 5397 // probably add an extra DbgValue to the DAG here, with a reference to 5398 // "noreg", to indicate that we have lost the debug location for the 5399 // variable. 5400 5401 if (!V->use_empty() ) { 5402 // Do not call getValue(V) yet, as we don't want to generate code. 5403 // Remember it for later. 5404 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder); 5405 return nullptr; 5406 } 5407 5408 LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5409 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5410 return nullptr; 5411 } 5412 5413 case Intrinsic::eh_typeid_for: { 5414 // Find the type id for the given typeinfo. 5415 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5416 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5417 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5418 setValue(&I, Res); 5419 return nullptr; 5420 } 5421 5422 case Intrinsic::eh_return_i32: 5423 case Intrinsic::eh_return_i64: 5424 DAG.getMachineFunction().setCallsEHReturn(true); 5425 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5426 MVT::Other, 5427 getControlRoot(), 5428 getValue(I.getArgOperand(0)), 5429 getValue(I.getArgOperand(1)))); 5430 return nullptr; 5431 case Intrinsic::eh_unwind_init: 5432 DAG.getMachineFunction().setCallsUnwindInit(true); 5433 return nullptr; 5434 case Intrinsic::eh_dwarf_cfa: 5435 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5436 TLI.getPointerTy(DAG.getDataLayout()), 5437 getValue(I.getArgOperand(0)))); 5438 return nullptr; 5439 case Intrinsic::eh_sjlj_callsite: { 5440 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5441 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5442 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5443 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5444 5445 MMI.setCurrentCallSite(CI->getZExtValue()); 5446 return nullptr; 5447 } 5448 case Intrinsic::eh_sjlj_functioncontext: { 5449 // Get and store the index of the function context. 5450 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5451 AllocaInst *FnCtx = 5452 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5453 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5454 MFI.setFunctionContextIndex(FI); 5455 return nullptr; 5456 } 5457 case Intrinsic::eh_sjlj_setjmp: { 5458 SDValue Ops[2]; 5459 Ops[0] = getRoot(); 5460 Ops[1] = getValue(I.getArgOperand(0)); 5461 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5462 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5463 setValue(&I, Op.getValue(0)); 5464 DAG.setRoot(Op.getValue(1)); 5465 return nullptr; 5466 } 5467 case Intrinsic::eh_sjlj_longjmp: 5468 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5469 getRoot(), getValue(I.getArgOperand(0)))); 5470 return nullptr; 5471 case Intrinsic::eh_sjlj_setup_dispatch: 5472 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5473 getRoot())); 5474 return nullptr; 5475 case Intrinsic::masked_gather: 5476 visitMaskedGather(I); 5477 return nullptr; 5478 case Intrinsic::masked_load: 5479 visitMaskedLoad(I); 5480 return nullptr; 5481 case Intrinsic::masked_scatter: 5482 visitMaskedScatter(I); 5483 return nullptr; 5484 case Intrinsic::masked_store: 5485 visitMaskedStore(I); 5486 return nullptr; 5487 case Intrinsic::masked_expandload: 5488 visitMaskedLoad(I, true /* IsExpanding */); 5489 return nullptr; 5490 case Intrinsic::masked_compressstore: 5491 visitMaskedStore(I, true /* IsCompressing */); 5492 return nullptr; 5493 case Intrinsic::x86_mmx_pslli_w: 5494 case Intrinsic::x86_mmx_pslli_d: 5495 case Intrinsic::x86_mmx_pslli_q: 5496 case Intrinsic::x86_mmx_psrli_w: 5497 case Intrinsic::x86_mmx_psrli_d: 5498 case Intrinsic::x86_mmx_psrli_q: 5499 case Intrinsic::x86_mmx_psrai_w: 5500 case Intrinsic::x86_mmx_psrai_d: { 5501 SDValue ShAmt = getValue(I.getArgOperand(1)); 5502 if (isa<ConstantSDNode>(ShAmt)) { 5503 visitTargetIntrinsic(I, Intrinsic); 5504 return nullptr; 5505 } 5506 unsigned NewIntrinsic = 0; 5507 EVT ShAmtVT = MVT::v2i32; 5508 switch (Intrinsic) { 5509 case Intrinsic::x86_mmx_pslli_w: 5510 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5511 break; 5512 case Intrinsic::x86_mmx_pslli_d: 5513 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5514 break; 5515 case Intrinsic::x86_mmx_pslli_q: 5516 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5517 break; 5518 case Intrinsic::x86_mmx_psrli_w: 5519 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5520 break; 5521 case Intrinsic::x86_mmx_psrli_d: 5522 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5523 break; 5524 case Intrinsic::x86_mmx_psrli_q: 5525 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5526 break; 5527 case Intrinsic::x86_mmx_psrai_w: 5528 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5529 break; 5530 case Intrinsic::x86_mmx_psrai_d: 5531 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5532 break; 5533 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5534 } 5535 5536 // The vector shift intrinsics with scalars uses 32b shift amounts but 5537 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5538 // to be zero. 5539 // We must do this early because v2i32 is not a legal type. 5540 SDValue ShOps[2]; 5541 ShOps[0] = ShAmt; 5542 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5543 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5544 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5545 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5546 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5547 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5548 getValue(I.getArgOperand(0)), ShAmt); 5549 setValue(&I, Res); 5550 return nullptr; 5551 } 5552 case Intrinsic::powi: 5553 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5554 getValue(I.getArgOperand(1)), DAG)); 5555 return nullptr; 5556 case Intrinsic::log: 5557 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5558 return nullptr; 5559 case Intrinsic::log2: 5560 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5561 return nullptr; 5562 case Intrinsic::log10: 5563 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5564 return nullptr; 5565 case Intrinsic::exp: 5566 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5567 return nullptr; 5568 case Intrinsic::exp2: 5569 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5570 return nullptr; 5571 case Intrinsic::pow: 5572 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5573 getValue(I.getArgOperand(1)), DAG, TLI)); 5574 return nullptr; 5575 case Intrinsic::sqrt: 5576 case Intrinsic::fabs: 5577 case Intrinsic::sin: 5578 case Intrinsic::cos: 5579 case Intrinsic::floor: 5580 case Intrinsic::ceil: 5581 case Intrinsic::trunc: 5582 case Intrinsic::rint: 5583 case Intrinsic::nearbyint: 5584 case Intrinsic::round: 5585 case Intrinsic::canonicalize: { 5586 unsigned Opcode; 5587 switch (Intrinsic) { 5588 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5589 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5590 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5591 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5592 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5593 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5594 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5595 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5596 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5597 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5598 case Intrinsic::round: Opcode = ISD::FROUND; break; 5599 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5600 } 5601 5602 setValue(&I, DAG.getNode(Opcode, sdl, 5603 getValue(I.getArgOperand(0)).getValueType(), 5604 getValue(I.getArgOperand(0)))); 5605 return nullptr; 5606 } 5607 case Intrinsic::minnum: { 5608 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5609 unsigned Opc = 5610 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT) 5611 ? ISD::FMINIMUM 5612 : ISD::FMINNUM; 5613 setValue(&I, DAG.getNode(Opc, sdl, VT, 5614 getValue(I.getArgOperand(0)), 5615 getValue(I.getArgOperand(1)))); 5616 return nullptr; 5617 } 5618 case Intrinsic::maxnum: { 5619 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5620 unsigned Opc = 5621 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT) 5622 ? ISD::FMAXIMUM 5623 : ISD::FMAXNUM; 5624 setValue(&I, DAG.getNode(Opc, sdl, VT, 5625 getValue(I.getArgOperand(0)), 5626 getValue(I.getArgOperand(1)))); 5627 return nullptr; 5628 } 5629 case Intrinsic::minimum: 5630 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl, 5631 getValue(I.getArgOperand(0)).getValueType(), 5632 getValue(I.getArgOperand(0)), 5633 getValue(I.getArgOperand(1)))); 5634 return nullptr; 5635 case Intrinsic::maximum: 5636 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl, 5637 getValue(I.getArgOperand(0)).getValueType(), 5638 getValue(I.getArgOperand(0)), 5639 getValue(I.getArgOperand(1)))); 5640 return nullptr; 5641 case Intrinsic::copysign: 5642 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5643 getValue(I.getArgOperand(0)).getValueType(), 5644 getValue(I.getArgOperand(0)), 5645 getValue(I.getArgOperand(1)))); 5646 return nullptr; 5647 case Intrinsic::fma: 5648 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5649 getValue(I.getArgOperand(0)).getValueType(), 5650 getValue(I.getArgOperand(0)), 5651 getValue(I.getArgOperand(1)), 5652 getValue(I.getArgOperand(2)))); 5653 return nullptr; 5654 case Intrinsic::experimental_constrained_fadd: 5655 case Intrinsic::experimental_constrained_fsub: 5656 case Intrinsic::experimental_constrained_fmul: 5657 case Intrinsic::experimental_constrained_fdiv: 5658 case Intrinsic::experimental_constrained_frem: 5659 case Intrinsic::experimental_constrained_fma: 5660 case Intrinsic::experimental_constrained_sqrt: 5661 case Intrinsic::experimental_constrained_pow: 5662 case Intrinsic::experimental_constrained_powi: 5663 case Intrinsic::experimental_constrained_sin: 5664 case Intrinsic::experimental_constrained_cos: 5665 case Intrinsic::experimental_constrained_exp: 5666 case Intrinsic::experimental_constrained_exp2: 5667 case Intrinsic::experimental_constrained_log: 5668 case Intrinsic::experimental_constrained_log10: 5669 case Intrinsic::experimental_constrained_log2: 5670 case Intrinsic::experimental_constrained_rint: 5671 case Intrinsic::experimental_constrained_nearbyint: 5672 case Intrinsic::experimental_constrained_maxnum: 5673 case Intrinsic::experimental_constrained_minnum: 5674 case Intrinsic::experimental_constrained_ceil: 5675 case Intrinsic::experimental_constrained_floor: 5676 case Intrinsic::experimental_constrained_round: 5677 case Intrinsic::experimental_constrained_trunc: 5678 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5679 return nullptr; 5680 case Intrinsic::fmuladd: { 5681 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5682 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5683 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5684 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5685 getValue(I.getArgOperand(0)).getValueType(), 5686 getValue(I.getArgOperand(0)), 5687 getValue(I.getArgOperand(1)), 5688 getValue(I.getArgOperand(2)))); 5689 } else { 5690 // TODO: Intrinsic calls should have fast-math-flags. 5691 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5692 getValue(I.getArgOperand(0)).getValueType(), 5693 getValue(I.getArgOperand(0)), 5694 getValue(I.getArgOperand(1))); 5695 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5696 getValue(I.getArgOperand(0)).getValueType(), 5697 Mul, 5698 getValue(I.getArgOperand(2))); 5699 setValue(&I, Add); 5700 } 5701 return nullptr; 5702 } 5703 case Intrinsic::convert_to_fp16: 5704 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5705 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5706 getValue(I.getArgOperand(0)), 5707 DAG.getTargetConstant(0, sdl, 5708 MVT::i32)))); 5709 return nullptr; 5710 case Intrinsic::convert_from_fp16: 5711 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5712 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5713 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5714 getValue(I.getArgOperand(0))))); 5715 return nullptr; 5716 case Intrinsic::pcmarker: { 5717 SDValue Tmp = getValue(I.getArgOperand(0)); 5718 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5719 return nullptr; 5720 } 5721 case Intrinsic::readcyclecounter: { 5722 SDValue Op = getRoot(); 5723 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5724 DAG.getVTList(MVT::i64, MVT::Other), Op); 5725 setValue(&I, Res); 5726 DAG.setRoot(Res.getValue(1)); 5727 return nullptr; 5728 } 5729 case Intrinsic::bitreverse: 5730 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5731 getValue(I.getArgOperand(0)).getValueType(), 5732 getValue(I.getArgOperand(0)))); 5733 return nullptr; 5734 case Intrinsic::bswap: 5735 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5736 getValue(I.getArgOperand(0)).getValueType(), 5737 getValue(I.getArgOperand(0)))); 5738 return nullptr; 5739 case Intrinsic::cttz: { 5740 SDValue Arg = getValue(I.getArgOperand(0)); 5741 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5742 EVT Ty = Arg.getValueType(); 5743 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5744 sdl, Ty, Arg)); 5745 return nullptr; 5746 } 5747 case Intrinsic::ctlz: { 5748 SDValue Arg = getValue(I.getArgOperand(0)); 5749 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5750 EVT Ty = Arg.getValueType(); 5751 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5752 sdl, Ty, Arg)); 5753 return nullptr; 5754 } 5755 case Intrinsic::ctpop: { 5756 SDValue Arg = getValue(I.getArgOperand(0)); 5757 EVT Ty = Arg.getValueType(); 5758 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5759 return nullptr; 5760 } 5761 case Intrinsic::fshl: 5762 case Intrinsic::fshr: { 5763 bool IsFSHL = Intrinsic == Intrinsic::fshl; 5764 SDValue X = getValue(I.getArgOperand(0)); 5765 SDValue Y = getValue(I.getArgOperand(1)); 5766 SDValue Z = getValue(I.getArgOperand(2)); 5767 EVT VT = X.getValueType(); 5768 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT); 5769 SDValue Zero = DAG.getConstant(0, sdl, VT); 5770 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC); 5771 5772 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR; 5773 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) { 5774 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z)); 5775 return nullptr; 5776 } 5777 5778 // When X == Y, this is rotate. If the data type has a power-of-2 size, we 5779 // avoid the select that is necessary in the general case to filter out 5780 // the 0-shift possibility that leads to UB. 5781 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) { 5782 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR; 5783 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5784 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z)); 5785 return nullptr; 5786 } 5787 5788 // Some targets only rotate one way. Try the opposite direction. 5789 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL; 5790 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) { 5791 // Negate the shift amount because it is safe to ignore the high bits. 5792 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5793 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt)); 5794 return nullptr; 5795 } 5796 5797 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW)) 5798 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW)) 5799 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z); 5800 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC); 5801 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt); 5802 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt); 5803 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY)); 5804 return nullptr; 5805 } 5806 5807 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 5808 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 5809 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt); 5810 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt); 5811 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt); 5812 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY); 5813 5814 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 5815 // and that is undefined. We must compare and select to avoid UB. 5816 EVT CCVT = MVT::i1; 5817 if (VT.isVector()) 5818 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements()); 5819 5820 // For fshl, 0-shift returns the 1st arg (X). 5821 // For fshr, 0-shift returns the 2nd arg (Y). 5822 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ); 5823 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or)); 5824 return nullptr; 5825 } 5826 case Intrinsic::sadd_sat: { 5827 SDValue Op1 = getValue(I.getArgOperand(0)); 5828 SDValue Op2 = getValue(I.getArgOperand(1)); 5829 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5830 return nullptr; 5831 } 5832 case Intrinsic::uadd_sat: { 5833 SDValue Op1 = getValue(I.getArgOperand(0)); 5834 SDValue Op2 = getValue(I.getArgOperand(1)); 5835 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2)); 5836 return nullptr; 5837 } 5838 case Intrinsic::ssub_sat: { 5839 SDValue Op1 = getValue(I.getArgOperand(0)); 5840 SDValue Op2 = getValue(I.getArgOperand(1)); 5841 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5842 return nullptr; 5843 } 5844 case Intrinsic::usub_sat: { 5845 SDValue Op1 = getValue(I.getArgOperand(0)); 5846 SDValue Op2 = getValue(I.getArgOperand(1)); 5847 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2)); 5848 return nullptr; 5849 } 5850 case Intrinsic::smul_fix: { 5851 SDValue Op1 = getValue(I.getArgOperand(0)); 5852 SDValue Op2 = getValue(I.getArgOperand(1)); 5853 SDValue Op3 = getValue(I.getArgOperand(2)); 5854 setValue(&I, 5855 DAG.getNode(ISD::SMULFIX, sdl, Op1.getValueType(), Op1, Op2, Op3)); 5856 return nullptr; 5857 } 5858 case Intrinsic::stacksave: { 5859 SDValue Op = getRoot(); 5860 Res = DAG.getNode( 5861 ISD::STACKSAVE, sdl, 5862 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5863 setValue(&I, Res); 5864 DAG.setRoot(Res.getValue(1)); 5865 return nullptr; 5866 } 5867 case Intrinsic::stackrestore: 5868 Res = getValue(I.getArgOperand(0)); 5869 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5870 return nullptr; 5871 case Intrinsic::get_dynamic_area_offset: { 5872 SDValue Op = getRoot(); 5873 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5874 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5875 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5876 // target. 5877 if (PtrTy != ResTy) 5878 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5879 " intrinsic!"); 5880 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5881 Op); 5882 DAG.setRoot(Op); 5883 setValue(&I, Res); 5884 return nullptr; 5885 } 5886 case Intrinsic::stackguard: { 5887 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5888 MachineFunction &MF = DAG.getMachineFunction(); 5889 const Module &M = *MF.getFunction().getParent(); 5890 SDValue Chain = getRoot(); 5891 if (TLI.useLoadStackGuardNode()) { 5892 Res = getLoadStackGuard(DAG, sdl, Chain); 5893 } else { 5894 const Value *Global = TLI.getSDagStackGuard(M); 5895 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5896 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5897 MachinePointerInfo(Global, 0), Align, 5898 MachineMemOperand::MOVolatile); 5899 } 5900 if (TLI.useStackGuardXorFP()) 5901 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl); 5902 DAG.setRoot(Chain); 5903 setValue(&I, Res); 5904 return nullptr; 5905 } 5906 case Intrinsic::stackprotector: { 5907 // Emit code into the DAG to store the stack guard onto the stack. 5908 MachineFunction &MF = DAG.getMachineFunction(); 5909 MachineFrameInfo &MFI = MF.getFrameInfo(); 5910 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5911 SDValue Src, Chain = getRoot(); 5912 5913 if (TLI.useLoadStackGuardNode()) 5914 Src = getLoadStackGuard(DAG, sdl, Chain); 5915 else 5916 Src = getValue(I.getArgOperand(0)); // The guard's value. 5917 5918 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5919 5920 int FI = FuncInfo.StaticAllocaMap[Slot]; 5921 MFI.setStackProtectorIndex(FI); 5922 5923 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5924 5925 // Store the stack protector onto the stack. 5926 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5927 DAG.getMachineFunction(), FI), 5928 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5929 setValue(&I, Res); 5930 DAG.setRoot(Res); 5931 return nullptr; 5932 } 5933 case Intrinsic::objectsize: { 5934 // If we don't know by now, we're never going to know. 5935 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5936 5937 assert(CI && "Non-constant type in __builtin_object_size?"); 5938 5939 SDValue Arg = getValue(I.getCalledValue()); 5940 EVT Ty = Arg.getValueType(); 5941 5942 if (CI->isZero()) 5943 Res = DAG.getConstant(-1ULL, sdl, Ty); 5944 else 5945 Res = DAG.getConstant(0, sdl, Ty); 5946 5947 setValue(&I, Res); 5948 return nullptr; 5949 } 5950 5951 case Intrinsic::is_constant: 5952 // If this wasn't constant-folded away by now, then it's not a 5953 // constant. 5954 setValue(&I, DAG.getConstant(0, sdl, MVT::i1)); 5955 return nullptr; 5956 5957 case Intrinsic::annotation: 5958 case Intrinsic::ptr_annotation: 5959 case Intrinsic::launder_invariant_group: 5960 case Intrinsic::strip_invariant_group: 5961 // Drop the intrinsic, but forward the value 5962 setValue(&I, getValue(I.getOperand(0))); 5963 return nullptr; 5964 case Intrinsic::assume: 5965 case Intrinsic::var_annotation: 5966 case Intrinsic::sideeffect: 5967 // Discard annotate attributes, assumptions, and artificial side-effects. 5968 return nullptr; 5969 5970 case Intrinsic::codeview_annotation: { 5971 // Emit a label associated with this metadata. 5972 MachineFunction &MF = DAG.getMachineFunction(); 5973 MCSymbol *Label = 5974 MF.getMMI().getContext().createTempSymbol("annotation", true); 5975 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5976 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5977 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5978 DAG.setRoot(Res); 5979 return nullptr; 5980 } 5981 5982 case Intrinsic::init_trampoline: { 5983 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5984 5985 SDValue Ops[6]; 5986 Ops[0] = getRoot(); 5987 Ops[1] = getValue(I.getArgOperand(0)); 5988 Ops[2] = getValue(I.getArgOperand(1)); 5989 Ops[3] = getValue(I.getArgOperand(2)); 5990 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5991 Ops[5] = DAG.getSrcValue(F); 5992 5993 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5994 5995 DAG.setRoot(Res); 5996 return nullptr; 5997 } 5998 case Intrinsic::adjust_trampoline: 5999 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 6000 TLI.getPointerTy(DAG.getDataLayout()), 6001 getValue(I.getArgOperand(0)))); 6002 return nullptr; 6003 case Intrinsic::gcroot: { 6004 assert(DAG.getMachineFunction().getFunction().hasGC() && 6005 "only valid in functions with gc specified, enforced by Verifier"); 6006 assert(GFI && "implied by previous"); 6007 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 6008 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 6009 6010 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 6011 GFI->addStackRoot(FI->getIndex(), TypeMap); 6012 return nullptr; 6013 } 6014 case Intrinsic::gcread: 6015 case Intrinsic::gcwrite: 6016 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 6017 case Intrinsic::flt_rounds: 6018 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 6019 return nullptr; 6020 6021 case Intrinsic::expect: 6022 // Just replace __builtin_expect(exp, c) with EXP. 6023 setValue(&I, getValue(I.getArgOperand(0))); 6024 return nullptr; 6025 6026 case Intrinsic::debugtrap: 6027 case Intrinsic::trap: { 6028 StringRef TrapFuncName = 6029 I.getAttributes() 6030 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 6031 .getValueAsString(); 6032 if (TrapFuncName.empty()) { 6033 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 6034 ISD::TRAP : ISD::DEBUGTRAP; 6035 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 6036 return nullptr; 6037 } 6038 TargetLowering::ArgListTy Args; 6039 6040 TargetLowering::CallLoweringInfo CLI(DAG); 6041 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 6042 CallingConv::C, I.getType(), 6043 DAG.getExternalSymbol(TrapFuncName.data(), 6044 TLI.getPointerTy(DAG.getDataLayout())), 6045 std::move(Args)); 6046 6047 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6048 DAG.setRoot(Result.second); 6049 return nullptr; 6050 } 6051 6052 case Intrinsic::uadd_with_overflow: 6053 case Intrinsic::sadd_with_overflow: 6054 case Intrinsic::usub_with_overflow: 6055 case Intrinsic::ssub_with_overflow: 6056 case Intrinsic::umul_with_overflow: 6057 case Intrinsic::smul_with_overflow: { 6058 ISD::NodeType Op; 6059 switch (Intrinsic) { 6060 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6061 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 6062 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 6063 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 6064 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 6065 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 6066 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 6067 } 6068 SDValue Op1 = getValue(I.getArgOperand(0)); 6069 SDValue Op2 = getValue(I.getArgOperand(1)); 6070 6071 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 6072 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 6073 return nullptr; 6074 } 6075 case Intrinsic::prefetch: { 6076 SDValue Ops[5]; 6077 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 6078 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore; 6079 Ops[0] = DAG.getRoot(); 6080 Ops[1] = getValue(I.getArgOperand(0)); 6081 Ops[2] = getValue(I.getArgOperand(1)); 6082 Ops[3] = getValue(I.getArgOperand(2)); 6083 Ops[4] = getValue(I.getArgOperand(3)); 6084 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 6085 DAG.getVTList(MVT::Other), Ops, 6086 EVT::getIntegerVT(*Context, 8), 6087 MachinePointerInfo(I.getArgOperand(0)), 6088 0, /* align */ 6089 Flags); 6090 6091 // Chain the prefetch in parallell with any pending loads, to stay out of 6092 // the way of later optimizations. 6093 PendingLoads.push_back(Result); 6094 Result = getRoot(); 6095 DAG.setRoot(Result); 6096 return nullptr; 6097 } 6098 case Intrinsic::lifetime_start: 6099 case Intrinsic::lifetime_end: { 6100 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 6101 // Stack coloring is not enabled in O0, discard region information. 6102 if (TM.getOptLevel() == CodeGenOpt::None) 6103 return nullptr; 6104 6105 SmallVector<Value *, 4> Allocas; 6106 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 6107 6108 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 6109 E = Allocas.end(); Object != E; ++Object) { 6110 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 6111 6112 // Could not find an Alloca. 6113 if (!LifetimeObject) 6114 continue; 6115 6116 // First check that the Alloca is static, otherwise it won't have a 6117 // valid frame index. 6118 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 6119 if (SI == FuncInfo.StaticAllocaMap.end()) 6120 return nullptr; 6121 6122 int FI = SI->second; 6123 6124 SDValue Ops[2]; 6125 Ops[0] = getRoot(); 6126 Ops[1] = 6127 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 6128 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 6129 6130 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 6131 DAG.setRoot(Res); 6132 } 6133 return nullptr; 6134 } 6135 case Intrinsic::invariant_start: 6136 // Discard region information. 6137 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 6138 return nullptr; 6139 case Intrinsic::invariant_end: 6140 // Discard region information. 6141 return nullptr; 6142 case Intrinsic::clear_cache: 6143 return TLI.getClearCacheBuiltinName(); 6144 case Intrinsic::donothing: 6145 // ignore 6146 return nullptr; 6147 case Intrinsic::experimental_stackmap: 6148 visitStackmap(I); 6149 return nullptr; 6150 case Intrinsic::experimental_patchpoint_void: 6151 case Intrinsic::experimental_patchpoint_i64: 6152 visitPatchpoint(&I); 6153 return nullptr; 6154 case Intrinsic::experimental_gc_statepoint: 6155 LowerStatepoint(ImmutableStatepoint(&I)); 6156 return nullptr; 6157 case Intrinsic::experimental_gc_result: 6158 visitGCResult(cast<GCResultInst>(I)); 6159 return nullptr; 6160 case Intrinsic::experimental_gc_relocate: 6161 visitGCRelocate(cast<GCRelocateInst>(I)); 6162 return nullptr; 6163 case Intrinsic::instrprof_increment: 6164 llvm_unreachable("instrprof failed to lower an increment"); 6165 case Intrinsic::instrprof_value_profile: 6166 llvm_unreachable("instrprof failed to lower a value profiling call"); 6167 case Intrinsic::localescape: { 6168 MachineFunction &MF = DAG.getMachineFunction(); 6169 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 6170 6171 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 6172 // is the same on all targets. 6173 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 6174 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 6175 if (isa<ConstantPointerNull>(Arg)) 6176 continue; // Skip null pointers. They represent a hole in index space. 6177 AllocaInst *Slot = cast<AllocaInst>(Arg); 6178 assert(FuncInfo.StaticAllocaMap.count(Slot) && 6179 "can only escape static allocas"); 6180 int FI = FuncInfo.StaticAllocaMap[Slot]; 6181 MCSymbol *FrameAllocSym = 6182 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6183 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 6184 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 6185 TII->get(TargetOpcode::LOCAL_ESCAPE)) 6186 .addSym(FrameAllocSym) 6187 .addFrameIndex(FI); 6188 } 6189 6190 MF.setHasLocalEscape(true); 6191 6192 return nullptr; 6193 } 6194 6195 case Intrinsic::localrecover: { 6196 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 6197 MachineFunction &MF = DAG.getMachineFunction(); 6198 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 6199 6200 // Get the symbol that defines the frame offset. 6201 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 6202 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 6203 unsigned IdxVal = 6204 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 6205 MCSymbol *FrameAllocSym = 6206 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 6207 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 6208 6209 // Create a MCSymbol for the label to avoid any target lowering 6210 // that would make this PC relative. 6211 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 6212 SDValue OffsetVal = 6213 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 6214 6215 // Add the offset to the FP. 6216 Value *FP = I.getArgOperand(1); 6217 SDValue FPVal = getValue(FP); 6218 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 6219 setValue(&I, Add); 6220 6221 return nullptr; 6222 } 6223 6224 case Intrinsic::eh_exceptionpointer: 6225 case Intrinsic::eh_exceptioncode: { 6226 // Get the exception pointer vreg, copy from it, and resize it to fit. 6227 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 6228 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 6229 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 6230 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 6231 SDValue N = 6232 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 6233 if (Intrinsic == Intrinsic::eh_exceptioncode) 6234 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 6235 setValue(&I, N); 6236 return nullptr; 6237 } 6238 case Intrinsic::xray_customevent: { 6239 // Here we want to make sure that the intrinsic behaves as if it has a 6240 // specific calling convention, and only for x86_64. 6241 // FIXME: Support other platforms later. 6242 const auto &Triple = DAG.getTarget().getTargetTriple(); 6243 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6244 return nullptr; 6245 6246 SDLoc DL = getCurSDLoc(); 6247 SmallVector<SDValue, 8> Ops; 6248 6249 // We want to say that we always want the arguments in registers. 6250 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 6251 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 6252 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6253 SDValue Chain = getRoot(); 6254 Ops.push_back(LogEntryVal); 6255 Ops.push_back(StrSizeVal); 6256 Ops.push_back(Chain); 6257 6258 // We need to enforce the calling convention for the callsite, so that 6259 // argument ordering is enforced correctly, and that register allocation can 6260 // see that some registers may be assumed clobbered and have to preserve 6261 // them across calls to the intrinsic. 6262 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 6263 DL, NodeTys, Ops); 6264 SDValue patchableNode = SDValue(MN, 0); 6265 DAG.setRoot(patchableNode); 6266 setValue(&I, patchableNode); 6267 return nullptr; 6268 } 6269 case Intrinsic::xray_typedevent: { 6270 // Here we want to make sure that the intrinsic behaves as if it has a 6271 // specific calling convention, and only for x86_64. 6272 // FIXME: Support other platforms later. 6273 const auto &Triple = DAG.getTarget().getTargetTriple(); 6274 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 6275 return nullptr; 6276 6277 SDLoc DL = getCurSDLoc(); 6278 SmallVector<SDValue, 8> Ops; 6279 6280 // We want to say that we always want the arguments in registers. 6281 // It's unclear to me how manipulating the selection DAG here forces callers 6282 // to provide arguments in registers instead of on the stack. 6283 SDValue LogTypeId = getValue(I.getArgOperand(0)); 6284 SDValue LogEntryVal = getValue(I.getArgOperand(1)); 6285 SDValue StrSizeVal = getValue(I.getArgOperand(2)); 6286 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 6287 SDValue Chain = getRoot(); 6288 Ops.push_back(LogTypeId); 6289 Ops.push_back(LogEntryVal); 6290 Ops.push_back(StrSizeVal); 6291 Ops.push_back(Chain); 6292 6293 // We need to enforce the calling convention for the callsite, so that 6294 // argument ordering is enforced correctly, and that register allocation can 6295 // see that some registers may be assumed clobbered and have to preserve 6296 // them across calls to the intrinsic. 6297 MachineSDNode *MN = DAG.getMachineNode( 6298 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops); 6299 SDValue patchableNode = SDValue(MN, 0); 6300 DAG.setRoot(patchableNode); 6301 setValue(&I, patchableNode); 6302 return nullptr; 6303 } 6304 case Intrinsic::experimental_deoptimize: 6305 LowerDeoptimizeCall(&I); 6306 return nullptr; 6307 6308 case Intrinsic::experimental_vector_reduce_fadd: 6309 case Intrinsic::experimental_vector_reduce_fmul: 6310 case Intrinsic::experimental_vector_reduce_add: 6311 case Intrinsic::experimental_vector_reduce_mul: 6312 case Intrinsic::experimental_vector_reduce_and: 6313 case Intrinsic::experimental_vector_reduce_or: 6314 case Intrinsic::experimental_vector_reduce_xor: 6315 case Intrinsic::experimental_vector_reduce_smax: 6316 case Intrinsic::experimental_vector_reduce_smin: 6317 case Intrinsic::experimental_vector_reduce_umax: 6318 case Intrinsic::experimental_vector_reduce_umin: 6319 case Intrinsic::experimental_vector_reduce_fmax: 6320 case Intrinsic::experimental_vector_reduce_fmin: 6321 visitVectorReduce(I, Intrinsic); 6322 return nullptr; 6323 6324 case Intrinsic::icall_branch_funnel: { 6325 SmallVector<SDValue, 16> Ops; 6326 Ops.push_back(DAG.getRoot()); 6327 Ops.push_back(getValue(I.getArgOperand(0))); 6328 6329 int64_t Offset; 6330 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6331 I.getArgOperand(1), Offset, DAG.getDataLayout())); 6332 if (!Base) 6333 report_fatal_error( 6334 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6335 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0)); 6336 6337 struct BranchFunnelTarget { 6338 int64_t Offset; 6339 SDValue Target; 6340 }; 6341 SmallVector<BranchFunnelTarget, 8> Targets; 6342 6343 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) { 6344 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset( 6345 I.getArgOperand(Op), Offset, DAG.getDataLayout())); 6346 if (ElemBase != Base) 6347 report_fatal_error("all llvm.icall.branch.funnel operands must refer " 6348 "to the same GlobalValue"); 6349 6350 SDValue Val = getValue(I.getArgOperand(Op + 1)); 6351 auto *GA = dyn_cast<GlobalAddressSDNode>(Val); 6352 if (!GA) 6353 report_fatal_error( 6354 "llvm.icall.branch.funnel operand must be a GlobalValue"); 6355 Targets.push_back({Offset, DAG.getTargetGlobalAddress( 6356 GA->getGlobal(), getCurSDLoc(), 6357 Val.getValueType(), GA->getOffset())}); 6358 } 6359 llvm::sort(Targets, 6360 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) { 6361 return T1.Offset < T2.Offset; 6362 }); 6363 6364 for (auto &T : Targets) { 6365 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32)); 6366 Ops.push_back(T.Target); 6367 } 6368 6369 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, 6370 getCurSDLoc(), MVT::Other, Ops), 6371 0); 6372 DAG.setRoot(N); 6373 setValue(&I, N); 6374 HasTailCall = true; 6375 return nullptr; 6376 } 6377 6378 case Intrinsic::wasm_landingpad_index: 6379 // Information this intrinsic contained has been transferred to 6380 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely 6381 // delete it now. 6382 return nullptr; 6383 } 6384 } 6385 6386 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6387 const ConstrainedFPIntrinsic &FPI) { 6388 SDLoc sdl = getCurSDLoc(); 6389 unsigned Opcode; 6390 switch (FPI.getIntrinsicID()) { 6391 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6392 case Intrinsic::experimental_constrained_fadd: 6393 Opcode = ISD::STRICT_FADD; 6394 break; 6395 case Intrinsic::experimental_constrained_fsub: 6396 Opcode = ISD::STRICT_FSUB; 6397 break; 6398 case Intrinsic::experimental_constrained_fmul: 6399 Opcode = ISD::STRICT_FMUL; 6400 break; 6401 case Intrinsic::experimental_constrained_fdiv: 6402 Opcode = ISD::STRICT_FDIV; 6403 break; 6404 case Intrinsic::experimental_constrained_frem: 6405 Opcode = ISD::STRICT_FREM; 6406 break; 6407 case Intrinsic::experimental_constrained_fma: 6408 Opcode = ISD::STRICT_FMA; 6409 break; 6410 case Intrinsic::experimental_constrained_sqrt: 6411 Opcode = ISD::STRICT_FSQRT; 6412 break; 6413 case Intrinsic::experimental_constrained_pow: 6414 Opcode = ISD::STRICT_FPOW; 6415 break; 6416 case Intrinsic::experimental_constrained_powi: 6417 Opcode = ISD::STRICT_FPOWI; 6418 break; 6419 case Intrinsic::experimental_constrained_sin: 6420 Opcode = ISD::STRICT_FSIN; 6421 break; 6422 case Intrinsic::experimental_constrained_cos: 6423 Opcode = ISD::STRICT_FCOS; 6424 break; 6425 case Intrinsic::experimental_constrained_exp: 6426 Opcode = ISD::STRICT_FEXP; 6427 break; 6428 case Intrinsic::experimental_constrained_exp2: 6429 Opcode = ISD::STRICT_FEXP2; 6430 break; 6431 case Intrinsic::experimental_constrained_log: 6432 Opcode = ISD::STRICT_FLOG; 6433 break; 6434 case Intrinsic::experimental_constrained_log10: 6435 Opcode = ISD::STRICT_FLOG10; 6436 break; 6437 case Intrinsic::experimental_constrained_log2: 6438 Opcode = ISD::STRICT_FLOG2; 6439 break; 6440 case Intrinsic::experimental_constrained_rint: 6441 Opcode = ISD::STRICT_FRINT; 6442 break; 6443 case Intrinsic::experimental_constrained_nearbyint: 6444 Opcode = ISD::STRICT_FNEARBYINT; 6445 break; 6446 case Intrinsic::experimental_constrained_maxnum: 6447 Opcode = ISD::STRICT_FMAXNUM; 6448 break; 6449 case Intrinsic::experimental_constrained_minnum: 6450 Opcode = ISD::STRICT_FMINNUM; 6451 break; 6452 case Intrinsic::experimental_constrained_ceil: 6453 Opcode = ISD::STRICT_FCEIL; 6454 break; 6455 case Intrinsic::experimental_constrained_floor: 6456 Opcode = ISD::STRICT_FFLOOR; 6457 break; 6458 case Intrinsic::experimental_constrained_round: 6459 Opcode = ISD::STRICT_FROUND; 6460 break; 6461 case Intrinsic::experimental_constrained_trunc: 6462 Opcode = ISD::STRICT_FTRUNC; 6463 break; 6464 } 6465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6466 SDValue Chain = getRoot(); 6467 SmallVector<EVT, 4> ValueVTs; 6468 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6469 ValueVTs.push_back(MVT::Other); // Out chain 6470 6471 SDVTList VTs = DAG.getVTList(ValueVTs); 6472 SDValue Result; 6473 if (FPI.isUnaryOp()) 6474 Result = DAG.getNode(Opcode, sdl, VTs, 6475 { Chain, getValue(FPI.getArgOperand(0)) }); 6476 else if (FPI.isTernaryOp()) 6477 Result = DAG.getNode(Opcode, sdl, VTs, 6478 { Chain, getValue(FPI.getArgOperand(0)), 6479 getValue(FPI.getArgOperand(1)), 6480 getValue(FPI.getArgOperand(2)) }); 6481 else 6482 Result = DAG.getNode(Opcode, sdl, VTs, 6483 { Chain, getValue(FPI.getArgOperand(0)), 6484 getValue(FPI.getArgOperand(1)) }); 6485 6486 assert(Result.getNode()->getNumValues() == 2); 6487 SDValue OutChain = Result.getValue(1); 6488 DAG.setRoot(OutChain); 6489 SDValue FPResult = Result.getValue(0); 6490 setValue(&FPI, FPResult); 6491 } 6492 6493 std::pair<SDValue, SDValue> 6494 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6495 const BasicBlock *EHPadBB) { 6496 MachineFunction &MF = DAG.getMachineFunction(); 6497 MachineModuleInfo &MMI = MF.getMMI(); 6498 MCSymbol *BeginLabel = nullptr; 6499 6500 if (EHPadBB) { 6501 // Insert a label before the invoke call to mark the try range. This can be 6502 // used to detect deletion of the invoke via the MachineModuleInfo. 6503 BeginLabel = MMI.getContext().createTempSymbol(); 6504 6505 // For SjLj, keep track of which landing pads go with which invokes 6506 // so as to maintain the ordering of pads in the LSDA. 6507 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6508 if (CallSiteIndex) { 6509 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6510 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6511 6512 // Now that the call site is handled, stop tracking it. 6513 MMI.setCurrentCallSite(0); 6514 } 6515 6516 // Both PendingLoads and PendingExports must be flushed here; 6517 // this call might not return. 6518 (void)getRoot(); 6519 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6520 6521 CLI.setChain(getRoot()); 6522 } 6523 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6524 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6525 6526 assert((CLI.IsTailCall || Result.second.getNode()) && 6527 "Non-null chain expected with non-tail call!"); 6528 assert((Result.second.getNode() || !Result.first.getNode()) && 6529 "Null value expected with tail call!"); 6530 6531 if (!Result.second.getNode()) { 6532 // As a special case, a null chain means that a tail call has been emitted 6533 // and the DAG root is already updated. 6534 HasTailCall = true; 6535 6536 // Since there's no actual continuation from this block, nothing can be 6537 // relying on us setting vregs for them. 6538 PendingExports.clear(); 6539 } else { 6540 DAG.setRoot(Result.second); 6541 } 6542 6543 if (EHPadBB) { 6544 // Insert a label at the end of the invoke call to mark the try range. This 6545 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6546 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6547 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6548 6549 // Inform MachineModuleInfo of range. 6550 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 6551 // There is a platform (e.g. wasm) that uses funclet style IR but does not 6552 // actually use outlined funclets and their LSDA info style. 6553 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) { 6554 assert(CLI.CS); 6555 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6556 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6557 BeginLabel, EndLabel); 6558 } else if (!isScopedEHPersonality(Pers)) { 6559 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6560 } 6561 } 6562 6563 return Result; 6564 } 6565 6566 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6567 bool isTailCall, 6568 const BasicBlock *EHPadBB) { 6569 auto &DL = DAG.getDataLayout(); 6570 FunctionType *FTy = CS.getFunctionType(); 6571 Type *RetTy = CS.getType(); 6572 6573 TargetLowering::ArgListTy Args; 6574 Args.reserve(CS.arg_size()); 6575 6576 const Value *SwiftErrorVal = nullptr; 6577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6578 6579 // We can't tail call inside a function with a swifterror argument. Lowering 6580 // does not support this yet. It would have to move into the swifterror 6581 // register before the call. 6582 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6583 if (TLI.supportSwiftError() && 6584 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6585 isTailCall = false; 6586 6587 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6588 i != e; ++i) { 6589 TargetLowering::ArgListEntry Entry; 6590 const Value *V = *i; 6591 6592 // Skip empty types 6593 if (V->getType()->isEmptyTy()) 6594 continue; 6595 6596 SDValue ArgNode = getValue(V); 6597 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6598 6599 Entry.setAttributes(&CS, i - CS.arg_begin()); 6600 6601 // Use swifterror virtual register as input to the call. 6602 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6603 SwiftErrorVal = V; 6604 // We find the virtual register for the actual swifterror argument. 6605 // Instead of using the Value, we use the virtual register instead. 6606 Entry.Node = DAG.getRegister(FuncInfo 6607 .getOrCreateSwiftErrorVRegUseAt( 6608 CS.getInstruction(), FuncInfo.MBB, V) 6609 .first, 6610 EVT(TLI.getPointerTy(DL))); 6611 } 6612 6613 Args.push_back(Entry); 6614 6615 // If we have an explicit sret argument that is an Instruction, (i.e., it 6616 // might point to function-local memory), we can't meaningfully tail-call. 6617 if (Entry.IsSRet && isa<Instruction>(V)) 6618 isTailCall = false; 6619 } 6620 6621 // Check if target-independent constraints permit a tail call here. 6622 // Target-dependent constraints are checked within TLI->LowerCallTo. 6623 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6624 isTailCall = false; 6625 6626 // Disable tail calls if there is an swifterror argument. Targets have not 6627 // been updated to support tail calls. 6628 if (TLI.supportSwiftError() && SwiftErrorVal) 6629 isTailCall = false; 6630 6631 TargetLowering::CallLoweringInfo CLI(DAG); 6632 CLI.setDebugLoc(getCurSDLoc()) 6633 .setChain(getRoot()) 6634 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6635 .setTailCall(isTailCall) 6636 .setConvergent(CS.isConvergent()); 6637 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6638 6639 if (Result.first.getNode()) { 6640 const Instruction *Inst = CS.getInstruction(); 6641 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6642 setValue(Inst, Result.first); 6643 } 6644 6645 // The last element of CLI.InVals has the SDValue for swifterror return. 6646 // Here we copy it to a virtual register and update SwiftErrorMap for 6647 // book-keeping. 6648 if (SwiftErrorVal && TLI.supportSwiftError()) { 6649 // Get the last element of InVals. 6650 SDValue Src = CLI.InVals.back(); 6651 unsigned VReg; bool CreatedVReg; 6652 std::tie(VReg, CreatedVReg) = 6653 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6654 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6655 // We update the virtual register for the actual swifterror argument. 6656 if (CreatedVReg) 6657 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6658 DAG.setRoot(CopyNode); 6659 } 6660 } 6661 6662 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6663 SelectionDAGBuilder &Builder) { 6664 // Check to see if this load can be trivially constant folded, e.g. if the 6665 // input is from a string literal. 6666 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6667 // Cast pointer to the type we really want to load. 6668 Type *LoadTy = 6669 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6670 if (LoadVT.isVector()) 6671 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6672 6673 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6674 PointerType::getUnqual(LoadTy)); 6675 6676 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6677 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6678 return Builder.getValue(LoadCst); 6679 } 6680 6681 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6682 // still constant memory, the input chain can be the entry node. 6683 SDValue Root; 6684 bool ConstantMemory = false; 6685 6686 // Do not serialize (non-volatile) loads of constant memory with anything. 6687 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6688 Root = Builder.DAG.getEntryNode(); 6689 ConstantMemory = true; 6690 } else { 6691 // Do not serialize non-volatile loads against each other. 6692 Root = Builder.DAG.getRoot(); 6693 } 6694 6695 SDValue Ptr = Builder.getValue(PtrVal); 6696 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6697 Ptr, MachinePointerInfo(PtrVal), 6698 /* Alignment = */ 1); 6699 6700 if (!ConstantMemory) 6701 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6702 return LoadVal; 6703 } 6704 6705 /// Record the value for an instruction that produces an integer result, 6706 /// converting the type where necessary. 6707 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6708 SDValue Value, 6709 bool IsSigned) { 6710 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6711 I.getType(), true); 6712 if (IsSigned) 6713 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6714 else 6715 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6716 setValue(&I, Value); 6717 } 6718 6719 /// See if we can lower a memcmp call into an optimized form. If so, return 6720 /// true and lower it. Otherwise return false, and it will be lowered like a 6721 /// normal call. 6722 /// The caller already checked that \p I calls the appropriate LibFunc with a 6723 /// correct prototype. 6724 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6725 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6726 const Value *Size = I.getArgOperand(2); 6727 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6728 if (CSize && CSize->getZExtValue() == 0) { 6729 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6730 I.getType(), true); 6731 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6732 return true; 6733 } 6734 6735 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6736 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6737 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6738 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6739 if (Res.first.getNode()) { 6740 processIntegerCallValue(I, Res.first, true); 6741 PendingLoads.push_back(Res.second); 6742 return true; 6743 } 6744 6745 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6746 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6747 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6748 return false; 6749 6750 // If the target has a fast compare for the given size, it will return a 6751 // preferred load type for that size. Require that the load VT is legal and 6752 // that the target supports unaligned loads of that type. Otherwise, return 6753 // INVALID. 6754 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6755 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6756 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6757 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6758 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6759 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6760 // TODO: Check alignment of src and dest ptrs. 6761 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6762 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6763 if (!TLI.isTypeLegal(LVT) || 6764 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6765 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6766 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6767 } 6768 6769 return LVT; 6770 }; 6771 6772 // This turns into unaligned loads. We only do this if the target natively 6773 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6774 // we'll only produce a small number of byte loads. 6775 MVT LoadVT; 6776 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6777 switch (NumBitsToCompare) { 6778 default: 6779 return false; 6780 case 16: 6781 LoadVT = MVT::i16; 6782 break; 6783 case 32: 6784 LoadVT = MVT::i32; 6785 break; 6786 case 64: 6787 case 128: 6788 case 256: 6789 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6790 break; 6791 } 6792 6793 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6794 return false; 6795 6796 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6797 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6798 6799 // Bitcast to a wide integer type if the loads are vectors. 6800 if (LoadVT.isVector()) { 6801 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6802 LoadL = DAG.getBitcast(CmpVT, LoadL); 6803 LoadR = DAG.getBitcast(CmpVT, LoadR); 6804 } 6805 6806 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6807 processIntegerCallValue(I, Cmp, false); 6808 return true; 6809 } 6810 6811 /// See if we can lower a memchr call into an optimized form. If so, return 6812 /// true and lower it. Otherwise return false, and it will be lowered like a 6813 /// normal call. 6814 /// The caller already checked that \p I calls the appropriate LibFunc with a 6815 /// correct prototype. 6816 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6817 const Value *Src = I.getArgOperand(0); 6818 const Value *Char = I.getArgOperand(1); 6819 const Value *Length = I.getArgOperand(2); 6820 6821 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6822 std::pair<SDValue, SDValue> Res = 6823 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6824 getValue(Src), getValue(Char), getValue(Length), 6825 MachinePointerInfo(Src)); 6826 if (Res.first.getNode()) { 6827 setValue(&I, Res.first); 6828 PendingLoads.push_back(Res.second); 6829 return true; 6830 } 6831 6832 return false; 6833 } 6834 6835 /// See if we can lower a mempcpy call into an optimized form. If so, return 6836 /// true and lower it. Otherwise return false, and it will be lowered like a 6837 /// normal call. 6838 /// The caller already checked that \p I calls the appropriate LibFunc with a 6839 /// correct prototype. 6840 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6841 SDValue Dst = getValue(I.getArgOperand(0)); 6842 SDValue Src = getValue(I.getArgOperand(1)); 6843 SDValue Size = getValue(I.getArgOperand(2)); 6844 6845 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6846 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6847 unsigned Align = std::min(DstAlign, SrcAlign); 6848 if (Align == 0) // Alignment of one or both could not be inferred. 6849 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6850 6851 bool isVol = false; 6852 SDLoc sdl = getCurSDLoc(); 6853 6854 // In the mempcpy context we need to pass in a false value for isTailCall 6855 // because the return pointer needs to be adjusted by the size of 6856 // the copied memory. 6857 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6858 false, /*isTailCall=*/false, 6859 MachinePointerInfo(I.getArgOperand(0)), 6860 MachinePointerInfo(I.getArgOperand(1))); 6861 assert(MC.getNode() != nullptr && 6862 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6863 DAG.setRoot(MC); 6864 6865 // Check if Size needs to be truncated or extended. 6866 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6867 6868 // Adjust return pointer to point just past the last dst byte. 6869 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6870 Dst, Size); 6871 setValue(&I, DstPlusSize); 6872 return true; 6873 } 6874 6875 /// See if we can lower a strcpy call into an optimized form. If so, return 6876 /// true and lower it, otherwise return false and it will be lowered like a 6877 /// normal call. 6878 /// The caller already checked that \p I calls the appropriate LibFunc with a 6879 /// correct prototype. 6880 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6881 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6882 6883 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6884 std::pair<SDValue, SDValue> Res = 6885 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6886 getValue(Arg0), getValue(Arg1), 6887 MachinePointerInfo(Arg0), 6888 MachinePointerInfo(Arg1), isStpcpy); 6889 if (Res.first.getNode()) { 6890 setValue(&I, Res.first); 6891 DAG.setRoot(Res.second); 6892 return true; 6893 } 6894 6895 return false; 6896 } 6897 6898 /// See if we can lower a strcmp call into an optimized form. If so, return 6899 /// true and lower it, otherwise return false and it will be lowered like a 6900 /// normal call. 6901 /// The caller already checked that \p I calls the appropriate LibFunc with a 6902 /// correct prototype. 6903 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6904 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6905 6906 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6907 std::pair<SDValue, SDValue> Res = 6908 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6909 getValue(Arg0), getValue(Arg1), 6910 MachinePointerInfo(Arg0), 6911 MachinePointerInfo(Arg1)); 6912 if (Res.first.getNode()) { 6913 processIntegerCallValue(I, Res.first, true); 6914 PendingLoads.push_back(Res.second); 6915 return true; 6916 } 6917 6918 return false; 6919 } 6920 6921 /// See if we can lower a strlen call into an optimized form. If so, return 6922 /// true and lower it, otherwise return false and it will be lowered like a 6923 /// normal call. 6924 /// The caller already checked that \p I calls the appropriate LibFunc with a 6925 /// correct prototype. 6926 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6927 const Value *Arg0 = I.getArgOperand(0); 6928 6929 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6930 std::pair<SDValue, SDValue> Res = 6931 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6932 getValue(Arg0), MachinePointerInfo(Arg0)); 6933 if (Res.first.getNode()) { 6934 processIntegerCallValue(I, Res.first, false); 6935 PendingLoads.push_back(Res.second); 6936 return true; 6937 } 6938 6939 return false; 6940 } 6941 6942 /// See if we can lower a strnlen call into an optimized form. If so, return 6943 /// true and lower it, otherwise return false and it will be lowered like a 6944 /// normal call. 6945 /// The caller already checked that \p I calls the appropriate LibFunc with a 6946 /// correct prototype. 6947 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6948 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6949 6950 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6951 std::pair<SDValue, SDValue> Res = 6952 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6953 getValue(Arg0), getValue(Arg1), 6954 MachinePointerInfo(Arg0)); 6955 if (Res.first.getNode()) { 6956 processIntegerCallValue(I, Res.first, false); 6957 PendingLoads.push_back(Res.second); 6958 return true; 6959 } 6960 6961 return false; 6962 } 6963 6964 /// See if we can lower a unary floating-point operation into an SDNode with 6965 /// the specified Opcode. If so, return true and lower it, otherwise return 6966 /// false and it will be lowered like a normal call. 6967 /// The caller already checked that \p I calls the appropriate LibFunc with a 6968 /// correct prototype. 6969 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6970 unsigned Opcode) { 6971 // We already checked this call's prototype; verify it doesn't modify errno. 6972 if (!I.onlyReadsMemory()) 6973 return false; 6974 6975 SDValue Tmp = getValue(I.getArgOperand(0)); 6976 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6977 return true; 6978 } 6979 6980 /// See if we can lower a binary floating-point operation into an SDNode with 6981 /// the specified Opcode. If so, return true and lower it. Otherwise return 6982 /// false, and it will be lowered like a normal call. 6983 /// The caller already checked that \p I calls the appropriate LibFunc with a 6984 /// correct prototype. 6985 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6986 unsigned Opcode) { 6987 // We already checked this call's prototype; verify it doesn't modify errno. 6988 if (!I.onlyReadsMemory()) 6989 return false; 6990 6991 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6992 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6993 EVT VT = Tmp0.getValueType(); 6994 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6995 return true; 6996 } 6997 6998 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6999 // Handle inline assembly differently. 7000 if (isa<InlineAsm>(I.getCalledValue())) { 7001 visitInlineAsm(&I); 7002 return; 7003 } 7004 7005 const char *RenameFn = nullptr; 7006 if (Function *F = I.getCalledFunction()) { 7007 if (F->isDeclaration()) { 7008 // Is this an LLVM intrinsic or a target-specific intrinsic? 7009 unsigned IID = F->getIntrinsicID(); 7010 if (!IID) 7011 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) 7012 IID = II->getIntrinsicID(F); 7013 7014 if (IID) { 7015 RenameFn = visitIntrinsicCall(I, IID); 7016 if (!RenameFn) 7017 return; 7018 } 7019 } 7020 7021 // Check for well-known libc/libm calls. If the function is internal, it 7022 // can't be a library call. Don't do the check if marked as nobuiltin for 7023 // some reason or the call site requires strict floating point semantics. 7024 LibFunc Func; 7025 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 7026 F->hasName() && LibInfo->getLibFunc(*F, Func) && 7027 LibInfo->hasOptimizedCodeGen(Func)) { 7028 switch (Func) { 7029 default: break; 7030 case LibFunc_copysign: 7031 case LibFunc_copysignf: 7032 case LibFunc_copysignl: 7033 // We already checked this call's prototype; verify it doesn't modify 7034 // errno. 7035 if (I.onlyReadsMemory()) { 7036 SDValue LHS = getValue(I.getArgOperand(0)); 7037 SDValue RHS = getValue(I.getArgOperand(1)); 7038 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 7039 LHS.getValueType(), LHS, RHS)); 7040 return; 7041 } 7042 break; 7043 case LibFunc_fabs: 7044 case LibFunc_fabsf: 7045 case LibFunc_fabsl: 7046 if (visitUnaryFloatCall(I, ISD::FABS)) 7047 return; 7048 break; 7049 case LibFunc_fmin: 7050 case LibFunc_fminf: 7051 case LibFunc_fminl: 7052 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 7053 return; 7054 break; 7055 case LibFunc_fmax: 7056 case LibFunc_fmaxf: 7057 case LibFunc_fmaxl: 7058 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 7059 return; 7060 break; 7061 case LibFunc_sin: 7062 case LibFunc_sinf: 7063 case LibFunc_sinl: 7064 if (visitUnaryFloatCall(I, ISD::FSIN)) 7065 return; 7066 break; 7067 case LibFunc_cos: 7068 case LibFunc_cosf: 7069 case LibFunc_cosl: 7070 if (visitUnaryFloatCall(I, ISD::FCOS)) 7071 return; 7072 break; 7073 case LibFunc_sqrt: 7074 case LibFunc_sqrtf: 7075 case LibFunc_sqrtl: 7076 case LibFunc_sqrt_finite: 7077 case LibFunc_sqrtf_finite: 7078 case LibFunc_sqrtl_finite: 7079 if (visitUnaryFloatCall(I, ISD::FSQRT)) 7080 return; 7081 break; 7082 case LibFunc_floor: 7083 case LibFunc_floorf: 7084 case LibFunc_floorl: 7085 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 7086 return; 7087 break; 7088 case LibFunc_nearbyint: 7089 case LibFunc_nearbyintf: 7090 case LibFunc_nearbyintl: 7091 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 7092 return; 7093 break; 7094 case LibFunc_ceil: 7095 case LibFunc_ceilf: 7096 case LibFunc_ceill: 7097 if (visitUnaryFloatCall(I, ISD::FCEIL)) 7098 return; 7099 break; 7100 case LibFunc_rint: 7101 case LibFunc_rintf: 7102 case LibFunc_rintl: 7103 if (visitUnaryFloatCall(I, ISD::FRINT)) 7104 return; 7105 break; 7106 case LibFunc_round: 7107 case LibFunc_roundf: 7108 case LibFunc_roundl: 7109 if (visitUnaryFloatCall(I, ISD::FROUND)) 7110 return; 7111 break; 7112 case LibFunc_trunc: 7113 case LibFunc_truncf: 7114 case LibFunc_truncl: 7115 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 7116 return; 7117 break; 7118 case LibFunc_log2: 7119 case LibFunc_log2f: 7120 case LibFunc_log2l: 7121 if (visitUnaryFloatCall(I, ISD::FLOG2)) 7122 return; 7123 break; 7124 case LibFunc_exp2: 7125 case LibFunc_exp2f: 7126 case LibFunc_exp2l: 7127 if (visitUnaryFloatCall(I, ISD::FEXP2)) 7128 return; 7129 break; 7130 case LibFunc_memcmp: 7131 if (visitMemCmpCall(I)) 7132 return; 7133 break; 7134 case LibFunc_mempcpy: 7135 if (visitMemPCpyCall(I)) 7136 return; 7137 break; 7138 case LibFunc_memchr: 7139 if (visitMemChrCall(I)) 7140 return; 7141 break; 7142 case LibFunc_strcpy: 7143 if (visitStrCpyCall(I, false)) 7144 return; 7145 break; 7146 case LibFunc_stpcpy: 7147 if (visitStrCpyCall(I, true)) 7148 return; 7149 break; 7150 case LibFunc_strcmp: 7151 if (visitStrCmpCall(I)) 7152 return; 7153 break; 7154 case LibFunc_strlen: 7155 if (visitStrLenCall(I)) 7156 return; 7157 break; 7158 case LibFunc_strnlen: 7159 if (visitStrNLenCall(I)) 7160 return; 7161 break; 7162 } 7163 } 7164 } 7165 7166 SDValue Callee; 7167 if (!RenameFn) 7168 Callee = getValue(I.getCalledValue()); 7169 else 7170 Callee = DAG.getExternalSymbol( 7171 RenameFn, 7172 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 7173 7174 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 7175 // have to do anything here to lower funclet bundles. 7176 assert(!I.hasOperandBundlesOtherThan( 7177 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 7178 "Cannot lower calls with arbitrary operand bundles!"); 7179 7180 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 7181 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 7182 else 7183 // Check if we can potentially perform a tail call. More detailed checking 7184 // is be done within LowerCallTo, after more information about the call is 7185 // known. 7186 LowerCallTo(&I, Callee, I.isTailCall()); 7187 } 7188 7189 namespace { 7190 7191 /// AsmOperandInfo - This contains information for each constraint that we are 7192 /// lowering. 7193 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 7194 public: 7195 /// CallOperand - If this is the result output operand or a clobber 7196 /// this is null, otherwise it is the incoming operand to the CallInst. 7197 /// This gets modified as the asm is processed. 7198 SDValue CallOperand; 7199 7200 /// AssignedRegs - If this is a register or register class operand, this 7201 /// contains the set of register corresponding to the operand. 7202 RegsForValue AssignedRegs; 7203 7204 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 7205 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 7206 } 7207 7208 /// Whether or not this operand accesses memory 7209 bool hasMemory(const TargetLowering &TLI) const { 7210 // Indirect operand accesses access memory. 7211 if (isIndirect) 7212 return true; 7213 7214 for (const auto &Code : Codes) 7215 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 7216 return true; 7217 7218 return false; 7219 } 7220 7221 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 7222 /// corresponds to. If there is no Value* for this operand, it returns 7223 /// MVT::Other. 7224 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 7225 const DataLayout &DL) const { 7226 if (!CallOperandVal) return MVT::Other; 7227 7228 if (isa<BasicBlock>(CallOperandVal)) 7229 return TLI.getPointerTy(DL); 7230 7231 llvm::Type *OpTy = CallOperandVal->getType(); 7232 7233 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 7234 // If this is an indirect operand, the operand is a pointer to the 7235 // accessed type. 7236 if (isIndirect) { 7237 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 7238 if (!PtrTy) 7239 report_fatal_error("Indirect operand for inline asm not a pointer!"); 7240 OpTy = PtrTy->getElementType(); 7241 } 7242 7243 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 7244 if (StructType *STy = dyn_cast<StructType>(OpTy)) 7245 if (STy->getNumElements() == 1) 7246 OpTy = STy->getElementType(0); 7247 7248 // If OpTy is not a single value, it may be a struct/union that we 7249 // can tile with integers. 7250 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 7251 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 7252 switch (BitSize) { 7253 default: break; 7254 case 1: 7255 case 8: 7256 case 16: 7257 case 32: 7258 case 64: 7259 case 128: 7260 OpTy = IntegerType::get(Context, BitSize); 7261 break; 7262 } 7263 } 7264 7265 return TLI.getValueType(DL, OpTy, true); 7266 } 7267 }; 7268 7269 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 7270 7271 } // end anonymous namespace 7272 7273 /// Make sure that the output operand \p OpInfo and its corresponding input 7274 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 7275 /// out). 7276 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 7277 SDISelAsmOperandInfo &MatchingOpInfo, 7278 SelectionDAG &DAG) { 7279 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 7280 return; 7281 7282 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 7283 const auto &TLI = DAG.getTargetLoweringInfo(); 7284 7285 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 7286 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 7287 OpInfo.ConstraintVT); 7288 std::pair<unsigned, const TargetRegisterClass *> InputRC = 7289 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 7290 MatchingOpInfo.ConstraintVT); 7291 if ((OpInfo.ConstraintVT.isInteger() != 7292 MatchingOpInfo.ConstraintVT.isInteger()) || 7293 (MatchRC.second != InputRC.second)) { 7294 // FIXME: error out in a more elegant fashion 7295 report_fatal_error("Unsupported asm: input constraint" 7296 " with a matching output constraint of" 7297 " incompatible type!"); 7298 } 7299 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 7300 } 7301 7302 /// Get a direct memory input to behave well as an indirect operand. 7303 /// This may introduce stores, hence the need for a \p Chain. 7304 /// \return The (possibly updated) chain. 7305 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 7306 SDISelAsmOperandInfo &OpInfo, 7307 SelectionDAG &DAG) { 7308 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7309 7310 // If we don't have an indirect input, put it in the constpool if we can, 7311 // otherwise spill it to a stack slot. 7312 // TODO: This isn't quite right. We need to handle these according to 7313 // the addressing mode that the constraint wants. Also, this may take 7314 // an additional register for the computation and we don't want that 7315 // either. 7316 7317 // If the operand is a float, integer, or vector constant, spill to a 7318 // constant pool entry to get its address. 7319 const Value *OpVal = OpInfo.CallOperandVal; 7320 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 7321 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 7322 OpInfo.CallOperand = DAG.getConstantPool( 7323 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 7324 return Chain; 7325 } 7326 7327 // Otherwise, create a stack slot and emit a store to it before the asm. 7328 Type *Ty = OpVal->getType(); 7329 auto &DL = DAG.getDataLayout(); 7330 uint64_t TySize = DL.getTypeAllocSize(Ty); 7331 unsigned Align = DL.getPrefTypeAlignment(Ty); 7332 MachineFunction &MF = DAG.getMachineFunction(); 7333 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 7334 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 7335 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 7336 MachinePointerInfo::getFixedStack(MF, SSFI)); 7337 OpInfo.CallOperand = StackSlot; 7338 7339 return Chain; 7340 } 7341 7342 /// GetRegistersForValue - Assign registers (virtual or physical) for the 7343 /// specified operand. We prefer to assign virtual registers, to allow the 7344 /// register allocator to handle the assignment process. However, if the asm 7345 /// uses features that we can't model on machineinstrs, we have SDISel do the 7346 /// allocation. This produces generally horrible, but correct, code. 7347 /// 7348 /// OpInfo describes the operand 7349 /// RefOpInfo describes the matching operand if any, the operand otherwise 7350 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL, 7351 SDISelAsmOperandInfo &OpInfo, 7352 SDISelAsmOperandInfo &RefOpInfo) { 7353 LLVMContext &Context = *DAG.getContext(); 7354 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7355 7356 MachineFunction &MF = DAG.getMachineFunction(); 7357 SmallVector<unsigned, 4> Regs; 7358 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 7359 7360 // No work to do for memory operations. 7361 if (OpInfo.ConstraintType == TargetLowering::C_Memory) 7362 return; 7363 7364 // If this is a constraint for a single physreg, or a constraint for a 7365 // register class, find it. 7366 unsigned AssignedReg; 7367 const TargetRegisterClass *RC; 7368 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint( 7369 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT); 7370 // RC is unset only on failure. Return immediately. 7371 if (!RC) 7372 return; 7373 7374 // Get the actual register value type. This is important, because the user 7375 // may have asked for (e.g.) the AX register in i32 type. We need to 7376 // remember that AX is actually i16 to get the right extension. 7377 const MVT RegVT = *TRI.legalclasstypes_begin(*RC); 7378 7379 if (OpInfo.ConstraintVT != MVT::Other) { 7380 // If this is an FP operand in an integer register (or visa versa), or more 7381 // generally if the operand value disagrees with the register class we plan 7382 // to stick it in, fix the operand type. 7383 // 7384 // If this is an input value, the bitcast to the new type is done now. 7385 // Bitcast for output value is done at the end of visitInlineAsm(). 7386 if ((OpInfo.Type == InlineAsm::isOutput || 7387 OpInfo.Type == InlineAsm::isInput) && 7388 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) { 7389 // Try to convert to the first EVT that the reg class contains. If the 7390 // types are identical size, use a bitcast to convert (e.g. two differing 7391 // vector types). Note: output bitcast is done at the end of 7392 // visitInlineAsm(). 7393 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 7394 // Exclude indirect inputs while they are unsupported because the code 7395 // to perform the load is missing and thus OpInfo.CallOperand still 7396 // refers to the input address rather than the pointed-to value. 7397 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect) 7398 OpInfo.CallOperand = 7399 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand); 7400 OpInfo.ConstraintVT = RegVT; 7401 // If the operand is an FP value and we want it in integer registers, 7402 // use the corresponding integer type. This turns an f64 value into 7403 // i64, which can be passed with two i32 values on a 32-bit machine. 7404 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7405 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7406 if (OpInfo.Type == InlineAsm::isInput) 7407 OpInfo.CallOperand = 7408 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand); 7409 OpInfo.ConstraintVT = VT; 7410 } 7411 } 7412 } 7413 7414 // No need to allocate a matching input constraint since the constraint it's 7415 // matching to has already been allocated. 7416 if (OpInfo.isMatchingInputConstraint()) 7417 return; 7418 7419 EVT ValueVT = OpInfo.ConstraintVT; 7420 if (OpInfo.ConstraintVT == MVT::Other) 7421 ValueVT = RegVT; 7422 7423 // Initialize NumRegs. 7424 unsigned NumRegs = 1; 7425 if (OpInfo.ConstraintVT != MVT::Other) 7426 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7427 7428 // If this is a constraint for a specific physical register, like {r17}, 7429 // assign it now. 7430 7431 // If this associated to a specific register, initialize iterator to correct 7432 // place. If virtual, make sure we have enough registers 7433 7434 // Initialize iterator if necessary 7435 TargetRegisterClass::iterator I = RC->begin(); 7436 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7437 7438 // Do not check for single registers. 7439 if (AssignedReg) { 7440 for (; *I != AssignedReg; ++I) 7441 assert(I != RC->end() && "AssignedReg should be member of RC"); 7442 } 7443 7444 for (; NumRegs; --NumRegs, ++I) { 7445 assert(I != RC->end() && "Ran out of registers to allocate!"); 7446 auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC); 7447 Regs.push_back(R); 7448 } 7449 7450 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7451 } 7452 7453 static unsigned 7454 findMatchingInlineAsmOperand(unsigned OperandNo, 7455 const std::vector<SDValue> &AsmNodeOperands) { 7456 // Scan until we find the definition we already emitted of this operand. 7457 unsigned CurOp = InlineAsm::Op_FirstOperand; 7458 for (; OperandNo; --OperandNo) { 7459 // Advance to the next operand. 7460 unsigned OpFlag = 7461 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7462 assert((InlineAsm::isRegDefKind(OpFlag) || 7463 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7464 InlineAsm::isMemKind(OpFlag)) && 7465 "Skipped past definitions?"); 7466 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7467 } 7468 return CurOp; 7469 } 7470 7471 namespace { 7472 7473 class ExtraFlags { 7474 unsigned Flags = 0; 7475 7476 public: 7477 explicit ExtraFlags(ImmutableCallSite CS) { 7478 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7479 if (IA->hasSideEffects()) 7480 Flags |= InlineAsm::Extra_HasSideEffects; 7481 if (IA->isAlignStack()) 7482 Flags |= InlineAsm::Extra_IsAlignStack; 7483 if (CS.isConvergent()) 7484 Flags |= InlineAsm::Extra_IsConvergent; 7485 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7486 } 7487 7488 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7489 // Ideally, we would only check against memory constraints. However, the 7490 // meaning of an Other constraint can be target-specific and we can't easily 7491 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7492 // for Other constraints as well. 7493 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7494 OpInfo.ConstraintType == TargetLowering::C_Other) { 7495 if (OpInfo.Type == InlineAsm::isInput) 7496 Flags |= InlineAsm::Extra_MayLoad; 7497 else if (OpInfo.Type == InlineAsm::isOutput) 7498 Flags |= InlineAsm::Extra_MayStore; 7499 else if (OpInfo.Type == InlineAsm::isClobber) 7500 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7501 } 7502 } 7503 7504 unsigned get() const { return Flags; } 7505 }; 7506 7507 } // end anonymous namespace 7508 7509 /// visitInlineAsm - Handle a call to an InlineAsm object. 7510 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7511 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7512 7513 /// ConstraintOperands - Information about all of the constraints. 7514 SDISelAsmOperandInfoVector ConstraintOperands; 7515 7516 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7517 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7518 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7519 7520 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack, 7521 // AsmDialect, MayLoad, MayStore). 7522 bool HasSideEffect = IA->hasSideEffects(); 7523 ExtraFlags ExtraInfo(CS); 7524 7525 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7526 unsigned ResNo = 0; // ResNo - The result number of the next output. 7527 for (auto &T : TargetConstraints) { 7528 ConstraintOperands.push_back(SDISelAsmOperandInfo(T)); 7529 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7530 7531 // Compute the value type for each operand. 7532 if (OpInfo.Type == InlineAsm::isInput || 7533 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7534 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7535 7536 // Process the call argument. BasicBlocks are labels, currently appearing 7537 // only in asm's. 7538 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7539 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7540 } else { 7541 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7542 } 7543 7544 OpInfo.ConstraintVT = 7545 OpInfo 7546 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7547 .getSimpleVT(); 7548 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7549 // The return value of the call is this value. As such, there is no 7550 // corresponding argument. 7551 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7552 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7553 OpInfo.ConstraintVT = TLI.getSimpleValueType( 7554 DAG.getDataLayout(), STy->getElementType(ResNo)); 7555 } else { 7556 assert(ResNo == 0 && "Asm only has one result!"); 7557 OpInfo.ConstraintVT = 7558 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7559 } 7560 ++ResNo; 7561 } else { 7562 OpInfo.ConstraintVT = MVT::Other; 7563 } 7564 7565 if (!HasSideEffect) 7566 HasSideEffect = OpInfo.hasMemory(TLI); 7567 7568 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7569 // FIXME: Could we compute this on OpInfo rather than T? 7570 7571 // Compute the constraint code and ConstraintType to use. 7572 TLI.ComputeConstraintToUse(T, SDValue()); 7573 7574 ExtraInfo.update(T); 7575 } 7576 7577 // We won't need to flush pending loads if this asm doesn't touch 7578 // memory and is nonvolatile. 7579 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot(); 7580 7581 // Second pass over the constraints: compute which constraint option to use. 7582 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7583 // If this is an output operand with a matching input operand, look up the 7584 // matching input. If their types mismatch, e.g. one is an integer, the 7585 // other is floating point, or their sizes are different, flag it as an 7586 // error. 7587 if (OpInfo.hasMatchingInput()) { 7588 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7589 patchMatchingInput(OpInfo, Input, DAG); 7590 } 7591 7592 // Compute the constraint code and ConstraintType to use. 7593 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7594 7595 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7596 OpInfo.Type == InlineAsm::isClobber) 7597 continue; 7598 7599 // If this is a memory input, and if the operand is not indirect, do what we 7600 // need to provide an address for the memory input. 7601 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7602 !OpInfo.isIndirect) { 7603 assert((OpInfo.isMultipleAlternative || 7604 (OpInfo.Type == InlineAsm::isInput)) && 7605 "Can only indirectify direct input operands!"); 7606 7607 // Memory operands really want the address of the value. 7608 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7609 7610 // There is no longer a Value* corresponding to this operand. 7611 OpInfo.CallOperandVal = nullptr; 7612 7613 // It is now an indirect operand. 7614 OpInfo.isIndirect = true; 7615 } 7616 7617 } 7618 7619 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7620 std::vector<SDValue> AsmNodeOperands; 7621 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7622 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7623 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7624 7625 // If we have a !srcloc metadata node associated with it, we want to attach 7626 // this to the ultimately generated inline asm machineinstr. To do this, we 7627 // pass in the third operand as this (potentially null) inline asm MDNode. 7628 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7629 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7630 7631 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7632 // bits as operand 3. 7633 AsmNodeOperands.push_back(DAG.getTargetConstant( 7634 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7635 7636 // Third pass: Loop over operands to prepare DAG-level operands.. As part of 7637 // this, assign virtual and physical registers for inputs and otput. 7638 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7639 // Assign Registers. 7640 SDISelAsmOperandInfo &RefOpInfo = 7641 OpInfo.isMatchingInputConstraint() 7642 ? ConstraintOperands[OpInfo.getMatchedOperand()] 7643 : OpInfo; 7644 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo); 7645 7646 switch (OpInfo.Type) { 7647 case InlineAsm::isOutput: 7648 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7649 OpInfo.ConstraintType != TargetLowering::C_Register) { 7650 // Memory output, or 'other' output (e.g. 'X' constraint). 7651 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7652 7653 unsigned ConstraintID = 7654 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7655 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7656 "Failed to convert memory constraint code to constraint id."); 7657 7658 // Add information to the INLINEASM node to know about this output. 7659 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7660 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7661 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7662 MVT::i32)); 7663 AsmNodeOperands.push_back(OpInfo.CallOperand); 7664 break; 7665 } else if (OpInfo.ConstraintType == TargetLowering::C_Register || 7666 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) { 7667 // Otherwise, this is a register or register class output. 7668 7669 // Copy the output from the appropriate register. Find a register that 7670 // we can use. 7671 if (OpInfo.AssignedRegs.Regs.empty()) { 7672 emitInlineAsmError( 7673 CS, "couldn't allocate output register for constraint '" + 7674 Twine(OpInfo.ConstraintCode) + "'"); 7675 return; 7676 } 7677 7678 // Add information to the INLINEASM node to know that this register is 7679 // set. 7680 OpInfo.AssignedRegs.AddInlineAsmOperands( 7681 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber 7682 : InlineAsm::Kind_RegDef, 7683 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7684 } 7685 break; 7686 7687 case InlineAsm::isInput: { 7688 SDValue InOperandVal = OpInfo.CallOperand; 7689 7690 if (OpInfo.isMatchingInputConstraint()) { 7691 // If this is required to match an output register we have already set, 7692 // just use its register. 7693 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7694 AsmNodeOperands); 7695 unsigned OpFlag = 7696 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7697 if (InlineAsm::isRegDefKind(OpFlag) || 7698 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7699 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7700 if (OpInfo.isIndirect) { 7701 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7702 emitInlineAsmError(CS, "inline asm not supported yet:" 7703 " don't know how to handle tied " 7704 "indirect register inputs"); 7705 return; 7706 } 7707 7708 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7709 SmallVector<unsigned, 4> Regs; 7710 7711 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) { 7712 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag); 7713 MachineRegisterInfo &RegInfo = 7714 DAG.getMachineFunction().getRegInfo(); 7715 for (unsigned i = 0; i != NumRegs; ++i) 7716 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7717 } else { 7718 emitInlineAsmError(CS, "inline asm error: This value type register " 7719 "class is not natively supported!"); 7720 return; 7721 } 7722 7723 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7724 7725 SDLoc dl = getCurSDLoc(); 7726 // Use the produced MatchedRegs object to 7727 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7728 CS.getInstruction()); 7729 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7730 true, OpInfo.getMatchedOperand(), dl, 7731 DAG, AsmNodeOperands); 7732 break; 7733 } 7734 7735 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7736 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7737 "Unexpected number of operands"); 7738 // Add information to the INLINEASM node to know about this input. 7739 // See InlineAsm.h isUseOperandTiedToDef. 7740 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7741 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7742 OpInfo.getMatchedOperand()); 7743 AsmNodeOperands.push_back(DAG.getTargetConstant( 7744 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7745 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7746 break; 7747 } 7748 7749 // Treat indirect 'X' constraint as memory. 7750 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7751 OpInfo.isIndirect) 7752 OpInfo.ConstraintType = TargetLowering::C_Memory; 7753 7754 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7755 std::vector<SDValue> Ops; 7756 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7757 Ops, DAG); 7758 if (Ops.empty()) { 7759 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7760 Twine(OpInfo.ConstraintCode) + "'"); 7761 return; 7762 } 7763 7764 // Add information to the INLINEASM node to know about this input. 7765 unsigned ResOpType = 7766 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7767 AsmNodeOperands.push_back(DAG.getTargetConstant( 7768 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7769 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7770 break; 7771 } 7772 7773 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7774 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7775 assert(InOperandVal.getValueType() == 7776 TLI.getPointerTy(DAG.getDataLayout()) && 7777 "Memory operands expect pointer values"); 7778 7779 unsigned ConstraintID = 7780 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7781 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7782 "Failed to convert memory constraint code to constraint id."); 7783 7784 // Add information to the INLINEASM node to know about this input. 7785 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7786 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7787 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7788 getCurSDLoc(), 7789 MVT::i32)); 7790 AsmNodeOperands.push_back(InOperandVal); 7791 break; 7792 } 7793 7794 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7795 OpInfo.ConstraintType == TargetLowering::C_Register) && 7796 "Unknown constraint type!"); 7797 7798 // TODO: Support this. 7799 if (OpInfo.isIndirect) { 7800 emitInlineAsmError( 7801 CS, "Don't know how to handle indirect register inputs yet " 7802 "for constraint '" + 7803 Twine(OpInfo.ConstraintCode) + "'"); 7804 return; 7805 } 7806 7807 // Copy the input into the appropriate registers. 7808 if (OpInfo.AssignedRegs.Regs.empty()) { 7809 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7810 Twine(OpInfo.ConstraintCode) + "'"); 7811 return; 7812 } 7813 7814 SDLoc dl = getCurSDLoc(); 7815 7816 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7817 Chain, &Flag, CS.getInstruction()); 7818 7819 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7820 dl, DAG, AsmNodeOperands); 7821 break; 7822 } 7823 case InlineAsm::isClobber: 7824 // Add the clobbered value to the operand list, so that the register 7825 // allocator is aware that the physreg got clobbered. 7826 if (!OpInfo.AssignedRegs.Regs.empty()) 7827 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7828 false, 0, getCurSDLoc(), DAG, 7829 AsmNodeOperands); 7830 break; 7831 } 7832 } 7833 7834 // Finish up input operands. Set the input chain and add the flag last. 7835 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7836 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7837 7838 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7839 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7840 Flag = Chain.getValue(1); 7841 7842 // Do additional work to generate outputs. 7843 7844 SmallVector<EVT, 1> ResultVTs; 7845 SmallVector<SDValue, 1> ResultValues; 7846 SmallVector<SDValue, 8> OutChains; 7847 7848 llvm::Type *CSResultType = CS.getType(); 7849 unsigned NumReturns = 0; 7850 ArrayRef<Type *> ResultTypes; 7851 if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) { 7852 NumReturns = StructResult->getNumElements(); 7853 ResultTypes = StructResult->elements(); 7854 } else if (!CSResultType->isVoidTy()) { 7855 NumReturns = 1; 7856 ResultTypes = makeArrayRef(CSResultType); 7857 } 7858 7859 auto CurResultType = ResultTypes.begin(); 7860 auto handleRegAssign = [&](SDValue V) { 7861 assert(CurResultType != ResultTypes.end() && "Unexpected value"); 7862 assert((*CurResultType)->isSized() && "Unexpected unsized type"); 7863 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType); 7864 ++CurResultType; 7865 // If the type of the inline asm call site return value is different but has 7866 // same size as the type of the asm output bitcast it. One example of this 7867 // is for vectors with different width / number of elements. This can 7868 // happen for register classes that can contain multiple different value 7869 // types. The preg or vreg allocated may not have the same VT as was 7870 // expected. 7871 // 7872 // This can also happen for a return value that disagrees with the register 7873 // class it is put in, eg. a double in a general-purpose register on a 7874 // 32-bit machine. 7875 if (ResultVT != V.getValueType() && 7876 ResultVT.getSizeInBits() == V.getValueSizeInBits()) 7877 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V); 7878 else if (ResultVT != V.getValueType() && ResultVT.isInteger() && 7879 V.getValueType().isInteger()) { 7880 // If a result value was tied to an input value, the computed result 7881 // may have a wider width than the expected result. Extract the 7882 // relevant portion. 7883 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V); 7884 } 7885 assert(ResultVT == V.getValueType() && "Asm result value mismatch!"); 7886 ResultVTs.push_back(ResultVT); 7887 ResultValues.push_back(V); 7888 }; 7889 7890 // Deal with assembly output fixups. 7891 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) { 7892 if (OpInfo.Type == InlineAsm::isOutput && 7893 (OpInfo.ConstraintType == TargetLowering::C_Register || 7894 OpInfo.ConstraintType == TargetLowering::C_RegisterClass)) { 7895 if (OpInfo.isIndirect) { 7896 // Register indirect are manifest as stores. 7897 const RegsForValue &OutRegs = OpInfo.AssignedRegs; 7898 const Value *Ptr = OpInfo.CallOperandVal; 7899 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7900 Chain, &Flag, IA); 7901 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), OutVal, getValue(Ptr), 7902 MachinePointerInfo(Ptr)); 7903 OutChains.push_back(Val); 7904 } else { 7905 // generate CopyFromRegs to associated registers. 7906 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7907 SDValue Val = OpInfo.AssignedRegs.getCopyFromRegs( 7908 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction()); 7909 if (Val.getOpcode() == ISD::MERGE_VALUES) { 7910 for (const SDValue &V : Val->op_values()) 7911 handleRegAssign(V); 7912 } else 7913 handleRegAssign(Val); 7914 } 7915 } 7916 } 7917 7918 // Set results. 7919 if (!ResultValues.empty()) { 7920 assert(CurResultType == ResultTypes.end() && 7921 "Mismatch in number of ResultTypes"); 7922 assert(ResultValues.size() == NumReturns && 7923 "Mismatch in number of output operands in asm result"); 7924 7925 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 7926 DAG.getVTList(ResultVTs), ResultValues); 7927 setValue(CS.getInstruction(), V); 7928 } 7929 7930 // Collect store chains. 7931 if (!OutChains.empty()) 7932 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7933 7934 // Only Update Root if inline assembly has a memory effect. 7935 if (ResultValues.empty() || HasSideEffect || !OutChains.empty()) 7936 DAG.setRoot(Chain); 7937 } 7938 7939 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7940 const Twine &Message) { 7941 LLVMContext &Ctx = *DAG.getContext(); 7942 Ctx.emitError(CS.getInstruction(), Message); 7943 7944 // Make sure we leave the DAG in a valid state 7945 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7946 SmallVector<EVT, 1> ValueVTs; 7947 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7948 7949 if (ValueVTs.empty()) 7950 return; 7951 7952 SmallVector<SDValue, 1> Ops; 7953 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i) 7954 Ops.push_back(DAG.getUNDEF(ValueVTs[i])); 7955 7956 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc())); 7957 } 7958 7959 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7960 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7961 MVT::Other, getRoot(), 7962 getValue(I.getArgOperand(0)), 7963 DAG.getSrcValue(I.getArgOperand(0)))); 7964 } 7965 7966 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7967 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7968 const DataLayout &DL = DAG.getDataLayout(); 7969 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7970 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7971 DAG.getSrcValue(I.getOperand(0)), 7972 DL.getABITypeAlignment(I.getType())); 7973 setValue(&I, V); 7974 DAG.setRoot(V.getValue(1)); 7975 } 7976 7977 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7978 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7979 MVT::Other, getRoot(), 7980 getValue(I.getArgOperand(0)), 7981 DAG.getSrcValue(I.getArgOperand(0)))); 7982 } 7983 7984 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7985 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7986 MVT::Other, getRoot(), 7987 getValue(I.getArgOperand(0)), 7988 getValue(I.getArgOperand(1)), 7989 DAG.getSrcValue(I.getArgOperand(0)), 7990 DAG.getSrcValue(I.getArgOperand(1)))); 7991 } 7992 7993 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7994 const Instruction &I, 7995 SDValue Op) { 7996 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7997 if (!Range) 7998 return Op; 7999 8000 ConstantRange CR = getConstantRangeFromMetadata(*Range); 8001 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 8002 return Op; 8003 8004 APInt Lo = CR.getUnsignedMin(); 8005 if (!Lo.isMinValue()) 8006 return Op; 8007 8008 APInt Hi = CR.getUnsignedMax(); 8009 unsigned Bits = std::max(Hi.getActiveBits(), 8010 static_cast<unsigned>(IntegerType::MIN_INT_BITS)); 8011 8012 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8013 8014 SDLoc SL = getCurSDLoc(); 8015 8016 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 8017 DAG.getValueType(SmallVT)); 8018 unsigned NumVals = Op.getNode()->getNumValues(); 8019 if (NumVals == 1) 8020 return ZExt; 8021 8022 SmallVector<SDValue, 4> Ops; 8023 8024 Ops.push_back(ZExt); 8025 for (unsigned I = 1; I != NumVals; ++I) 8026 Ops.push_back(Op.getValue(I)); 8027 8028 return DAG.getMergeValues(Ops, SL); 8029 } 8030 8031 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of 8032 /// the call being lowered. 8033 /// 8034 /// This is a helper for lowering intrinsics that follow a target calling 8035 /// convention or require stack pointer adjustment. Only a subset of the 8036 /// intrinsic's operands need to participate in the calling convention. 8037 void SelectionDAGBuilder::populateCallLoweringInfo( 8038 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 8039 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 8040 bool IsPatchPoint) { 8041 TargetLowering::ArgListTy Args; 8042 Args.reserve(NumArgs); 8043 8044 // Populate the argument list. 8045 // Attributes for args start at offset 1, after the return attribute. 8046 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 8047 ArgI != ArgE; ++ArgI) { 8048 const Value *V = CS->getOperand(ArgI); 8049 8050 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 8051 8052 TargetLowering::ArgListEntry Entry; 8053 Entry.Node = getValue(V); 8054 Entry.Ty = V->getType(); 8055 Entry.setAttributes(&CS, ArgI); 8056 Args.push_back(Entry); 8057 } 8058 8059 CLI.setDebugLoc(getCurSDLoc()) 8060 .setChain(getRoot()) 8061 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 8062 .setDiscardResult(CS->use_empty()) 8063 .setIsPatchPoint(IsPatchPoint); 8064 } 8065 8066 /// Add a stack map intrinsic call's live variable operands to a stackmap 8067 /// or patchpoint target node's operand list. 8068 /// 8069 /// Constants are converted to TargetConstants purely as an optimization to 8070 /// avoid constant materialization and register allocation. 8071 /// 8072 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 8073 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 8074 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 8075 /// address materialization and register allocation, but may also be required 8076 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 8077 /// alloca in the entry block, then the runtime may assume that the alloca's 8078 /// StackMap location can be read immediately after compilation and that the 8079 /// location is valid at any point during execution (this is similar to the 8080 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 8081 /// only available in a register, then the runtime would need to trap when 8082 /// execution reaches the StackMap in order to read the alloca's location. 8083 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 8084 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 8085 SelectionDAGBuilder &Builder) { 8086 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 8087 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 8088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 8089 Ops.push_back( 8090 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 8091 Ops.push_back( 8092 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 8093 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 8094 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 8095 Ops.push_back(Builder.DAG.getTargetFrameIndex( 8096 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 8097 } else 8098 Ops.push_back(OpVal); 8099 } 8100 } 8101 8102 /// Lower llvm.experimental.stackmap directly to its target opcode. 8103 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 8104 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 8105 // [live variables...]) 8106 8107 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 8108 8109 SDValue Chain, InFlag, Callee, NullPtr; 8110 SmallVector<SDValue, 32> Ops; 8111 8112 SDLoc DL = getCurSDLoc(); 8113 Callee = getValue(CI.getCalledValue()); 8114 NullPtr = DAG.getIntPtrConstant(0, DL, true); 8115 8116 // The stackmap intrinsic only records the live variables (the arguemnts 8117 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 8118 // intrinsic, this won't be lowered to a function call. This means we don't 8119 // have to worry about calling conventions and target specific lowering code. 8120 // Instead we perform the call lowering right here. 8121 // 8122 // chain, flag = CALLSEQ_START(chain, 0, 0) 8123 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 8124 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 8125 // 8126 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 8127 InFlag = Chain.getValue(1); 8128 8129 // Add the <id> and <numBytes> constants. 8130 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 8131 Ops.push_back(DAG.getTargetConstant( 8132 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 8133 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 8134 Ops.push_back(DAG.getTargetConstant( 8135 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 8136 MVT::i32)); 8137 8138 // Push live variables for the stack map. 8139 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 8140 8141 // We are not pushing any register mask info here on the operands list, 8142 // because the stackmap doesn't clobber anything. 8143 8144 // Push the chain and the glue flag. 8145 Ops.push_back(Chain); 8146 Ops.push_back(InFlag); 8147 8148 // Create the STACKMAP node. 8149 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8150 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 8151 Chain = SDValue(SM, 0); 8152 InFlag = Chain.getValue(1); 8153 8154 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 8155 8156 // Stackmaps don't generate values, so nothing goes into the NodeMap. 8157 8158 // Set the root to the target-lowered call chain. 8159 DAG.setRoot(Chain); 8160 8161 // Inform the Frame Information that we have a stackmap in this function. 8162 FuncInfo.MF->getFrameInfo().setHasStackMap(); 8163 } 8164 8165 /// Lower llvm.experimental.patchpoint directly to its target opcode. 8166 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 8167 const BasicBlock *EHPadBB) { 8168 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 8169 // i32 <numBytes>, 8170 // i8* <target>, 8171 // i32 <numArgs>, 8172 // [Args...], 8173 // [live variables...]) 8174 8175 CallingConv::ID CC = CS.getCallingConv(); 8176 bool IsAnyRegCC = CC == CallingConv::AnyReg; 8177 bool HasDef = !CS->getType()->isVoidTy(); 8178 SDLoc dl = getCurSDLoc(); 8179 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 8180 8181 // Handle immediate and symbolic callees. 8182 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 8183 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 8184 /*isTarget=*/true); 8185 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 8186 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 8187 SDLoc(SymbolicCallee), 8188 SymbolicCallee->getValueType(0)); 8189 8190 // Get the real number of arguments participating in the call <numArgs> 8191 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 8192 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 8193 8194 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 8195 // Intrinsics include all meta-operands up to but not including CC. 8196 unsigned NumMetaOpers = PatchPointOpers::CCPos; 8197 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 8198 "Not enough arguments provided to the patchpoint intrinsic"); 8199 8200 // For AnyRegCC the arguments are lowered later on manually. 8201 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 8202 Type *ReturnTy = 8203 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 8204 8205 TargetLowering::CallLoweringInfo CLI(DAG); 8206 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 8207 true); 8208 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 8209 8210 SDNode *CallEnd = Result.second.getNode(); 8211 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 8212 CallEnd = CallEnd->getOperand(0).getNode(); 8213 8214 /// Get a call instruction from the call sequence chain. 8215 /// Tail calls are not allowed. 8216 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 8217 "Expected a callseq node."); 8218 SDNode *Call = CallEnd->getOperand(0).getNode(); 8219 bool HasGlue = Call->getGluedNode(); 8220 8221 // Replace the target specific call node with the patchable intrinsic. 8222 SmallVector<SDValue, 8> Ops; 8223 8224 // Add the <id> and <numBytes> constants. 8225 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 8226 Ops.push_back(DAG.getTargetConstant( 8227 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 8228 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 8229 Ops.push_back(DAG.getTargetConstant( 8230 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 8231 MVT::i32)); 8232 8233 // Add the callee. 8234 Ops.push_back(Callee); 8235 8236 // Adjust <numArgs> to account for any arguments that have been passed on the 8237 // stack instead. 8238 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 8239 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 8240 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 8241 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 8242 8243 // Add the calling convention 8244 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 8245 8246 // Add the arguments we omitted previously. The register allocator should 8247 // place these in any free register. 8248 if (IsAnyRegCC) 8249 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 8250 Ops.push_back(getValue(CS.getArgument(i))); 8251 8252 // Push the arguments from the call instruction up to the register mask. 8253 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 8254 Ops.append(Call->op_begin() + 2, e); 8255 8256 // Push live variables for the stack map. 8257 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 8258 8259 // Push the register mask info. 8260 if (HasGlue) 8261 Ops.push_back(*(Call->op_end()-2)); 8262 else 8263 Ops.push_back(*(Call->op_end()-1)); 8264 8265 // Push the chain (this is originally the first operand of the call, but 8266 // becomes now the last or second to last operand). 8267 Ops.push_back(*(Call->op_begin())); 8268 8269 // Push the glue flag (last operand). 8270 if (HasGlue) 8271 Ops.push_back(*(Call->op_end()-1)); 8272 8273 SDVTList NodeTys; 8274 if (IsAnyRegCC && HasDef) { 8275 // Create the return types based on the intrinsic definition 8276 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8277 SmallVector<EVT, 3> ValueVTs; 8278 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 8279 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 8280 8281 // There is always a chain and a glue type at the end 8282 ValueVTs.push_back(MVT::Other); 8283 ValueVTs.push_back(MVT::Glue); 8284 NodeTys = DAG.getVTList(ValueVTs); 8285 } else 8286 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 8287 8288 // Replace the target specific call node with a PATCHPOINT node. 8289 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 8290 dl, NodeTys, Ops); 8291 8292 // Update the NodeMap. 8293 if (HasDef) { 8294 if (IsAnyRegCC) 8295 setValue(CS.getInstruction(), SDValue(MN, 0)); 8296 else 8297 setValue(CS.getInstruction(), Result.first); 8298 } 8299 8300 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 8301 // call sequence. Furthermore the location of the chain and glue can change 8302 // when the AnyReg calling convention is used and the intrinsic returns a 8303 // value. 8304 if (IsAnyRegCC && HasDef) { 8305 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 8306 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 8307 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 8308 } else 8309 DAG.ReplaceAllUsesWith(Call, MN); 8310 DAG.DeleteNode(Call); 8311 8312 // Inform the Frame Information that we have a patchpoint in this function. 8313 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 8314 } 8315 8316 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 8317 unsigned Intrinsic) { 8318 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8319 SDValue Op1 = getValue(I.getArgOperand(0)); 8320 SDValue Op2; 8321 if (I.getNumArgOperands() > 1) 8322 Op2 = getValue(I.getArgOperand(1)); 8323 SDLoc dl = getCurSDLoc(); 8324 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 8325 SDValue Res; 8326 FastMathFlags FMF; 8327 if (isa<FPMathOperator>(I)) 8328 FMF = I.getFastMathFlags(); 8329 8330 switch (Intrinsic) { 8331 case Intrinsic::experimental_vector_reduce_fadd: 8332 if (FMF.isFast()) 8333 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 8334 else 8335 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 8336 break; 8337 case Intrinsic::experimental_vector_reduce_fmul: 8338 if (FMF.isFast()) 8339 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 8340 else 8341 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 8342 break; 8343 case Intrinsic::experimental_vector_reduce_add: 8344 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 8345 break; 8346 case Intrinsic::experimental_vector_reduce_mul: 8347 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 8348 break; 8349 case Intrinsic::experimental_vector_reduce_and: 8350 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 8351 break; 8352 case Intrinsic::experimental_vector_reduce_or: 8353 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 8354 break; 8355 case Intrinsic::experimental_vector_reduce_xor: 8356 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 8357 break; 8358 case Intrinsic::experimental_vector_reduce_smax: 8359 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 8360 break; 8361 case Intrinsic::experimental_vector_reduce_smin: 8362 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 8363 break; 8364 case Intrinsic::experimental_vector_reduce_umax: 8365 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 8366 break; 8367 case Intrinsic::experimental_vector_reduce_umin: 8368 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 8369 break; 8370 case Intrinsic::experimental_vector_reduce_fmax: 8371 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1); 8372 break; 8373 case Intrinsic::experimental_vector_reduce_fmin: 8374 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1); 8375 break; 8376 default: 8377 llvm_unreachable("Unhandled vector reduce intrinsic"); 8378 } 8379 setValue(&I, Res); 8380 } 8381 8382 /// Returns an AttributeList representing the attributes applied to the return 8383 /// value of the given call. 8384 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8385 SmallVector<Attribute::AttrKind, 2> Attrs; 8386 if (CLI.RetSExt) 8387 Attrs.push_back(Attribute::SExt); 8388 if (CLI.RetZExt) 8389 Attrs.push_back(Attribute::ZExt); 8390 if (CLI.IsInReg) 8391 Attrs.push_back(Attribute::InReg); 8392 8393 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8394 Attrs); 8395 } 8396 8397 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8398 /// implementation, which just calls LowerCall. 8399 /// FIXME: When all targets are 8400 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8401 std::pair<SDValue, SDValue> 8402 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8403 // Handle the incoming return values from the call. 8404 CLI.Ins.clear(); 8405 Type *OrigRetTy = CLI.RetTy; 8406 SmallVector<EVT, 4> RetTys; 8407 SmallVector<uint64_t, 4> Offsets; 8408 auto &DL = CLI.DAG.getDataLayout(); 8409 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8410 8411 if (CLI.IsPostTypeLegalization) { 8412 // If we are lowering a libcall after legalization, split the return type. 8413 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8414 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8415 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8416 EVT RetVT = OldRetTys[i]; 8417 uint64_t Offset = OldOffsets[i]; 8418 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8419 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8420 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8421 RetTys.append(NumRegs, RegisterVT); 8422 for (unsigned j = 0; j != NumRegs; ++j) 8423 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8424 } 8425 } 8426 8427 SmallVector<ISD::OutputArg, 4> Outs; 8428 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8429 8430 bool CanLowerReturn = 8431 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8432 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8433 8434 SDValue DemoteStackSlot; 8435 int DemoteStackIdx = -100; 8436 if (!CanLowerReturn) { 8437 // FIXME: equivalent assert? 8438 // assert(!CS.hasInAllocaArgument() && 8439 // "sret demotion is incompatible with inalloca"); 8440 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8441 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8442 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8443 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8444 Type *StackSlotPtrType = PointerType::get(CLI.RetTy, 8445 DL.getAllocaAddrSpace()); 8446 8447 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8448 ArgListEntry Entry; 8449 Entry.Node = DemoteStackSlot; 8450 Entry.Ty = StackSlotPtrType; 8451 Entry.IsSExt = false; 8452 Entry.IsZExt = false; 8453 Entry.IsInReg = false; 8454 Entry.IsSRet = true; 8455 Entry.IsNest = false; 8456 Entry.IsByVal = false; 8457 Entry.IsReturned = false; 8458 Entry.IsSwiftSelf = false; 8459 Entry.IsSwiftError = false; 8460 Entry.Alignment = Align; 8461 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8462 CLI.NumFixedArgs += 1; 8463 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8464 8465 // sret demotion isn't compatible with tail-calls, since the sret argument 8466 // points into the callers stack frame. 8467 CLI.IsTailCall = false; 8468 } else { 8469 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8470 EVT VT = RetTys[I]; 8471 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8472 CLI.CallConv, VT); 8473 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8474 CLI.CallConv, VT); 8475 for (unsigned i = 0; i != NumRegs; ++i) { 8476 ISD::InputArg MyFlags; 8477 MyFlags.VT = RegisterVT; 8478 MyFlags.ArgVT = VT; 8479 MyFlags.Used = CLI.IsReturnValueUsed; 8480 if (CLI.RetSExt) 8481 MyFlags.Flags.setSExt(); 8482 if (CLI.RetZExt) 8483 MyFlags.Flags.setZExt(); 8484 if (CLI.IsInReg) 8485 MyFlags.Flags.setInReg(); 8486 CLI.Ins.push_back(MyFlags); 8487 } 8488 } 8489 } 8490 8491 // We push in swifterror return as the last element of CLI.Ins. 8492 ArgListTy &Args = CLI.getArgs(); 8493 if (supportSwiftError()) { 8494 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8495 if (Args[i].IsSwiftError) { 8496 ISD::InputArg MyFlags; 8497 MyFlags.VT = getPointerTy(DL); 8498 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8499 MyFlags.Flags.setSwiftError(); 8500 CLI.Ins.push_back(MyFlags); 8501 } 8502 } 8503 } 8504 8505 // Handle all of the outgoing arguments. 8506 CLI.Outs.clear(); 8507 CLI.OutVals.clear(); 8508 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8509 SmallVector<EVT, 4> ValueVTs; 8510 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8511 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8512 Type *FinalType = Args[i].Ty; 8513 if (Args[i].IsByVal) 8514 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8515 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8516 FinalType, CLI.CallConv, CLI.IsVarArg); 8517 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8518 ++Value) { 8519 EVT VT = ValueVTs[Value]; 8520 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8521 SDValue Op = SDValue(Args[i].Node.getNode(), 8522 Args[i].Node.getResNo() + Value); 8523 ISD::ArgFlagsTy Flags; 8524 8525 // Certain targets (such as MIPS), may have a different ABI alignment 8526 // for a type depending on the context. Give the target a chance to 8527 // specify the alignment it wants. 8528 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8529 8530 if (Args[i].IsZExt) 8531 Flags.setZExt(); 8532 if (Args[i].IsSExt) 8533 Flags.setSExt(); 8534 if (Args[i].IsInReg) { 8535 // If we are using vectorcall calling convention, a structure that is 8536 // passed InReg - is surely an HVA 8537 if (CLI.CallConv == CallingConv::X86_VectorCall && 8538 isa<StructType>(FinalType)) { 8539 // The first value of a structure is marked 8540 if (0 == Value) 8541 Flags.setHvaStart(); 8542 Flags.setHva(); 8543 } 8544 // Set InReg Flag 8545 Flags.setInReg(); 8546 } 8547 if (Args[i].IsSRet) 8548 Flags.setSRet(); 8549 if (Args[i].IsSwiftSelf) 8550 Flags.setSwiftSelf(); 8551 if (Args[i].IsSwiftError) 8552 Flags.setSwiftError(); 8553 if (Args[i].IsByVal) 8554 Flags.setByVal(); 8555 if (Args[i].IsInAlloca) { 8556 Flags.setInAlloca(); 8557 // Set the byval flag for CCAssignFn callbacks that don't know about 8558 // inalloca. This way we can know how many bytes we should've allocated 8559 // and how many bytes a callee cleanup function will pop. If we port 8560 // inalloca to more targets, we'll have to add custom inalloca handling 8561 // in the various CC lowering callbacks. 8562 Flags.setByVal(); 8563 } 8564 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8565 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8566 Type *ElementTy = Ty->getElementType(); 8567 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8568 // For ByVal, alignment should come from FE. BE will guess if this 8569 // info is not there but there are cases it cannot get right. 8570 unsigned FrameAlign; 8571 if (Args[i].Alignment) 8572 FrameAlign = Args[i].Alignment; 8573 else 8574 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8575 Flags.setByValAlign(FrameAlign); 8576 } 8577 if (Args[i].IsNest) 8578 Flags.setNest(); 8579 if (NeedsRegBlock) 8580 Flags.setInConsecutiveRegs(); 8581 Flags.setOrigAlign(OriginalAlignment); 8582 8583 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8584 CLI.CallConv, VT); 8585 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8586 CLI.CallConv, VT); 8587 SmallVector<SDValue, 4> Parts(NumParts); 8588 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8589 8590 if (Args[i].IsSExt) 8591 ExtendKind = ISD::SIGN_EXTEND; 8592 else if (Args[i].IsZExt) 8593 ExtendKind = ISD::ZERO_EXTEND; 8594 8595 // Conservatively only handle 'returned' on non-vectors that can be lowered, 8596 // for now. 8597 if (Args[i].IsReturned && !Op.getValueType().isVector() && 8598 CanLowerReturn) { 8599 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8600 "unexpected use of 'returned'"); 8601 // Before passing 'returned' to the target lowering code, ensure that 8602 // either the register MVT and the actual EVT are the same size or that 8603 // the return value and argument are extended in the same way; in these 8604 // cases it's safe to pass the argument register value unchanged as the 8605 // return register value (although it's at the target's option whether 8606 // to do so) 8607 // TODO: allow code generation to take advantage of partially preserved 8608 // registers rather than clobbering the entire register when the 8609 // parameter extension method is not compatible with the return 8610 // extension method 8611 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8612 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8613 CLI.RetZExt == Args[i].IsZExt)) 8614 Flags.setReturned(); 8615 } 8616 8617 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8618 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind); 8619 8620 for (unsigned j = 0; j != NumParts; ++j) { 8621 // if it isn't first piece, alignment must be 1 8622 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8623 i < CLI.NumFixedArgs, 8624 i, j*Parts[j].getValueType().getStoreSize()); 8625 if (NumParts > 1 && j == 0) 8626 MyFlags.Flags.setSplit(); 8627 else if (j != 0) { 8628 MyFlags.Flags.setOrigAlign(1); 8629 if (j == NumParts - 1) 8630 MyFlags.Flags.setSplitEnd(); 8631 } 8632 8633 CLI.Outs.push_back(MyFlags); 8634 CLI.OutVals.push_back(Parts[j]); 8635 } 8636 8637 if (NeedsRegBlock && Value == NumValues - 1) 8638 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8639 } 8640 } 8641 8642 SmallVector<SDValue, 4> InVals; 8643 CLI.Chain = LowerCall(CLI, InVals); 8644 8645 // Update CLI.InVals to use outside of this function. 8646 CLI.InVals = InVals; 8647 8648 // Verify that the target's LowerCall behaved as expected. 8649 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8650 "LowerCall didn't return a valid chain!"); 8651 assert((!CLI.IsTailCall || InVals.empty()) && 8652 "LowerCall emitted a return value for a tail call!"); 8653 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8654 "LowerCall didn't emit the correct number of values!"); 8655 8656 // For a tail call, the return value is merely live-out and there aren't 8657 // any nodes in the DAG representing it. Return a special value to 8658 // indicate that a tail call has been emitted and no more Instructions 8659 // should be processed in the current block. 8660 if (CLI.IsTailCall) { 8661 CLI.DAG.setRoot(CLI.Chain); 8662 return std::make_pair(SDValue(), SDValue()); 8663 } 8664 8665 #ifndef NDEBUG 8666 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8667 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8668 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8669 "LowerCall emitted a value with the wrong type!"); 8670 } 8671 #endif 8672 8673 SmallVector<SDValue, 4> ReturnValues; 8674 if (!CanLowerReturn) { 8675 // The instruction result is the result of loading from the 8676 // hidden sret parameter. 8677 SmallVector<EVT, 1> PVTs; 8678 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8679 8680 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8681 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8682 EVT PtrVT = PVTs[0]; 8683 8684 unsigned NumValues = RetTys.size(); 8685 ReturnValues.resize(NumValues); 8686 SmallVector<SDValue, 4> Chains(NumValues); 8687 8688 // An aggregate return value cannot wrap around the address space, so 8689 // offsets to its parts don't wrap either. 8690 SDNodeFlags Flags; 8691 Flags.setNoUnsignedWrap(true); 8692 8693 for (unsigned i = 0; i < NumValues; ++i) { 8694 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8695 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8696 PtrVT), Flags); 8697 SDValue L = CLI.DAG.getLoad( 8698 RetTys[i], CLI.DL, CLI.Chain, Add, 8699 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8700 DemoteStackIdx, Offsets[i]), 8701 /* Alignment = */ 1); 8702 ReturnValues[i] = L; 8703 Chains[i] = L.getValue(1); 8704 } 8705 8706 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8707 } else { 8708 // Collect the legal value parts into potentially illegal values 8709 // that correspond to the original function's return values. 8710 Optional<ISD::NodeType> AssertOp; 8711 if (CLI.RetSExt) 8712 AssertOp = ISD::AssertSext; 8713 else if (CLI.RetZExt) 8714 AssertOp = ISD::AssertZext; 8715 unsigned CurReg = 0; 8716 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8717 EVT VT = RetTys[I]; 8718 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), 8719 CLI.CallConv, VT); 8720 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(), 8721 CLI.CallConv, VT); 8722 8723 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8724 NumRegs, RegisterVT, VT, nullptr, 8725 CLI.CallConv, AssertOp)); 8726 CurReg += NumRegs; 8727 } 8728 8729 // For a function returning void, there is no return value. We can't create 8730 // such a node, so we just return a null return value in that case. In 8731 // that case, nothing will actually look at the value. 8732 if (ReturnValues.empty()) 8733 return std::make_pair(SDValue(), CLI.Chain); 8734 } 8735 8736 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8737 CLI.DAG.getVTList(RetTys), ReturnValues); 8738 return std::make_pair(Res, CLI.Chain); 8739 } 8740 8741 void TargetLowering::LowerOperationWrapper(SDNode *N, 8742 SmallVectorImpl<SDValue> &Results, 8743 SelectionDAG &DAG) const { 8744 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8745 Results.push_back(Res); 8746 } 8747 8748 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8749 llvm_unreachable("LowerOperation not implemented for this target!"); 8750 } 8751 8752 void 8753 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8754 SDValue Op = getNonRegisterValue(V); 8755 assert((Op.getOpcode() != ISD::CopyFromReg || 8756 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8757 "Copy from a reg to the same reg!"); 8758 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8759 8760 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8761 // If this is an InlineAsm we have to match the registers required, not the 8762 // notional registers required by the type. 8763 8764 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(), 8765 None); // This is not an ABI copy. 8766 SDValue Chain = DAG.getEntryNode(); 8767 8768 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8769 FuncInfo.PreferredExtendType.end()) 8770 ? ISD::ANY_EXTEND 8771 : FuncInfo.PreferredExtendType[V]; 8772 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8773 PendingExports.push_back(Chain); 8774 } 8775 8776 #include "llvm/CodeGen/SelectionDAGISel.h" 8777 8778 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8779 /// entry block, return true. This includes arguments used by switches, since 8780 /// the switch may expand into multiple basic blocks. 8781 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8782 // With FastISel active, we may be splitting blocks, so force creation 8783 // of virtual registers for all non-dead arguments. 8784 if (FastISel) 8785 return A->use_empty(); 8786 8787 const BasicBlock &Entry = A->getParent()->front(); 8788 for (const User *U : A->users()) 8789 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8790 return false; // Use not in entry block. 8791 8792 return true; 8793 } 8794 8795 using ArgCopyElisionMapTy = 8796 DenseMap<const Argument *, 8797 std::pair<const AllocaInst *, const StoreInst *>>; 8798 8799 /// Scan the entry block of the function in FuncInfo for arguments that look 8800 /// like copies into a local alloca. Record any copied arguments in 8801 /// ArgCopyElisionCandidates. 8802 static void 8803 findArgumentCopyElisionCandidates(const DataLayout &DL, 8804 FunctionLoweringInfo *FuncInfo, 8805 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8806 // Record the state of every static alloca used in the entry block. Argument 8807 // allocas are all used in the entry block, so we need approximately as many 8808 // entries as we have arguments. 8809 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8810 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8811 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8812 StaticAllocas.reserve(NumArgs * 2); 8813 8814 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8815 if (!V) 8816 return nullptr; 8817 V = V->stripPointerCasts(); 8818 const auto *AI = dyn_cast<AllocaInst>(V); 8819 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8820 return nullptr; 8821 auto Iter = StaticAllocas.insert({AI, Unknown}); 8822 return &Iter.first->second; 8823 }; 8824 8825 // Look for stores of arguments to static allocas. Look through bitcasts and 8826 // GEPs to handle type coercions, as long as the alloca is fully initialized 8827 // by the store. Any non-store use of an alloca escapes it and any subsequent 8828 // unanalyzed store might write it. 8829 // FIXME: Handle structs initialized with multiple stores. 8830 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8831 // Look for stores, and handle non-store uses conservatively. 8832 const auto *SI = dyn_cast<StoreInst>(&I); 8833 if (!SI) { 8834 // We will look through cast uses, so ignore them completely. 8835 if (I.isCast()) 8836 continue; 8837 // Ignore debug info intrinsics, they don't escape or store to allocas. 8838 if (isa<DbgInfoIntrinsic>(I)) 8839 continue; 8840 // This is an unknown instruction. Assume it escapes or writes to all 8841 // static alloca operands. 8842 for (const Use &U : I.operands()) { 8843 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8844 *Info = StaticAllocaInfo::Clobbered; 8845 } 8846 continue; 8847 } 8848 8849 // If the stored value is a static alloca, mark it as escaped. 8850 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8851 *Info = StaticAllocaInfo::Clobbered; 8852 8853 // Check if the destination is a static alloca. 8854 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8855 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8856 if (!Info) 8857 continue; 8858 const AllocaInst *AI = cast<AllocaInst>(Dst); 8859 8860 // Skip allocas that have been initialized or clobbered. 8861 if (*Info != StaticAllocaInfo::Unknown) 8862 continue; 8863 8864 // Check if the stored value is an argument, and that this store fully 8865 // initializes the alloca. Don't elide copies from the same argument twice. 8866 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8867 const auto *Arg = dyn_cast<Argument>(Val); 8868 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8869 Arg->getType()->isEmptyTy() || 8870 DL.getTypeStoreSize(Arg->getType()) != 8871 DL.getTypeAllocSize(AI->getAllocatedType()) || 8872 ArgCopyElisionCandidates.count(Arg)) { 8873 *Info = StaticAllocaInfo::Clobbered; 8874 continue; 8875 } 8876 8877 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI 8878 << '\n'); 8879 8880 // Mark this alloca and store for argument copy elision. 8881 *Info = StaticAllocaInfo::Elidable; 8882 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8883 8884 // Stop scanning if we've seen all arguments. This will happen early in -O0 8885 // builds, which is useful, because -O0 builds have large entry blocks and 8886 // many allocas. 8887 if (ArgCopyElisionCandidates.size() == NumArgs) 8888 break; 8889 } 8890 } 8891 8892 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8893 /// ArgVal is a load from a suitable fixed stack object. 8894 static void tryToElideArgumentCopy( 8895 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8896 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8897 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8898 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8899 SDValue ArgVal, bool &ArgHasUses) { 8900 // Check if this is a load from a fixed stack object. 8901 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8902 if (!LNode) 8903 return; 8904 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8905 if (!FINode) 8906 return; 8907 8908 // Check that the fixed stack object is the right size and alignment. 8909 // Look at the alignment that the user wrote on the alloca instead of looking 8910 // at the stack object. 8911 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8912 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8913 const AllocaInst *AI = ArgCopyIter->second.first; 8914 int FixedIndex = FINode->getIndex(); 8915 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8916 int OldIndex = AllocaIndex; 8917 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8918 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8919 LLVM_DEBUG( 8920 dbgs() << " argument copy elision failed due to bad fixed stack " 8921 "object size\n"); 8922 return; 8923 } 8924 unsigned RequiredAlignment = AI->getAlignment(); 8925 if (!RequiredAlignment) { 8926 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8927 AI->getAllocatedType()); 8928 } 8929 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8930 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8931 "greater than stack argument alignment (" 8932 << RequiredAlignment << " vs " 8933 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8934 return; 8935 } 8936 8937 // Perform the elision. Delete the old stack object and replace its only use 8938 // in the variable info map. Mark the stack object as mutable. 8939 LLVM_DEBUG({ 8940 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8941 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8942 << '\n'; 8943 }); 8944 MFI.RemoveStackObject(OldIndex); 8945 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8946 AllocaIndex = FixedIndex; 8947 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8948 Chains.push_back(ArgVal.getValue(1)); 8949 8950 // Avoid emitting code for the store implementing the copy. 8951 const StoreInst *SI = ArgCopyIter->second.second; 8952 ElidedArgCopyInstrs.insert(SI); 8953 8954 // Check for uses of the argument again so that we can avoid exporting ArgVal 8955 // if it is't used by anything other than the store. 8956 for (const Value *U : Arg.users()) { 8957 if (U != SI) { 8958 ArgHasUses = true; 8959 break; 8960 } 8961 } 8962 } 8963 8964 void SelectionDAGISel::LowerArguments(const Function &F) { 8965 SelectionDAG &DAG = SDB->DAG; 8966 SDLoc dl = SDB->getCurSDLoc(); 8967 const DataLayout &DL = DAG.getDataLayout(); 8968 SmallVector<ISD::InputArg, 16> Ins; 8969 8970 if (!FuncInfo->CanLowerReturn) { 8971 // Put in an sret pointer parameter before all the other parameters. 8972 SmallVector<EVT, 1> ValueVTs; 8973 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8974 F.getReturnType()->getPointerTo( 8975 DAG.getDataLayout().getAllocaAddrSpace()), 8976 ValueVTs); 8977 8978 // NOTE: Assuming that a pointer will never break down to more than one VT 8979 // or one register. 8980 ISD::ArgFlagsTy Flags; 8981 Flags.setSRet(); 8982 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8983 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8984 ISD::InputArg::NoArgIndex, 0); 8985 Ins.push_back(RetArg); 8986 } 8987 8988 // Look for stores of arguments to static allocas. Mark such arguments with a 8989 // flag to ask the target to give us the memory location of that argument if 8990 // available. 8991 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8992 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8993 8994 // Set up the incoming argument description vector. 8995 for (const Argument &Arg : F.args()) { 8996 unsigned ArgNo = Arg.getArgNo(); 8997 SmallVector<EVT, 4> ValueVTs; 8998 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8999 bool isArgValueUsed = !Arg.use_empty(); 9000 unsigned PartBase = 0; 9001 Type *FinalType = Arg.getType(); 9002 if (Arg.hasAttribute(Attribute::ByVal)) 9003 FinalType = cast<PointerType>(FinalType)->getElementType(); 9004 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 9005 FinalType, F.getCallingConv(), F.isVarArg()); 9006 for (unsigned Value = 0, NumValues = ValueVTs.size(); 9007 Value != NumValues; ++Value) { 9008 EVT VT = ValueVTs[Value]; 9009 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 9010 ISD::ArgFlagsTy Flags; 9011 9012 // Certain targets (such as MIPS), may have a different ABI alignment 9013 // for a type depending on the context. Give the target a chance to 9014 // specify the alignment it wants. 9015 unsigned OriginalAlignment = 9016 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 9017 9018 if (Arg.hasAttribute(Attribute::ZExt)) 9019 Flags.setZExt(); 9020 if (Arg.hasAttribute(Attribute::SExt)) 9021 Flags.setSExt(); 9022 if (Arg.hasAttribute(Attribute::InReg)) { 9023 // If we are using vectorcall calling convention, a structure that is 9024 // passed InReg - is surely an HVA 9025 if (F.getCallingConv() == CallingConv::X86_VectorCall && 9026 isa<StructType>(Arg.getType())) { 9027 // The first value of a structure is marked 9028 if (0 == Value) 9029 Flags.setHvaStart(); 9030 Flags.setHva(); 9031 } 9032 // Set InReg Flag 9033 Flags.setInReg(); 9034 } 9035 if (Arg.hasAttribute(Attribute::StructRet)) 9036 Flags.setSRet(); 9037 if (Arg.hasAttribute(Attribute::SwiftSelf)) 9038 Flags.setSwiftSelf(); 9039 if (Arg.hasAttribute(Attribute::SwiftError)) 9040 Flags.setSwiftError(); 9041 if (Arg.hasAttribute(Attribute::ByVal)) 9042 Flags.setByVal(); 9043 if (Arg.hasAttribute(Attribute::InAlloca)) { 9044 Flags.setInAlloca(); 9045 // Set the byval flag for CCAssignFn callbacks that don't know about 9046 // inalloca. This way we can know how many bytes we should've allocated 9047 // and how many bytes a callee cleanup function will pop. If we port 9048 // inalloca to more targets, we'll have to add custom inalloca handling 9049 // in the various CC lowering callbacks. 9050 Flags.setByVal(); 9051 } 9052 if (F.getCallingConv() == CallingConv::X86_INTR) { 9053 // IA Interrupt passes frame (1st parameter) by value in the stack. 9054 if (ArgNo == 0) 9055 Flags.setByVal(); 9056 } 9057 if (Flags.isByVal() || Flags.isInAlloca()) { 9058 PointerType *Ty = cast<PointerType>(Arg.getType()); 9059 Type *ElementTy = Ty->getElementType(); 9060 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 9061 // For ByVal, alignment should be passed from FE. BE will guess if 9062 // this info is not there but there are cases it cannot get right. 9063 unsigned FrameAlign; 9064 if (Arg.getParamAlignment()) 9065 FrameAlign = Arg.getParamAlignment(); 9066 else 9067 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 9068 Flags.setByValAlign(FrameAlign); 9069 } 9070 if (Arg.hasAttribute(Attribute::Nest)) 9071 Flags.setNest(); 9072 if (NeedsRegBlock) 9073 Flags.setInConsecutiveRegs(); 9074 Flags.setOrigAlign(OriginalAlignment); 9075 if (ArgCopyElisionCandidates.count(&Arg)) 9076 Flags.setCopyElisionCandidate(); 9077 9078 MVT RegisterVT = TLI->getRegisterTypeForCallingConv( 9079 *CurDAG->getContext(), F.getCallingConv(), VT); 9080 unsigned NumRegs = TLI->getNumRegistersForCallingConv( 9081 *CurDAG->getContext(), F.getCallingConv(), VT); 9082 for (unsigned i = 0; i != NumRegs; ++i) { 9083 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 9084 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 9085 if (NumRegs > 1 && i == 0) 9086 MyFlags.Flags.setSplit(); 9087 // if it isn't first piece, alignment must be 1 9088 else if (i > 0) { 9089 MyFlags.Flags.setOrigAlign(1); 9090 if (i == NumRegs - 1) 9091 MyFlags.Flags.setSplitEnd(); 9092 } 9093 Ins.push_back(MyFlags); 9094 } 9095 if (NeedsRegBlock && Value == NumValues - 1) 9096 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 9097 PartBase += VT.getStoreSize(); 9098 } 9099 } 9100 9101 // Call the target to set up the argument values. 9102 SmallVector<SDValue, 8> InVals; 9103 SDValue NewRoot = TLI->LowerFormalArguments( 9104 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 9105 9106 // Verify that the target's LowerFormalArguments behaved as expected. 9107 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 9108 "LowerFormalArguments didn't return a valid chain!"); 9109 assert(InVals.size() == Ins.size() && 9110 "LowerFormalArguments didn't emit the correct number of values!"); 9111 LLVM_DEBUG({ 9112 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 9113 assert(InVals[i].getNode() && 9114 "LowerFormalArguments emitted a null value!"); 9115 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 9116 "LowerFormalArguments emitted a value with the wrong type!"); 9117 } 9118 }); 9119 9120 // Update the DAG with the new chain value resulting from argument lowering. 9121 DAG.setRoot(NewRoot); 9122 9123 // Set up the argument values. 9124 unsigned i = 0; 9125 if (!FuncInfo->CanLowerReturn) { 9126 // Create a virtual register for the sret pointer, and put in a copy 9127 // from the sret argument into it. 9128 SmallVector<EVT, 1> ValueVTs; 9129 ComputeValueVTs(*TLI, DAG.getDataLayout(), 9130 F.getReturnType()->getPointerTo( 9131 DAG.getDataLayout().getAllocaAddrSpace()), 9132 ValueVTs); 9133 MVT VT = ValueVTs[0].getSimpleVT(); 9134 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 9135 Optional<ISD::NodeType> AssertOp = None; 9136 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, 9137 nullptr, F.getCallingConv(), AssertOp); 9138 9139 MachineFunction& MF = SDB->DAG.getMachineFunction(); 9140 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 9141 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 9142 FuncInfo->DemoteRegister = SRetReg; 9143 NewRoot = 9144 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 9145 DAG.setRoot(NewRoot); 9146 9147 // i indexes lowered arguments. Bump it past the hidden sret argument. 9148 ++i; 9149 } 9150 9151 SmallVector<SDValue, 4> Chains; 9152 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 9153 for (const Argument &Arg : F.args()) { 9154 SmallVector<SDValue, 4> ArgValues; 9155 SmallVector<EVT, 4> ValueVTs; 9156 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 9157 unsigned NumValues = ValueVTs.size(); 9158 if (NumValues == 0) 9159 continue; 9160 9161 bool ArgHasUses = !Arg.use_empty(); 9162 9163 // Elide the copying store if the target loaded this argument from a 9164 // suitable fixed stack object. 9165 if (Ins[i].Flags.isCopyElisionCandidate()) { 9166 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 9167 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 9168 InVals[i], ArgHasUses); 9169 } 9170 9171 // If this argument is unused then remember its value. It is used to generate 9172 // debugging information. 9173 bool isSwiftErrorArg = 9174 TLI->supportSwiftError() && 9175 Arg.hasAttribute(Attribute::SwiftError); 9176 if (!ArgHasUses && !isSwiftErrorArg) { 9177 SDB->setUnusedArgValue(&Arg, InVals[i]); 9178 9179 // Also remember any frame index for use in FastISel. 9180 if (FrameIndexSDNode *FI = 9181 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 9182 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9183 } 9184 9185 for (unsigned Val = 0; Val != NumValues; ++Val) { 9186 EVT VT = ValueVTs[Val]; 9187 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), 9188 F.getCallingConv(), VT); 9189 unsigned NumParts = TLI->getNumRegistersForCallingConv( 9190 *CurDAG->getContext(), F.getCallingConv(), VT); 9191 9192 // Even an apparant 'unused' swifterror argument needs to be returned. So 9193 // we do generate a copy for it that can be used on return from the 9194 // function. 9195 if (ArgHasUses || isSwiftErrorArg) { 9196 Optional<ISD::NodeType> AssertOp; 9197 if (Arg.hasAttribute(Attribute::SExt)) 9198 AssertOp = ISD::AssertSext; 9199 else if (Arg.hasAttribute(Attribute::ZExt)) 9200 AssertOp = ISD::AssertZext; 9201 9202 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 9203 PartVT, VT, nullptr, 9204 F.getCallingConv(), AssertOp)); 9205 } 9206 9207 i += NumParts; 9208 } 9209 9210 // We don't need to do anything else for unused arguments. 9211 if (ArgValues.empty()) 9212 continue; 9213 9214 // Note down frame index. 9215 if (FrameIndexSDNode *FI = 9216 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 9217 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9218 9219 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 9220 SDB->getCurSDLoc()); 9221 9222 SDB->setValue(&Arg, Res); 9223 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 9224 // We want to associate the argument with the frame index, among 9225 // involved operands, that correspond to the lowest address. The 9226 // getCopyFromParts function, called earlier, is swapping the order of 9227 // the operands to BUILD_PAIR depending on endianness. The result of 9228 // that swapping is that the least significant bits of the argument will 9229 // be in the first operand of the BUILD_PAIR node, and the most 9230 // significant bits will be in the second operand. 9231 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 9232 if (LoadSDNode *LNode = 9233 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 9234 if (FrameIndexSDNode *FI = 9235 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 9236 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 9237 } 9238 9239 // Update the SwiftErrorVRegDefMap. 9240 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 9241 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9242 if (TargetRegisterInfo::isVirtualRegister(Reg)) 9243 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 9244 FuncInfo->SwiftErrorArg, Reg); 9245 } 9246 9247 // If this argument is live outside of the entry block, insert a copy from 9248 // wherever we got it to the vreg that other BB's will reference it as. 9249 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 9250 // If we can, though, try to skip creating an unnecessary vreg. 9251 // FIXME: This isn't very clean... it would be nice to make this more 9252 // general. It's also subtly incompatible with the hacks FastISel 9253 // uses with vregs. 9254 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 9255 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 9256 FuncInfo->ValueMap[&Arg] = Reg; 9257 continue; 9258 } 9259 } 9260 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 9261 FuncInfo->InitializeRegForValue(&Arg); 9262 SDB->CopyToExportRegsIfNeeded(&Arg); 9263 } 9264 } 9265 9266 if (!Chains.empty()) { 9267 Chains.push_back(NewRoot); 9268 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 9269 } 9270 9271 DAG.setRoot(NewRoot); 9272 9273 assert(i == InVals.size() && "Argument register count mismatch!"); 9274 9275 // If any argument copy elisions occurred and we have debug info, update the 9276 // stale frame indices used in the dbg.declare variable info table. 9277 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 9278 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 9279 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 9280 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 9281 if (I != ArgCopyElisionFrameIndexMap.end()) 9282 VI.Slot = I->second; 9283 } 9284 } 9285 9286 // Finally, if the target has anything special to do, allow it to do so. 9287 EmitFunctionEntryCode(); 9288 } 9289 9290 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 9291 /// ensure constants are generated when needed. Remember the virtual registers 9292 /// that need to be added to the Machine PHI nodes as input. We cannot just 9293 /// directly add them, because expansion might result in multiple MBB's for one 9294 /// BB. As such, the start of the BB might correspond to a different MBB than 9295 /// the end. 9296 void 9297 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 9298 const Instruction *TI = LLVMBB->getTerminator(); 9299 9300 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 9301 9302 // Check PHI nodes in successors that expect a value to be available from this 9303 // block. 9304 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 9305 const BasicBlock *SuccBB = TI->getSuccessor(succ); 9306 if (!isa<PHINode>(SuccBB->begin())) continue; 9307 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 9308 9309 // If this terminator has multiple identical successors (common for 9310 // switches), only handle each succ once. 9311 if (!SuccsHandled.insert(SuccMBB).second) 9312 continue; 9313 9314 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 9315 9316 // At this point we know that there is a 1-1 correspondence between LLVM PHI 9317 // nodes and Machine PHI nodes, but the incoming operands have not been 9318 // emitted yet. 9319 for (const PHINode &PN : SuccBB->phis()) { 9320 // Ignore dead phi's. 9321 if (PN.use_empty()) 9322 continue; 9323 9324 // Skip empty types 9325 if (PN.getType()->isEmptyTy()) 9326 continue; 9327 9328 unsigned Reg; 9329 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB); 9330 9331 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 9332 unsigned &RegOut = ConstantsOut[C]; 9333 if (RegOut == 0) { 9334 RegOut = FuncInfo.CreateRegs(C->getType()); 9335 CopyValueToVirtualRegister(C, RegOut); 9336 } 9337 Reg = RegOut; 9338 } else { 9339 DenseMap<const Value *, unsigned>::iterator I = 9340 FuncInfo.ValueMap.find(PHIOp); 9341 if (I != FuncInfo.ValueMap.end()) 9342 Reg = I->second; 9343 else { 9344 assert(isa<AllocaInst>(PHIOp) && 9345 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 9346 "Didn't codegen value into a register!??"); 9347 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 9348 CopyValueToVirtualRegister(PHIOp, Reg); 9349 } 9350 } 9351 9352 // Remember that this register needs to added to the machine PHI node as 9353 // the input for this MBB. 9354 SmallVector<EVT, 4> ValueVTs; 9355 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9356 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs); 9357 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 9358 EVT VT = ValueVTs[vti]; 9359 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 9360 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 9361 FuncInfo.PHINodesToUpdate.push_back( 9362 std::make_pair(&*MBBI++, Reg + i)); 9363 Reg += NumRegisters; 9364 } 9365 } 9366 } 9367 9368 ConstantsOut.clear(); 9369 } 9370 9371 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 9372 /// is 0. 9373 MachineBasicBlock * 9374 SelectionDAGBuilder::StackProtectorDescriptor:: 9375 AddSuccessorMBB(const BasicBlock *BB, 9376 MachineBasicBlock *ParentMBB, 9377 bool IsLikely, 9378 MachineBasicBlock *SuccMBB) { 9379 // If SuccBB has not been created yet, create it. 9380 if (!SuccMBB) { 9381 MachineFunction *MF = ParentMBB->getParent(); 9382 MachineFunction::iterator BBI(ParentMBB); 9383 SuccMBB = MF->CreateMachineBasicBlock(BB); 9384 MF->insert(++BBI, SuccMBB); 9385 } 9386 // Add it as a successor of ParentMBB. 9387 ParentMBB->addSuccessor( 9388 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9389 return SuccMBB; 9390 } 9391 9392 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9393 MachineFunction::iterator I(MBB); 9394 if (++I == FuncInfo.MF->end()) 9395 return nullptr; 9396 return &*I; 9397 } 9398 9399 /// During lowering new call nodes can be created (such as memset, etc.). 9400 /// Those will become new roots of the current DAG, but complications arise 9401 /// when they are tail calls. In such cases, the call lowering will update 9402 /// the root, but the builder still needs to know that a tail call has been 9403 /// lowered in order to avoid generating an additional return. 9404 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9405 // If the node is null, we do have a tail call. 9406 if (MaybeTC.getNode() != nullptr) 9407 DAG.setRoot(MaybeTC); 9408 else 9409 HasTailCall = true; 9410 } 9411 9412 uint64_t 9413 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9414 unsigned First, unsigned Last) const { 9415 assert(Last >= First); 9416 const APInt &LowCase = Clusters[First].Low->getValue(); 9417 const APInt &HighCase = Clusters[Last].High->getValue(); 9418 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9419 9420 // FIXME: A range of consecutive cases has 100% density, but only requires one 9421 // comparison to lower. We should discriminate against such consecutive ranges 9422 // in jump tables. 9423 9424 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9425 } 9426 9427 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9428 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9429 unsigned Last) const { 9430 assert(Last >= First); 9431 assert(TotalCases[Last] >= TotalCases[First]); 9432 uint64_t NumCases = 9433 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9434 return NumCases; 9435 } 9436 9437 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9438 unsigned First, unsigned Last, 9439 const SwitchInst *SI, 9440 MachineBasicBlock *DefaultMBB, 9441 CaseCluster &JTCluster) { 9442 assert(First <= Last); 9443 9444 auto Prob = BranchProbability::getZero(); 9445 unsigned NumCmps = 0; 9446 std::vector<MachineBasicBlock*> Table; 9447 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9448 9449 // Initialize probabilities in JTProbs. 9450 for (unsigned I = First; I <= Last; ++I) 9451 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9452 9453 for (unsigned I = First; I <= Last; ++I) { 9454 assert(Clusters[I].Kind == CC_Range); 9455 Prob += Clusters[I].Prob; 9456 const APInt &Low = Clusters[I].Low->getValue(); 9457 const APInt &High = Clusters[I].High->getValue(); 9458 NumCmps += (Low == High) ? 1 : 2; 9459 if (I != First) { 9460 // Fill the gap between this and the previous cluster. 9461 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9462 assert(PreviousHigh.slt(Low)); 9463 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9464 for (uint64_t J = 0; J < Gap; J++) 9465 Table.push_back(DefaultMBB); 9466 } 9467 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9468 for (uint64_t J = 0; J < ClusterSize; ++J) 9469 Table.push_back(Clusters[I].MBB); 9470 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9471 } 9472 9473 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9474 unsigned NumDests = JTProbs.size(); 9475 if (TLI.isSuitableForBitTests( 9476 NumDests, NumCmps, Clusters[First].Low->getValue(), 9477 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9478 // Clusters[First..Last] should be lowered as bit tests instead. 9479 return false; 9480 } 9481 9482 // Create the MBB that will load from and jump through the table. 9483 // Note: We create it here, but it's not inserted into the function yet. 9484 MachineFunction *CurMF = FuncInfo.MF; 9485 MachineBasicBlock *JumpTableMBB = 9486 CurMF->CreateMachineBasicBlock(SI->getParent()); 9487 9488 // Add successors. Note: use table order for determinism. 9489 SmallPtrSet<MachineBasicBlock *, 8> Done; 9490 for (MachineBasicBlock *Succ : Table) { 9491 if (Done.count(Succ)) 9492 continue; 9493 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9494 Done.insert(Succ); 9495 } 9496 JumpTableMBB->normalizeSuccProbs(); 9497 9498 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9499 ->createJumpTableIndex(Table); 9500 9501 // Set up the jump table info. 9502 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9503 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9504 Clusters[Last].High->getValue(), SI->getCondition(), 9505 nullptr, false); 9506 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9507 9508 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9509 JTCases.size() - 1, Prob); 9510 return true; 9511 } 9512 9513 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9514 const SwitchInst *SI, 9515 MachineBasicBlock *DefaultMBB) { 9516 #ifndef NDEBUG 9517 // Clusters must be non-empty, sorted, and only contain Range clusters. 9518 assert(!Clusters.empty()); 9519 for (CaseCluster &C : Clusters) 9520 assert(C.Kind == CC_Range); 9521 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9522 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9523 #endif 9524 9525 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9526 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9527 return; 9528 9529 const int64_t N = Clusters.size(); 9530 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9531 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9532 9533 if (N < 2 || N < MinJumpTableEntries) 9534 return; 9535 9536 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9537 SmallVector<unsigned, 8> TotalCases(N); 9538 for (unsigned i = 0; i < N; ++i) { 9539 const APInt &Hi = Clusters[i].High->getValue(); 9540 const APInt &Lo = Clusters[i].Low->getValue(); 9541 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9542 if (i != 0) 9543 TotalCases[i] += TotalCases[i - 1]; 9544 } 9545 9546 // Cheap case: the whole range may be suitable for jump table. 9547 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9548 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9549 assert(NumCases < UINT64_MAX / 100); 9550 assert(Range >= NumCases); 9551 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9552 CaseCluster JTCluster; 9553 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9554 Clusters[0] = JTCluster; 9555 Clusters.resize(1); 9556 return; 9557 } 9558 } 9559 9560 // The algorithm below is not suitable for -O0. 9561 if (TM.getOptLevel() == CodeGenOpt::None) 9562 return; 9563 9564 // Split Clusters into minimum number of dense partitions. The algorithm uses 9565 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9566 // for the Case Statement'" (1994), but builds the MinPartitions array in 9567 // reverse order to make it easier to reconstruct the partitions in ascending 9568 // order. In the choice between two optimal partitionings, it picks the one 9569 // which yields more jump tables. 9570 9571 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9572 SmallVector<unsigned, 8> MinPartitions(N); 9573 // LastElement[i] is the last element of the partition starting at i. 9574 SmallVector<unsigned, 8> LastElement(N); 9575 // PartitionsScore[i] is used to break ties when choosing between two 9576 // partitionings resulting in the same number of partitions. 9577 SmallVector<unsigned, 8> PartitionsScore(N); 9578 // For PartitionsScore, a small number of comparisons is considered as good as 9579 // a jump table and a single comparison is considered better than a jump 9580 // table. 9581 enum PartitionScores : unsigned { 9582 NoTable = 0, 9583 Table = 1, 9584 FewCases = 1, 9585 SingleCase = 2 9586 }; 9587 9588 // Base case: There is only one way to partition Clusters[N-1]. 9589 MinPartitions[N - 1] = 1; 9590 LastElement[N - 1] = N - 1; 9591 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9592 9593 // Note: loop indexes are signed to avoid underflow. 9594 for (int64_t i = N - 2; i >= 0; i--) { 9595 // Find optimal partitioning of Clusters[i..N-1]. 9596 // Baseline: Put Clusters[i] into a partition on its own. 9597 MinPartitions[i] = MinPartitions[i + 1] + 1; 9598 LastElement[i] = i; 9599 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9600 9601 // Search for a solution that results in fewer partitions. 9602 for (int64_t j = N - 1; j > i; j--) { 9603 // Try building a partition from Clusters[i..j]. 9604 uint64_t Range = getJumpTableRange(Clusters, i, j); 9605 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9606 assert(NumCases < UINT64_MAX / 100); 9607 assert(Range >= NumCases); 9608 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9609 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9610 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9611 int64_t NumEntries = j - i + 1; 9612 9613 if (NumEntries == 1) 9614 Score += PartitionScores::SingleCase; 9615 else if (NumEntries <= SmallNumberOfEntries) 9616 Score += PartitionScores::FewCases; 9617 else if (NumEntries >= MinJumpTableEntries) 9618 Score += PartitionScores::Table; 9619 9620 // If this leads to fewer partitions, or to the same number of 9621 // partitions with better score, it is a better partitioning. 9622 if (NumPartitions < MinPartitions[i] || 9623 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9624 MinPartitions[i] = NumPartitions; 9625 LastElement[i] = j; 9626 PartitionsScore[i] = Score; 9627 } 9628 } 9629 } 9630 } 9631 9632 // Iterate over the partitions, replacing some with jump tables in-place. 9633 unsigned DstIndex = 0; 9634 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9635 Last = LastElement[First]; 9636 assert(Last >= First); 9637 assert(DstIndex <= First); 9638 unsigned NumClusters = Last - First + 1; 9639 9640 CaseCluster JTCluster; 9641 if (NumClusters >= MinJumpTableEntries && 9642 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9643 Clusters[DstIndex++] = JTCluster; 9644 } else { 9645 for (unsigned I = First; I <= Last; ++I) 9646 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9647 } 9648 } 9649 Clusters.resize(DstIndex); 9650 } 9651 9652 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9653 unsigned First, unsigned Last, 9654 const SwitchInst *SI, 9655 CaseCluster &BTCluster) { 9656 assert(First <= Last); 9657 if (First == Last) 9658 return false; 9659 9660 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9661 unsigned NumCmps = 0; 9662 for (int64_t I = First; I <= Last; ++I) { 9663 assert(Clusters[I].Kind == CC_Range); 9664 Dests.set(Clusters[I].MBB->getNumber()); 9665 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9666 } 9667 unsigned NumDests = Dests.count(); 9668 9669 APInt Low = Clusters[First].Low->getValue(); 9670 APInt High = Clusters[Last].High->getValue(); 9671 assert(Low.slt(High)); 9672 9673 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9674 const DataLayout &DL = DAG.getDataLayout(); 9675 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9676 return false; 9677 9678 APInt LowBound; 9679 APInt CmpRange; 9680 9681 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9682 assert(TLI.rangeFitsInWord(Low, High, DL) && 9683 "Case range must fit in bit mask!"); 9684 9685 // Check if the clusters cover a contiguous range such that no value in the 9686 // range will jump to the default statement. 9687 bool ContiguousRange = true; 9688 for (int64_t I = First + 1; I <= Last; ++I) { 9689 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9690 ContiguousRange = false; 9691 break; 9692 } 9693 } 9694 9695 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9696 // Optimize the case where all the case values fit in a word without having 9697 // to subtract minValue. In this case, we can optimize away the subtraction. 9698 LowBound = APInt::getNullValue(Low.getBitWidth()); 9699 CmpRange = High; 9700 ContiguousRange = false; 9701 } else { 9702 LowBound = Low; 9703 CmpRange = High - Low; 9704 } 9705 9706 CaseBitsVector CBV; 9707 auto TotalProb = BranchProbability::getZero(); 9708 for (unsigned i = First; i <= Last; ++i) { 9709 // Find the CaseBits for this destination. 9710 unsigned j; 9711 for (j = 0; j < CBV.size(); ++j) 9712 if (CBV[j].BB == Clusters[i].MBB) 9713 break; 9714 if (j == CBV.size()) 9715 CBV.push_back( 9716 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9717 CaseBits *CB = &CBV[j]; 9718 9719 // Update Mask, Bits and ExtraProb. 9720 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9721 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9722 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9723 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9724 CB->Bits += Hi - Lo + 1; 9725 CB->ExtraProb += Clusters[i].Prob; 9726 TotalProb += Clusters[i].Prob; 9727 } 9728 9729 BitTestInfo BTI; 9730 llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 9731 // Sort by probability first, number of bits second, bit mask third. 9732 if (a.ExtraProb != b.ExtraProb) 9733 return a.ExtraProb > b.ExtraProb; 9734 if (a.Bits != b.Bits) 9735 return a.Bits > b.Bits; 9736 return a.Mask < b.Mask; 9737 }); 9738 9739 for (auto &CB : CBV) { 9740 MachineBasicBlock *BitTestBB = 9741 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9742 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9743 } 9744 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9745 SI->getCondition(), -1U, MVT::Other, false, 9746 ContiguousRange, nullptr, nullptr, std::move(BTI), 9747 TotalProb); 9748 9749 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9750 BitTestCases.size() - 1, TotalProb); 9751 return true; 9752 } 9753 9754 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9755 const SwitchInst *SI) { 9756 // Partition Clusters into as few subsets as possible, where each subset has a 9757 // range that fits in a machine word and has <= 3 unique destinations. 9758 9759 #ifndef NDEBUG 9760 // Clusters must be sorted and contain Range or JumpTable clusters. 9761 assert(!Clusters.empty()); 9762 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9763 for (const CaseCluster &C : Clusters) 9764 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9765 for (unsigned i = 1; i < Clusters.size(); ++i) 9766 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9767 #endif 9768 9769 // The algorithm below is not suitable for -O0. 9770 if (TM.getOptLevel() == CodeGenOpt::None) 9771 return; 9772 9773 // If target does not have legal shift left, do not emit bit tests at all. 9774 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9775 const DataLayout &DL = DAG.getDataLayout(); 9776 9777 EVT PTy = TLI.getPointerTy(DL); 9778 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9779 return; 9780 9781 int BitWidth = PTy.getSizeInBits(); 9782 const int64_t N = Clusters.size(); 9783 9784 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9785 SmallVector<unsigned, 8> MinPartitions(N); 9786 // LastElement[i] is the last element of the partition starting at i. 9787 SmallVector<unsigned, 8> LastElement(N); 9788 9789 // FIXME: This might not be the best algorithm for finding bit test clusters. 9790 9791 // Base case: There is only one way to partition Clusters[N-1]. 9792 MinPartitions[N - 1] = 1; 9793 LastElement[N - 1] = N - 1; 9794 9795 // Note: loop indexes are signed to avoid underflow. 9796 for (int64_t i = N - 2; i >= 0; --i) { 9797 // Find optimal partitioning of Clusters[i..N-1]. 9798 // Baseline: Put Clusters[i] into a partition on its own. 9799 MinPartitions[i] = MinPartitions[i + 1] + 1; 9800 LastElement[i] = i; 9801 9802 // Search for a solution that results in fewer partitions. 9803 // Note: the search is limited by BitWidth, reducing time complexity. 9804 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9805 // Try building a partition from Clusters[i..j]. 9806 9807 // Check the range. 9808 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9809 Clusters[j].High->getValue(), DL)) 9810 continue; 9811 9812 // Check nbr of destinations and cluster types. 9813 // FIXME: This works, but doesn't seem very efficient. 9814 bool RangesOnly = true; 9815 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9816 for (int64_t k = i; k <= j; k++) { 9817 if (Clusters[k].Kind != CC_Range) { 9818 RangesOnly = false; 9819 break; 9820 } 9821 Dests.set(Clusters[k].MBB->getNumber()); 9822 } 9823 if (!RangesOnly || Dests.count() > 3) 9824 break; 9825 9826 // Check if it's a better partition. 9827 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9828 if (NumPartitions < MinPartitions[i]) { 9829 // Found a better partition. 9830 MinPartitions[i] = NumPartitions; 9831 LastElement[i] = j; 9832 } 9833 } 9834 } 9835 9836 // Iterate over the partitions, replacing with bit-test clusters in-place. 9837 unsigned DstIndex = 0; 9838 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9839 Last = LastElement[First]; 9840 assert(First <= Last); 9841 assert(DstIndex <= First); 9842 9843 CaseCluster BitTestCluster; 9844 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9845 Clusters[DstIndex++] = BitTestCluster; 9846 } else { 9847 size_t NumClusters = Last - First + 1; 9848 std::memmove(&Clusters[DstIndex], &Clusters[First], 9849 sizeof(Clusters[0]) * NumClusters); 9850 DstIndex += NumClusters; 9851 } 9852 } 9853 Clusters.resize(DstIndex); 9854 } 9855 9856 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9857 MachineBasicBlock *SwitchMBB, 9858 MachineBasicBlock *DefaultMBB) { 9859 MachineFunction *CurMF = FuncInfo.MF; 9860 MachineBasicBlock *NextMBB = nullptr; 9861 MachineFunction::iterator BBI(W.MBB); 9862 if (++BBI != FuncInfo.MF->end()) 9863 NextMBB = &*BBI; 9864 9865 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9866 9867 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9868 9869 if (Size == 2 && W.MBB == SwitchMBB) { 9870 // If any two of the cases has the same destination, and if one value 9871 // is the same as the other, but has one bit unset that the other has set, 9872 // use bit manipulation to do two compares at once. For example: 9873 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9874 // TODO: This could be extended to merge any 2 cases in switches with 3 9875 // cases. 9876 // TODO: Handle cases where W.CaseBB != SwitchBB. 9877 CaseCluster &Small = *W.FirstCluster; 9878 CaseCluster &Big = *W.LastCluster; 9879 9880 if (Small.Low == Small.High && Big.Low == Big.High && 9881 Small.MBB == Big.MBB) { 9882 const APInt &SmallValue = Small.Low->getValue(); 9883 const APInt &BigValue = Big.Low->getValue(); 9884 9885 // Check that there is only one bit different. 9886 APInt CommonBit = BigValue ^ SmallValue; 9887 if (CommonBit.isPowerOf2()) { 9888 SDValue CondLHS = getValue(Cond); 9889 EVT VT = CondLHS.getValueType(); 9890 SDLoc DL = getCurSDLoc(); 9891 9892 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9893 DAG.getConstant(CommonBit, DL, VT)); 9894 SDValue Cond = DAG.getSetCC( 9895 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9896 ISD::SETEQ); 9897 9898 // Update successor info. 9899 // Both Small and Big will jump to Small.BB, so we sum up the 9900 // probabilities. 9901 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9902 if (BPI) 9903 addSuccessorWithProb( 9904 SwitchMBB, DefaultMBB, 9905 // The default destination is the first successor in IR. 9906 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9907 else 9908 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9909 9910 // Insert the true branch. 9911 SDValue BrCond = 9912 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9913 DAG.getBasicBlock(Small.MBB)); 9914 // Insert the false branch. 9915 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9916 DAG.getBasicBlock(DefaultMBB)); 9917 9918 DAG.setRoot(BrCond); 9919 return; 9920 } 9921 } 9922 } 9923 9924 if (TM.getOptLevel() != CodeGenOpt::None) { 9925 // Here, we order cases by probability so the most likely case will be 9926 // checked first. However, two clusters can have the same probability in 9927 // which case their relative ordering is non-deterministic. So we use Low 9928 // as a tie-breaker as clusters are guaranteed to never overlap. 9929 llvm::sort(W.FirstCluster, W.LastCluster + 1, 9930 [](const CaseCluster &a, const CaseCluster &b) { 9931 return a.Prob != b.Prob ? 9932 a.Prob > b.Prob : 9933 a.Low->getValue().slt(b.Low->getValue()); 9934 }); 9935 9936 // Rearrange the case blocks so that the last one falls through if possible 9937 // without changing the order of probabilities. 9938 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9939 --I; 9940 if (I->Prob > W.LastCluster->Prob) 9941 break; 9942 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9943 std::swap(*I, *W.LastCluster); 9944 break; 9945 } 9946 } 9947 } 9948 9949 // Compute total probability. 9950 BranchProbability DefaultProb = W.DefaultProb; 9951 BranchProbability UnhandledProbs = DefaultProb; 9952 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9953 UnhandledProbs += I->Prob; 9954 9955 MachineBasicBlock *CurMBB = W.MBB; 9956 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9957 MachineBasicBlock *Fallthrough; 9958 if (I == W.LastCluster) { 9959 // For the last cluster, fall through to the default destination. 9960 Fallthrough = DefaultMBB; 9961 } else { 9962 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9963 CurMF->insert(BBI, Fallthrough); 9964 // Put Cond in a virtual register to make it available from the new blocks. 9965 ExportFromCurrentBlock(Cond); 9966 } 9967 UnhandledProbs -= I->Prob; 9968 9969 switch (I->Kind) { 9970 case CC_JumpTable: { 9971 // FIXME: Optimize away range check based on pivot comparisons. 9972 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9973 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9974 9975 // The jump block hasn't been inserted yet; insert it here. 9976 MachineBasicBlock *JumpMBB = JT->MBB; 9977 CurMF->insert(BBI, JumpMBB); 9978 9979 auto JumpProb = I->Prob; 9980 auto FallthroughProb = UnhandledProbs; 9981 9982 // If the default statement is a target of the jump table, we evenly 9983 // distribute the default probability to successors of CurMBB. Also 9984 // update the probability on the edge from JumpMBB to Fallthrough. 9985 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9986 SE = JumpMBB->succ_end(); 9987 SI != SE; ++SI) { 9988 if (*SI == DefaultMBB) { 9989 JumpProb += DefaultProb / 2; 9990 FallthroughProb -= DefaultProb / 2; 9991 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9992 JumpMBB->normalizeSuccProbs(); 9993 break; 9994 } 9995 } 9996 9997 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9998 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9999 CurMBB->normalizeSuccProbs(); 10000 10001 // The jump table header will be inserted in our current block, do the 10002 // range check, and fall through to our fallthrough block. 10003 JTH->HeaderBB = CurMBB; 10004 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 10005 10006 // If we're in the right place, emit the jump table header right now. 10007 if (CurMBB == SwitchMBB) { 10008 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 10009 JTH->Emitted = true; 10010 } 10011 break; 10012 } 10013 case CC_BitTests: { 10014 // FIXME: Optimize away range check based on pivot comparisons. 10015 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 10016 10017 // The bit test blocks haven't been inserted yet; insert them here. 10018 for (BitTestCase &BTC : BTB->Cases) 10019 CurMF->insert(BBI, BTC.ThisBB); 10020 10021 // Fill in fields of the BitTestBlock. 10022 BTB->Parent = CurMBB; 10023 BTB->Default = Fallthrough; 10024 10025 BTB->DefaultProb = UnhandledProbs; 10026 // If the cases in bit test don't form a contiguous range, we evenly 10027 // distribute the probability on the edge to Fallthrough to two 10028 // successors of CurMBB. 10029 if (!BTB->ContiguousRange) { 10030 BTB->Prob += DefaultProb / 2; 10031 BTB->DefaultProb -= DefaultProb / 2; 10032 } 10033 10034 // If we're in the right place, emit the bit test header right now. 10035 if (CurMBB == SwitchMBB) { 10036 visitBitTestHeader(*BTB, SwitchMBB); 10037 BTB->Emitted = true; 10038 } 10039 break; 10040 } 10041 case CC_Range: { 10042 const Value *RHS, *LHS, *MHS; 10043 ISD::CondCode CC; 10044 if (I->Low == I->High) { 10045 // Check Cond == I->Low. 10046 CC = ISD::SETEQ; 10047 LHS = Cond; 10048 RHS=I->Low; 10049 MHS = nullptr; 10050 } else { 10051 // Check I->Low <= Cond <= I->High. 10052 CC = ISD::SETLE; 10053 LHS = I->Low; 10054 MHS = Cond; 10055 RHS = I->High; 10056 } 10057 10058 // The false probability is the sum of all unhandled cases. 10059 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 10060 getCurSDLoc(), I->Prob, UnhandledProbs); 10061 10062 if (CurMBB == SwitchMBB) 10063 visitSwitchCase(CB, SwitchMBB); 10064 else 10065 SwitchCases.push_back(CB); 10066 10067 break; 10068 } 10069 } 10070 CurMBB = Fallthrough; 10071 } 10072 } 10073 10074 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 10075 CaseClusterIt First, 10076 CaseClusterIt Last) { 10077 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 10078 if (X.Prob != CC.Prob) 10079 return X.Prob > CC.Prob; 10080 10081 // Ties are broken by comparing the case value. 10082 return X.Low->getValue().slt(CC.Low->getValue()); 10083 }); 10084 } 10085 10086 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 10087 const SwitchWorkListItem &W, 10088 Value *Cond, 10089 MachineBasicBlock *SwitchMBB) { 10090 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 10091 "Clusters not sorted?"); 10092 10093 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 10094 10095 // Balance the tree based on branch probabilities to create a near-optimal (in 10096 // terms of search time given key frequency) binary search tree. See e.g. Kurt 10097 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 10098 CaseClusterIt LastLeft = W.FirstCluster; 10099 CaseClusterIt FirstRight = W.LastCluster; 10100 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 10101 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 10102 10103 // Move LastLeft and FirstRight towards each other from opposite directions to 10104 // find a partitioning of the clusters which balances the probability on both 10105 // sides. If LeftProb and RightProb are equal, alternate which side is 10106 // taken to ensure 0-probability nodes are distributed evenly. 10107 unsigned I = 0; 10108 while (LastLeft + 1 < FirstRight) { 10109 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 10110 LeftProb += (++LastLeft)->Prob; 10111 else 10112 RightProb += (--FirstRight)->Prob; 10113 I++; 10114 } 10115 10116 while (true) { 10117 // Our binary search tree differs from a typical BST in that ours can have up 10118 // to three values in each leaf. The pivot selection above doesn't take that 10119 // into account, which means the tree might require more nodes and be less 10120 // efficient. We compensate for this here. 10121 10122 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 10123 unsigned NumRight = W.LastCluster - FirstRight + 1; 10124 10125 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 10126 // If one side has less than 3 clusters, and the other has more than 3, 10127 // consider taking a cluster from the other side. 10128 10129 if (NumLeft < NumRight) { 10130 // Consider moving the first cluster on the right to the left side. 10131 CaseCluster &CC = *FirstRight; 10132 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10133 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10134 if (LeftSideRank <= RightSideRank) { 10135 // Moving the cluster to the left does not demote it. 10136 ++LastLeft; 10137 ++FirstRight; 10138 continue; 10139 } 10140 } else { 10141 assert(NumRight < NumLeft); 10142 // Consider moving the last element on the left to the right side. 10143 CaseCluster &CC = *LastLeft; 10144 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 10145 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 10146 if (RightSideRank <= LeftSideRank) { 10147 // Moving the cluster to the right does not demot it. 10148 --LastLeft; 10149 --FirstRight; 10150 continue; 10151 } 10152 } 10153 } 10154 break; 10155 } 10156 10157 assert(LastLeft + 1 == FirstRight); 10158 assert(LastLeft >= W.FirstCluster); 10159 assert(FirstRight <= W.LastCluster); 10160 10161 // Use the first element on the right as pivot since we will make less-than 10162 // comparisons against it. 10163 CaseClusterIt PivotCluster = FirstRight; 10164 assert(PivotCluster > W.FirstCluster); 10165 assert(PivotCluster <= W.LastCluster); 10166 10167 CaseClusterIt FirstLeft = W.FirstCluster; 10168 CaseClusterIt LastRight = W.LastCluster; 10169 10170 const ConstantInt *Pivot = PivotCluster->Low; 10171 10172 // New blocks will be inserted immediately after the current one. 10173 MachineFunction::iterator BBI(W.MBB); 10174 ++BBI; 10175 10176 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 10177 // we can branch to its destination directly if it's squeezed exactly in 10178 // between the known lower bound and Pivot - 1. 10179 MachineBasicBlock *LeftMBB; 10180 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 10181 FirstLeft->Low == W.GE && 10182 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 10183 LeftMBB = FirstLeft->MBB; 10184 } else { 10185 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10186 FuncInfo.MF->insert(BBI, LeftMBB); 10187 WorkList.push_back( 10188 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 10189 // Put Cond in a virtual register to make it available from the new blocks. 10190 ExportFromCurrentBlock(Cond); 10191 } 10192 10193 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 10194 // single cluster, RHS.Low == Pivot, and we can branch to its destination 10195 // directly if RHS.High equals the current upper bound. 10196 MachineBasicBlock *RightMBB; 10197 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 10198 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 10199 RightMBB = FirstRight->MBB; 10200 } else { 10201 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 10202 FuncInfo.MF->insert(BBI, RightMBB); 10203 WorkList.push_back( 10204 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 10205 // Put Cond in a virtual register to make it available from the new blocks. 10206 ExportFromCurrentBlock(Cond); 10207 } 10208 10209 // Create the CaseBlock record that will be used to lower the branch. 10210 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 10211 getCurSDLoc(), LeftProb, RightProb); 10212 10213 if (W.MBB == SwitchMBB) 10214 visitSwitchCase(CB, SwitchMBB); 10215 else 10216 SwitchCases.push_back(CB); 10217 } 10218 10219 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 10220 // from the swith statement. 10221 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 10222 BranchProbability PeeledCaseProb) { 10223 if (PeeledCaseProb == BranchProbability::getOne()) 10224 return BranchProbability::getZero(); 10225 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 10226 10227 uint32_t Numerator = CaseProb.getNumerator(); 10228 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 10229 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 10230 } 10231 10232 // Try to peel the top probability case if it exceeds the threshold. 10233 // Return current MachineBasicBlock for the switch statement if the peeling 10234 // does not occur. 10235 // If the peeling is performed, return the newly created MachineBasicBlock 10236 // for the peeled switch statement. Also update Clusters to remove the peeled 10237 // case. PeeledCaseProb is the BranchProbability for the peeled case. 10238 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 10239 const SwitchInst &SI, CaseClusterVector &Clusters, 10240 BranchProbability &PeeledCaseProb) { 10241 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10242 // Don't perform if there is only one cluster or optimizing for size. 10243 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 10244 TM.getOptLevel() == CodeGenOpt::None || 10245 SwitchMBB->getParent()->getFunction().optForMinSize()) 10246 return SwitchMBB; 10247 10248 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 10249 unsigned PeeledCaseIndex = 0; 10250 bool SwitchPeeled = false; 10251 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 10252 CaseCluster &CC = Clusters[Index]; 10253 if (CC.Prob < TopCaseProb) 10254 continue; 10255 TopCaseProb = CC.Prob; 10256 PeeledCaseIndex = Index; 10257 SwitchPeeled = true; 10258 } 10259 if (!SwitchPeeled) 10260 return SwitchMBB; 10261 10262 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " 10263 << TopCaseProb << "\n"); 10264 10265 // Record the MBB for the peeled switch statement. 10266 MachineFunction::iterator BBI(SwitchMBB); 10267 ++BBI; 10268 MachineBasicBlock *PeeledSwitchMBB = 10269 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 10270 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 10271 10272 ExportFromCurrentBlock(SI.getCondition()); 10273 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 10274 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 10275 nullptr, nullptr, TopCaseProb.getCompl()}; 10276 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 10277 10278 Clusters.erase(PeeledCaseIt); 10279 for (CaseCluster &CC : Clusters) { 10280 LLVM_DEBUG( 10281 dbgs() << "Scale the probablity for one cluster, before scaling: " 10282 << CC.Prob << "\n"); 10283 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 10284 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 10285 } 10286 PeeledCaseProb = TopCaseProb; 10287 return PeeledSwitchMBB; 10288 } 10289 10290 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 10291 // Extract cases from the switch. 10292 BranchProbabilityInfo *BPI = FuncInfo.BPI; 10293 CaseClusterVector Clusters; 10294 Clusters.reserve(SI.getNumCases()); 10295 for (auto I : SI.cases()) { 10296 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 10297 const ConstantInt *CaseVal = I.getCaseValue(); 10298 BranchProbability Prob = 10299 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 10300 : BranchProbability(1, SI.getNumCases() + 1); 10301 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 10302 } 10303 10304 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 10305 10306 // Cluster adjacent cases with the same destination. We do this at all 10307 // optimization levels because it's cheap to do and will make codegen faster 10308 // if there are many clusters. 10309 sortAndRangeify(Clusters); 10310 10311 if (TM.getOptLevel() != CodeGenOpt::None) { 10312 // Replace an unreachable default with the most popular destination. 10313 // FIXME: Exploit unreachable default more aggressively. 10314 bool UnreachableDefault = 10315 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 10316 if (UnreachableDefault && !Clusters.empty()) { 10317 DenseMap<const BasicBlock *, unsigned> Popularity; 10318 unsigned MaxPop = 0; 10319 const BasicBlock *MaxBB = nullptr; 10320 for (auto I : SI.cases()) { 10321 const BasicBlock *BB = I.getCaseSuccessor(); 10322 if (++Popularity[BB] > MaxPop) { 10323 MaxPop = Popularity[BB]; 10324 MaxBB = BB; 10325 } 10326 } 10327 // Set new default. 10328 assert(MaxPop > 0 && MaxBB); 10329 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 10330 10331 // Remove cases that were pointing to the destination that is now the 10332 // default. 10333 CaseClusterVector New; 10334 New.reserve(Clusters.size()); 10335 for (CaseCluster &CC : Clusters) { 10336 if (CC.MBB != DefaultMBB) 10337 New.push_back(CC); 10338 } 10339 Clusters = std::move(New); 10340 } 10341 } 10342 10343 // The branch probablity of the peeled case. 10344 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 10345 MachineBasicBlock *PeeledSwitchMBB = 10346 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 10347 10348 // If there is only the default destination, jump there directly. 10349 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 10350 if (Clusters.empty()) { 10351 assert(PeeledSwitchMBB == SwitchMBB); 10352 SwitchMBB->addSuccessor(DefaultMBB); 10353 if (DefaultMBB != NextBlock(SwitchMBB)) { 10354 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 10355 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 10356 } 10357 return; 10358 } 10359 10360 findJumpTables(Clusters, &SI, DefaultMBB); 10361 findBitTestClusters(Clusters, &SI); 10362 10363 LLVM_DEBUG({ 10364 dbgs() << "Case clusters: "; 10365 for (const CaseCluster &C : Clusters) { 10366 if (C.Kind == CC_JumpTable) 10367 dbgs() << "JT:"; 10368 if (C.Kind == CC_BitTests) 10369 dbgs() << "BT:"; 10370 10371 C.Low->getValue().print(dbgs(), true); 10372 if (C.Low != C.High) { 10373 dbgs() << '-'; 10374 C.High->getValue().print(dbgs(), true); 10375 } 10376 dbgs() << ' '; 10377 } 10378 dbgs() << '\n'; 10379 }); 10380 10381 assert(!Clusters.empty()); 10382 SwitchWorkList WorkList; 10383 CaseClusterIt First = Clusters.begin(); 10384 CaseClusterIt Last = Clusters.end() - 1; 10385 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 10386 // Scale the branchprobability for DefaultMBB if the peel occurs and 10387 // DefaultMBB is not replaced. 10388 if (PeeledCaseProb != BranchProbability::getZero() && 10389 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10390 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10391 WorkList.push_back( 10392 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10393 10394 while (!WorkList.empty()) { 10395 SwitchWorkListItem W = WorkList.back(); 10396 WorkList.pop_back(); 10397 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10398 10399 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10400 !DefaultMBB->getParent()->getFunction().optForMinSize()) { 10401 // For optimized builds, lower large range as a balanced binary tree. 10402 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10403 continue; 10404 } 10405 10406 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10407 } 10408 } 10409