1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements routines for translating from LLVM IR into SelectionDAG IR. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SelectionDAGBuilder.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/MachineValueType.h" 53 #include "llvm/CodeGen/RuntimeLibcalls.h" 54 #include "llvm/CodeGen/SelectionDAG.h" 55 #include "llvm/CodeGen/SelectionDAGNodes.h" 56 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 57 #include "llvm/CodeGen/StackMaps.h" 58 #include "llvm/CodeGen/TargetFrameLowering.h" 59 #include "llvm/CodeGen/TargetInstrInfo.h" 60 #include "llvm/CodeGen/TargetLowering.h" 61 #include "llvm/CodeGen/TargetOpcodes.h" 62 #include "llvm/CodeGen/TargetRegisterInfo.h" 63 #include "llvm/CodeGen/TargetSubtargetInfo.h" 64 #include "llvm/CodeGen/ValueTypes.h" 65 #include "llvm/CodeGen/WinEHFuncInfo.h" 66 #include "llvm/IR/Argument.h" 67 #include "llvm/IR/Attributes.h" 68 #include "llvm/IR/BasicBlock.h" 69 #include "llvm/IR/CFG.h" 70 #include "llvm/IR/CallSite.h" 71 #include "llvm/IR/CallingConv.h" 72 #include "llvm/IR/Constant.h" 73 #include "llvm/IR/ConstantRange.h" 74 #include "llvm/IR/Constants.h" 75 #include "llvm/IR/DataLayout.h" 76 #include "llvm/IR/DebugInfoMetadata.h" 77 #include "llvm/IR/DebugLoc.h" 78 #include "llvm/IR/DerivedTypes.h" 79 #include "llvm/IR/Function.h" 80 #include "llvm/IR/GetElementPtrTypeIterator.h" 81 #include "llvm/IR/InlineAsm.h" 82 #include "llvm/IR/InstrTypes.h" 83 #include "llvm/IR/Instruction.h" 84 #include "llvm/IR/Instructions.h" 85 #include "llvm/IR/IntrinsicInst.h" 86 #include "llvm/IR/Intrinsics.h" 87 #include "llvm/IR/LLVMContext.h" 88 #include "llvm/IR/Metadata.h" 89 #include "llvm/IR/Module.h" 90 #include "llvm/IR/Operator.h" 91 #include "llvm/IR/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/MathExtras.h" 106 #include "llvm/Support/raw_ostream.h" 107 #include "llvm/Target/TargetIntrinsicInfo.h" 108 #include "llvm/Target/TargetMachine.h" 109 #include "llvm/Target/TargetOptions.h" 110 #include <algorithm> 111 #include <cassert> 112 #include <cstddef> 113 #include <cstdint> 114 #include <cstring> 115 #include <iterator> 116 #include <limits> 117 #include <numeric> 118 #include <tuple> 119 #include <utility> 120 #include <vector> 121 122 using namespace llvm; 123 124 #define DEBUG_TYPE "isel" 125 126 /// LimitFloatPrecision - Generate low-precision inline sequences for 127 /// some float libcalls (6, 8 or 12 bits). 128 static unsigned LimitFloatPrecision; 129 130 static cl::opt<unsigned, true> 131 LimitFPPrecision("limit-float-precision", 132 cl::desc("Generate low-precision inline sequences " 133 "for some float libcalls"), 134 cl::location(LimitFloatPrecision), 135 cl::init(0)); 136 137 static cl::opt<unsigned> SwitchPeelThreshold( 138 "switch-peel-threshold", cl::Hidden, cl::init(66), 139 cl::desc("Set the case probability threshold for peeling the case from a " 140 "switch statement. A value greater than 100 will void this " 141 "optimization")); 142 143 // Limit the width of DAG chains. This is important in general to prevent 144 // DAG-based analysis from blowing up. For example, alias analysis and 145 // load clustering may not complete in reasonable time. It is difficult to 146 // recognize and avoid this situation within each individual analysis, and 147 // future analyses are likely to have the same behavior. Limiting DAG width is 148 // the safe approach and will be especially important with global DAGs. 149 // 150 // MaxParallelChains default is arbitrarily high to avoid affecting 151 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 152 // sequence over this should have been converted to llvm.memcpy by the 153 // frontend. It is easy to induce this behavior with .ll code such as: 154 // %buffer = alloca [4096 x i8] 155 // %data = load [4096 x i8]* %argPtr 156 // store [4096 x i8] %data, [4096 x i8]* %buffer 157 static const unsigned MaxParallelChains = 64; 158 159 // True if the Value passed requires ABI mangling as it is a parameter to a 160 // function or a return value from a function which is not an intrinsic. 161 static bool isABIRegCopy(const Value *V) { 162 const bool IsRetInst = V && isa<ReturnInst>(V); 163 const bool IsCallInst = V && isa<CallInst>(V); 164 const bool IsInLineAsm = 165 IsCallInst && static_cast<const CallInst *>(V)->isInlineAsm(); 166 const bool IsIndirectFunctionCall = 167 IsCallInst && !IsInLineAsm && 168 !static_cast<const CallInst *>(V)->getCalledFunction(); 169 // It is possible that the call instruction is an inline asm statement or an 170 // indirect function call in which case the return value of 171 // getCalledFunction() would be nullptr. 172 const bool IsInstrinsicCall = 173 IsCallInst && !IsInLineAsm && !IsIndirectFunctionCall && 174 static_cast<const CallInst *>(V)->getCalledFunction()->getIntrinsicID() != 175 Intrinsic::not_intrinsic; 176 177 return IsRetInst || (IsCallInst && (!IsInLineAsm && !IsInstrinsicCall)); 178 } 179 180 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 181 const SDValue *Parts, unsigned NumParts, 182 MVT PartVT, EVT ValueVT, const Value *V, 183 bool IsABIRegCopy); 184 185 /// getCopyFromParts - Create a value that contains the specified legal parts 186 /// combined into the value they represent. If the parts combine to a type 187 /// larger than ValueVT then AssertOp can be used to specify whether the extra 188 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 189 /// (ISD::AssertSext). 190 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, 191 const SDValue *Parts, unsigned NumParts, 192 MVT PartVT, EVT ValueVT, const Value *V, 193 Optional<ISD::NodeType> AssertOp = None, 194 bool IsABIRegCopy = false) { 195 if (ValueVT.isVector()) 196 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, 197 PartVT, ValueVT, V, IsABIRegCopy); 198 199 assert(NumParts > 0 && "No parts to assemble!"); 200 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 201 SDValue Val = Parts[0]; 202 203 if (NumParts > 1) { 204 // Assemble the value from multiple parts. 205 if (ValueVT.isInteger()) { 206 unsigned PartBits = PartVT.getSizeInBits(); 207 unsigned ValueBits = ValueVT.getSizeInBits(); 208 209 // Assemble the power of 2 part. 210 unsigned RoundParts = NumParts & (NumParts - 1) ? 211 1 << Log2_32(NumParts) : NumParts; 212 unsigned RoundBits = PartBits * RoundParts; 213 EVT RoundVT = RoundBits == ValueBits ? 214 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 215 SDValue Lo, Hi; 216 217 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 218 219 if (RoundParts > 2) { 220 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 221 PartVT, HalfVT, V); 222 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 223 RoundParts / 2, PartVT, HalfVT, V); 224 } else { 225 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 226 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 227 } 228 229 if (DAG.getDataLayout().isBigEndian()) 230 std::swap(Lo, Hi); 231 232 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 233 234 if (RoundParts < NumParts) { 235 // Assemble the trailing non-power-of-2 part. 236 unsigned OddParts = NumParts - RoundParts; 237 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 238 Hi = getCopyFromParts(DAG, DL, 239 Parts + RoundParts, OddParts, PartVT, OddVT, V); 240 241 // Combine the round and odd parts. 242 Lo = Val; 243 if (DAG.getDataLayout().isBigEndian()) 244 std::swap(Lo, Hi); 245 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 246 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 247 Hi = 248 DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 249 DAG.getConstant(Lo.getValueSizeInBits(), DL, 250 TLI.getPointerTy(DAG.getDataLayout()))); 251 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 252 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 253 } 254 } else if (PartVT.isFloatingPoint()) { 255 // FP split into multiple FP parts (for ppcf128) 256 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 257 "Unexpected split"); 258 SDValue Lo, Hi; 259 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 260 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 261 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout())) 262 std::swap(Lo, Hi); 263 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 264 } else { 265 // FP split into integer parts (soft fp) 266 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 267 !PartVT.isVector() && "Unexpected split"); 268 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 269 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V); 270 } 271 } 272 273 // There is now one part, held in Val. Correct it to match ValueVT. 274 // PartEVT is the type of the register class that holds the value. 275 // ValueVT is the type of the inline asm operation. 276 EVT PartEVT = Val.getValueType(); 277 278 if (PartEVT == ValueVT) 279 return Val; 280 281 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() && 282 ValueVT.bitsLT(PartEVT)) { 283 // For an FP value in an integer part, we need to truncate to the right 284 // width first. 285 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 286 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val); 287 } 288 289 // Handle types that have the same size. 290 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 291 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 292 293 // Handle types with different sizes. 294 if (PartEVT.isInteger() && ValueVT.isInteger()) { 295 if (ValueVT.bitsLT(PartEVT)) { 296 // For a truncate, see if we have any information to 297 // indicate whether the truncated bits will always be 298 // zero or sign-extension. 299 if (AssertOp.hasValue()) 300 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val, 301 DAG.getValueType(ValueVT)); 302 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 303 } 304 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 305 } 306 307 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 308 // FP_ROUND's are always exact here. 309 if (ValueVT.bitsLT(Val.getValueType())) 310 return DAG.getNode( 311 ISD::FP_ROUND, DL, ValueVT, Val, 312 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()))); 313 314 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 315 } 316 317 llvm_unreachable("Unknown mismatch!"); 318 } 319 320 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V, 321 const Twine &ErrMsg) { 322 const Instruction *I = dyn_cast_or_null<Instruction>(V); 323 if (!V) 324 return Ctx.emitError(ErrMsg); 325 326 const char *AsmError = ", possible invalid constraint for vector type"; 327 if (const CallInst *CI = dyn_cast<CallInst>(I)) 328 if (isa<InlineAsm>(CI->getCalledValue())) 329 return Ctx.emitError(I, ErrMsg + AsmError); 330 331 return Ctx.emitError(I, ErrMsg); 332 } 333 334 /// getCopyFromPartsVector - Create a value that contains the specified legal 335 /// parts combined into the value they represent. If the parts combine to a 336 /// type larger than ValueVT then AssertOp can be used to specify whether the 337 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 338 /// ValueVT (ISD::AssertSext). 339 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL, 340 const SDValue *Parts, unsigned NumParts, 341 MVT PartVT, EVT ValueVT, const Value *V, 342 bool IsABIRegCopy) { 343 assert(ValueVT.isVector() && "Not a vector value"); 344 assert(NumParts > 0 && "No parts to assemble!"); 345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 346 SDValue Val = Parts[0]; 347 348 // Handle a multi-element vector. 349 if (NumParts > 1) { 350 EVT IntermediateVT; 351 MVT RegisterVT; 352 unsigned NumIntermediates; 353 unsigned NumRegs; 354 355 if (IsABIRegCopy) { 356 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 357 *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates, 358 RegisterVT); 359 } else { 360 NumRegs = 361 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 362 NumIntermediates, RegisterVT); 363 } 364 365 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 366 NumParts = NumRegs; // Silence a compiler warning. 367 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 368 assert(RegisterVT.getSizeInBits() == 369 Parts[0].getSimpleValueType().getSizeInBits() && 370 "Part type sizes don't match!"); 371 372 // Assemble the parts into intermediate operands. 373 SmallVector<SDValue, 8> Ops(NumIntermediates); 374 if (NumIntermediates == NumParts) { 375 // If the register was not expanded, truncate or copy the value, 376 // as appropriate. 377 for (unsigned i = 0; i != NumParts; ++i) 378 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 379 PartVT, IntermediateVT, V); 380 } else if (NumParts > 0) { 381 // If the intermediate type was expanded, build the intermediate 382 // operands from the parts. 383 assert(NumParts % NumIntermediates == 0 && 384 "Must expand into a divisible number of parts!"); 385 unsigned Factor = NumParts / NumIntermediates; 386 for (unsigned i = 0; i != NumIntermediates; ++i) 387 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 388 PartVT, IntermediateVT, V); 389 } 390 391 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 392 // intermediate operands. 393 EVT BuiltVectorTy = 394 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(), 395 (IntermediateVT.isVector() 396 ? IntermediateVT.getVectorNumElements() * NumParts 397 : NumIntermediates)); 398 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS 399 : ISD::BUILD_VECTOR, 400 DL, BuiltVectorTy, Ops); 401 } 402 403 // There is now one part, held in Val. Correct it to match ValueVT. 404 EVT PartEVT = Val.getValueType(); 405 406 if (PartEVT == ValueVT) 407 return Val; 408 409 if (PartEVT.isVector()) { 410 // If the element type of the source/dest vectors are the same, but the 411 // parts vector has more elements than the value vector, then we have a 412 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 413 // elements we want. 414 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 415 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 416 "Cannot narrow, it would be a lossy transformation"); 417 return DAG.getNode( 418 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 419 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 420 } 421 422 // Vector/Vector bitcast. 423 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 424 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 425 426 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 427 "Cannot handle this kind of promotion"); 428 // Promoted vector extract 429 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT); 430 431 } 432 433 // Trivial bitcast if the types are the same size and the destination 434 // vector type is legal. 435 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 436 TLI.isTypeLegal(ValueVT)) 437 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 438 439 if (ValueVT.getVectorNumElements() != 1) { 440 // Certain ABIs require that vectors are passed as integers. For vectors 441 // are the same size, this is an obvious bitcast. 442 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) { 443 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 444 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) { 445 // Bitcast Val back the original type and extract the corresponding 446 // vector we want. 447 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits(); 448 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(), 449 ValueVT.getVectorElementType(), Elts); 450 Val = DAG.getBitcast(WiderVecType, Val); 451 return DAG.getNode( 452 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 453 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 454 } 455 456 diagnosePossiblyInvalidConstraint( 457 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion"); 458 return DAG.getUNDEF(ValueVT); 459 } 460 461 // Handle cases such as i8 -> <1 x i1> 462 EVT ValueSVT = ValueVT.getVectorElementType(); 463 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) 464 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT) 465 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT); 466 467 return DAG.getBuildVector(ValueVT, DL, Val); 468 } 469 470 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl, 471 SDValue Val, SDValue *Parts, unsigned NumParts, 472 MVT PartVT, const Value *V, bool IsABIRegCopy); 473 474 /// getCopyToParts - Create a series of nodes that contain the specified value 475 /// split into legal parts. If the parts contain more bits than Val, then, for 476 /// integers, ExtendKind can be used to specify how to generate the extra bits. 477 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, 478 SDValue *Parts, unsigned NumParts, MVT PartVT, 479 const Value *V, 480 ISD::NodeType ExtendKind = ISD::ANY_EXTEND, 481 bool IsABIRegCopy = false) { 482 EVT ValueVT = Val.getValueType(); 483 484 // Handle the vector case separately. 485 if (ValueVT.isVector()) 486 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V, 487 IsABIRegCopy); 488 489 unsigned PartBits = PartVT.getSizeInBits(); 490 unsigned OrigNumParts = NumParts; 491 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && 492 "Copying to an illegal type!"); 493 494 if (NumParts == 0) 495 return; 496 497 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 498 EVT PartEVT = PartVT; 499 if (PartEVT == ValueVT) { 500 assert(NumParts == 1 && "No-op copy with multiple parts!"); 501 Parts[0] = Val; 502 return; 503 } 504 505 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 506 // If the parts cover more bits than the value has, promote the value. 507 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 508 assert(NumParts == 1 && "Do not know what to promote to!"); 509 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 510 } else { 511 if (ValueVT.isFloatingPoint()) { 512 // FP values need to be bitcast, then extended if they are being put 513 // into a larger container. 514 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 515 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 516 } 517 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 518 ValueVT.isInteger() && 519 "Unknown mismatch!"); 520 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 521 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 522 if (PartVT == MVT::x86mmx) 523 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 524 } 525 } else if (PartBits == ValueVT.getSizeInBits()) { 526 // Different types of the same size. 527 assert(NumParts == 1 && PartEVT != ValueVT); 528 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 529 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 530 // If the parts cover less bits than value has, truncate the value. 531 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 532 ValueVT.isInteger() && 533 "Unknown mismatch!"); 534 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 535 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 536 if (PartVT == MVT::x86mmx) 537 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 538 } 539 540 // The value may have changed - recompute ValueVT. 541 ValueVT = Val.getValueType(); 542 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 543 "Failed to tile the value with PartVT!"); 544 545 if (NumParts == 1) { 546 if (PartEVT != ValueVT) { 547 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V, 548 "scalar-to-vector conversion failed"); 549 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 550 } 551 552 Parts[0] = Val; 553 return; 554 } 555 556 // Expand the value into multiple parts. 557 if (NumParts & (NumParts - 1)) { 558 // The number of parts is not a power of 2. Split off and copy the tail. 559 assert(PartVT.isInteger() && ValueVT.isInteger() && 560 "Do not know what to expand to!"); 561 unsigned RoundParts = 1 << Log2_32(NumParts); 562 unsigned RoundBits = RoundParts * PartBits; 563 unsigned OddParts = NumParts - RoundParts; 564 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 565 DAG.getIntPtrConstant(RoundBits, DL)); 566 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V); 567 568 if (DAG.getDataLayout().isBigEndian()) 569 // The odd parts were reversed by getCopyToParts - unreverse them. 570 std::reverse(Parts + RoundParts, Parts + NumParts); 571 572 NumParts = RoundParts; 573 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 574 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 575 } 576 577 // The number of parts is a power of 2. Repeatedly bisect the value using 578 // EXTRACT_ELEMENT. 579 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 580 EVT::getIntegerVT(*DAG.getContext(), 581 ValueVT.getSizeInBits()), 582 Val); 583 584 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 585 for (unsigned i = 0; i < NumParts; i += StepSize) { 586 unsigned ThisBits = StepSize * PartBits / 2; 587 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 588 SDValue &Part0 = Parts[i]; 589 SDValue &Part1 = Parts[i+StepSize/2]; 590 591 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 592 ThisVT, Part0, DAG.getIntPtrConstant(1, DL)); 593 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 594 ThisVT, Part0, DAG.getIntPtrConstant(0, DL)); 595 596 if (ThisBits == PartBits && ThisVT != PartVT) { 597 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 598 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 599 } 600 } 601 } 602 603 if (DAG.getDataLayout().isBigEndian()) 604 std::reverse(Parts, Parts + OrigNumParts); 605 } 606 607 608 /// getCopyToPartsVector - Create a series of nodes that contain the specified 609 /// value split into legal parts. 610 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL, 611 SDValue Val, SDValue *Parts, unsigned NumParts, 612 MVT PartVT, const Value *V, 613 bool IsABIRegCopy) { 614 EVT ValueVT = Val.getValueType(); 615 assert(ValueVT.isVector() && "Not a vector"); 616 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 617 618 if (NumParts == 1) { 619 EVT PartEVT = PartVT; 620 if (PartEVT == ValueVT) { 621 // Nothing to do. 622 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 623 // Bitconvert vector->vector case. 624 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 625 } else if (PartVT.isVector() && 626 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 627 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 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 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 633 Ops.push_back(DAG.getNode( 634 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val, 635 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())))); 636 637 for (unsigned i = ValueVT.getVectorNumElements(), 638 e = PartVT.getVectorNumElements(); i != e; ++i) 639 Ops.push_back(DAG.getUNDEF(ElementVT)); 640 641 Val = DAG.getBuildVector(PartVT, DL, Ops); 642 643 // FIXME: Use CONCAT for 2x -> 4x. 644 645 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 646 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 647 } else if (PartVT.isVector() && 648 PartEVT.getVectorElementType().bitsGE( 649 ValueVT.getVectorElementType()) && 650 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 651 652 // Promoted vector extract 653 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 654 } else { 655 if (ValueVT.getVectorNumElements() == 1) { 656 Val = DAG.getNode( 657 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val, 658 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 659 } else { 660 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() && 661 "lossy conversion of vector to scalar type"); 662 EVT IntermediateType = 663 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 664 Val = DAG.getBitcast(IntermediateType, Val); 665 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT); 666 } 667 } 668 669 assert(Val.getValueType() == PartVT && "Unexpected vector part value type"); 670 Parts[0] = Val; 671 return; 672 } 673 674 // Handle a multi-element vector. 675 EVT IntermediateVT; 676 MVT RegisterVT; 677 unsigned NumIntermediates; 678 unsigned NumRegs; 679 if (IsABIRegCopy) { 680 NumRegs = TLI.getVectorTypeBreakdownForCallingConv( 681 *DAG.getContext(), ValueVT, IntermediateVT, NumIntermediates, 682 RegisterVT); 683 } else { 684 NumRegs = 685 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 686 NumIntermediates, RegisterVT); 687 } 688 unsigned NumElements = ValueVT.getVectorNumElements(); 689 690 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 691 NumParts = NumRegs; // Silence a compiler warning. 692 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 693 694 // Convert the vector to the appropiate type if necessary. 695 unsigned DestVectorNoElts = 696 NumIntermediates * 697 (IntermediateVT.isVector() ? IntermediateVT.getVectorNumElements() : 1); 698 EVT BuiltVectorTy = EVT::getVectorVT( 699 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts); 700 if (Val.getValueType() != BuiltVectorTy) 701 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val); 702 703 // Split the vector into intermediate operands. 704 SmallVector<SDValue, 8> Ops(NumIntermediates); 705 for (unsigned i = 0; i != NumIntermediates; ++i) { 706 if (IntermediateVT.isVector()) 707 Ops[i] = 708 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val, 709 DAG.getConstant(i * (NumElements / NumIntermediates), DL, 710 TLI.getVectorIdxTy(DAG.getDataLayout()))); 711 else 712 Ops[i] = DAG.getNode( 713 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val, 714 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 715 } 716 717 // Split the intermediate operands into legal parts. 718 if (NumParts == NumIntermediates) { 719 // If the register was not expanded, promote or copy the value, 720 // as appropriate. 721 for (unsigned i = 0; i != NumParts; ++i) 722 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V); 723 } else if (NumParts > 0) { 724 // If the intermediate type was expanded, split each the value into 725 // legal parts. 726 assert(NumIntermediates != 0 && "division by zero"); 727 assert(NumParts % NumIntermediates == 0 && 728 "Must expand into a divisible number of parts!"); 729 unsigned Factor = NumParts / NumIntermediates; 730 for (unsigned i = 0; i != NumIntermediates; ++i) 731 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V); 732 } 733 } 734 735 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt, 736 EVT valuevt, bool IsABIMangledValue) 737 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs), 738 RegCount(1, regs.size()), IsABIMangled(IsABIMangledValue) {} 739 740 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI, 741 const DataLayout &DL, unsigned Reg, Type *Ty, 742 bool IsABIMangledValue) { 743 ComputeValueVTs(TLI, DL, Ty, ValueVTs); 744 745 IsABIMangled = IsABIMangledValue; 746 747 for (EVT ValueVT : ValueVTs) { 748 unsigned NumRegs = IsABIMangledValue 749 ? TLI.getNumRegistersForCallingConv(Context, ValueVT) 750 : TLI.getNumRegisters(Context, ValueVT); 751 MVT RegisterVT = IsABIMangledValue 752 ? TLI.getRegisterTypeForCallingConv(Context, ValueVT) 753 : TLI.getRegisterType(Context, ValueVT); 754 for (unsigned i = 0; i != NumRegs; ++i) 755 Regs.push_back(Reg + i); 756 RegVTs.push_back(RegisterVT); 757 RegCount.push_back(NumRegs); 758 Reg += NumRegs; 759 } 760 } 761 762 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 763 FunctionLoweringInfo &FuncInfo, 764 const SDLoc &dl, SDValue &Chain, 765 SDValue *Flag, const Value *V) const { 766 // A Value with type {} or [0 x %t] needs no registers. 767 if (ValueVTs.empty()) 768 return SDValue(); 769 770 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 771 772 // Assemble the legal parts into the final values. 773 SmallVector<SDValue, 4> Values(ValueVTs.size()); 774 SmallVector<SDValue, 8> Parts; 775 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 776 // Copy the legal parts from the registers. 777 EVT ValueVT = ValueVTs[Value]; 778 unsigned NumRegs = RegCount[Value]; 779 MVT RegisterVT = IsABIMangled 780 ? TLI.getRegisterTypeForCallingConv(RegVTs[Value]) 781 : RegVTs[Value]; 782 783 Parts.resize(NumRegs); 784 for (unsigned i = 0; i != NumRegs; ++i) { 785 SDValue P; 786 if (!Flag) { 787 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 788 } else { 789 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 790 *Flag = P.getValue(2); 791 } 792 793 Chain = P.getValue(1); 794 Parts[i] = P; 795 796 // If the source register was virtual and if we know something about it, 797 // add an assert node. 798 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 799 !RegisterVT.isInteger() || RegisterVT.isVector()) 800 continue; 801 802 const FunctionLoweringInfo::LiveOutInfo *LOI = 803 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 804 if (!LOI) 805 continue; 806 807 unsigned RegSize = RegisterVT.getSizeInBits(); 808 unsigned NumSignBits = LOI->NumSignBits; 809 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros(); 810 811 if (NumZeroBits == RegSize) { 812 // The current value is a zero. 813 // Explicitly express that as it would be easier for 814 // optimizations to kick in. 815 Parts[i] = DAG.getConstant(0, dl, RegisterVT); 816 continue; 817 } 818 819 // FIXME: We capture more information than the dag can represent. For 820 // now, just use the tightest assertzext/assertsext possible. 821 bool isSExt = true; 822 EVT FromVT(MVT::Other); 823 if (NumSignBits == RegSize) { 824 isSExt = true; // ASSERT SEXT 1 825 FromVT = MVT::i1; 826 } else if (NumZeroBits >= RegSize - 1) { 827 isSExt = false; // ASSERT ZEXT 1 828 FromVT = MVT::i1; 829 } else if (NumSignBits > RegSize - 8) { 830 isSExt = true; // ASSERT SEXT 8 831 FromVT = MVT::i8; 832 } else if (NumZeroBits >= RegSize - 8) { 833 isSExt = false; // ASSERT ZEXT 8 834 FromVT = MVT::i8; 835 } else if (NumSignBits > RegSize - 16) { 836 isSExt = true; // ASSERT SEXT 16 837 FromVT = MVT::i16; 838 } else if (NumZeroBits >= RegSize - 16) { 839 isSExt = false; // ASSERT ZEXT 16 840 FromVT = MVT::i16; 841 } else if (NumSignBits > RegSize - 32) { 842 isSExt = true; // ASSERT SEXT 32 843 FromVT = MVT::i32; 844 } else if (NumZeroBits >= RegSize - 32) { 845 isSExt = false; // ASSERT ZEXT 32 846 FromVT = MVT::i32; 847 } else { 848 continue; 849 } 850 // Add an assertion node. 851 assert(FromVT != MVT::Other); 852 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 853 RegisterVT, P, DAG.getValueType(FromVT)); 854 } 855 856 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 857 NumRegs, RegisterVT, ValueVT, V); 858 Part += NumRegs; 859 Parts.clear(); 860 } 861 862 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values); 863 } 864 865 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, 866 const SDLoc &dl, SDValue &Chain, SDValue *Flag, 867 const Value *V, 868 ISD::NodeType PreferredExtendType) const { 869 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 870 ISD::NodeType ExtendKind = PreferredExtendType; 871 872 // Get the list of the values's legal parts. 873 unsigned NumRegs = Regs.size(); 874 SmallVector<SDValue, 8> Parts(NumRegs); 875 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 876 unsigned NumParts = RegCount[Value]; 877 878 MVT RegisterVT = IsABIMangled 879 ? TLI.getRegisterTypeForCallingConv(RegVTs[Value]) 880 : RegVTs[Value]; 881 882 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT)) 883 ExtendKind = ISD::ZERO_EXTEND; 884 885 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 886 &Parts[Part], NumParts, RegisterVT, V, ExtendKind); 887 Part += NumParts; 888 } 889 890 // Copy the parts into the registers. 891 SmallVector<SDValue, 8> Chains(NumRegs); 892 for (unsigned i = 0; i != NumRegs; ++i) { 893 SDValue Part; 894 if (!Flag) { 895 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 896 } else { 897 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 898 *Flag = Part.getValue(1); 899 } 900 901 Chains[i] = Part.getValue(0); 902 } 903 904 if (NumRegs == 1 || Flag) 905 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 906 // flagged to it. That is the CopyToReg nodes and the user are considered 907 // a single scheduling unit. If we create a TokenFactor and return it as 908 // chain, then the TokenFactor is both a predecessor (operand) of the 909 // user as well as a successor (the TF operands are flagged to the user). 910 // c1, f1 = CopyToReg 911 // c2, f2 = CopyToReg 912 // c3 = TokenFactor c1, c2 913 // ... 914 // = op c3, ..., f2 915 Chain = Chains[NumRegs-1]; 916 else 917 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 918 } 919 920 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 921 unsigned MatchingIdx, const SDLoc &dl, 922 SelectionDAG &DAG, 923 std::vector<SDValue> &Ops) const { 924 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 925 926 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 927 if (HasMatching) 928 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 929 else if (!Regs.empty() && 930 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 931 // Put the register class of the virtual registers in the flag word. That 932 // way, later passes can recompute register class constraints for inline 933 // assembly as well as normal instructions. 934 // Don't do this for tied operands that can use the regclass information 935 // from the def. 936 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 937 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 938 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 939 } 940 941 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32); 942 Ops.push_back(Res); 943 944 if (Code == InlineAsm::Kind_Clobber) { 945 // Clobbers should always have a 1:1 mapping with registers, and may 946 // reference registers that have illegal (e.g. vector) types. Hence, we 947 // shouldn't try to apply any sort of splitting logic to them. 948 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && 949 "No 1:1 mapping from clobbers to regs?"); 950 unsigned SP = TLI.getStackPointerRegisterToSaveRestore(); 951 (void)SP; 952 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) { 953 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I])); 954 assert( 955 (Regs[I] != SP || 956 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && 957 "If we clobbered the stack pointer, MFI should know about it."); 958 } 959 return; 960 } 961 962 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 963 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 964 MVT RegisterVT = RegVTs[Value]; 965 for (unsigned i = 0; i != NumRegs; ++i) { 966 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 967 unsigned TheReg = Regs[Reg++]; 968 Ops.push_back(DAG.getRegister(TheReg, RegisterVT)); 969 } 970 } 971 } 972 973 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa, 974 const TargetLibraryInfo *li) { 975 AA = aa; 976 GFI = gfi; 977 LibInfo = li; 978 DL = &DAG.getDataLayout(); 979 Context = DAG.getContext(); 980 LPadToCallSiteMap.clear(); 981 } 982 983 void SelectionDAGBuilder::clear() { 984 NodeMap.clear(); 985 UnusedArgNodeMap.clear(); 986 PendingLoads.clear(); 987 PendingExports.clear(); 988 CurInst = nullptr; 989 HasTailCall = false; 990 SDNodeOrder = LowestSDNodeOrder; 991 StatepointLowering.clear(); 992 } 993 994 void SelectionDAGBuilder::clearDanglingDebugInfo() { 995 DanglingDebugInfoMap.clear(); 996 } 997 998 SDValue SelectionDAGBuilder::getRoot() { 999 if (PendingLoads.empty()) 1000 return DAG.getRoot(); 1001 1002 if (PendingLoads.size() == 1) { 1003 SDValue Root = PendingLoads[0]; 1004 DAG.setRoot(Root); 1005 PendingLoads.clear(); 1006 return Root; 1007 } 1008 1009 // Otherwise, we have to make a token factor node. 1010 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1011 PendingLoads); 1012 PendingLoads.clear(); 1013 DAG.setRoot(Root); 1014 return Root; 1015 } 1016 1017 SDValue SelectionDAGBuilder::getControlRoot() { 1018 SDValue Root = DAG.getRoot(); 1019 1020 if (PendingExports.empty()) 1021 return Root; 1022 1023 // Turn all of the CopyToReg chains into one factored node. 1024 if (Root.getOpcode() != ISD::EntryToken) { 1025 unsigned i = 0, e = PendingExports.size(); 1026 for (; i != e; ++i) { 1027 assert(PendingExports[i].getNode()->getNumOperands() > 1); 1028 if (PendingExports[i].getNode()->getOperand(0) == Root) 1029 break; // Don't add the root if we already indirectly depend on it. 1030 } 1031 1032 if (i == e) 1033 PendingExports.push_back(Root); 1034 } 1035 1036 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 1037 PendingExports); 1038 PendingExports.clear(); 1039 DAG.setRoot(Root); 1040 return Root; 1041 } 1042 1043 void SelectionDAGBuilder::visit(const Instruction &I) { 1044 // Set up outgoing PHI node register values before emitting the terminator. 1045 if (isa<TerminatorInst>(&I)) { 1046 HandlePHINodesInSuccessorBlocks(I.getParent()); 1047 } 1048 1049 // Increase the SDNodeOrder if dealing with a non-debug instruction. 1050 if (!isa<DbgInfoIntrinsic>(I)) 1051 ++SDNodeOrder; 1052 1053 CurInst = &I; 1054 1055 visit(I.getOpcode(), I); 1056 1057 if (!isa<TerminatorInst>(&I) && !HasTailCall && 1058 !isStatepoint(&I)) // statepoints handle their exports internally 1059 CopyToExportRegsIfNeeded(&I); 1060 1061 CurInst = nullptr; 1062 } 1063 1064 void SelectionDAGBuilder::visitPHI(const PHINode &) { 1065 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 1066 } 1067 1068 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 1069 // Note: this doesn't use InstVisitor, because it has to work with 1070 // ConstantExpr's in addition to instructions. 1071 switch (Opcode) { 1072 default: llvm_unreachable("Unknown instruction type encountered!"); 1073 // Build the switch statement using the Instruction.def file. 1074 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1075 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 1076 #include "llvm/IR/Instruction.def" 1077 } 1078 } 1079 1080 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 1081 // generate the debug data structures now that we've seen its definition. 1082 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 1083 SDValue Val) { 1084 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 1085 if (DDI.getDI()) { 1086 const DbgValueInst *DI = DDI.getDI(); 1087 DebugLoc dl = DDI.getdl(); 1088 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 1089 DILocalVariable *Variable = DI->getVariable(); 1090 DIExpression *Expr = DI->getExpression(); 1091 assert(Variable->isValidLocationForIntrinsic(dl) && 1092 "Expected inlined-at fields to agree"); 1093 SDDbgValue *SDV; 1094 if (Val.getNode()) { 1095 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) { 1096 SDV = getDbgValue(Val, Variable, Expr, dl, DbgSDNodeOrder); 1097 DAG.AddDbgValue(SDV, Val.getNode(), false); 1098 } 1099 } else 1100 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1101 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 1102 } 1103 } 1104 1105 /// getCopyFromRegs - If there was virtual register allocated for the value V 1106 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise. 1107 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) { 1108 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1109 SDValue Result; 1110 1111 if (It != FuncInfo.ValueMap.end()) { 1112 unsigned InReg = It->second; 1113 1114 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), 1115 DAG.getDataLayout(), InReg, Ty, isABIRegCopy(V)); 1116 SDValue Chain = DAG.getEntryNode(); 1117 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, 1118 V); 1119 resolveDanglingDebugInfo(V, Result); 1120 } 1121 1122 return Result; 1123 } 1124 1125 /// getValue - Return an SDValue for the given Value. 1126 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1127 // If we already have an SDValue for this value, use it. It's important 1128 // to do this first, so that we don't create a CopyFromReg if we already 1129 // have a regular SDValue. 1130 SDValue &N = NodeMap[V]; 1131 if (N.getNode()) return N; 1132 1133 // If there's a virtual register allocated and initialized for this 1134 // value, use it. 1135 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType())) 1136 return copyFromReg; 1137 1138 // Otherwise create a new SDValue and remember it. 1139 SDValue Val = getValueImpl(V); 1140 NodeMap[V] = Val; 1141 resolveDanglingDebugInfo(V, Val); 1142 return Val; 1143 } 1144 1145 // Return true if SDValue exists for the given Value 1146 bool SelectionDAGBuilder::findValue(const Value *V) const { 1147 return (NodeMap.find(V) != NodeMap.end()) || 1148 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end()); 1149 } 1150 1151 /// getNonRegisterValue - Return an SDValue for the given Value, but 1152 /// don't look in FuncInfo.ValueMap for a virtual register. 1153 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1154 // If we already have an SDValue for this value, use it. 1155 SDValue &N = NodeMap[V]; 1156 if (N.getNode()) { 1157 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) { 1158 // Remove the debug location from the node as the node is about to be used 1159 // in a location which may differ from the original debug location. This 1160 // is relevant to Constant and ConstantFP nodes because they can appear 1161 // as constant expressions inside PHI nodes. 1162 N->setDebugLoc(DebugLoc()); 1163 } 1164 return N; 1165 } 1166 1167 // Otherwise create a new SDValue and remember it. 1168 SDValue Val = getValueImpl(V); 1169 NodeMap[V] = Val; 1170 resolveDanglingDebugInfo(V, Val); 1171 return Val; 1172 } 1173 1174 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1175 /// Create an SDValue for the given value. 1176 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1177 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1178 1179 if (const Constant *C = dyn_cast<Constant>(V)) { 1180 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true); 1181 1182 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1183 return DAG.getConstant(*CI, getCurSDLoc(), VT); 1184 1185 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1186 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1187 1188 if (isa<ConstantPointerNull>(C)) { 1189 unsigned AS = V->getType()->getPointerAddressSpace(); 1190 return DAG.getConstant(0, getCurSDLoc(), 1191 TLI.getPointerTy(DAG.getDataLayout(), AS)); 1192 } 1193 1194 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1195 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT); 1196 1197 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1198 return DAG.getUNDEF(VT); 1199 1200 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1201 visit(CE->getOpcode(), *CE); 1202 SDValue N1 = NodeMap[V]; 1203 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1204 return N1; 1205 } 1206 1207 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1208 SmallVector<SDValue, 4> Constants; 1209 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1210 OI != OE; ++OI) { 1211 SDNode *Val = getValue(*OI).getNode(); 1212 // If the operand is an empty aggregate, there are no values. 1213 if (!Val) continue; 1214 // Add each leaf value from the operand to the Constants list 1215 // to form a flattened list of all the values. 1216 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1217 Constants.push_back(SDValue(Val, i)); 1218 } 1219 1220 return DAG.getMergeValues(Constants, getCurSDLoc()); 1221 } 1222 1223 if (const ConstantDataSequential *CDS = 1224 dyn_cast<ConstantDataSequential>(C)) { 1225 SmallVector<SDValue, 4> Ops; 1226 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1227 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1228 // Add each leaf value from the operand to the Constants list 1229 // to form a flattened list of all the values. 1230 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1231 Ops.push_back(SDValue(Val, i)); 1232 } 1233 1234 if (isa<ArrayType>(CDS->getType())) 1235 return DAG.getMergeValues(Ops, getCurSDLoc()); 1236 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1237 } 1238 1239 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1240 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1241 "Unknown struct or array constant!"); 1242 1243 SmallVector<EVT, 4> ValueVTs; 1244 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs); 1245 unsigned NumElts = ValueVTs.size(); 1246 if (NumElts == 0) 1247 return SDValue(); // empty struct 1248 SmallVector<SDValue, 4> Constants(NumElts); 1249 for (unsigned i = 0; i != NumElts; ++i) { 1250 EVT EltVT = ValueVTs[i]; 1251 if (isa<UndefValue>(C)) 1252 Constants[i] = DAG.getUNDEF(EltVT); 1253 else if (EltVT.isFloatingPoint()) 1254 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1255 else 1256 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT); 1257 } 1258 1259 return DAG.getMergeValues(Constants, getCurSDLoc()); 1260 } 1261 1262 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1263 return DAG.getBlockAddress(BA, VT); 1264 1265 VectorType *VecTy = cast<VectorType>(V->getType()); 1266 unsigned NumElements = VecTy->getNumElements(); 1267 1268 // Now that we know the number and type of the elements, get that number of 1269 // elements into the Ops array based on what kind of constant it is. 1270 SmallVector<SDValue, 16> Ops; 1271 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1272 for (unsigned i = 0; i != NumElements; ++i) 1273 Ops.push_back(getValue(CV->getOperand(i))); 1274 } else { 1275 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1276 EVT EltVT = 1277 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType()); 1278 1279 SDValue Op; 1280 if (EltVT.isFloatingPoint()) 1281 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT); 1282 else 1283 Op = DAG.getConstant(0, getCurSDLoc(), EltVT); 1284 Ops.assign(NumElements, Op); 1285 } 1286 1287 // Create a BUILD_VECTOR node. 1288 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops); 1289 } 1290 1291 // If this is a static alloca, generate it as the frameindex instead of 1292 // computation. 1293 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1294 DenseMap<const AllocaInst*, int>::iterator SI = 1295 FuncInfo.StaticAllocaMap.find(AI); 1296 if (SI != FuncInfo.StaticAllocaMap.end()) 1297 return DAG.getFrameIndex(SI->second, 1298 TLI.getFrameIndexTy(DAG.getDataLayout())); 1299 } 1300 1301 // If this is an instruction which fast-isel has deferred, select it now. 1302 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1303 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1304 1305 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg, 1306 Inst->getType(), isABIRegCopy(V)); 1307 SDValue Chain = DAG.getEntryNode(); 1308 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V); 1309 } 1310 1311 llvm_unreachable("Can't get register for value!"); 1312 } 1313 1314 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) { 1315 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1316 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX; 1317 bool IsCoreCLR = Pers == EHPersonality::CoreCLR; 1318 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB; 1319 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues. 1320 if (IsMSVCCXX || IsCoreCLR) 1321 CatchPadMBB->setIsEHFuncletEntry(); 1322 1323 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other, getControlRoot())); 1324 } 1325 1326 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) { 1327 // Update machine-CFG edge. 1328 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()]; 1329 FuncInfo.MBB->addSuccessor(TargetMBB); 1330 1331 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1332 bool IsSEH = isAsynchronousEHPersonality(Pers); 1333 if (IsSEH) { 1334 // If this is not a fall-through branch or optimizations are switched off, 1335 // emit the branch. 1336 if (TargetMBB != NextBlock(FuncInfo.MBB) || 1337 TM.getOptLevel() == CodeGenOpt::None) 1338 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 1339 getControlRoot(), DAG.getBasicBlock(TargetMBB))); 1340 return; 1341 } 1342 1343 // Figure out the funclet membership for the catchret's successor. 1344 // This will be used by the FuncletLayout pass to determine how to order the 1345 // BB's. 1346 // A 'catchret' returns to the outer scope's color. 1347 Value *ParentPad = I.getCatchSwitchParentPad(); 1348 const BasicBlock *SuccessorColor; 1349 if (isa<ConstantTokenNone>(ParentPad)) 1350 SuccessorColor = &FuncInfo.Fn->getEntryBlock(); 1351 else 1352 SuccessorColor = cast<Instruction>(ParentPad)->getParent(); 1353 assert(SuccessorColor && "No parent funclet for catchret!"); 1354 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor]; 1355 assert(SuccessorColorMBB && "No MBB for SuccessorColor!"); 1356 1357 // Create the terminator node. 1358 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other, 1359 getControlRoot(), DAG.getBasicBlock(TargetMBB), 1360 DAG.getBasicBlock(SuccessorColorMBB)); 1361 DAG.setRoot(Ret); 1362 } 1363 1364 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) { 1365 // Don't emit any special code for the cleanuppad instruction. It just marks 1366 // the start of a funclet. 1367 FuncInfo.MBB->setIsEHFuncletEntry(); 1368 FuncInfo.MBB->setIsCleanupFuncletEntry(); 1369 } 1370 1371 /// When an invoke or a cleanupret unwinds to the next EH pad, there are 1372 /// many places it could ultimately go. In the IR, we have a single unwind 1373 /// destination, but in the machine CFG, we enumerate all the possible blocks. 1374 /// This function skips over imaginary basic blocks that hold catchswitch 1375 /// instructions, and finds all the "real" machine 1376 /// basic block destinations. As those destinations may not be successors of 1377 /// EHPadBB, here we also calculate the edge probability to those destinations. 1378 /// The passed-in Prob is the edge probability to EHPadBB. 1379 static void findUnwindDestinations( 1380 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB, 1381 BranchProbability Prob, 1382 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 1383 &UnwindDests) { 1384 EHPersonality Personality = 1385 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()); 1386 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 1387 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 1388 1389 while (EHPadBB) { 1390 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 1391 BasicBlock *NewEHPadBB = nullptr; 1392 if (isa<LandingPadInst>(Pad)) { 1393 // Stop on landingpads. They are not funclets. 1394 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1395 break; 1396 } else if (isa<CleanupPadInst>(Pad)) { 1397 // Stop on cleanup pads. Cleanups are always funclet entries for all known 1398 // personalities. 1399 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob); 1400 UnwindDests.back().first->setIsEHFuncletEntry(); 1401 break; 1402 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 1403 // Add the catchpad handlers to the possible destinations. 1404 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 1405 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob); 1406 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 1407 if (IsMSVCCXX || IsCoreCLR) 1408 UnwindDests.back().first->setIsEHFuncletEntry(); 1409 } 1410 NewEHPadBB = CatchSwitch->getUnwindDest(); 1411 } else { 1412 continue; 1413 } 1414 1415 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1416 if (BPI && NewEHPadBB) 1417 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 1418 EHPadBB = NewEHPadBB; 1419 } 1420 } 1421 1422 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) { 1423 // Update successor info. 1424 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 1425 auto UnwindDest = I.getUnwindDest(); 1426 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1427 BranchProbability UnwindDestProb = 1428 (BPI && UnwindDest) 1429 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest) 1430 : BranchProbability::getZero(); 1431 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests); 1432 for (auto &UnwindDest : UnwindDests) { 1433 UnwindDest.first->setIsEHPad(); 1434 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second); 1435 } 1436 FuncInfo.MBB->normalizeSuccProbs(); 1437 1438 // Create the terminator node. 1439 SDValue Ret = 1440 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot()); 1441 DAG.setRoot(Ret); 1442 } 1443 1444 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) { 1445 report_fatal_error("visitCatchSwitch not yet implemented!"); 1446 } 1447 1448 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1449 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 1450 auto &DL = DAG.getDataLayout(); 1451 SDValue Chain = getControlRoot(); 1452 SmallVector<ISD::OutputArg, 8> Outs; 1453 SmallVector<SDValue, 8> OutVals; 1454 1455 // Calls to @llvm.experimental.deoptimize don't generate a return value, so 1456 // lower 1457 // 1458 // %val = call <ty> @llvm.experimental.deoptimize() 1459 // ret <ty> %val 1460 // 1461 // differently. 1462 if (I.getParent()->getTerminatingDeoptimizeCall()) { 1463 LowerDeoptimizingReturn(); 1464 return; 1465 } 1466 1467 if (!FuncInfo.CanLowerReturn) { 1468 unsigned DemoteReg = FuncInfo.DemoteRegister; 1469 const Function *F = I.getParent()->getParent(); 1470 1471 // Emit a store of the return value through the virtual register. 1472 // Leave Outs empty so that LowerReturn won't try to load return 1473 // registers the usual way. 1474 SmallVector<EVT, 1> PtrValueVTs; 1475 ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()), 1476 PtrValueVTs); 1477 1478 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 1479 DemoteReg, PtrValueVTs[0]); 1480 SDValue RetOp = getValue(I.getOperand(0)); 1481 1482 SmallVector<EVT, 4> ValueVTs; 1483 SmallVector<uint64_t, 4> Offsets; 1484 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1485 unsigned NumValues = ValueVTs.size(); 1486 1487 SmallVector<SDValue, 4> Chains(NumValues); 1488 for (unsigned i = 0; i != NumValues; ++i) { 1489 // An aggregate return value cannot wrap around the address space, so 1490 // offsets to its parts don't wrap either. 1491 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]); 1492 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), 1493 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1494 // FIXME: better loc info would be nice. 1495 Ptr, MachinePointerInfo()); 1496 } 1497 1498 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1499 MVT::Other, Chains); 1500 } else if (I.getNumOperands() != 0) { 1501 SmallVector<EVT, 4> ValueVTs; 1502 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs); 1503 unsigned NumValues = ValueVTs.size(); 1504 if (NumValues) { 1505 SDValue RetOp = getValue(I.getOperand(0)); 1506 1507 const Function *F = I.getParent()->getParent(); 1508 1509 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1510 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1511 Attribute::SExt)) 1512 ExtendKind = ISD::SIGN_EXTEND; 1513 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex, 1514 Attribute::ZExt)) 1515 ExtendKind = ISD::ZERO_EXTEND; 1516 1517 LLVMContext &Context = F->getContext(); 1518 bool RetInReg = F->getAttributes().hasAttribute( 1519 AttributeList::ReturnIndex, Attribute::InReg); 1520 1521 for (unsigned j = 0; j != NumValues; ++j) { 1522 EVT VT = ValueVTs[j]; 1523 1524 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1525 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind); 1526 1527 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, VT); 1528 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, VT); 1529 SmallVector<SDValue, 4> Parts(NumParts); 1530 getCopyToParts(DAG, getCurSDLoc(), 1531 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1532 &Parts[0], NumParts, PartVT, &I, ExtendKind, true); 1533 1534 // 'inreg' on function refers to return value 1535 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1536 if (RetInReg) 1537 Flags.setInReg(); 1538 1539 // Propagate extension type if any 1540 if (ExtendKind == ISD::SIGN_EXTEND) 1541 Flags.setSExt(); 1542 else if (ExtendKind == ISD::ZERO_EXTEND) 1543 Flags.setZExt(); 1544 1545 for (unsigned i = 0; i < NumParts; ++i) { 1546 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1547 VT, /*isfixed=*/true, 0, 0)); 1548 OutVals.push_back(Parts[i]); 1549 } 1550 } 1551 } 1552 } 1553 1554 // Push in swifterror virtual register as the last element of Outs. This makes 1555 // sure swifterror virtual register will be returned in the swifterror 1556 // physical register. 1557 const Function *F = I.getParent()->getParent(); 1558 if (TLI.supportSwiftError() && 1559 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) { 1560 assert(FuncInfo.SwiftErrorArg && "Need a swift error argument"); 1561 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1562 Flags.setSwiftError(); 1563 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/, 1564 EVT(TLI.getPointerTy(DL)) /*argvt*/, 1565 true /*isfixed*/, 1 /*origidx*/, 1566 0 /*partOffs*/)); 1567 // Create SDNode for the swifterror virtual register. 1568 OutVals.push_back( 1569 DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt( 1570 &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first, 1571 EVT(TLI.getPointerTy(DL)))); 1572 } 1573 1574 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 1575 CallingConv::ID CallConv = 1576 DAG.getMachineFunction().getFunction()->getCallingConv(); 1577 Chain = DAG.getTargetLoweringInfo().LowerReturn( 1578 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG); 1579 1580 // Verify that the target's LowerReturn behaved as expected. 1581 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1582 "LowerReturn didn't return a valid chain!"); 1583 1584 // Update the DAG with the new chain value resulting from return lowering. 1585 DAG.setRoot(Chain); 1586 } 1587 1588 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1589 /// created for it, emit nodes to copy the value into the virtual 1590 /// registers. 1591 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1592 // Skip empty types 1593 if (V->getType()->isEmptyTy()) 1594 return; 1595 1596 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1597 if (VMI != FuncInfo.ValueMap.end()) { 1598 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1599 CopyValueToVirtualRegister(V, VMI->second); 1600 } 1601 } 1602 1603 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1604 /// the current basic block, add it to ValueMap now so that we'll get a 1605 /// CopyTo/FromReg. 1606 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1607 // No need to export constants. 1608 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1609 1610 // Already exported? 1611 if (FuncInfo.isExportedInst(V)) return; 1612 1613 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1614 CopyValueToVirtualRegister(V, Reg); 1615 } 1616 1617 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1618 const BasicBlock *FromBB) { 1619 // The operands of the setcc have to be in this block. We don't know 1620 // how to export them from some other block. 1621 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1622 // Can export from current BB. 1623 if (VI->getParent() == FromBB) 1624 return true; 1625 1626 // Is already exported, noop. 1627 return FuncInfo.isExportedInst(V); 1628 } 1629 1630 // If this is an argument, we can export it if the BB is the entry block or 1631 // if it is already exported. 1632 if (isa<Argument>(V)) { 1633 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1634 return true; 1635 1636 // Otherwise, can only export this if it is already exported. 1637 return FuncInfo.isExportedInst(V); 1638 } 1639 1640 // Otherwise, constants can always be exported. 1641 return true; 1642 } 1643 1644 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1645 BranchProbability 1646 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src, 1647 const MachineBasicBlock *Dst) const { 1648 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1649 const BasicBlock *SrcBB = Src->getBasicBlock(); 1650 const BasicBlock *DstBB = Dst->getBasicBlock(); 1651 if (!BPI) { 1652 // If BPI is not available, set the default probability as 1 / N, where N is 1653 // the number of successors. 1654 auto SuccSize = std::max<uint32_t>( 1655 std::distance(succ_begin(SrcBB), succ_end(SrcBB)), 1); 1656 return BranchProbability(1, SuccSize); 1657 } 1658 return BPI->getEdgeProbability(SrcBB, DstBB); 1659 } 1660 1661 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src, 1662 MachineBasicBlock *Dst, 1663 BranchProbability Prob) { 1664 if (!FuncInfo.BPI) 1665 Src->addSuccessorWithoutProb(Dst); 1666 else { 1667 if (Prob.isUnknown()) 1668 Prob = getEdgeProbability(Src, Dst); 1669 Src->addSuccessor(Dst, Prob); 1670 } 1671 } 1672 1673 static bool InBlock(const Value *V, const BasicBlock *BB) { 1674 if (const Instruction *I = dyn_cast<Instruction>(V)) 1675 return I->getParent() == BB; 1676 return true; 1677 } 1678 1679 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1680 /// This function emits a branch and is used at the leaves of an OR or an 1681 /// AND operator tree. 1682 void 1683 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1684 MachineBasicBlock *TBB, 1685 MachineBasicBlock *FBB, 1686 MachineBasicBlock *CurBB, 1687 MachineBasicBlock *SwitchBB, 1688 BranchProbability TProb, 1689 BranchProbability FProb, 1690 bool InvertCond) { 1691 const BasicBlock *BB = CurBB->getBasicBlock(); 1692 1693 // If the leaf of the tree is a comparison, merge the condition into 1694 // the caseblock. 1695 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1696 // The operands of the cmp have to be in this block. We don't know 1697 // how to export them from some other block. If this is the first block 1698 // of the sequence, no exporting is needed. 1699 if (CurBB == SwitchBB || 1700 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1701 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1702 ISD::CondCode Condition; 1703 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1704 ICmpInst::Predicate Pred = 1705 InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 1706 Condition = getICmpCondCode(Pred); 1707 } else { 1708 const FCmpInst *FC = cast<FCmpInst>(Cond); 1709 FCmpInst::Predicate Pred = 1710 InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 1711 Condition = getFCmpCondCode(Pred); 1712 if (TM.Options.NoNaNsFPMath) 1713 Condition = getFCmpCodeWithoutNaN(Condition); 1714 } 1715 1716 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr, 1717 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1718 SwitchCases.push_back(CB); 1719 return; 1720 } 1721 } 1722 1723 // Create a CaseBlock record representing this branch. 1724 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ; 1725 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()), 1726 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb); 1727 SwitchCases.push_back(CB); 1728 } 1729 1730 /// FindMergedConditions - If Cond is an expression like 1731 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1732 MachineBasicBlock *TBB, 1733 MachineBasicBlock *FBB, 1734 MachineBasicBlock *CurBB, 1735 MachineBasicBlock *SwitchBB, 1736 Instruction::BinaryOps Opc, 1737 BranchProbability TProb, 1738 BranchProbability FProb, 1739 bool InvertCond) { 1740 // Skip over not part of the tree and remember to invert op and operands at 1741 // next level. 1742 if (BinaryOperator::isNot(Cond) && Cond->hasOneUse()) { 1743 const Value *CondOp = BinaryOperator::getNotArgument(Cond); 1744 if (InBlock(CondOp, CurBB->getBasicBlock())) { 1745 FindMergedConditions(CondOp, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 1746 !InvertCond); 1747 return; 1748 } 1749 } 1750 1751 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1752 // Compute the effective opcode for Cond, taking into account whether it needs 1753 // to be inverted, e.g. 1754 // and (not (or A, B)), C 1755 // gets lowered as 1756 // and (and (not A, not B), C) 1757 unsigned BOpc = 0; 1758 if (BOp) { 1759 BOpc = BOp->getOpcode(); 1760 if (InvertCond) { 1761 if (BOpc == Instruction::And) 1762 BOpc = Instruction::Or; 1763 else if (BOpc == Instruction::Or) 1764 BOpc = Instruction::And; 1765 } 1766 } 1767 1768 // If this node is not part of the or/and tree, emit it as a branch. 1769 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1770 BOpc != Opc || !BOp->hasOneUse() || 1771 BOp->getParent() != CurBB->getBasicBlock() || 1772 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1773 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1774 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, 1775 TProb, FProb, InvertCond); 1776 return; 1777 } 1778 1779 // Create TmpBB after CurBB. 1780 MachineFunction::iterator BBI(CurBB); 1781 MachineFunction &MF = DAG.getMachineFunction(); 1782 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1783 CurBB->getParent()->insert(++BBI, TmpBB); 1784 1785 if (Opc == Instruction::Or) { 1786 // Codegen X | Y as: 1787 // BB1: 1788 // jmp_if_X TBB 1789 // jmp TmpBB 1790 // TmpBB: 1791 // jmp_if_Y TBB 1792 // jmp FBB 1793 // 1794 1795 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1796 // The requirement is that 1797 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 1798 // = TrueProb for original BB. 1799 // Assuming the original probabilities are A and B, one choice is to set 1800 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 1801 // A/(1+B) and 2B/(1+B). This choice assumes that 1802 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 1803 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 1804 // TmpBB, but the math is more complicated. 1805 1806 auto NewTrueProb = TProb / 2; 1807 auto NewFalseProb = TProb / 2 + FProb; 1808 // Emit the LHS condition. 1809 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 1810 NewTrueProb, NewFalseProb, InvertCond); 1811 1812 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 1813 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 1814 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1815 // Emit the RHS condition into TmpBB. 1816 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1817 Probs[0], Probs[1], InvertCond); 1818 } else { 1819 assert(Opc == Instruction::And && "Unknown merge op!"); 1820 // Codegen X & Y as: 1821 // BB1: 1822 // jmp_if_X TmpBB 1823 // jmp FBB 1824 // TmpBB: 1825 // jmp_if_Y TBB 1826 // jmp FBB 1827 // 1828 // This requires creation of TmpBB after CurBB. 1829 1830 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 1831 // The requirement is that 1832 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 1833 // = FalseProb for original BB. 1834 // Assuming the original probabilities are A and B, one choice is to set 1835 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 1836 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 1837 // TrueProb for BB1 * FalseProb for TmpBB. 1838 1839 auto NewTrueProb = TProb + FProb / 2; 1840 auto NewFalseProb = FProb / 2; 1841 // Emit the LHS condition. 1842 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 1843 NewTrueProb, NewFalseProb, InvertCond); 1844 1845 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 1846 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 1847 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 1848 // Emit the RHS condition into TmpBB. 1849 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 1850 Probs[0], Probs[1], InvertCond); 1851 } 1852 } 1853 1854 /// If the set of cases should be emitted as a series of branches, return true. 1855 /// If we should emit this as a bunch of and/or'd together conditions, return 1856 /// false. 1857 bool 1858 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1859 if (Cases.size() != 2) return true; 1860 1861 // If this is two comparisons of the same values or'd or and'd together, they 1862 // will get folded into a single comparison, so don't emit two blocks. 1863 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1864 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1865 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1866 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1867 return false; 1868 } 1869 1870 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1871 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1872 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1873 Cases[0].CC == Cases[1].CC && 1874 isa<Constant>(Cases[0].CmpRHS) && 1875 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1876 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1877 return false; 1878 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1879 return false; 1880 } 1881 1882 return true; 1883 } 1884 1885 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1886 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1887 1888 // Update machine-CFG edges. 1889 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1890 1891 if (I.isUnconditional()) { 1892 // Update machine-CFG edges. 1893 BrMBB->addSuccessor(Succ0MBB); 1894 1895 // If this is not a fall-through branch or optimizations are switched off, 1896 // emit the branch. 1897 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None) 1898 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1899 MVT::Other, getControlRoot(), 1900 DAG.getBasicBlock(Succ0MBB))); 1901 1902 return; 1903 } 1904 1905 // If this condition is one of the special cases we handle, do special stuff 1906 // now. 1907 const Value *CondVal = I.getCondition(); 1908 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1909 1910 // If this is a series of conditions that are or'd or and'd together, emit 1911 // this as a sequence of branches instead of setcc's with and/or operations. 1912 // As long as jumps are not expensive, this should improve performance. 1913 // For example, instead of something like: 1914 // cmp A, B 1915 // C = seteq 1916 // cmp D, E 1917 // F = setle 1918 // or C, F 1919 // jnz foo 1920 // Emit: 1921 // cmp A, B 1922 // je foo 1923 // cmp D, E 1924 // jle foo 1925 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1926 Instruction::BinaryOps Opcode = BOp->getOpcode(); 1927 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() && 1928 !I.getMetadata(LLVMContext::MD_unpredictable) && 1929 (Opcode == Instruction::And || Opcode == Instruction::Or)) { 1930 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1931 Opcode, 1932 getEdgeProbability(BrMBB, Succ0MBB), 1933 getEdgeProbability(BrMBB, Succ1MBB), 1934 /*InvertCond=*/false); 1935 // If the compares in later blocks need to use values not currently 1936 // exported from this block, export them now. This block should always 1937 // be the first entry. 1938 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1939 1940 // Allow some cases to be rejected. 1941 if (ShouldEmitAsBranches(SwitchCases)) { 1942 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1943 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1944 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1945 } 1946 1947 // Emit the branch for this block. 1948 visitSwitchCase(SwitchCases[0], BrMBB); 1949 SwitchCases.erase(SwitchCases.begin()); 1950 return; 1951 } 1952 1953 // Okay, we decided not to do this, remove any inserted MBB's and clear 1954 // SwitchCases. 1955 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1956 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1957 1958 SwitchCases.clear(); 1959 } 1960 } 1961 1962 // Create a CaseBlock record representing this branch. 1963 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1964 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc()); 1965 1966 // Use visitSwitchCase to actually insert the fast branch sequence for this 1967 // cond branch. 1968 visitSwitchCase(CB, BrMBB); 1969 } 1970 1971 /// visitSwitchCase - Emits the necessary code to represent a single node in 1972 /// the binary search tree resulting from lowering a switch instruction. 1973 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1974 MachineBasicBlock *SwitchBB) { 1975 SDValue Cond; 1976 SDValue CondLHS = getValue(CB.CmpLHS); 1977 SDLoc dl = CB.DL; 1978 1979 // Build the setcc now. 1980 if (!CB.CmpMHS) { 1981 // Fold "(X == true)" to X and "(X == false)" to !X to 1982 // handle common cases produced by branch lowering. 1983 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1984 CB.CC == ISD::SETEQ) 1985 Cond = CondLHS; 1986 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1987 CB.CC == ISD::SETEQ) { 1988 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType()); 1989 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1990 } else 1991 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1992 } else { 1993 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now"); 1994 1995 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1996 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1997 1998 SDValue CmpOp = getValue(CB.CmpMHS); 1999 EVT VT = CmpOp.getValueType(); 2000 2001 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 2002 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT), 2003 ISD::SETLE); 2004 } else { 2005 SDValue SUB = DAG.getNode(ISD::SUB, dl, 2006 VT, CmpOp, DAG.getConstant(Low, dl, VT)); 2007 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 2008 DAG.getConstant(High-Low, dl, VT), ISD::SETULE); 2009 } 2010 } 2011 2012 // Update successor info 2013 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb); 2014 // TrueBB and FalseBB are always different unless the incoming IR is 2015 // degenerate. This only happens when running llc on weird IR. 2016 if (CB.TrueBB != CB.FalseBB) 2017 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb); 2018 SwitchBB->normalizeSuccProbs(); 2019 2020 // If the lhs block is the next block, invert the condition so that we can 2021 // fall through to the lhs instead of the rhs block. 2022 if (CB.TrueBB == NextBlock(SwitchBB)) { 2023 std::swap(CB.TrueBB, CB.FalseBB); 2024 SDValue True = DAG.getConstant(1, dl, Cond.getValueType()); 2025 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 2026 } 2027 2028 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2029 MVT::Other, getControlRoot(), Cond, 2030 DAG.getBasicBlock(CB.TrueBB)); 2031 2032 // Insert the false branch. Do this even if it's a fall through branch, 2033 // this makes it easier to do DAG optimizations which require inverting 2034 // the branch condition. 2035 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2036 DAG.getBasicBlock(CB.FalseBB)); 2037 2038 DAG.setRoot(BrCond); 2039 } 2040 2041 /// visitJumpTable - Emit JumpTable node in the current MBB 2042 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 2043 // Emit the code for the jump table 2044 assert(JT.Reg != -1U && "Should lower JT Header first!"); 2045 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); 2046 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 2047 JT.Reg, PTy); 2048 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 2049 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 2050 MVT::Other, Index.getValue(1), 2051 Table, Index); 2052 DAG.setRoot(BrJumpTable); 2053 } 2054 2055 /// visitJumpTableHeader - This function emits necessary code to produce index 2056 /// in the JumpTable from switch case. 2057 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 2058 JumpTableHeader &JTH, 2059 MachineBasicBlock *SwitchBB) { 2060 SDLoc dl = getCurSDLoc(); 2061 2062 // Subtract the lowest switch case value from the value being switched on and 2063 // conditional branch to default mbb if the result is greater than the 2064 // difference between smallest and largest cases. 2065 SDValue SwitchOp = getValue(JTH.SValue); 2066 EVT VT = SwitchOp.getValueType(); 2067 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2068 DAG.getConstant(JTH.First, dl, VT)); 2069 2070 // The SDNode we just created, which holds the value being switched on minus 2071 // the smallest case value, needs to be copied to a virtual register so it 2072 // can be used as an index into the jump table in a subsequent basic block. 2073 // This value may be smaller or larger than the target's pointer type, and 2074 // therefore require extension or truncating. 2075 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2076 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout())); 2077 2078 unsigned JumpTableReg = 2079 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout())); 2080 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, 2081 JumpTableReg, SwitchOp); 2082 JT.Reg = JumpTableReg; 2083 2084 // Emit the range check for the jump table, and branch to the default block 2085 // for the switch statement if the value being switched on exceeds the largest 2086 // case in the switch. 2087 SDValue CMP = DAG.getSetCC( 2088 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2089 Sub.getValueType()), 2090 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT); 2091 2092 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2093 MVT::Other, CopyTo, CMP, 2094 DAG.getBasicBlock(JT.Default)); 2095 2096 // Avoid emitting unnecessary branches to the next block. 2097 if (JT.MBB != NextBlock(SwitchBB)) 2098 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 2099 DAG.getBasicBlock(JT.MBB)); 2100 2101 DAG.setRoot(BrCond); 2102 } 2103 2104 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global 2105 /// variable if there exists one. 2106 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL, 2107 SDValue &Chain) { 2108 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2109 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2110 MachineFunction &MF = DAG.getMachineFunction(); 2111 Value *Global = TLI.getSDagStackGuard(*MF.getFunction()->getParent()); 2112 MachineSDNode *Node = 2113 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain); 2114 if (Global) { 2115 MachinePointerInfo MPInfo(Global); 2116 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1); 2117 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 2118 MachineMemOperand::MODereferenceable; 2119 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags, PtrTy.getSizeInBits() / 8, 2120 DAG.getEVTAlignment(PtrTy)); 2121 Node->setMemRefs(MemRefs, MemRefs + 1); 2122 } 2123 return SDValue(Node, 0); 2124 } 2125 2126 /// Codegen a new tail for a stack protector check ParentMBB which has had its 2127 /// tail spliced into a stack protector check success bb. 2128 /// 2129 /// For a high level explanation of how this fits into the stack protector 2130 /// generation see the comment on the declaration of class 2131 /// StackProtectorDescriptor. 2132 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 2133 MachineBasicBlock *ParentBB) { 2134 2135 // First create the loads to the guard/stack slot for the comparison. 2136 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2137 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 2138 2139 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo(); 2140 int FI = MFI.getStackProtectorIndex(); 2141 2142 SDValue Guard; 2143 SDLoc dl = getCurSDLoc(); 2144 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 2145 const Module &M = *ParentBB->getParent()->getFunction()->getParent(); 2146 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext())); 2147 2148 // Generate code to load the content of the guard slot. 2149 SDValue StackSlot = DAG.getLoad( 2150 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr, 2151 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align, 2152 MachineMemOperand::MOVolatile); 2153 2154 // Retrieve guard check function, nullptr if instrumentation is inlined. 2155 if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) { 2156 // The target provides a guard check function to validate the guard value. 2157 // Generate a call to that function with the content of the guard slot as 2158 // argument. 2159 auto *Fn = cast<Function>(GuardCheck); 2160 FunctionType *FnTy = Fn->getFunctionType(); 2161 assert(FnTy->getNumParams() == 1 && "Invalid function signature"); 2162 2163 TargetLowering::ArgListTy Args; 2164 TargetLowering::ArgListEntry Entry; 2165 Entry.Node = StackSlot; 2166 Entry.Ty = FnTy->getParamType(0); 2167 if (Fn->hasAttribute(1, Attribute::AttrKind::InReg)) 2168 Entry.IsInReg = true; 2169 Args.push_back(Entry); 2170 2171 TargetLowering::CallLoweringInfo CLI(DAG); 2172 CLI.setDebugLoc(getCurSDLoc()) 2173 .setChain(DAG.getEntryNode()) 2174 .setCallee(Fn->getCallingConv(), FnTy->getReturnType(), 2175 getValue(GuardCheck), std::move(Args)); 2176 2177 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 2178 DAG.setRoot(Result.second); 2179 return; 2180 } 2181 2182 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD. 2183 // Otherwise, emit a volatile load to retrieve the stack guard value. 2184 SDValue Chain = DAG.getEntryNode(); 2185 if (TLI.useLoadStackGuardNode()) { 2186 Guard = getLoadStackGuard(DAG, dl, Chain); 2187 } else { 2188 const Value *IRGuard = TLI.getSDagStackGuard(M); 2189 SDValue GuardPtr = getValue(IRGuard); 2190 2191 Guard = 2192 DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0), 2193 Align, MachineMemOperand::MOVolatile); 2194 } 2195 2196 // Perform the comparison via a subtract/getsetcc. 2197 EVT VT = Guard.getValueType(); 2198 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot); 2199 2200 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(), 2201 *DAG.getContext(), 2202 Sub.getValueType()), 2203 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE); 2204 2205 // If the sub is not 0, then we know the guard/stackslot do not equal, so 2206 // branch to failure MBB. 2207 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 2208 MVT::Other, StackSlot.getOperand(0), 2209 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 2210 // Otherwise branch to success MBB. 2211 SDValue Br = DAG.getNode(ISD::BR, dl, 2212 MVT::Other, BrCond, 2213 DAG.getBasicBlock(SPD.getSuccessMBB())); 2214 2215 DAG.setRoot(Br); 2216 } 2217 2218 /// Codegen the failure basic block for a stack protector check. 2219 /// 2220 /// A failure stack protector machine basic block consists simply of a call to 2221 /// __stack_chk_fail(). 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 2227 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 2228 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2229 SDValue Chain = 2230 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid, 2231 None, false, getCurSDLoc(), false, false).second; 2232 DAG.setRoot(Chain); 2233 } 2234 2235 /// visitBitTestHeader - This function emits necessary code to produce value 2236 /// suitable for "bit tests" 2237 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 2238 MachineBasicBlock *SwitchBB) { 2239 SDLoc dl = getCurSDLoc(); 2240 2241 // Subtract the minimum value 2242 SDValue SwitchOp = getValue(B.SValue); 2243 EVT VT = SwitchOp.getValueType(); 2244 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp, 2245 DAG.getConstant(B.First, dl, VT)); 2246 2247 // Check range 2248 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2249 SDValue RangeCmp = DAG.getSetCC( 2250 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 2251 Sub.getValueType()), 2252 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT); 2253 2254 // Determine the type of the test operands. 2255 bool UsePtrType = false; 2256 if (!TLI.isTypeLegal(VT)) 2257 UsePtrType = true; 2258 else { 2259 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 2260 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 2261 // Switch table case range are encoded into series of masks. 2262 // Just use pointer type, it's guaranteed to fit. 2263 UsePtrType = true; 2264 break; 2265 } 2266 } 2267 if (UsePtrType) { 2268 VT = TLI.getPointerTy(DAG.getDataLayout()); 2269 Sub = DAG.getZExtOrTrunc(Sub, dl, VT); 2270 } 2271 2272 B.RegVT = VT.getSimpleVT(); 2273 B.Reg = FuncInfo.CreateReg(B.RegVT); 2274 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub); 2275 2276 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 2277 2278 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 2279 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 2280 SwitchBB->normalizeSuccProbs(); 2281 2282 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl, 2283 MVT::Other, CopyTo, RangeCmp, 2284 DAG.getBasicBlock(B.Default)); 2285 2286 // Avoid emitting unnecessary branches to the next block. 2287 if (MBB != NextBlock(SwitchBB)) 2288 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange, 2289 DAG.getBasicBlock(MBB)); 2290 2291 DAG.setRoot(BrRange); 2292 } 2293 2294 /// visitBitTestCase - this function produces one "bit test" 2295 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 2296 MachineBasicBlock* NextMBB, 2297 BranchProbability BranchProbToNext, 2298 unsigned Reg, 2299 BitTestCase &B, 2300 MachineBasicBlock *SwitchBB) { 2301 SDLoc dl = getCurSDLoc(); 2302 MVT VT = BB.RegVT; 2303 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT); 2304 SDValue Cmp; 2305 unsigned PopCount = countPopulation(B.Mask); 2306 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2307 if (PopCount == 1) { 2308 // Testing for a single bit; just compare the shift count with what it 2309 // would need to be to shift a 1 bit in that position. 2310 Cmp = DAG.getSetCC( 2311 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2312 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), 2313 ISD::SETEQ); 2314 } else if (PopCount == BB.Range) { 2315 // There is only one zero bit in the range, test for it directly. 2316 Cmp = DAG.getSetCC( 2317 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2318 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), 2319 ISD::SETNE); 2320 } else { 2321 // Make desired shift 2322 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT, 2323 DAG.getConstant(1, dl, VT), ShiftOp); 2324 2325 // Emit bit tests and jumps 2326 SDValue AndOp = DAG.getNode(ISD::AND, dl, 2327 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT)); 2328 Cmp = DAG.getSetCC( 2329 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT), 2330 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE); 2331 } 2332 2333 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 2334 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 2335 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 2336 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 2337 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 2338 // one as they are relative probabilities (and thus work more like weights), 2339 // and hence we need to normalize them to let the sum of them become one. 2340 SwitchBB->normalizeSuccProbs(); 2341 2342 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl, 2343 MVT::Other, getControlRoot(), 2344 Cmp, DAG.getBasicBlock(B.TargetBB)); 2345 2346 // Avoid emitting unnecessary branches to the next block. 2347 if (NextMBB != NextBlock(SwitchBB)) 2348 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd, 2349 DAG.getBasicBlock(NextMBB)); 2350 2351 DAG.setRoot(BrAnd); 2352 } 2353 2354 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 2355 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 2356 2357 // Retrieve successors. Look through artificial IR level blocks like 2358 // catchswitch for successors. 2359 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 2360 const BasicBlock *EHPadBB = I.getSuccessor(1); 2361 2362 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 2363 // have to do anything here to lower funclet bundles. 2364 assert(!I.hasOperandBundlesOtherThan( 2365 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 2366 "Cannot lower invokes with arbitrary operand bundles yet!"); 2367 2368 const Value *Callee(I.getCalledValue()); 2369 const Function *Fn = dyn_cast<Function>(Callee); 2370 if (isa<InlineAsm>(Callee)) 2371 visitInlineAsm(&I); 2372 else if (Fn && Fn->isIntrinsic()) { 2373 switch (Fn->getIntrinsicID()) { 2374 default: 2375 llvm_unreachable("Cannot invoke this intrinsic"); 2376 case Intrinsic::donothing: 2377 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 2378 break; 2379 case Intrinsic::experimental_patchpoint_void: 2380 case Intrinsic::experimental_patchpoint_i64: 2381 visitPatchpoint(&I, EHPadBB); 2382 break; 2383 case Intrinsic::experimental_gc_statepoint: 2384 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB); 2385 break; 2386 } 2387 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) { 2388 // Currently we do not lower any intrinsic calls with deopt operand bundles. 2389 // Eventually we will support lowering the @llvm.experimental.deoptimize 2390 // intrinsic, and right now there are no plans to support other intrinsics 2391 // with deopt state. 2392 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB); 2393 } else { 2394 LowerCallTo(&I, getValue(Callee), false, EHPadBB); 2395 } 2396 2397 // If the value of the invoke is used outside of its defining block, make it 2398 // available as a virtual register. 2399 // We already took care of the exported value for the statepoint instruction 2400 // during call to the LowerStatepoint. 2401 if (!isStatepoint(I)) { 2402 CopyToExportRegsIfNeeded(&I); 2403 } 2404 2405 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2406 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2407 BranchProbability EHPadBBProb = 2408 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2409 : BranchProbability::getZero(); 2410 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests); 2411 2412 // Update successor info. 2413 addSuccessorWithProb(InvokeMBB, Return); 2414 for (auto &UnwindDest : UnwindDests) { 2415 UnwindDest.first->setIsEHPad(); 2416 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2417 } 2418 InvokeMBB->normalizeSuccProbs(); 2419 2420 // Drop into normal successor. 2421 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2422 MVT::Other, getControlRoot(), 2423 DAG.getBasicBlock(Return))); 2424 } 2425 2426 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 2427 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 2428 } 2429 2430 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 2431 assert(FuncInfo.MBB->isEHPad() && 2432 "Call to landingpad not in landing pad!"); 2433 2434 MachineBasicBlock *MBB = FuncInfo.MBB; 2435 addLandingPadInfo(LP, *MBB); 2436 2437 // If there aren't registers to copy the values into (e.g., during SjLj 2438 // exceptions), then don't bother to create these DAG nodes. 2439 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2440 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn(); 2441 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2442 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2443 return; 2444 2445 // If landingpad's return type is token type, we don't create DAG nodes 2446 // for its exception pointer and selector value. The extraction of exception 2447 // pointer or selector value from token type landingpads is not currently 2448 // supported. 2449 if (LP.getType()->isTokenTy()) 2450 return; 2451 2452 SmallVector<EVT, 2> ValueVTs; 2453 SDLoc dl = getCurSDLoc(); 2454 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs); 2455 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 2456 2457 // Get the two live-in registers as SDValues. The physregs have already been 2458 // copied into virtual registers. 2459 SDValue Ops[2]; 2460 if (FuncInfo.ExceptionPointerVirtReg) { 2461 Ops[0] = DAG.getZExtOrTrunc( 2462 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2463 FuncInfo.ExceptionPointerVirtReg, 2464 TLI.getPointerTy(DAG.getDataLayout())), 2465 dl, ValueVTs[0]); 2466 } else { 2467 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())); 2468 } 2469 Ops[1] = DAG.getZExtOrTrunc( 2470 DAG.getCopyFromReg(DAG.getEntryNode(), dl, 2471 FuncInfo.ExceptionSelectorVirtReg, 2472 TLI.getPointerTy(DAG.getDataLayout())), 2473 dl, ValueVTs[1]); 2474 2475 // Merge into one. 2476 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, 2477 DAG.getVTList(ValueVTs), Ops); 2478 setValue(&LP, Res); 2479 } 2480 2481 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) { 2482 #ifndef NDEBUG 2483 for (const CaseCluster &CC : Clusters) 2484 assert(CC.Low == CC.High && "Input clusters must be single-case"); 2485 #endif 2486 2487 std::sort(Clusters.begin(), Clusters.end(), 2488 [](const CaseCluster &a, const CaseCluster &b) { 2489 return a.Low->getValue().slt(b.Low->getValue()); 2490 }); 2491 2492 // Merge adjacent clusters with the same destination. 2493 const unsigned N = Clusters.size(); 2494 unsigned DstIndex = 0; 2495 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 2496 CaseCluster &CC = Clusters[SrcIndex]; 2497 const ConstantInt *CaseVal = CC.Low; 2498 MachineBasicBlock *Succ = CC.MBB; 2499 2500 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 2501 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 2502 // If this case has the same successor and is a neighbour, merge it into 2503 // the previous cluster. 2504 Clusters[DstIndex - 1].High = CaseVal; 2505 Clusters[DstIndex - 1].Prob += CC.Prob; 2506 } else { 2507 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 2508 sizeof(Clusters[SrcIndex])); 2509 } 2510 } 2511 Clusters.resize(DstIndex); 2512 } 2513 2514 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2515 MachineBasicBlock *Last) { 2516 // Update JTCases. 2517 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2518 if (JTCases[i].first.HeaderBB == First) 2519 JTCases[i].first.HeaderBB = Last; 2520 2521 // Update BitTestCases. 2522 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2523 if (BitTestCases[i].Parent == First) 2524 BitTestCases[i].Parent = Last; 2525 } 2526 2527 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2528 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2529 2530 // Update machine-CFG edges with unique successors. 2531 SmallSet<BasicBlock*, 32> Done; 2532 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2533 BasicBlock *BB = I.getSuccessor(i); 2534 bool Inserted = Done.insert(BB).second; 2535 if (!Inserted) 2536 continue; 2537 2538 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2539 addSuccessorWithProb(IndirectBrMBB, Succ); 2540 } 2541 IndirectBrMBB->normalizeSuccProbs(); 2542 2543 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2544 MVT::Other, getControlRoot(), 2545 getValue(I.getAddress()))); 2546 } 2547 2548 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) { 2549 if (DAG.getTarget().Options.TrapUnreachable) 2550 DAG.setRoot( 2551 DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot())); 2552 } 2553 2554 void SelectionDAGBuilder::visitFSub(const User &I) { 2555 // -0.0 - X --> fneg 2556 Type *Ty = I.getType(); 2557 if (isa<Constant>(I.getOperand(0)) && 2558 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2559 SDValue Op2 = getValue(I.getOperand(1)); 2560 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2561 Op2.getValueType(), Op2)); 2562 return; 2563 } 2564 2565 visitBinary(I, ISD::FSUB); 2566 } 2567 2568 /// Checks if the given instruction performs a vector reduction, in which case 2569 /// we have the freedom to alter the elements in the result as long as the 2570 /// reduction of them stays unchanged. 2571 static bool isVectorReductionOp(const User *I) { 2572 const Instruction *Inst = dyn_cast<Instruction>(I); 2573 if (!Inst || !Inst->getType()->isVectorTy()) 2574 return false; 2575 2576 auto OpCode = Inst->getOpcode(); 2577 switch (OpCode) { 2578 case Instruction::Add: 2579 case Instruction::Mul: 2580 case Instruction::And: 2581 case Instruction::Or: 2582 case Instruction::Xor: 2583 break; 2584 case Instruction::FAdd: 2585 case Instruction::FMul: 2586 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2587 if (FPOp->getFastMathFlags().isFast()) 2588 break; 2589 LLVM_FALLTHROUGH; 2590 default: 2591 return false; 2592 } 2593 2594 unsigned ElemNum = Inst->getType()->getVectorNumElements(); 2595 unsigned ElemNumToReduce = ElemNum; 2596 2597 // Do DFS search on the def-use chain from the given instruction. We only 2598 // allow four kinds of operations during the search until we reach the 2599 // instruction that extracts the first element from the vector: 2600 // 2601 // 1. The reduction operation of the same opcode as the given instruction. 2602 // 2603 // 2. PHI node. 2604 // 2605 // 3. ShuffleVector instruction together with a reduction operation that 2606 // does a partial reduction. 2607 // 2608 // 4. ExtractElement that extracts the first element from the vector, and we 2609 // stop searching the def-use chain here. 2610 // 2611 // 3 & 4 above perform a reduction on all elements of the vector. We push defs 2612 // from 1-3 to the stack to continue the DFS. The given instruction is not 2613 // a reduction operation if we meet any other instructions other than those 2614 // listed above. 2615 2616 SmallVector<const User *, 16> UsersToVisit{Inst}; 2617 SmallPtrSet<const User *, 16> Visited; 2618 bool ReduxExtracted = false; 2619 2620 while (!UsersToVisit.empty()) { 2621 auto User = UsersToVisit.back(); 2622 UsersToVisit.pop_back(); 2623 if (!Visited.insert(User).second) 2624 continue; 2625 2626 for (const auto &U : User->users()) { 2627 auto Inst = dyn_cast<Instruction>(U); 2628 if (!Inst) 2629 return false; 2630 2631 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) { 2632 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst)) 2633 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast()) 2634 return false; 2635 UsersToVisit.push_back(U); 2636 } else if (const ShuffleVectorInst *ShufInst = 2637 dyn_cast<ShuffleVectorInst>(U)) { 2638 // Detect the following pattern: A ShuffleVector instruction together 2639 // with a reduction that do partial reduction on the first and second 2640 // ElemNumToReduce / 2 elements, and store the result in 2641 // ElemNumToReduce / 2 elements in another vector. 2642 2643 unsigned ResultElements = ShufInst->getType()->getVectorNumElements(); 2644 if (ResultElements < ElemNum) 2645 return false; 2646 2647 if (ElemNumToReduce == 1) 2648 return false; 2649 if (!isa<UndefValue>(U->getOperand(1))) 2650 return false; 2651 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i) 2652 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2)) 2653 return false; 2654 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i) 2655 if (ShufInst->getMaskValue(i) != -1) 2656 return false; 2657 2658 // There is only one user of this ShuffleVector instruction, which 2659 // must be a reduction operation. 2660 if (!U->hasOneUse()) 2661 return false; 2662 2663 auto U2 = dyn_cast<Instruction>(*U->user_begin()); 2664 if (!U2 || U2->getOpcode() != OpCode) 2665 return false; 2666 2667 // Check operands of the reduction operation. 2668 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) || 2669 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) { 2670 UsersToVisit.push_back(U2); 2671 ElemNumToReduce /= 2; 2672 } else 2673 return false; 2674 } else if (isa<ExtractElementInst>(U)) { 2675 // At this moment we should have reduced all elements in the vector. 2676 if (ElemNumToReduce != 1) 2677 return false; 2678 2679 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1)); 2680 if (!Val || Val->getZExtValue() != 0) 2681 return false; 2682 2683 ReduxExtracted = true; 2684 } else 2685 return false; 2686 } 2687 } 2688 return ReduxExtracted; 2689 } 2690 2691 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2692 SDValue Op1 = getValue(I.getOperand(0)); 2693 SDValue Op2 = getValue(I.getOperand(1)); 2694 2695 bool nuw = false; 2696 bool nsw = false; 2697 bool exact = false; 2698 bool vec_redux = false; 2699 FastMathFlags FMF; 2700 2701 if (const OverflowingBinaryOperator *OFBinOp = 2702 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2703 nuw = OFBinOp->hasNoUnsignedWrap(); 2704 nsw = OFBinOp->hasNoSignedWrap(); 2705 } 2706 if (const PossiblyExactOperator *ExactOp = 2707 dyn_cast<const PossiblyExactOperator>(&I)) 2708 exact = ExactOp->isExact(); 2709 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I)) 2710 FMF = FPOp->getFastMathFlags(); 2711 2712 if (isVectorReductionOp(&I)) { 2713 vec_redux = true; 2714 DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n"); 2715 } 2716 2717 SDNodeFlags Flags; 2718 Flags.setExact(exact); 2719 Flags.setNoSignedWrap(nsw); 2720 Flags.setNoUnsignedWrap(nuw); 2721 Flags.setVectorReduction(vec_redux); 2722 Flags.setAllowReciprocal(FMF.allowReciprocal()); 2723 Flags.setAllowContract(FMF.allowContract()); 2724 Flags.setNoInfs(FMF.noInfs()); 2725 Flags.setNoNaNs(FMF.noNaNs()); 2726 Flags.setNoSignedZeros(FMF.noSignedZeros()); 2727 Flags.setUnsafeAlgebra(FMF.isFast()); 2728 2729 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(), 2730 Op1, Op2, Flags); 2731 setValue(&I, BinNodeValue); 2732 } 2733 2734 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2735 SDValue Op1 = getValue(I.getOperand(0)); 2736 SDValue Op2 = getValue(I.getOperand(1)); 2737 2738 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy( 2739 Op2.getValueType(), DAG.getDataLayout()); 2740 2741 // Coerce the shift amount to the right type if we can. 2742 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2743 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2744 unsigned Op2Size = Op2.getValueSizeInBits(); 2745 SDLoc DL = getCurSDLoc(); 2746 2747 // If the operand is smaller than the shift count type, promote it. 2748 if (ShiftSize > Op2Size) 2749 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2750 2751 // If the operand is larger than the shift count type but the shift 2752 // count type has enough bits to represent any shift value, truncate 2753 // it now. This is a common case and it exposes the truncate to 2754 // optimization early. 2755 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits())) 2756 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2757 // Otherwise we'll need to temporarily settle for some other convenient 2758 // type. Type legalization will make adjustments once the shiftee is split. 2759 else 2760 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2761 } 2762 2763 bool nuw = false; 2764 bool nsw = false; 2765 bool exact = false; 2766 2767 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) { 2768 2769 if (const OverflowingBinaryOperator *OFBinOp = 2770 dyn_cast<const OverflowingBinaryOperator>(&I)) { 2771 nuw = OFBinOp->hasNoUnsignedWrap(); 2772 nsw = OFBinOp->hasNoSignedWrap(); 2773 } 2774 if (const PossiblyExactOperator *ExactOp = 2775 dyn_cast<const PossiblyExactOperator>(&I)) 2776 exact = ExactOp->isExact(); 2777 } 2778 SDNodeFlags Flags; 2779 Flags.setExact(exact); 2780 Flags.setNoSignedWrap(nsw); 2781 Flags.setNoUnsignedWrap(nuw); 2782 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2, 2783 Flags); 2784 setValue(&I, Res); 2785 } 2786 2787 void SelectionDAGBuilder::visitSDiv(const User &I) { 2788 SDValue Op1 = getValue(I.getOperand(0)); 2789 SDValue Op2 = getValue(I.getOperand(1)); 2790 2791 SDNodeFlags Flags; 2792 Flags.setExact(isa<PossiblyExactOperator>(&I) && 2793 cast<PossiblyExactOperator>(&I)->isExact()); 2794 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1, 2795 Op2, Flags)); 2796 } 2797 2798 void SelectionDAGBuilder::visitICmp(const User &I) { 2799 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2800 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2801 predicate = IC->getPredicate(); 2802 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2803 predicate = ICmpInst::Predicate(IC->getPredicate()); 2804 SDValue Op1 = getValue(I.getOperand(0)); 2805 SDValue Op2 = getValue(I.getOperand(1)); 2806 ISD::CondCode Opcode = getICmpCondCode(predicate); 2807 2808 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2809 I.getType()); 2810 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2811 } 2812 2813 void SelectionDAGBuilder::visitFCmp(const User &I) { 2814 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2815 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2816 predicate = FC->getPredicate(); 2817 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2818 predicate = FCmpInst::Predicate(FC->getPredicate()); 2819 SDValue Op1 = getValue(I.getOperand(0)); 2820 SDValue Op2 = getValue(I.getOperand(1)); 2821 ISD::CondCode Condition = getFCmpCondCode(predicate); 2822 2823 // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them. 2824 // FIXME: We should propagate the fast-math-flags to the DAG node itself for 2825 // further optimization, but currently FMF is only applicable to binary nodes. 2826 if (TM.Options.NoNaNsFPMath) 2827 Condition = getFCmpCodeWithoutNaN(Condition); 2828 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2829 I.getType()); 2830 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2831 } 2832 2833 // Check if the condition of the select has one use or two users that are both 2834 // selects with the same condition. 2835 static bool hasOnlySelectUsers(const Value *Cond) { 2836 return llvm::all_of(Cond->users(), [](const Value *V) { 2837 return isa<SelectInst>(V); 2838 }); 2839 } 2840 2841 void SelectionDAGBuilder::visitSelect(const User &I) { 2842 SmallVector<EVT, 4> ValueVTs; 2843 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(), 2844 ValueVTs); 2845 unsigned NumValues = ValueVTs.size(); 2846 if (NumValues == 0) return; 2847 2848 SmallVector<SDValue, 4> Values(NumValues); 2849 SDValue Cond = getValue(I.getOperand(0)); 2850 SDValue LHSVal = getValue(I.getOperand(1)); 2851 SDValue RHSVal = getValue(I.getOperand(2)); 2852 auto BaseOps = {Cond}; 2853 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2854 ISD::VSELECT : ISD::SELECT; 2855 2856 // Min/max matching is only viable if all output VTs are the same. 2857 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) { 2858 EVT VT = ValueVTs[0]; 2859 LLVMContext &Ctx = *DAG.getContext(); 2860 auto &TLI = DAG.getTargetLoweringInfo(); 2861 2862 // We care about the legality of the operation after it has been type 2863 // legalized. 2864 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal && 2865 VT != TLI.getTypeToTransformTo(Ctx, VT)) 2866 VT = TLI.getTypeToTransformTo(Ctx, VT); 2867 2868 // If the vselect is legal, assume we want to leave this as a vector setcc + 2869 // vselect. Otherwise, if this is going to be scalarized, we want to see if 2870 // min/max is legal on the scalar type. 2871 bool UseScalarMinMax = VT.isVector() && 2872 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT); 2873 2874 Value *LHS, *RHS; 2875 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS); 2876 ISD::NodeType Opc = ISD::DELETED_NODE; 2877 switch (SPR.Flavor) { 2878 case SPF_UMAX: Opc = ISD::UMAX; break; 2879 case SPF_UMIN: Opc = ISD::UMIN; break; 2880 case SPF_SMAX: Opc = ISD::SMAX; break; 2881 case SPF_SMIN: Opc = ISD::SMIN; break; 2882 case SPF_FMINNUM: 2883 switch (SPR.NaNBehavior) { 2884 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2885 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break; 2886 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break; 2887 case SPNB_RETURNS_ANY: { 2888 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT)) 2889 Opc = ISD::FMINNUM; 2890 else if (TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT)) 2891 Opc = ISD::FMINNAN; 2892 else if (UseScalarMinMax) 2893 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ? 2894 ISD::FMINNUM : ISD::FMINNAN; 2895 break; 2896 } 2897 } 2898 break; 2899 case SPF_FMAXNUM: 2900 switch (SPR.NaNBehavior) { 2901 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?"); 2902 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break; 2903 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break; 2904 case SPNB_RETURNS_ANY: 2905 2906 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT)) 2907 Opc = ISD::FMAXNUM; 2908 else if (TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT)) 2909 Opc = ISD::FMAXNAN; 2910 else if (UseScalarMinMax) 2911 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ? 2912 ISD::FMAXNUM : ISD::FMAXNAN; 2913 break; 2914 } 2915 break; 2916 default: break; 2917 } 2918 2919 if (Opc != ISD::DELETED_NODE && 2920 (TLI.isOperationLegalOrCustom(Opc, VT) || 2921 (UseScalarMinMax && 2922 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) && 2923 // If the underlying comparison instruction is used by any other 2924 // instruction, the consumed instructions won't be destroyed, so it is 2925 // not profitable to convert to a min/max. 2926 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) { 2927 OpCode = Opc; 2928 LHSVal = getValue(LHS); 2929 RHSVal = getValue(RHS); 2930 BaseOps = {}; 2931 } 2932 } 2933 2934 for (unsigned i = 0; i != NumValues; ++i) { 2935 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end()); 2936 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i)); 2937 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i)); 2938 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 2939 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i), 2940 Ops); 2941 } 2942 2943 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2944 DAG.getVTList(ValueVTs), Values)); 2945 } 2946 2947 void SelectionDAGBuilder::visitTrunc(const User &I) { 2948 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2949 SDValue N = getValue(I.getOperand(0)); 2950 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2951 I.getType()); 2952 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 2953 } 2954 2955 void SelectionDAGBuilder::visitZExt(const User &I) { 2956 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2957 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2958 SDValue N = getValue(I.getOperand(0)); 2959 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2960 I.getType()); 2961 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 2962 } 2963 2964 void SelectionDAGBuilder::visitSExt(const User &I) { 2965 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2966 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2967 SDValue N = getValue(I.getOperand(0)); 2968 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2969 I.getType()); 2970 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 2971 } 2972 2973 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2974 // FPTrunc is never a no-op cast, no need to check 2975 SDValue N = getValue(I.getOperand(0)); 2976 SDLoc dl = getCurSDLoc(); 2977 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2978 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 2979 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N, 2980 DAG.getTargetConstant( 2981 0, dl, TLI.getPointerTy(DAG.getDataLayout())))); 2982 } 2983 2984 void SelectionDAGBuilder::visitFPExt(const User &I) { 2985 // FPExt is never a no-op cast, no need to check 2986 SDValue N = getValue(I.getOperand(0)); 2987 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2988 I.getType()); 2989 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 2990 } 2991 2992 void SelectionDAGBuilder::visitFPToUI(const User &I) { 2993 // FPToUI is never a no-op cast, no need to check 2994 SDValue N = getValue(I.getOperand(0)); 2995 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 2996 I.getType()); 2997 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 2998 } 2999 3000 void SelectionDAGBuilder::visitFPToSI(const User &I) { 3001 // FPToSI is never a no-op cast, no need to check 3002 SDValue N = getValue(I.getOperand(0)); 3003 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3004 I.getType()); 3005 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 3006 } 3007 3008 void SelectionDAGBuilder::visitUIToFP(const User &I) { 3009 // UIToFP is never a no-op cast, no need to check 3010 SDValue N = getValue(I.getOperand(0)); 3011 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3012 I.getType()); 3013 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 3014 } 3015 3016 void SelectionDAGBuilder::visitSIToFP(const User &I) { 3017 // SIToFP is never a no-op cast, no need to check 3018 SDValue N = getValue(I.getOperand(0)); 3019 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3020 I.getType()); 3021 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 3022 } 3023 3024 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 3025 // What to do depends on the size of the integer and the size of the pointer. 3026 // We can either truncate, zero extend, or no-op, accordingly. 3027 SDValue N = getValue(I.getOperand(0)); 3028 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3029 I.getType()); 3030 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3031 } 3032 3033 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 3034 // What to do depends on the size of the integer and the size of the pointer. 3035 // We can either truncate, zero extend, or no-op, accordingly. 3036 SDValue N = getValue(I.getOperand(0)); 3037 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3038 I.getType()); 3039 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 3040 } 3041 3042 void SelectionDAGBuilder::visitBitCast(const User &I) { 3043 SDValue N = getValue(I.getOperand(0)); 3044 SDLoc dl = getCurSDLoc(); 3045 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 3046 I.getType()); 3047 3048 // BitCast assures us that source and destination are the same size so this is 3049 // either a BITCAST or a no-op. 3050 if (DestVT != N.getValueType()) 3051 setValue(&I, DAG.getNode(ISD::BITCAST, dl, 3052 DestVT, N)); // convert types. 3053 // Check if the original LLVM IR Operand was a ConstantInt, because getValue() 3054 // might fold any kind of constant expression to an integer constant and that 3055 // is not what we are looking for. Only recognize a bitcast of a genuine 3056 // constant integer as an opaque constant. 3057 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0))) 3058 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false, 3059 /*isOpaque*/true)); 3060 else 3061 setValue(&I, N); // noop cast. 3062 } 3063 3064 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) { 3065 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3066 const Value *SV = I.getOperand(0); 3067 SDValue N = getValue(SV); 3068 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3069 3070 unsigned SrcAS = SV->getType()->getPointerAddressSpace(); 3071 unsigned DestAS = I.getType()->getPointerAddressSpace(); 3072 3073 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) 3074 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS); 3075 3076 setValue(&I, N); 3077 } 3078 3079 void SelectionDAGBuilder::visitInsertElement(const User &I) { 3080 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3081 SDValue InVec = getValue(I.getOperand(0)); 3082 SDValue InVal = getValue(I.getOperand(1)); 3083 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(), 3084 TLI.getVectorIdxTy(DAG.getDataLayout())); 3085 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 3086 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3087 InVec, InVal, InIdx)); 3088 } 3089 3090 void SelectionDAGBuilder::visitExtractElement(const User &I) { 3091 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3092 SDValue InVec = getValue(I.getOperand(0)); 3093 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(), 3094 TLI.getVectorIdxTy(DAG.getDataLayout())); 3095 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3096 TLI.getValueType(DAG.getDataLayout(), I.getType()), 3097 InVec, InIdx)); 3098 } 3099 3100 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 3101 SDValue Src1 = getValue(I.getOperand(0)); 3102 SDValue Src2 = getValue(I.getOperand(1)); 3103 SDLoc DL = getCurSDLoc(); 3104 3105 SmallVector<int, 8> Mask; 3106 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 3107 unsigned MaskNumElts = Mask.size(); 3108 3109 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3110 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 3111 EVT SrcVT = Src1.getValueType(); 3112 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 3113 3114 if (SrcNumElts == MaskNumElts) { 3115 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask)); 3116 return; 3117 } 3118 3119 // Normalize the shuffle vector since mask and vector length don't match. 3120 if (SrcNumElts < MaskNumElts) { 3121 // Mask is longer than the source vectors. We can use concatenate vector to 3122 // make the mask and vectors lengths match. 3123 3124 if (MaskNumElts % SrcNumElts == 0) { 3125 // Mask length is a multiple of the source vector length. 3126 // Check if the shuffle is some kind of concatenation of the input 3127 // vectors. 3128 unsigned NumConcat = MaskNumElts / SrcNumElts; 3129 bool IsConcat = true; 3130 SmallVector<int, 8> ConcatSrcs(NumConcat, -1); 3131 for (unsigned i = 0; i != MaskNumElts; ++i) { 3132 int Idx = Mask[i]; 3133 if (Idx < 0) 3134 continue; 3135 // Ensure the indices in each SrcVT sized piece are sequential and that 3136 // the same source is used for the whole piece. 3137 if ((Idx % SrcNumElts != (i % SrcNumElts)) || 3138 (ConcatSrcs[i / SrcNumElts] >= 0 && 3139 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) { 3140 IsConcat = false; 3141 break; 3142 } 3143 // Remember which source this index came from. 3144 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts; 3145 } 3146 3147 // The shuffle is concatenating multiple vectors together. Just emit 3148 // a CONCAT_VECTORS operation. 3149 if (IsConcat) { 3150 SmallVector<SDValue, 8> ConcatOps; 3151 for (auto Src : ConcatSrcs) { 3152 if (Src < 0) 3153 ConcatOps.push_back(DAG.getUNDEF(SrcVT)); 3154 else if (Src == 0) 3155 ConcatOps.push_back(Src1); 3156 else 3157 ConcatOps.push_back(Src2); 3158 } 3159 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps)); 3160 return; 3161 } 3162 } 3163 3164 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts); 3165 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts; 3166 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 3167 PaddedMaskNumElts); 3168 3169 // Pad both vectors with undefs to make them the same length as the mask. 3170 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3171 3172 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3173 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3174 MOps1[0] = Src1; 3175 MOps2[0] = Src2; 3176 3177 Src1 = Src1.isUndef() 3178 ? DAG.getUNDEF(PaddedVT) 3179 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1); 3180 Src2 = Src2.isUndef() 3181 ? DAG.getUNDEF(PaddedVT) 3182 : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2); 3183 3184 // Readjust mask for new input vector length. 3185 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1); 3186 for (unsigned i = 0; i != MaskNumElts; ++i) { 3187 int Idx = Mask[i]; 3188 if (Idx >= (int)SrcNumElts) 3189 Idx -= SrcNumElts - PaddedMaskNumElts; 3190 MappedOps[i] = Idx; 3191 } 3192 3193 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps); 3194 3195 // If the concatenated vector was padded, extract a subvector with the 3196 // correct number of elements. 3197 if (MaskNumElts != PaddedMaskNumElts) 3198 Result = DAG.getNode( 3199 ISD::EXTRACT_SUBVECTOR, DL, VT, Result, 3200 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))); 3201 3202 setValue(&I, Result); 3203 return; 3204 } 3205 3206 if (SrcNumElts > MaskNumElts) { 3207 // Analyze the access pattern of the vector to see if we can extract 3208 // two subvectors and do the shuffle. 3209 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from 3210 bool CanExtract = true; 3211 for (int Idx : Mask) { 3212 unsigned Input = 0; 3213 if (Idx < 0) 3214 continue; 3215 3216 if (Idx >= (int)SrcNumElts) { 3217 Input = 1; 3218 Idx -= SrcNumElts; 3219 } 3220 3221 // If all the indices come from the same MaskNumElts sized portion of 3222 // the sources we can use extract. Also make sure the extract wouldn't 3223 // extract past the end of the source. 3224 int NewStartIdx = alignDown(Idx, MaskNumElts); 3225 if (NewStartIdx + MaskNumElts > SrcNumElts || 3226 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx)) 3227 CanExtract = false; 3228 // Make sure we always update StartIdx as we use it to track if all 3229 // elements are undef. 3230 StartIdx[Input] = NewStartIdx; 3231 } 3232 3233 if (StartIdx[0] < 0 && StartIdx[1] < 0) { 3234 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3235 return; 3236 } 3237 if (CanExtract) { 3238 // Extract appropriate subvector and generate a vector shuffle 3239 for (unsigned Input = 0; Input < 2; ++Input) { 3240 SDValue &Src = Input == 0 ? Src1 : Src2; 3241 if (StartIdx[Input] < 0) 3242 Src = DAG.getUNDEF(VT); 3243 else { 3244 Src = DAG.getNode( 3245 ISD::EXTRACT_SUBVECTOR, DL, VT, Src, 3246 DAG.getConstant(StartIdx[Input], DL, 3247 TLI.getVectorIdxTy(DAG.getDataLayout()))); 3248 } 3249 } 3250 3251 // Calculate new mask. 3252 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end()); 3253 for (int &Idx : MappedOps) { 3254 if (Idx >= (int)SrcNumElts) 3255 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3256 else if (Idx >= 0) 3257 Idx -= StartIdx[0]; 3258 } 3259 3260 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps)); 3261 return; 3262 } 3263 } 3264 3265 // We can't use either concat vectors or extract subvectors so fall back to 3266 // replacing the shuffle with extract and build vector. 3267 // to insert and build vector. 3268 EVT EltVT = VT.getVectorElementType(); 3269 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 3270 SmallVector<SDValue,8> Ops; 3271 for (int Idx : Mask) { 3272 SDValue Res; 3273 3274 if (Idx < 0) { 3275 Res = DAG.getUNDEF(EltVT); 3276 } else { 3277 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3278 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3279 3280 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 3281 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT)); 3282 } 3283 3284 Ops.push_back(Res); 3285 } 3286 3287 setValue(&I, DAG.getBuildVector(VT, DL, Ops)); 3288 } 3289 3290 void SelectionDAGBuilder::visitInsertValue(const User &I) { 3291 ArrayRef<unsigned> Indices; 3292 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I)) 3293 Indices = IV->getIndices(); 3294 else 3295 Indices = cast<ConstantExpr>(&I)->getIndices(); 3296 3297 const Value *Op0 = I.getOperand(0); 3298 const Value *Op1 = I.getOperand(1); 3299 Type *AggTy = I.getType(); 3300 Type *ValTy = Op1->getType(); 3301 bool IntoUndef = isa<UndefValue>(Op0); 3302 bool FromUndef = isa<UndefValue>(Op1); 3303 3304 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3305 3306 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3307 SmallVector<EVT, 4> AggValueVTs; 3308 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs); 3309 SmallVector<EVT, 4> ValValueVTs; 3310 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3311 3312 unsigned NumAggValues = AggValueVTs.size(); 3313 unsigned NumValValues = ValValueVTs.size(); 3314 SmallVector<SDValue, 4> Values(NumAggValues); 3315 3316 // Ignore an insertvalue that produces an empty object 3317 if (!NumAggValues) { 3318 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3319 return; 3320 } 3321 3322 SDValue Agg = getValue(Op0); 3323 unsigned i = 0; 3324 // Copy the beginning value(s) from the original aggregate. 3325 for (; i != LinearIndex; ++i) 3326 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3327 SDValue(Agg.getNode(), Agg.getResNo() + i); 3328 // Copy values from the inserted value(s). 3329 if (NumValValues) { 3330 SDValue Val = getValue(Op1); 3331 for (; i != LinearIndex + NumValValues; ++i) 3332 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3333 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3334 } 3335 // Copy remaining value(s) from the original aggregate. 3336 for (; i != NumAggValues; ++i) 3337 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3338 SDValue(Agg.getNode(), Agg.getResNo() + i); 3339 3340 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3341 DAG.getVTList(AggValueVTs), Values)); 3342 } 3343 3344 void SelectionDAGBuilder::visitExtractValue(const User &I) { 3345 ArrayRef<unsigned> Indices; 3346 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I)) 3347 Indices = EV->getIndices(); 3348 else 3349 Indices = cast<ConstantExpr>(&I)->getIndices(); 3350 3351 const Value *Op0 = I.getOperand(0); 3352 Type *AggTy = Op0->getType(); 3353 Type *ValTy = I.getType(); 3354 bool OutOfUndef = isa<UndefValue>(Op0); 3355 3356 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices); 3357 3358 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3359 SmallVector<EVT, 4> ValValueVTs; 3360 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs); 3361 3362 unsigned NumValValues = ValValueVTs.size(); 3363 3364 // Ignore a extractvalue that produces an empty object 3365 if (!NumValValues) { 3366 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3367 return; 3368 } 3369 3370 SmallVector<SDValue, 4> Values(NumValValues); 3371 3372 SDValue Agg = getValue(Op0); 3373 // Copy out the selected value(s). 3374 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3375 Values[i - LinearIndex] = 3376 OutOfUndef ? 3377 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3378 SDValue(Agg.getNode(), Agg.getResNo() + i); 3379 3380 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3381 DAG.getVTList(ValValueVTs), Values)); 3382 } 3383 3384 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3385 Value *Op0 = I.getOperand(0); 3386 // Note that the pointer operand may be a vector of pointers. Take the scalar 3387 // element which holds a pointer. 3388 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace(); 3389 SDValue N = getValue(Op0); 3390 SDLoc dl = getCurSDLoc(); 3391 3392 // Normalize Vector GEP - all scalar operands should be converted to the 3393 // splat vector. 3394 unsigned VectorWidth = I.getType()->isVectorTy() ? 3395 cast<VectorType>(I.getType())->getVectorNumElements() : 0; 3396 3397 if (VectorWidth && !N.getValueType().isVector()) { 3398 LLVMContext &Context = *DAG.getContext(); 3399 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth); 3400 N = DAG.getSplatBuildVector(VT, dl, N); 3401 } 3402 3403 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I); 3404 GTI != E; ++GTI) { 3405 const Value *Idx = GTI.getOperand(); 3406 if (StructType *StTy = GTI.getStructTypeOrNull()) { 3407 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3408 if (Field) { 3409 // N = N + Offset 3410 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field); 3411 3412 // In an inbounds GEP with an offset that is nonnegative even when 3413 // interpreted as signed, assume there is no unsigned overflow. 3414 SDNodeFlags Flags; 3415 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds()) 3416 Flags.setNoUnsignedWrap(true); 3417 3418 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, 3419 DAG.getConstant(Offset, dl, N.getValueType()), Flags); 3420 } 3421 } else { 3422 MVT PtrTy = 3423 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS); 3424 unsigned PtrSize = PtrTy.getSizeInBits(); 3425 APInt ElementSize(PtrSize, DL->getTypeAllocSize(GTI.getIndexedType())); 3426 3427 // If this is a scalar constant or a splat vector of constants, 3428 // handle it quickly. 3429 const auto *CI = dyn_cast<ConstantInt>(Idx); 3430 if (!CI && isa<ConstantDataVector>(Idx) && 3431 cast<ConstantDataVector>(Idx)->getSplatValue()) 3432 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue()); 3433 3434 if (CI) { 3435 if (CI->isZero()) 3436 continue; 3437 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize); 3438 LLVMContext &Context = *DAG.getContext(); 3439 SDValue OffsVal = VectorWidth ? 3440 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, PtrTy, VectorWidth)) : 3441 DAG.getConstant(Offs, dl, PtrTy); 3442 3443 // In an inbouds GEP with an offset that is nonnegative even when 3444 // interpreted as signed, assume there is no unsigned overflow. 3445 SDNodeFlags Flags; 3446 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds()) 3447 Flags.setNoUnsignedWrap(true); 3448 3449 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags); 3450 continue; 3451 } 3452 3453 // N = N + Idx * ElementSize; 3454 SDValue IdxN = getValue(Idx); 3455 3456 if (!IdxN.getValueType().isVector() && VectorWidth) { 3457 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth); 3458 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN); 3459 } 3460 3461 // If the index is smaller or larger than intptr_t, truncate or extend 3462 // it. 3463 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType()); 3464 3465 // If this is a multiply by a power of two, turn it into a shl 3466 // immediately. This is a very common case. 3467 if (ElementSize != 1) { 3468 if (ElementSize.isPowerOf2()) { 3469 unsigned Amt = ElementSize.logBase2(); 3470 IdxN = DAG.getNode(ISD::SHL, dl, 3471 N.getValueType(), IdxN, 3472 DAG.getConstant(Amt, dl, IdxN.getValueType())); 3473 } else { 3474 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType()); 3475 IdxN = DAG.getNode(ISD::MUL, dl, 3476 N.getValueType(), IdxN, Scale); 3477 } 3478 } 3479 3480 N = DAG.getNode(ISD::ADD, dl, 3481 N.getValueType(), N, IdxN); 3482 } 3483 } 3484 3485 setValue(&I, N); 3486 } 3487 3488 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3489 // If this is a fixed sized alloca in the entry block of the function, 3490 // allocate it statically on the stack. 3491 if (FuncInfo.StaticAllocaMap.count(&I)) 3492 return; // getValue will auto-populate this. 3493 3494 SDLoc dl = getCurSDLoc(); 3495 Type *Ty = I.getAllocatedType(); 3496 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3497 auto &DL = DAG.getDataLayout(); 3498 uint64_t TySize = DL.getTypeAllocSize(Ty); 3499 unsigned Align = 3500 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment()); 3501 3502 SDValue AllocSize = getValue(I.getArraySize()); 3503 3504 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace()); 3505 if (AllocSize.getValueType() != IntPtr) 3506 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr); 3507 3508 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, 3509 AllocSize, 3510 DAG.getConstant(TySize, dl, IntPtr)); 3511 3512 // Handle alignment. If the requested alignment is less than or equal to 3513 // the stack alignment, ignore it. If the size is greater than or equal to 3514 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3515 unsigned StackAlign = 3516 DAG.getSubtarget().getFrameLowering()->getStackAlignment(); 3517 if (Align <= StackAlign) 3518 Align = 0; 3519 3520 // Round the size of the allocation up to the stack alignment size 3521 // by add SA-1 to the size. This doesn't overflow because we're computing 3522 // an address inside an alloca. 3523 SDNodeFlags Flags; 3524 Flags.setNoUnsignedWrap(true); 3525 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize, 3526 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags); 3527 3528 // Mask out the low bits for alignment purposes. 3529 AllocSize = 3530 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize, 3531 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr)); 3532 3533 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)}; 3534 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3535 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops); 3536 setValue(&I, DSA); 3537 DAG.setRoot(DSA.getValue(1)); 3538 3539 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects()); 3540 } 3541 3542 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3543 if (I.isAtomic()) 3544 return visitAtomicLoad(I); 3545 3546 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3547 const Value *SV = I.getOperand(0); 3548 if (TLI.supportSwiftError()) { 3549 // Swifterror values can come from either a function parameter with 3550 // swifterror attribute or an alloca with swifterror attribute. 3551 if (const Argument *Arg = dyn_cast<Argument>(SV)) { 3552 if (Arg->hasSwiftErrorAttr()) 3553 return visitLoadFromSwiftError(I); 3554 } 3555 3556 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) { 3557 if (Alloca->isSwiftError()) 3558 return visitLoadFromSwiftError(I); 3559 } 3560 } 3561 3562 SDValue Ptr = getValue(SV); 3563 3564 Type *Ty = I.getType(); 3565 3566 bool isVolatile = I.isVolatile(); 3567 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr; 3568 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr; 3569 bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout()); 3570 unsigned Alignment = I.getAlignment(); 3571 3572 AAMDNodes AAInfo; 3573 I.getAAMetadata(AAInfo); 3574 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3575 3576 SmallVector<EVT, 4> ValueVTs; 3577 SmallVector<uint64_t, 4> Offsets; 3578 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets); 3579 unsigned NumValues = ValueVTs.size(); 3580 if (NumValues == 0) 3581 return; 3582 3583 SDValue Root; 3584 bool ConstantMemory = false; 3585 if (isVolatile || NumValues > MaxParallelChains) 3586 // Serialize volatile loads with other side effects. 3587 Root = getRoot(); 3588 else if (AA && AA->pointsToConstantMemory(MemoryLocation( 3589 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) { 3590 // Do not serialize (non-volatile) loads of constant memory with anything. 3591 Root = DAG.getEntryNode(); 3592 ConstantMemory = true; 3593 } else { 3594 // Do not serialize non-volatile loads against each other. 3595 Root = DAG.getRoot(); 3596 } 3597 3598 SDLoc dl = getCurSDLoc(); 3599 3600 if (isVolatile) 3601 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG); 3602 3603 // An aggregate load cannot wrap around the address space, so offsets to its 3604 // parts don't wrap either. 3605 SDNodeFlags Flags; 3606 Flags.setNoUnsignedWrap(true); 3607 3608 SmallVector<SDValue, 4> Values(NumValues); 3609 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3610 EVT PtrVT = Ptr.getValueType(); 3611 unsigned ChainI = 0; 3612 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3613 // Serializing loads here may result in excessive register pressure, and 3614 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3615 // could recover a bit by hoisting nodes upward in the chain by recognizing 3616 // they are side-effect free or do not alias. The optimizer should really 3617 // avoid this case by converting large object/array copies to llvm.memcpy 3618 // (MaxParallelChains should always remain as failsafe). 3619 if (ChainI == MaxParallelChains) { 3620 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3621 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3622 makeArrayRef(Chains.data(), ChainI)); 3623 Root = Chain; 3624 ChainI = 0; 3625 } 3626 SDValue A = DAG.getNode(ISD::ADD, dl, 3627 PtrVT, Ptr, 3628 DAG.getConstant(Offsets[i], dl, PtrVT), 3629 Flags); 3630 auto MMOFlags = MachineMemOperand::MONone; 3631 if (isVolatile) 3632 MMOFlags |= MachineMemOperand::MOVolatile; 3633 if (isNonTemporal) 3634 MMOFlags |= MachineMemOperand::MONonTemporal; 3635 if (isInvariant) 3636 MMOFlags |= MachineMemOperand::MOInvariant; 3637 if (isDereferenceable) 3638 MMOFlags |= MachineMemOperand::MODereferenceable; 3639 MMOFlags |= TLI.getMMOFlags(I); 3640 3641 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A, 3642 MachinePointerInfo(SV, Offsets[i]), Alignment, 3643 MMOFlags, AAInfo, Ranges); 3644 3645 Values[i] = L; 3646 Chains[ChainI] = L.getValue(1); 3647 } 3648 3649 if (!ConstantMemory) { 3650 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3651 makeArrayRef(Chains.data(), ChainI)); 3652 if (isVolatile) 3653 DAG.setRoot(Chain); 3654 else 3655 PendingLoads.push_back(Chain); 3656 } 3657 3658 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl, 3659 DAG.getVTList(ValueVTs), Values)); 3660 } 3661 3662 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) { 3663 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3664 "call visitStoreToSwiftError when backend supports swifterror"); 3665 3666 SmallVector<EVT, 4> ValueVTs; 3667 SmallVector<uint64_t, 4> Offsets; 3668 const Value *SrcV = I.getOperand(0); 3669 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3670 SrcV->getType(), ValueVTs, &Offsets); 3671 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3672 "expect a single EVT for swifterror"); 3673 3674 SDValue Src = getValue(SrcV); 3675 // Create a virtual register, then update the virtual register. 3676 unsigned VReg; bool CreatedVReg; 3677 std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I); 3678 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue 3679 // Chain can be getRoot or getControlRoot. 3680 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg, 3681 SDValue(Src.getNode(), Src.getResNo())); 3682 DAG.setRoot(CopyNode); 3683 if (CreatedVReg) 3684 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg); 3685 } 3686 3687 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) { 3688 assert(DAG.getTargetLoweringInfo().supportSwiftError() && 3689 "call visitLoadFromSwiftError when backend supports swifterror"); 3690 3691 assert(!I.isVolatile() && 3692 I.getMetadata(LLVMContext::MD_nontemporal) == nullptr && 3693 I.getMetadata(LLVMContext::MD_invariant_load) == nullptr && 3694 "Support volatile, non temporal, invariant for load_from_swift_error"); 3695 3696 const Value *SV = I.getOperand(0); 3697 Type *Ty = I.getType(); 3698 AAMDNodes AAInfo; 3699 I.getAAMetadata(AAInfo); 3700 assert((!AA || !AA->pointsToConstantMemory(MemoryLocation( 3701 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) && 3702 "load_from_swift_error should not be constant memory"); 3703 3704 SmallVector<EVT, 4> ValueVTs; 3705 SmallVector<uint64_t, 4> Offsets; 3706 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty, 3707 ValueVTs, &Offsets); 3708 assert(ValueVTs.size() == 1 && Offsets[0] == 0 && 3709 "expect a single EVT for swifterror"); 3710 3711 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT 3712 SDValue L = DAG.getCopyFromReg( 3713 getRoot(), getCurSDLoc(), 3714 FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first, 3715 ValueVTs[0]); 3716 3717 setValue(&I, L); 3718 } 3719 3720 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3721 if (I.isAtomic()) 3722 return visitAtomicStore(I); 3723 3724 const Value *SrcV = I.getOperand(0); 3725 const Value *PtrV = I.getOperand(1); 3726 3727 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3728 if (TLI.supportSwiftError()) { 3729 // Swifterror values can come from either a function parameter with 3730 // swifterror attribute or an alloca with swifterror attribute. 3731 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) { 3732 if (Arg->hasSwiftErrorAttr()) 3733 return visitStoreToSwiftError(I); 3734 } 3735 3736 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) { 3737 if (Alloca->isSwiftError()) 3738 return visitStoreToSwiftError(I); 3739 } 3740 } 3741 3742 SmallVector<EVT, 4> ValueVTs; 3743 SmallVector<uint64_t, 4> Offsets; 3744 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), 3745 SrcV->getType(), ValueVTs, &Offsets); 3746 unsigned NumValues = ValueVTs.size(); 3747 if (NumValues == 0) 3748 return; 3749 3750 // Get the lowered operands. Note that we do this after 3751 // checking if NumResults is zero, because with zero results 3752 // the operands won't have values in the map. 3753 SDValue Src = getValue(SrcV); 3754 SDValue Ptr = getValue(PtrV); 3755 3756 SDValue Root = getRoot(); 3757 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues)); 3758 SDLoc dl = getCurSDLoc(); 3759 EVT PtrVT = Ptr.getValueType(); 3760 unsigned Alignment = I.getAlignment(); 3761 AAMDNodes AAInfo; 3762 I.getAAMetadata(AAInfo); 3763 3764 auto MMOFlags = MachineMemOperand::MONone; 3765 if (I.isVolatile()) 3766 MMOFlags |= MachineMemOperand::MOVolatile; 3767 if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr) 3768 MMOFlags |= MachineMemOperand::MONonTemporal; 3769 MMOFlags |= TLI.getMMOFlags(I); 3770 3771 // An aggregate load cannot wrap around the address space, so offsets to its 3772 // parts don't wrap either. 3773 SDNodeFlags Flags; 3774 Flags.setNoUnsignedWrap(true); 3775 3776 unsigned ChainI = 0; 3777 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3778 // See visitLoad comments. 3779 if (ChainI == MaxParallelChains) { 3780 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3781 makeArrayRef(Chains.data(), ChainI)); 3782 Root = Chain; 3783 ChainI = 0; 3784 } 3785 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3786 DAG.getConstant(Offsets[i], dl, PtrVT), Flags); 3787 SDValue St = DAG.getStore( 3788 Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add, 3789 MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo); 3790 Chains[ChainI] = St; 3791 } 3792 3793 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3794 makeArrayRef(Chains.data(), ChainI)); 3795 DAG.setRoot(StoreNode); 3796 } 3797 3798 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I, 3799 bool IsCompressing) { 3800 SDLoc sdl = getCurSDLoc(); 3801 3802 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3803 unsigned& Alignment) { 3804 // llvm.masked.store.*(Src0, Ptr, alignment, Mask) 3805 Src0 = I.getArgOperand(0); 3806 Ptr = I.getArgOperand(1); 3807 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); 3808 Mask = I.getArgOperand(3); 3809 }; 3810 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3811 unsigned& Alignment) { 3812 // llvm.masked.compressstore.*(Src0, Ptr, Mask) 3813 Src0 = I.getArgOperand(0); 3814 Ptr = I.getArgOperand(1); 3815 Mask = I.getArgOperand(2); 3816 Alignment = 0; 3817 }; 3818 3819 Value *PtrOperand, *MaskOperand, *Src0Operand; 3820 unsigned Alignment; 3821 if (IsCompressing) 3822 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3823 else 3824 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3825 3826 SDValue Ptr = getValue(PtrOperand); 3827 SDValue Src0 = getValue(Src0Operand); 3828 SDValue Mask = getValue(MaskOperand); 3829 3830 EVT VT = Src0.getValueType(); 3831 if (!Alignment) 3832 Alignment = DAG.getEVTAlignment(VT); 3833 3834 AAMDNodes AAInfo; 3835 I.getAAMetadata(AAInfo); 3836 3837 MachineMemOperand *MMO = 3838 DAG.getMachineFunction(). 3839 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3840 MachineMemOperand::MOStore, VT.getStoreSize(), 3841 Alignment, AAInfo); 3842 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT, 3843 MMO, false /* Truncating */, 3844 IsCompressing); 3845 DAG.setRoot(StoreNode); 3846 setValue(&I, StoreNode); 3847 } 3848 3849 // Get a uniform base for the Gather/Scatter intrinsic. 3850 // The first argument of the Gather/Scatter intrinsic is a vector of pointers. 3851 // We try to represent it as a base pointer + vector of indices. 3852 // Usually, the vector of pointers comes from a 'getelementptr' instruction. 3853 // The first operand of the GEP may be a single pointer or a vector of pointers 3854 // Example: 3855 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind 3856 // or 3857 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind 3858 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, .. 3859 // 3860 // When the first GEP operand is a single pointer - it is the uniform base we 3861 // are looking for. If first operand of the GEP is a splat vector - we 3862 // extract the splat value and use it as a uniform base. 3863 // In all other cases the function returns 'false'. 3864 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index, 3865 SelectionDAGBuilder* SDB) { 3866 SelectionDAG& DAG = SDB->DAG; 3867 LLVMContext &Context = *DAG.getContext(); 3868 3869 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type"); 3870 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3871 if (!GEP) 3872 return false; 3873 3874 const Value *GEPPtr = GEP->getPointerOperand(); 3875 if (!GEPPtr->getType()->isVectorTy()) 3876 Ptr = GEPPtr; 3877 else if (!(Ptr = getSplatValue(GEPPtr))) 3878 return false; 3879 3880 unsigned FinalIndex = GEP->getNumOperands() - 1; 3881 Value *IndexVal = GEP->getOperand(FinalIndex); 3882 3883 // Ensure all the other indices are 0. 3884 for (unsigned i = 1; i < FinalIndex; ++i) { 3885 auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i)); 3886 if (!C || !C->isZero()) 3887 return false; 3888 } 3889 3890 // The operands of the GEP may be defined in another basic block. 3891 // In this case we'll not find nodes for the operands. 3892 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal)) 3893 return false; 3894 3895 Base = SDB->getValue(Ptr); 3896 Index = SDB->getValue(IndexVal); 3897 3898 if (!Index.getValueType().isVector()) { 3899 unsigned GEPWidth = GEP->getType()->getVectorNumElements(); 3900 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth); 3901 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index); 3902 } 3903 return true; 3904 } 3905 3906 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) { 3907 SDLoc sdl = getCurSDLoc(); 3908 3909 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask) 3910 const Value *Ptr = I.getArgOperand(1); 3911 SDValue Src0 = getValue(I.getArgOperand(0)); 3912 SDValue Mask = getValue(I.getArgOperand(3)); 3913 EVT VT = Src0.getValueType(); 3914 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue(); 3915 if (!Alignment) 3916 Alignment = DAG.getEVTAlignment(VT); 3917 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3918 3919 AAMDNodes AAInfo; 3920 I.getAAMetadata(AAInfo); 3921 3922 SDValue Base; 3923 SDValue Index; 3924 const Value *BasePtr = Ptr; 3925 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 3926 3927 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr; 3928 MachineMemOperand *MMO = DAG.getMachineFunction(). 3929 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr), 3930 MachineMemOperand::MOStore, VT.getStoreSize(), 3931 Alignment, AAInfo); 3932 if (!UniformBase) { 3933 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 3934 Index = getValue(Ptr); 3935 } 3936 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index }; 3937 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl, 3938 Ops, MMO); 3939 DAG.setRoot(Scatter); 3940 setValue(&I, Scatter); 3941 } 3942 3943 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) { 3944 SDLoc sdl = getCurSDLoc(); 3945 3946 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3947 unsigned& Alignment) { 3948 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0) 3949 Ptr = I.getArgOperand(0); 3950 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 3951 Mask = I.getArgOperand(2); 3952 Src0 = I.getArgOperand(3); 3953 }; 3954 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0, 3955 unsigned& Alignment) { 3956 // @llvm.masked.expandload.*(Ptr, Mask, Src0) 3957 Ptr = I.getArgOperand(0); 3958 Alignment = 0; 3959 Mask = I.getArgOperand(1); 3960 Src0 = I.getArgOperand(2); 3961 }; 3962 3963 Value *PtrOperand, *MaskOperand, *Src0Operand; 3964 unsigned Alignment; 3965 if (IsExpanding) 3966 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3967 else 3968 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment); 3969 3970 SDValue Ptr = getValue(PtrOperand); 3971 SDValue Src0 = getValue(Src0Operand); 3972 SDValue Mask = getValue(MaskOperand); 3973 3974 EVT VT = Src0.getValueType(); 3975 if (!Alignment) 3976 Alignment = DAG.getEVTAlignment(VT); 3977 3978 AAMDNodes AAInfo; 3979 I.getAAMetadata(AAInfo); 3980 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3981 3982 // Do not serialize masked loads of constant memory with anything. 3983 bool AddToChain = !AA || !AA->pointsToConstantMemory(MemoryLocation( 3984 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()), AAInfo)); 3985 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode(); 3986 3987 MachineMemOperand *MMO = 3988 DAG.getMachineFunction(). 3989 getMachineMemOperand(MachinePointerInfo(PtrOperand), 3990 MachineMemOperand::MOLoad, VT.getStoreSize(), 3991 Alignment, AAInfo, Ranges); 3992 3993 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO, 3994 ISD::NON_EXTLOAD, IsExpanding); 3995 if (AddToChain) { 3996 SDValue OutChain = Load.getValue(1); 3997 DAG.setRoot(OutChain); 3998 } 3999 setValue(&I, Load); 4000 } 4001 4002 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) { 4003 SDLoc sdl = getCurSDLoc(); 4004 4005 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0) 4006 const Value *Ptr = I.getArgOperand(0); 4007 SDValue Src0 = getValue(I.getArgOperand(3)); 4008 SDValue Mask = getValue(I.getArgOperand(2)); 4009 4010 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4011 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4012 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue(); 4013 if (!Alignment) 4014 Alignment = DAG.getEVTAlignment(VT); 4015 4016 AAMDNodes AAInfo; 4017 I.getAAMetadata(AAInfo); 4018 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 4019 4020 SDValue Root = DAG.getRoot(); 4021 SDValue Base; 4022 SDValue Index; 4023 const Value *BasePtr = Ptr; 4024 bool UniformBase = getUniformBase(BasePtr, Base, Index, this); 4025 bool ConstantMemory = false; 4026 if (UniformBase && 4027 AA && AA->pointsToConstantMemory(MemoryLocation( 4028 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()), 4029 AAInfo))) { 4030 // Do not serialize (non-volatile) loads of constant memory with anything. 4031 Root = DAG.getEntryNode(); 4032 ConstantMemory = true; 4033 } 4034 4035 MachineMemOperand *MMO = 4036 DAG.getMachineFunction(). 4037 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr), 4038 MachineMemOperand::MOLoad, VT.getStoreSize(), 4039 Alignment, AAInfo, Ranges); 4040 4041 if (!UniformBase) { 4042 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())); 4043 Index = getValue(Ptr); 4044 } 4045 SDValue Ops[] = { Root, Src0, Mask, Base, Index }; 4046 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl, 4047 Ops, MMO); 4048 4049 SDValue OutChain = Gather.getValue(1); 4050 if (!ConstantMemory) 4051 PendingLoads.push_back(OutChain); 4052 setValue(&I, Gather); 4053 } 4054 4055 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 4056 SDLoc dl = getCurSDLoc(); 4057 AtomicOrdering SuccessOrder = I.getSuccessOrdering(); 4058 AtomicOrdering FailureOrder = I.getFailureOrdering(); 4059 SyncScope::ID SSID = I.getSyncScopeID(); 4060 4061 SDValue InChain = getRoot(); 4062 4063 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType(); 4064 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other); 4065 SDValue L = DAG.getAtomicCmpSwap( 4066 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain, 4067 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()), 4068 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()), 4069 /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID); 4070 4071 SDValue OutChain = L.getValue(2); 4072 4073 setValue(&I, L); 4074 DAG.setRoot(OutChain); 4075 } 4076 4077 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 4078 SDLoc dl = getCurSDLoc(); 4079 ISD::NodeType NT; 4080 switch (I.getOperation()) { 4081 default: llvm_unreachable("Unknown atomicrmw operation"); 4082 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 4083 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 4084 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 4085 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 4086 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 4087 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 4088 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 4089 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 4090 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 4091 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 4092 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 4093 } 4094 AtomicOrdering Order = I.getOrdering(); 4095 SyncScope::ID SSID = I.getSyncScopeID(); 4096 4097 SDValue InChain = getRoot(); 4098 4099 SDValue L = 4100 DAG.getAtomic(NT, dl, 4101 getValue(I.getValOperand()).getSimpleValueType(), 4102 InChain, 4103 getValue(I.getPointerOperand()), 4104 getValue(I.getValOperand()), 4105 I.getPointerOperand(), 4106 /* Alignment=*/ 0, Order, SSID); 4107 4108 SDValue OutChain = L.getValue(1); 4109 4110 setValue(&I, L); 4111 DAG.setRoot(OutChain); 4112 } 4113 4114 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 4115 SDLoc dl = getCurSDLoc(); 4116 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4117 SDValue Ops[3]; 4118 Ops[0] = getRoot(); 4119 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl, 4120 TLI.getFenceOperandTy(DAG.getDataLayout())); 4121 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl, 4122 TLI.getFenceOperandTy(DAG.getDataLayout())); 4123 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops)); 4124 } 4125 4126 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 4127 SDLoc dl = getCurSDLoc(); 4128 AtomicOrdering Order = I.getOrdering(); 4129 SyncScope::ID SSID = I.getSyncScopeID(); 4130 4131 SDValue InChain = getRoot(); 4132 4133 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4134 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4135 4136 if (I.getAlignment() < VT.getStoreSize()) 4137 report_fatal_error("Cannot generate unaligned atomic load"); 4138 4139 MachineMemOperand *MMO = 4140 DAG.getMachineFunction(). 4141 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 4142 MachineMemOperand::MOVolatile | 4143 MachineMemOperand::MOLoad, 4144 VT.getStoreSize(), 4145 I.getAlignment() ? I.getAlignment() : 4146 DAG.getEVTAlignment(VT), 4147 AAMDNodes(), nullptr, SSID, Order); 4148 4149 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG); 4150 SDValue L = 4151 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 4152 getValue(I.getPointerOperand()), MMO); 4153 4154 SDValue OutChain = L.getValue(1); 4155 4156 setValue(&I, L); 4157 DAG.setRoot(OutChain); 4158 } 4159 4160 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 4161 SDLoc dl = getCurSDLoc(); 4162 4163 AtomicOrdering Order = I.getOrdering(); 4164 SyncScope::ID SSID = I.getSyncScopeID(); 4165 4166 SDValue InChain = getRoot(); 4167 4168 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4169 EVT VT = 4170 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType()); 4171 4172 if (I.getAlignment() < VT.getStoreSize()) 4173 report_fatal_error("Cannot generate unaligned atomic store"); 4174 4175 SDValue OutChain = 4176 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 4177 InChain, 4178 getValue(I.getPointerOperand()), 4179 getValue(I.getValueOperand()), 4180 I.getPointerOperand(), I.getAlignment(), 4181 Order, SSID); 4182 4183 DAG.setRoot(OutChain); 4184 } 4185 4186 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 4187 /// node. 4188 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 4189 unsigned Intrinsic) { 4190 // Ignore the callsite's attributes. A specific call site may be marked with 4191 // readnone, but the lowering code will expect the chain based on the 4192 // definition. 4193 const Function *F = I.getCalledFunction(); 4194 bool HasChain = !F->doesNotAccessMemory(); 4195 bool OnlyLoad = HasChain && F->onlyReadsMemory(); 4196 4197 // Build the operand list. 4198 SmallVector<SDValue, 8> Ops; 4199 if (HasChain) { // If this intrinsic has side-effects, chainify it. 4200 if (OnlyLoad) { 4201 // We don't need to serialize loads against other loads. 4202 Ops.push_back(DAG.getRoot()); 4203 } else { 4204 Ops.push_back(getRoot()); 4205 } 4206 } 4207 4208 // Info is set by getTgtMemInstrinsic 4209 TargetLowering::IntrinsicInfo Info; 4210 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4211 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic); 4212 4213 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 4214 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 4215 Info.opc == ISD::INTRINSIC_W_CHAIN) 4216 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(), 4217 TLI.getPointerTy(DAG.getDataLayout()))); 4218 4219 // Add all operands of the call to the operand list. 4220 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 4221 SDValue Op = getValue(I.getArgOperand(i)); 4222 Ops.push_back(Op); 4223 } 4224 4225 SmallVector<EVT, 4> ValueVTs; 4226 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs); 4227 4228 if (HasChain) 4229 ValueVTs.push_back(MVT::Other); 4230 4231 SDVTList VTs = DAG.getVTList(ValueVTs); 4232 4233 // Create the node. 4234 SDValue Result; 4235 if (IsTgtIntrinsic) { 4236 // This is target intrinsic that touches memory 4237 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), 4238 VTs, Ops, Info.memVT, 4239 MachinePointerInfo(Info.ptrVal, Info.offset), 4240 Info.align, Info.vol, 4241 Info.readMem, Info.writeMem, Info.size); 4242 } else if (!HasChain) { 4243 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops); 4244 } else if (!I.getType()->isVoidTy()) { 4245 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops); 4246 } else { 4247 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops); 4248 } 4249 4250 if (HasChain) { 4251 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 4252 if (OnlyLoad) 4253 PendingLoads.push_back(Chain); 4254 else 4255 DAG.setRoot(Chain); 4256 } 4257 4258 if (!I.getType()->isVoidTy()) { 4259 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 4260 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy); 4261 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 4262 } else 4263 Result = lowerRangeToAssertZExt(DAG, I, Result); 4264 4265 setValue(&I, Result); 4266 } 4267 } 4268 4269 /// GetSignificand - Get the significand and build it into a floating-point 4270 /// number with exponent of 1: 4271 /// 4272 /// Op = (Op & 0x007fffff) | 0x3f800000; 4273 /// 4274 /// where Op is the hexadecimal representation of floating point value. 4275 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) { 4276 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4277 DAG.getConstant(0x007fffff, dl, MVT::i32)); 4278 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 4279 DAG.getConstant(0x3f800000, dl, MVT::i32)); 4280 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 4281 } 4282 4283 /// GetExponent - Get the exponent: 4284 /// 4285 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 4286 /// 4287 /// where Op is the hexadecimal representation of floating point value. 4288 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op, 4289 const TargetLowering &TLI, const SDLoc &dl) { 4290 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 4291 DAG.getConstant(0x7f800000, dl, MVT::i32)); 4292 SDValue t1 = DAG.getNode( 4293 ISD::SRL, dl, MVT::i32, t0, 4294 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout()))); 4295 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 4296 DAG.getConstant(127, dl, MVT::i32)); 4297 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 4298 } 4299 4300 /// getF32Constant - Get 32-bit floating point constant. 4301 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt, 4302 const SDLoc &dl) { 4303 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl, 4304 MVT::f32); 4305 } 4306 4307 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl, 4308 SelectionDAG &DAG) { 4309 // TODO: What fast-math-flags should be set on the floating-point nodes? 4310 4311 // IntegerPartOfX = ((int32_t)(t0); 4312 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4313 4314 // FractionalPartOfX = t0 - (float)IntegerPartOfX; 4315 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4316 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4317 4318 // IntegerPartOfX <<= 23; 4319 IntegerPartOfX = DAG.getNode( 4320 ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4321 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy( 4322 DAG.getDataLayout()))); 4323 4324 SDValue TwoToFractionalPartOfX; 4325 if (LimitFloatPrecision <= 6) { 4326 // For floating-point precision of 6: 4327 // 4328 // TwoToFractionalPartOfX = 4329 // 0.997535578f + 4330 // (0.735607626f + 0.252464424f * x) * x; 4331 // 4332 // error 0.0144103317, which is 6 bits 4333 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4334 getF32Constant(DAG, 0x3e814304, dl)); 4335 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4336 getF32Constant(DAG, 0x3f3c50c8, dl)); 4337 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4338 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4339 getF32Constant(DAG, 0x3f7f5e7e, dl)); 4340 } else if (LimitFloatPrecision <= 12) { 4341 // For floating-point precision of 12: 4342 // 4343 // TwoToFractionalPartOfX = 4344 // 0.999892986f + 4345 // (0.696457318f + 4346 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4347 // 4348 // error 0.000107046256, which is 13 to 14 bits 4349 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4350 getF32Constant(DAG, 0x3da235e3, dl)); 4351 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4352 getF32Constant(DAG, 0x3e65b8f3, dl)); 4353 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4354 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4355 getF32Constant(DAG, 0x3f324b07, dl)); 4356 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4357 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4358 getF32Constant(DAG, 0x3f7ff8fd, dl)); 4359 } else { // LimitFloatPrecision <= 18 4360 // For floating-point precision of 18: 4361 // 4362 // TwoToFractionalPartOfX = 4363 // 0.999999982f + 4364 // (0.693148872f + 4365 // (0.240227044f + 4366 // (0.554906021e-1f + 4367 // (0.961591928e-2f + 4368 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4369 // error 2.47208000*10^(-7), which is better than 18 bits 4370 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4371 getF32Constant(DAG, 0x3924b03e, dl)); 4372 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4373 getF32Constant(DAG, 0x3ab24b87, dl)); 4374 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4375 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4376 getF32Constant(DAG, 0x3c1d8c17, dl)); 4377 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4378 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4379 getF32Constant(DAG, 0x3d634a1d, dl)); 4380 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4381 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4382 getF32Constant(DAG, 0x3e75fe14, dl)); 4383 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4384 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4385 getF32Constant(DAG, 0x3f317234, dl)); 4386 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4387 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4388 getF32Constant(DAG, 0x3f800000, dl)); 4389 } 4390 4391 // Add the exponent into the result in integer domain. 4392 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX); 4393 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4394 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX)); 4395 } 4396 4397 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 4398 /// limited-precision mode. 4399 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4400 const TargetLowering &TLI) { 4401 if (Op.getValueType() == MVT::f32 && 4402 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4403 4404 // Put the exponent in the right bit position for later addition to the 4405 // final result: 4406 // 4407 // #define LOG2OFe 1.4426950f 4408 // t0 = Op * LOG2OFe 4409 4410 // TODO: What fast-math-flags should be set here? 4411 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 4412 getF32Constant(DAG, 0x3fb8aa3b, dl)); 4413 return getLimitedPrecisionExp2(t0, dl, DAG); 4414 } 4415 4416 // No special expansion. 4417 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 4418 } 4419 4420 /// expandLog - Lower a log intrinsic. Handles the special sequences for 4421 /// limited-precision mode. 4422 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4423 const TargetLowering &TLI) { 4424 // TODO: What fast-math-flags should be set on the floating-point nodes? 4425 4426 if (Op.getValueType() == MVT::f32 && 4427 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4428 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4429 4430 // Scale the exponent by log(2) [0.69314718f]. 4431 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4432 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4433 getF32Constant(DAG, 0x3f317218, dl)); 4434 4435 // Get the significand and build it into a floating-point number with 4436 // exponent of 1. 4437 SDValue X = GetSignificand(DAG, Op1, dl); 4438 4439 SDValue LogOfMantissa; 4440 if (LimitFloatPrecision <= 6) { 4441 // For floating-point precision of 6: 4442 // 4443 // LogofMantissa = 4444 // -1.1609546f + 4445 // (1.4034025f - 0.23903021f * x) * x; 4446 // 4447 // error 0.0034276066, which is better than 8 bits 4448 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4449 getF32Constant(DAG, 0xbe74c456, dl)); 4450 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4451 getF32Constant(DAG, 0x3fb3a2b1, dl)); 4452 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4453 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4454 getF32Constant(DAG, 0x3f949a29, dl)); 4455 } else if (LimitFloatPrecision <= 12) { 4456 // For floating-point precision of 12: 4457 // 4458 // LogOfMantissa = 4459 // -1.7417939f + 4460 // (2.8212026f + 4461 // (-1.4699568f + 4462 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 4463 // 4464 // error 0.000061011436, which is 14 bits 4465 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4466 getF32Constant(DAG, 0xbd67b6d6, dl)); 4467 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4468 getF32Constant(DAG, 0x3ee4f4b8, dl)); 4469 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4470 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4471 getF32Constant(DAG, 0x3fbc278b, dl)); 4472 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4473 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4474 getF32Constant(DAG, 0x40348e95, dl)); 4475 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4476 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4477 getF32Constant(DAG, 0x3fdef31a, dl)); 4478 } else { // LimitFloatPrecision <= 18 4479 // For floating-point precision of 18: 4480 // 4481 // LogOfMantissa = 4482 // -2.1072184f + 4483 // (4.2372794f + 4484 // (-3.7029485f + 4485 // (2.2781945f + 4486 // (-0.87823314f + 4487 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 4488 // 4489 // error 0.0000023660568, which is better than 18 bits 4490 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4491 getF32Constant(DAG, 0xbc91e5ac, dl)); 4492 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4493 getF32Constant(DAG, 0x3e4350aa, dl)); 4494 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4495 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4496 getF32Constant(DAG, 0x3f60d3e3, dl)); 4497 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4498 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4499 getF32Constant(DAG, 0x4011cdf0, dl)); 4500 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4501 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4502 getF32Constant(DAG, 0x406cfd1c, dl)); 4503 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4504 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4505 getF32Constant(DAG, 0x408797cb, dl)); 4506 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4507 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4508 getF32Constant(DAG, 0x4006dcab, dl)); 4509 } 4510 4511 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 4512 } 4513 4514 // No special expansion. 4515 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 4516 } 4517 4518 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 4519 /// limited-precision mode. 4520 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4521 const TargetLowering &TLI) { 4522 // TODO: What fast-math-flags should be set on the floating-point nodes? 4523 4524 if (Op.getValueType() == MVT::f32 && 4525 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4526 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4527 4528 // Get the exponent. 4529 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 4530 4531 // Get the significand and build it into a floating-point number with 4532 // exponent of 1. 4533 SDValue X = GetSignificand(DAG, Op1, dl); 4534 4535 // Different possible minimax approximations of significand in 4536 // floating-point for various degrees of accuracy over [1,2]. 4537 SDValue Log2ofMantissa; 4538 if (LimitFloatPrecision <= 6) { 4539 // For floating-point precision of 6: 4540 // 4541 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4542 // 4543 // error 0.0049451742, which is more than 7 bits 4544 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4545 getF32Constant(DAG, 0xbeb08fe0, dl)); 4546 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4547 getF32Constant(DAG, 0x40019463, dl)); 4548 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4549 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4550 getF32Constant(DAG, 0x3fd6633d, dl)); 4551 } else if (LimitFloatPrecision <= 12) { 4552 // For floating-point precision of 12: 4553 // 4554 // Log2ofMantissa = 4555 // -2.51285454f + 4556 // (4.07009056f + 4557 // (-2.12067489f + 4558 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4559 // 4560 // error 0.0000876136000, which is better than 13 bits 4561 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4562 getF32Constant(DAG, 0xbda7262e, dl)); 4563 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4564 getF32Constant(DAG, 0x3f25280b, dl)); 4565 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4566 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4567 getF32Constant(DAG, 0x4007b923, dl)); 4568 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4569 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4570 getF32Constant(DAG, 0x40823e2f, dl)); 4571 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4572 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4573 getF32Constant(DAG, 0x4020d29c, dl)); 4574 } else { // LimitFloatPrecision <= 18 4575 // For floating-point precision of 18: 4576 // 4577 // Log2ofMantissa = 4578 // -3.0400495f + 4579 // (6.1129976f + 4580 // (-5.3420409f + 4581 // (3.2865683f + 4582 // (-1.2669343f + 4583 // (0.27515199f - 4584 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4585 // 4586 // error 0.0000018516, which is better than 18 bits 4587 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4588 getF32Constant(DAG, 0xbcd2769e, dl)); 4589 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4590 getF32Constant(DAG, 0x3e8ce0b9, dl)); 4591 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4592 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4593 getF32Constant(DAG, 0x3fa22ae7, dl)); 4594 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4595 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4596 getF32Constant(DAG, 0x40525723, dl)); 4597 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4598 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4599 getF32Constant(DAG, 0x40aaf200, dl)); 4600 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4601 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4602 getF32Constant(DAG, 0x40c39dad, dl)); 4603 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4604 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4605 getF32Constant(DAG, 0x4042902c, dl)); 4606 } 4607 4608 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4609 } 4610 4611 // No special expansion. 4612 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4613 } 4614 4615 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4616 /// limited-precision mode. 4617 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4618 const TargetLowering &TLI) { 4619 // TODO: What fast-math-flags should be set on the floating-point nodes? 4620 4621 if (Op.getValueType() == MVT::f32 && 4622 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4623 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4624 4625 // Scale the exponent by log10(2) [0.30102999f]. 4626 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4627 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4628 getF32Constant(DAG, 0x3e9a209a, dl)); 4629 4630 // Get the significand and build it into a floating-point number with 4631 // exponent of 1. 4632 SDValue X = GetSignificand(DAG, Op1, dl); 4633 4634 SDValue Log10ofMantissa; 4635 if (LimitFloatPrecision <= 6) { 4636 // For floating-point precision of 6: 4637 // 4638 // Log10ofMantissa = 4639 // -0.50419619f + 4640 // (0.60948995f - 0.10380950f * x) * x; 4641 // 4642 // error 0.0014886165, which is 6 bits 4643 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4644 getF32Constant(DAG, 0xbdd49a13, dl)); 4645 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4646 getF32Constant(DAG, 0x3f1c0789, dl)); 4647 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4648 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4649 getF32Constant(DAG, 0x3f011300, dl)); 4650 } else if (LimitFloatPrecision <= 12) { 4651 // For floating-point precision of 12: 4652 // 4653 // Log10ofMantissa = 4654 // -0.64831180f + 4655 // (0.91751397f + 4656 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4657 // 4658 // error 0.00019228036, which is better than 12 bits 4659 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4660 getF32Constant(DAG, 0x3d431f31, dl)); 4661 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4662 getF32Constant(DAG, 0x3ea21fb2, dl)); 4663 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4664 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4665 getF32Constant(DAG, 0x3f6ae232, dl)); 4666 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4667 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4668 getF32Constant(DAG, 0x3f25f7c3, dl)); 4669 } else { // LimitFloatPrecision <= 18 4670 // For floating-point precision of 18: 4671 // 4672 // Log10ofMantissa = 4673 // -0.84299375f + 4674 // (1.5327582f + 4675 // (-1.0688956f + 4676 // (0.49102474f + 4677 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4678 // 4679 // error 0.0000037995730, which is better than 18 bits 4680 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4681 getF32Constant(DAG, 0x3c5d51ce, dl)); 4682 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4683 getF32Constant(DAG, 0x3e00685a, dl)); 4684 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4685 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4686 getF32Constant(DAG, 0x3efb6798, dl)); 4687 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4688 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4689 getF32Constant(DAG, 0x3f88d192, dl)); 4690 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4691 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4692 getF32Constant(DAG, 0x3fc4316c, dl)); 4693 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4694 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4695 getF32Constant(DAG, 0x3f57ce70, dl)); 4696 } 4697 4698 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4699 } 4700 4701 // No special expansion. 4702 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4703 } 4704 4705 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4706 /// limited-precision mode. 4707 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG, 4708 const TargetLowering &TLI) { 4709 if (Op.getValueType() == MVT::f32 && 4710 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) 4711 return getLimitedPrecisionExp2(Op, dl, DAG); 4712 4713 // No special expansion. 4714 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4715 } 4716 4717 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4718 /// limited-precision mode with x == 10.0f. 4719 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS, 4720 SelectionDAG &DAG, const TargetLowering &TLI) { 4721 bool IsExp10 = false; 4722 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 && 4723 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4724 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4725 APFloat Ten(10.0f); 4726 IsExp10 = LHSC->isExactlyValue(Ten); 4727 } 4728 } 4729 4730 // TODO: What fast-math-flags should be set on the FMUL node? 4731 if (IsExp10) { 4732 // Put the exponent in the right bit position for later addition to the 4733 // final result: 4734 // 4735 // #define LOG2OF10 3.3219281f 4736 // t0 = Op * LOG2OF10; 4737 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4738 getF32Constant(DAG, 0x40549a78, dl)); 4739 return getLimitedPrecisionExp2(t0, dl, DAG); 4740 } 4741 4742 // No special expansion. 4743 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4744 } 4745 4746 /// ExpandPowI - Expand a llvm.powi intrinsic. 4747 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS, 4748 SelectionDAG &DAG) { 4749 // If RHS is a constant, we can expand this out to a multiplication tree, 4750 // otherwise we end up lowering to a call to __powidf2 (for example). When 4751 // optimizing for size, we only want to do this if the expansion would produce 4752 // a small number of multiplies, otherwise we do the full expansion. 4753 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4754 // Get the exponent as a positive value. 4755 unsigned Val = RHSC->getSExtValue(); 4756 if ((int)Val < 0) Val = -Val; 4757 4758 // powi(x, 0) -> 1.0 4759 if (Val == 0) 4760 return DAG.getConstantFP(1.0, DL, LHS.getValueType()); 4761 4762 const Function *F = DAG.getMachineFunction().getFunction(); 4763 if (!F->optForSize() || 4764 // If optimizing for size, don't insert too many multiplies. 4765 // This inserts up to 5 multiplies. 4766 countPopulation(Val) + Log2_32(Val) < 7) { 4767 // We use the simple binary decomposition method to generate the multiply 4768 // sequence. There are more optimal ways to do this (for example, 4769 // powi(x,15) generates one more multiply than it should), but this has 4770 // the benefit of being both really simple and much better than a libcall. 4771 SDValue Res; // Logically starts equal to 1.0 4772 SDValue CurSquare = LHS; 4773 // TODO: Intrinsics should have fast-math-flags that propagate to these 4774 // nodes. 4775 while (Val) { 4776 if (Val & 1) { 4777 if (Res.getNode()) 4778 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4779 else 4780 Res = CurSquare; // 1.0*CurSquare. 4781 } 4782 4783 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4784 CurSquare, CurSquare); 4785 Val >>= 1; 4786 } 4787 4788 // If the original was negative, invert the result, producing 1/(x*x*x). 4789 if (RHSC->getSExtValue() < 0) 4790 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4791 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res); 4792 return Res; 4793 } 4794 } 4795 4796 // Otherwise, expand to a libcall. 4797 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4798 } 4799 4800 // getUnderlyingArgReg - Find underlying register used for a truncated or 4801 // bitcasted argument. 4802 static unsigned getUnderlyingArgReg(const SDValue &N) { 4803 switch (N.getOpcode()) { 4804 case ISD::CopyFromReg: 4805 return cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4806 case ISD::BITCAST: 4807 case ISD::AssertZext: 4808 case ISD::AssertSext: 4809 case ISD::TRUNCATE: 4810 return getUnderlyingArgReg(N.getOperand(0)); 4811 default: 4812 return 0; 4813 } 4814 } 4815 4816 /// If the DbgValueInst is a dbg_value of a function argument, create the 4817 /// corresponding DBG_VALUE machine instruction for it now. At the end of 4818 /// instruction selection, they will be inserted to the entry BB. 4819 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue( 4820 const Value *V, DILocalVariable *Variable, DIExpression *Expr, 4821 DILocation *DL, bool IsDbgDeclare, const SDValue &N) { 4822 const Argument *Arg = dyn_cast<Argument>(V); 4823 if (!Arg) 4824 return false; 4825 4826 MachineFunction &MF = DAG.getMachineFunction(); 4827 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 4828 4829 bool IsIndirect = false; 4830 Optional<MachineOperand> Op; 4831 // Some arguments' frame index is recorded during argument lowering. 4832 int FI = FuncInfo.getArgumentFrameIndex(Arg); 4833 if (FI != std::numeric_limits<int>::max()) 4834 Op = MachineOperand::CreateFI(FI); 4835 4836 if (!Op && N.getNode()) { 4837 unsigned Reg = getUnderlyingArgReg(N); 4838 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4839 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4840 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4841 if (PR) 4842 Reg = PR; 4843 } 4844 if (Reg) { 4845 Op = MachineOperand::CreateReg(Reg, false); 4846 IsIndirect = IsDbgDeclare; 4847 } 4848 } 4849 4850 if (!Op) { 4851 // Check if ValueMap has reg number. 4852 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4853 if (VMI != FuncInfo.ValueMap.end()) { 4854 const auto &TLI = DAG.getTargetLoweringInfo(); 4855 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second, 4856 V->getType(), isABIRegCopy(V)); 4857 unsigned NumRegs = 4858 std::accumulate(RFV.RegCount.begin(), RFV.RegCount.end(), 0); 4859 if (NumRegs > 1) { 4860 unsigned I = 0; 4861 unsigned Offset = 0; 4862 auto RegisterVT = RFV.RegVTs.begin(); 4863 for (auto RegCount : RFV.RegCount) { 4864 unsigned RegisterSize = (RegisterVT++)->getSizeInBits(); 4865 for (unsigned E = I + RegCount; I != E; ++I) { 4866 // The vregs are guaranteed to be allocated in sequence. 4867 Op = MachineOperand::CreateReg(VMI->second + I, false); 4868 auto FragmentExpr = DIExpression::createFragmentExpression( 4869 Expr, Offset, RegisterSize); 4870 if (!FragmentExpr) 4871 continue; 4872 FuncInfo.ArgDbgValues.push_back( 4873 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare, 4874 Op->getReg(), Variable, *FragmentExpr)); 4875 Offset += RegisterSize; 4876 } 4877 } 4878 return true; 4879 } 4880 Op = MachineOperand::CreateReg(VMI->second, false); 4881 IsIndirect = IsDbgDeclare; 4882 } 4883 } 4884 4885 if (!Op && N.getNode()) 4886 // Check if frame index is available. 4887 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4888 if (FrameIndexSDNode *FINode = 4889 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4890 Op = MachineOperand::CreateFI(FINode->getIndex()); 4891 4892 if (!Op) 4893 return false; 4894 4895 assert(Variable->isValidLocationForIntrinsic(DL) && 4896 "Expected inlined-at fields to agree"); 4897 if (Op->isReg()) 4898 FuncInfo.ArgDbgValues.push_back( 4899 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 4900 Op->getReg(), Variable, Expr)); 4901 else 4902 FuncInfo.ArgDbgValues.push_back( 4903 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE)) 4904 .add(*Op) 4905 .addImm(0) 4906 .addMetadata(Variable) 4907 .addMetadata(Expr)); 4908 4909 return true; 4910 } 4911 4912 /// Return the appropriate SDDbgValue based on N. 4913 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N, 4914 DILocalVariable *Variable, 4915 DIExpression *Expr, 4916 const DebugLoc &dl, 4917 unsigned DbgSDNodeOrder) { 4918 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) { 4919 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe 4920 // stack slot locations as such instead of as indirectly addressed 4921 // locations. 4922 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(), dl, 4923 DbgSDNodeOrder); 4924 } 4925 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(), false, dl, 4926 DbgSDNodeOrder); 4927 } 4928 4929 // VisualStudio defines setjmp as _setjmp 4930 #if defined(_MSC_VER) && defined(setjmp) && \ 4931 !defined(setjmp_undefined_for_msvc) 4932 # pragma push_macro("setjmp") 4933 # undef setjmp 4934 # define setjmp_undefined_for_msvc 4935 #endif 4936 4937 /// Lower the call to the specified intrinsic function. If we want to emit this 4938 /// as a call to a named external function, return the name. Otherwise, lower it 4939 /// and return null. 4940 const char * 4941 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4942 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4943 SDLoc sdl = getCurSDLoc(); 4944 DebugLoc dl = getCurDebugLoc(); 4945 SDValue Res; 4946 4947 switch (Intrinsic) { 4948 default: 4949 // By default, turn this into a target intrinsic node. 4950 visitTargetIntrinsic(I, Intrinsic); 4951 return nullptr; 4952 case Intrinsic::vastart: visitVAStart(I); return nullptr; 4953 case Intrinsic::vaend: visitVAEnd(I); return nullptr; 4954 case Intrinsic::vacopy: visitVACopy(I); return nullptr; 4955 case Intrinsic::returnaddress: 4956 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, 4957 TLI.getPointerTy(DAG.getDataLayout()), 4958 getValue(I.getArgOperand(0)))); 4959 return nullptr; 4960 case Intrinsic::addressofreturnaddress: 4961 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl, 4962 TLI.getPointerTy(DAG.getDataLayout()))); 4963 return nullptr; 4964 case Intrinsic::frameaddress: 4965 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, 4966 TLI.getPointerTy(DAG.getDataLayout()), 4967 getValue(I.getArgOperand(0)))); 4968 return nullptr; 4969 case Intrinsic::read_register: { 4970 Value *Reg = I.getArgOperand(0); 4971 SDValue Chain = getRoot(); 4972 SDValue RegName = 4973 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4974 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 4975 Res = DAG.getNode(ISD::READ_REGISTER, sdl, 4976 DAG.getVTList(VT, MVT::Other), Chain, RegName); 4977 setValue(&I, Res); 4978 DAG.setRoot(Res.getValue(1)); 4979 return nullptr; 4980 } 4981 case Intrinsic::write_register: { 4982 Value *Reg = I.getArgOperand(0); 4983 Value *RegValue = I.getArgOperand(1); 4984 SDValue Chain = getRoot(); 4985 SDValue RegName = 4986 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata())); 4987 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain, 4988 RegName, getValue(RegValue))); 4989 return nullptr; 4990 } 4991 case Intrinsic::setjmp: 4992 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()]; 4993 case Intrinsic::longjmp: 4994 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()]; 4995 case Intrinsic::memcpy: { 4996 SDValue Op1 = getValue(I.getArgOperand(0)); 4997 SDValue Op2 = getValue(I.getArgOperand(1)); 4998 SDValue Op3 = getValue(I.getArgOperand(2)); 4999 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 5000 if (!Align) 5001 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment. 5002 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 5003 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5004 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5005 false, isTC, 5006 MachinePointerInfo(I.getArgOperand(0)), 5007 MachinePointerInfo(I.getArgOperand(1))); 5008 updateDAGForMaybeTailCall(MC); 5009 return nullptr; 5010 } 5011 case Intrinsic::memset: { 5012 SDValue Op1 = getValue(I.getArgOperand(0)); 5013 SDValue Op2 = getValue(I.getArgOperand(1)); 5014 SDValue Op3 = getValue(I.getArgOperand(2)); 5015 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 5016 if (!Align) 5017 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment. 5018 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 5019 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5020 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5021 isTC, MachinePointerInfo(I.getArgOperand(0))); 5022 updateDAGForMaybeTailCall(MS); 5023 return nullptr; 5024 } 5025 case Intrinsic::memmove: { 5026 SDValue Op1 = getValue(I.getArgOperand(0)); 5027 SDValue Op2 = getValue(I.getArgOperand(1)); 5028 SDValue Op3 = getValue(I.getArgOperand(2)); 5029 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 5030 if (!Align) 5031 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment. 5032 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 5033 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget()); 5034 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 5035 isTC, MachinePointerInfo(I.getArgOperand(0)), 5036 MachinePointerInfo(I.getArgOperand(1))); 5037 updateDAGForMaybeTailCall(MM); 5038 return nullptr; 5039 } 5040 case Intrinsic::memcpy_element_unordered_atomic: { 5041 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I); 5042 SDValue Dst = getValue(MI.getRawDest()); 5043 SDValue Src = getValue(MI.getRawSource()); 5044 SDValue Length = getValue(MI.getLength()); 5045 5046 // Emit a library call. 5047 TargetLowering::ArgListTy Args; 5048 TargetLowering::ArgListEntry Entry; 5049 Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 5050 Entry.Node = Dst; 5051 Args.push_back(Entry); 5052 5053 Entry.Node = Src; 5054 Args.push_back(Entry); 5055 5056 Entry.Ty = MI.getLength()->getType(); 5057 Entry.Node = Length; 5058 Args.push_back(Entry); 5059 5060 uint64_t ElementSizeConstant = MI.getElementSizeInBytes(); 5061 RTLIB::Libcall LibraryCall = 5062 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant); 5063 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 5064 report_fatal_error("Unsupported element size"); 5065 5066 TargetLowering::CallLoweringInfo CLI(DAG); 5067 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5068 TLI.getLibcallCallingConv(LibraryCall), 5069 Type::getVoidTy(*DAG.getContext()), 5070 DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall), 5071 TLI.getPointerTy(DAG.getDataLayout())), 5072 std::move(Args)); 5073 5074 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 5075 DAG.setRoot(CallResult.second); 5076 return nullptr; 5077 } 5078 case Intrinsic::memmove_element_unordered_atomic: { 5079 auto &MI = cast<AtomicMemMoveInst>(I); 5080 SDValue Dst = getValue(MI.getRawDest()); 5081 SDValue Src = getValue(MI.getRawSource()); 5082 SDValue Length = getValue(MI.getLength()); 5083 5084 // Emit a library call. 5085 TargetLowering::ArgListTy Args; 5086 TargetLowering::ArgListEntry Entry; 5087 Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 5088 Entry.Node = Dst; 5089 Args.push_back(Entry); 5090 5091 Entry.Node = Src; 5092 Args.push_back(Entry); 5093 5094 Entry.Ty = MI.getLength()->getType(); 5095 Entry.Node = Length; 5096 Args.push_back(Entry); 5097 5098 uint64_t ElementSizeConstant = MI.getElementSizeInBytes(); 5099 RTLIB::Libcall LibraryCall = 5100 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant); 5101 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 5102 report_fatal_error("Unsupported element size"); 5103 5104 TargetLowering::CallLoweringInfo CLI(DAG); 5105 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5106 TLI.getLibcallCallingConv(LibraryCall), 5107 Type::getVoidTy(*DAG.getContext()), 5108 DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall), 5109 TLI.getPointerTy(DAG.getDataLayout())), 5110 std::move(Args)); 5111 5112 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 5113 DAG.setRoot(CallResult.second); 5114 return nullptr; 5115 } 5116 case Intrinsic::memset_element_unordered_atomic: { 5117 auto &MI = cast<AtomicMemSetInst>(I); 5118 SDValue Dst = getValue(MI.getRawDest()); 5119 SDValue Val = getValue(MI.getValue()); 5120 SDValue Length = getValue(MI.getLength()); 5121 5122 // Emit a library call. 5123 TargetLowering::ArgListTy Args; 5124 TargetLowering::ArgListEntry Entry; 5125 Entry.Ty = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); 5126 Entry.Node = Dst; 5127 Args.push_back(Entry); 5128 5129 Entry.Ty = Type::getInt8Ty(*DAG.getContext()); 5130 Entry.Node = Val; 5131 Args.push_back(Entry); 5132 5133 Entry.Ty = MI.getLength()->getType(); 5134 Entry.Node = Length; 5135 Args.push_back(Entry); 5136 5137 uint64_t ElementSizeConstant = MI.getElementSizeInBytes(); 5138 RTLIB::Libcall LibraryCall = 5139 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElementSizeConstant); 5140 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 5141 report_fatal_error("Unsupported element size"); 5142 5143 TargetLowering::CallLoweringInfo CLI(DAG); 5144 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5145 TLI.getLibcallCallingConv(LibraryCall), 5146 Type::getVoidTy(*DAG.getContext()), 5147 DAG.getExternalSymbol(TLI.getLibcallName(LibraryCall), 5148 TLI.getPointerTy(DAG.getDataLayout())), 5149 std::move(Args)); 5150 5151 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI); 5152 DAG.setRoot(CallResult.second); 5153 return nullptr; 5154 } 5155 case Intrinsic::dbg_addr: 5156 case Intrinsic::dbg_declare: { 5157 const DbgInfoIntrinsic &DI = cast<DbgInfoIntrinsic>(I); 5158 DILocalVariable *Variable = DI.getVariable(); 5159 DIExpression *Expression = DI.getExpression(); 5160 assert(Variable && "Missing variable"); 5161 5162 // Check if address has undef value. 5163 const Value *Address = DI.getVariableLocation(); 5164 if (!Address || isa<UndefValue>(Address) || 5165 (Address->use_empty() && !isa<Argument>(Address))) { 5166 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5167 return nullptr; 5168 } 5169 5170 bool isParameter = Variable->isParameter() || isa<Argument>(Address); 5171 5172 // Check if this variable can be described by a frame index, typically 5173 // either as a static alloca or a byval parameter. 5174 int FI = std::numeric_limits<int>::max(); 5175 if (const auto *AI = 5176 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) { 5177 if (AI->isStaticAlloca()) { 5178 auto I = FuncInfo.StaticAllocaMap.find(AI); 5179 if (I != FuncInfo.StaticAllocaMap.end()) 5180 FI = I->second; 5181 } 5182 } else if (const auto *Arg = dyn_cast<Argument>( 5183 Address->stripInBoundsConstantOffsets())) { 5184 FI = FuncInfo.getArgumentFrameIndex(Arg); 5185 } 5186 5187 // llvm.dbg.addr is control dependent and always generates indirect 5188 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in 5189 // the MachineFunction variable table. 5190 if (FI != std::numeric_limits<int>::max()) { 5191 if (Intrinsic == Intrinsic::dbg_addr) 5192 DAG.AddDbgValue(DAG.getFrameIndexDbgValue(Variable, Expression, FI, dl, 5193 SDNodeOrder), 5194 getRoot().getNode(), isParameter); 5195 return nullptr; 5196 } 5197 5198 SDValue &N = NodeMap[Address]; 5199 if (!N.getNode() && isa<Argument>(Address)) 5200 // Check unused arguments map. 5201 N = UnusedArgNodeMap[Address]; 5202 SDDbgValue *SDV; 5203 if (N.getNode()) { 5204 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 5205 Address = BCI->getOperand(0); 5206 // Parameters are handled specially. 5207 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 5208 if (isParameter && FINode) { 5209 // Byval parameter. We have a frame index at this point. 5210 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, 5211 FINode->getIndex(), dl, SDNodeOrder); 5212 } else if (isa<Argument>(Address)) { 5213 // Address is an argument, so try to emit its dbg value using 5214 // virtual register info from the FuncInfo.ValueMap. 5215 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N); 5216 return nullptr; 5217 } else { 5218 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(), 5219 true, dl, SDNodeOrder); 5220 } 5221 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 5222 } else { 5223 // If Address is an argument then try to emit its dbg value using 5224 // virtual register info from the FuncInfo.ValueMap. 5225 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, 5226 N)) { 5227 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 5228 } 5229 } 5230 return nullptr; 5231 } 5232 case Intrinsic::dbg_value: { 5233 const DbgValueInst &DI = cast<DbgValueInst>(I); 5234 assert(DI.getVariable() && "Missing variable"); 5235 5236 DILocalVariable *Variable = DI.getVariable(); 5237 DIExpression *Expression = DI.getExpression(); 5238 const Value *V = DI.getValue(); 5239 if (!V) 5240 return nullptr; 5241 5242 SDDbgValue *SDV; 5243 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 5244 SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder); 5245 DAG.AddDbgValue(SDV, nullptr, false); 5246 return nullptr; 5247 } 5248 5249 // Do not use getValue() in here; we don't want to generate code at 5250 // this point if it hasn't been done yet. 5251 SDValue N = NodeMap[V]; 5252 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map. 5253 N = UnusedArgNodeMap[V]; 5254 if (N.getNode()) { 5255 if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N)) 5256 return nullptr; 5257 SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder); 5258 DAG.AddDbgValue(SDV, N.getNode(), false); 5259 return nullptr; 5260 } 5261 5262 if (!V->use_empty() ) { 5263 // Do not call getValue(V) yet, as we don't want to generate code. 5264 // Remember it for later. 5265 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 5266 DanglingDebugInfoMap[V] = DDI; 5267 return nullptr; 5268 } 5269 5270 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 5271 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 5272 return nullptr; 5273 } 5274 5275 case Intrinsic::eh_typeid_for: { 5276 // Find the type id for the given typeinfo. 5277 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0)); 5278 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV); 5279 Res = DAG.getConstant(TypeID, sdl, MVT::i32); 5280 setValue(&I, Res); 5281 return nullptr; 5282 } 5283 5284 case Intrinsic::eh_return_i32: 5285 case Intrinsic::eh_return_i64: 5286 DAG.getMachineFunction().setCallsEHReturn(true); 5287 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 5288 MVT::Other, 5289 getControlRoot(), 5290 getValue(I.getArgOperand(0)), 5291 getValue(I.getArgOperand(1)))); 5292 return nullptr; 5293 case Intrinsic::eh_unwind_init: 5294 DAG.getMachineFunction().setCallsUnwindInit(true); 5295 return nullptr; 5296 case Intrinsic::eh_dwarf_cfa: 5297 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl, 5298 TLI.getPointerTy(DAG.getDataLayout()), 5299 getValue(I.getArgOperand(0)))); 5300 return nullptr; 5301 case Intrinsic::eh_sjlj_callsite: { 5302 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5303 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 5304 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 5305 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 5306 5307 MMI.setCurrentCallSite(CI->getZExtValue()); 5308 return nullptr; 5309 } 5310 case Intrinsic::eh_sjlj_functioncontext: { 5311 // Get and store the index of the function context. 5312 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5313 AllocaInst *FnCtx = 5314 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 5315 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 5316 MFI.setFunctionContextIndex(FI); 5317 return nullptr; 5318 } 5319 case Intrinsic::eh_sjlj_setjmp: { 5320 SDValue Ops[2]; 5321 Ops[0] = getRoot(); 5322 Ops[1] = getValue(I.getArgOperand(0)); 5323 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 5324 DAG.getVTList(MVT::i32, MVT::Other), Ops); 5325 setValue(&I, Op.getValue(0)); 5326 DAG.setRoot(Op.getValue(1)); 5327 return nullptr; 5328 } 5329 case Intrinsic::eh_sjlj_longjmp: 5330 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 5331 getRoot(), getValue(I.getArgOperand(0)))); 5332 return nullptr; 5333 case Intrinsic::eh_sjlj_setup_dispatch: 5334 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other, 5335 getRoot())); 5336 return nullptr; 5337 case Intrinsic::masked_gather: 5338 visitMaskedGather(I); 5339 return nullptr; 5340 case Intrinsic::masked_load: 5341 visitMaskedLoad(I); 5342 return nullptr; 5343 case Intrinsic::masked_scatter: 5344 visitMaskedScatter(I); 5345 return nullptr; 5346 case Intrinsic::masked_store: 5347 visitMaskedStore(I); 5348 return nullptr; 5349 case Intrinsic::masked_expandload: 5350 visitMaskedLoad(I, true /* IsExpanding */); 5351 return nullptr; 5352 case Intrinsic::masked_compressstore: 5353 visitMaskedStore(I, true /* IsCompressing */); 5354 return nullptr; 5355 case Intrinsic::x86_mmx_pslli_w: 5356 case Intrinsic::x86_mmx_pslli_d: 5357 case Intrinsic::x86_mmx_pslli_q: 5358 case Intrinsic::x86_mmx_psrli_w: 5359 case Intrinsic::x86_mmx_psrli_d: 5360 case Intrinsic::x86_mmx_psrli_q: 5361 case Intrinsic::x86_mmx_psrai_w: 5362 case Intrinsic::x86_mmx_psrai_d: { 5363 SDValue ShAmt = getValue(I.getArgOperand(1)); 5364 if (isa<ConstantSDNode>(ShAmt)) { 5365 visitTargetIntrinsic(I, Intrinsic); 5366 return nullptr; 5367 } 5368 unsigned NewIntrinsic = 0; 5369 EVT ShAmtVT = MVT::v2i32; 5370 switch (Intrinsic) { 5371 case Intrinsic::x86_mmx_pslli_w: 5372 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 5373 break; 5374 case Intrinsic::x86_mmx_pslli_d: 5375 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 5376 break; 5377 case Intrinsic::x86_mmx_pslli_q: 5378 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 5379 break; 5380 case Intrinsic::x86_mmx_psrli_w: 5381 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 5382 break; 5383 case Intrinsic::x86_mmx_psrli_d: 5384 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 5385 break; 5386 case Intrinsic::x86_mmx_psrli_q: 5387 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 5388 break; 5389 case Intrinsic::x86_mmx_psrai_w: 5390 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 5391 break; 5392 case Intrinsic::x86_mmx_psrai_d: 5393 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 5394 break; 5395 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5396 } 5397 5398 // The vector shift intrinsics with scalars uses 32b shift amounts but 5399 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 5400 // to be zero. 5401 // We must do this early because v2i32 is not a legal type. 5402 SDValue ShOps[2]; 5403 ShOps[0] = ShAmt; 5404 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32); 5405 ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps); 5406 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5407 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 5408 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 5409 DAG.getConstant(NewIntrinsic, sdl, MVT::i32), 5410 getValue(I.getArgOperand(0)), ShAmt); 5411 setValue(&I, Res); 5412 return nullptr; 5413 } 5414 case Intrinsic::powi: 5415 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 5416 getValue(I.getArgOperand(1)), DAG)); 5417 return nullptr; 5418 case Intrinsic::log: 5419 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5420 return nullptr; 5421 case Intrinsic::log2: 5422 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5423 return nullptr; 5424 case Intrinsic::log10: 5425 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5426 return nullptr; 5427 case Intrinsic::exp: 5428 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5429 return nullptr; 5430 case Intrinsic::exp2: 5431 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI)); 5432 return nullptr; 5433 case Intrinsic::pow: 5434 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 5435 getValue(I.getArgOperand(1)), DAG, TLI)); 5436 return nullptr; 5437 case Intrinsic::sqrt: 5438 case Intrinsic::fabs: 5439 case Intrinsic::sin: 5440 case Intrinsic::cos: 5441 case Intrinsic::floor: 5442 case Intrinsic::ceil: 5443 case Intrinsic::trunc: 5444 case Intrinsic::rint: 5445 case Intrinsic::nearbyint: 5446 case Intrinsic::round: 5447 case Intrinsic::canonicalize: { 5448 unsigned Opcode; 5449 switch (Intrinsic) { 5450 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5451 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 5452 case Intrinsic::fabs: Opcode = ISD::FABS; break; 5453 case Intrinsic::sin: Opcode = ISD::FSIN; break; 5454 case Intrinsic::cos: Opcode = ISD::FCOS; break; 5455 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 5456 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 5457 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 5458 case Intrinsic::rint: Opcode = ISD::FRINT; break; 5459 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 5460 case Intrinsic::round: Opcode = ISD::FROUND; break; 5461 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break; 5462 } 5463 5464 setValue(&I, DAG.getNode(Opcode, sdl, 5465 getValue(I.getArgOperand(0)).getValueType(), 5466 getValue(I.getArgOperand(0)))); 5467 return nullptr; 5468 } 5469 case Intrinsic::minnum: { 5470 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5471 unsigned Opc = 5472 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINNAN, VT) 5473 ? ISD::FMINNAN 5474 : ISD::FMINNUM; 5475 setValue(&I, DAG.getNode(Opc, sdl, VT, 5476 getValue(I.getArgOperand(0)), 5477 getValue(I.getArgOperand(1)))); 5478 return nullptr; 5479 } 5480 case Intrinsic::maxnum: { 5481 auto VT = getValue(I.getArgOperand(0)).getValueType(); 5482 unsigned Opc = 5483 I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXNAN, VT) 5484 ? ISD::FMAXNAN 5485 : ISD::FMAXNUM; 5486 setValue(&I, DAG.getNode(Opc, sdl, VT, 5487 getValue(I.getArgOperand(0)), 5488 getValue(I.getArgOperand(1)))); 5489 return nullptr; 5490 } 5491 case Intrinsic::copysign: 5492 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5493 getValue(I.getArgOperand(0)).getValueType(), 5494 getValue(I.getArgOperand(0)), 5495 getValue(I.getArgOperand(1)))); 5496 return nullptr; 5497 case Intrinsic::fma: 5498 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5499 getValue(I.getArgOperand(0)).getValueType(), 5500 getValue(I.getArgOperand(0)), 5501 getValue(I.getArgOperand(1)), 5502 getValue(I.getArgOperand(2)))); 5503 return nullptr; 5504 case Intrinsic::experimental_constrained_fadd: 5505 case Intrinsic::experimental_constrained_fsub: 5506 case Intrinsic::experimental_constrained_fmul: 5507 case Intrinsic::experimental_constrained_fdiv: 5508 case Intrinsic::experimental_constrained_frem: 5509 case Intrinsic::experimental_constrained_fma: 5510 case Intrinsic::experimental_constrained_sqrt: 5511 case Intrinsic::experimental_constrained_pow: 5512 case Intrinsic::experimental_constrained_powi: 5513 case Intrinsic::experimental_constrained_sin: 5514 case Intrinsic::experimental_constrained_cos: 5515 case Intrinsic::experimental_constrained_exp: 5516 case Intrinsic::experimental_constrained_exp2: 5517 case Intrinsic::experimental_constrained_log: 5518 case Intrinsic::experimental_constrained_log10: 5519 case Intrinsic::experimental_constrained_log2: 5520 case Intrinsic::experimental_constrained_rint: 5521 case Intrinsic::experimental_constrained_nearbyint: 5522 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I)); 5523 return nullptr; 5524 case Intrinsic::fmuladd: { 5525 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5526 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5527 TLI.isFMAFasterThanFMulAndFAdd(VT)) { 5528 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5529 getValue(I.getArgOperand(0)).getValueType(), 5530 getValue(I.getArgOperand(0)), 5531 getValue(I.getArgOperand(1)), 5532 getValue(I.getArgOperand(2)))); 5533 } else { 5534 // TODO: Intrinsic calls should have fast-math-flags. 5535 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5536 getValue(I.getArgOperand(0)).getValueType(), 5537 getValue(I.getArgOperand(0)), 5538 getValue(I.getArgOperand(1))); 5539 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5540 getValue(I.getArgOperand(0)).getValueType(), 5541 Mul, 5542 getValue(I.getArgOperand(2))); 5543 setValue(&I, Add); 5544 } 5545 return nullptr; 5546 } 5547 case Intrinsic::convert_to_fp16: 5548 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16, 5549 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16, 5550 getValue(I.getArgOperand(0)), 5551 DAG.getTargetConstant(0, sdl, 5552 MVT::i32)))); 5553 return nullptr; 5554 case Intrinsic::convert_from_fp16: 5555 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl, 5556 TLI.getValueType(DAG.getDataLayout(), I.getType()), 5557 DAG.getNode(ISD::BITCAST, sdl, MVT::f16, 5558 getValue(I.getArgOperand(0))))); 5559 return nullptr; 5560 case Intrinsic::pcmarker: { 5561 SDValue Tmp = getValue(I.getArgOperand(0)); 5562 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5563 return nullptr; 5564 } 5565 case Intrinsic::readcyclecounter: { 5566 SDValue Op = getRoot(); 5567 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5568 DAG.getVTList(MVT::i64, MVT::Other), Op); 5569 setValue(&I, Res); 5570 DAG.setRoot(Res.getValue(1)); 5571 return nullptr; 5572 } 5573 case Intrinsic::bitreverse: 5574 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl, 5575 getValue(I.getArgOperand(0)).getValueType(), 5576 getValue(I.getArgOperand(0)))); 5577 return nullptr; 5578 case Intrinsic::bswap: 5579 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5580 getValue(I.getArgOperand(0)).getValueType(), 5581 getValue(I.getArgOperand(0)))); 5582 return nullptr; 5583 case Intrinsic::cttz: { 5584 SDValue Arg = getValue(I.getArgOperand(0)); 5585 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5586 EVT Ty = Arg.getValueType(); 5587 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5588 sdl, Ty, Arg)); 5589 return nullptr; 5590 } 5591 case Intrinsic::ctlz: { 5592 SDValue Arg = getValue(I.getArgOperand(0)); 5593 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5594 EVT Ty = Arg.getValueType(); 5595 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5596 sdl, Ty, Arg)); 5597 return nullptr; 5598 } 5599 case Intrinsic::ctpop: { 5600 SDValue Arg = getValue(I.getArgOperand(0)); 5601 EVT Ty = Arg.getValueType(); 5602 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5603 return nullptr; 5604 } 5605 case Intrinsic::stacksave: { 5606 SDValue Op = getRoot(); 5607 Res = DAG.getNode( 5608 ISD::STACKSAVE, sdl, 5609 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op); 5610 setValue(&I, Res); 5611 DAG.setRoot(Res.getValue(1)); 5612 return nullptr; 5613 } 5614 case Intrinsic::stackrestore: 5615 Res = getValue(I.getArgOperand(0)); 5616 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5617 return nullptr; 5618 case Intrinsic::get_dynamic_area_offset: { 5619 SDValue Op = getRoot(); 5620 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5621 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType()); 5622 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for 5623 // target. 5624 if (PtrTy != ResTy) 5625 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset" 5626 " intrinsic!"); 5627 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy), 5628 Op); 5629 DAG.setRoot(Op); 5630 setValue(&I, Res); 5631 return nullptr; 5632 } 5633 case Intrinsic::stackguard: { 5634 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5635 MachineFunction &MF = DAG.getMachineFunction(); 5636 const Module &M = *MF.getFunction()->getParent(); 5637 SDValue Chain = getRoot(); 5638 if (TLI.useLoadStackGuardNode()) { 5639 Res = getLoadStackGuard(DAG, sdl, Chain); 5640 } else { 5641 const Value *Global = TLI.getSDagStackGuard(M); 5642 unsigned Align = DL->getPrefTypeAlignment(Global->getType()); 5643 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global), 5644 MachinePointerInfo(Global, 0), Align, 5645 MachineMemOperand::MOVolatile); 5646 } 5647 DAG.setRoot(Chain); 5648 setValue(&I, Res); 5649 return nullptr; 5650 } 5651 case Intrinsic::stackprotector: { 5652 // Emit code into the DAG to store the stack guard onto the stack. 5653 MachineFunction &MF = DAG.getMachineFunction(); 5654 MachineFrameInfo &MFI = MF.getFrameInfo(); 5655 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout()); 5656 SDValue Src, Chain = getRoot(); 5657 5658 if (TLI.useLoadStackGuardNode()) 5659 Src = getLoadStackGuard(DAG, sdl, Chain); 5660 else 5661 Src = getValue(I.getArgOperand(0)); // The guard's value. 5662 5663 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5664 5665 int FI = FuncInfo.StaticAllocaMap[Slot]; 5666 MFI.setStackProtectorIndex(FI); 5667 5668 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5669 5670 // Store the stack protector onto the stack. 5671 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack( 5672 DAG.getMachineFunction(), FI), 5673 /* Alignment = */ 0, MachineMemOperand::MOVolatile); 5674 setValue(&I, Res); 5675 DAG.setRoot(Res); 5676 return nullptr; 5677 } 5678 case Intrinsic::objectsize: { 5679 // If we don't know by now, we're never going to know. 5680 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5681 5682 assert(CI && "Non-constant type in __builtin_object_size?"); 5683 5684 SDValue Arg = getValue(I.getCalledValue()); 5685 EVT Ty = Arg.getValueType(); 5686 5687 if (CI->isZero()) 5688 Res = DAG.getConstant(-1ULL, sdl, Ty); 5689 else 5690 Res = DAG.getConstant(0, sdl, Ty); 5691 5692 setValue(&I, Res); 5693 return nullptr; 5694 } 5695 case Intrinsic::annotation: 5696 case Intrinsic::ptr_annotation: 5697 case Intrinsic::invariant_group_barrier: 5698 // Drop the intrinsic, but forward the value 5699 setValue(&I, getValue(I.getOperand(0))); 5700 return nullptr; 5701 case Intrinsic::assume: 5702 case Intrinsic::var_annotation: 5703 case Intrinsic::sideeffect: 5704 // Discard annotate attributes, assumptions, and artificial side-effects. 5705 return nullptr; 5706 5707 case Intrinsic::codeview_annotation: { 5708 // Emit a label associated with this metadata. 5709 MachineFunction &MF = DAG.getMachineFunction(); 5710 MCSymbol *Label = 5711 MF.getMMI().getContext().createTempSymbol("annotation", true); 5712 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata(); 5713 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD)); 5714 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label); 5715 DAG.setRoot(Res); 5716 return nullptr; 5717 } 5718 5719 case Intrinsic::init_trampoline: { 5720 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5721 5722 SDValue Ops[6]; 5723 Ops[0] = getRoot(); 5724 Ops[1] = getValue(I.getArgOperand(0)); 5725 Ops[2] = getValue(I.getArgOperand(1)); 5726 Ops[3] = getValue(I.getArgOperand(2)); 5727 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5728 Ops[5] = DAG.getSrcValue(F); 5729 5730 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops); 5731 5732 DAG.setRoot(Res); 5733 return nullptr; 5734 } 5735 case Intrinsic::adjust_trampoline: 5736 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5737 TLI.getPointerTy(DAG.getDataLayout()), 5738 getValue(I.getArgOperand(0)))); 5739 return nullptr; 5740 case Intrinsic::gcroot: { 5741 MachineFunction &MF = DAG.getMachineFunction(); 5742 const Function *F = MF.getFunction(); 5743 (void)F; 5744 assert(F->hasGC() && 5745 "only valid in functions with gc specified, enforced by Verifier"); 5746 assert(GFI && "implied by previous"); 5747 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5748 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5749 5750 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5751 GFI->addStackRoot(FI->getIndex(), TypeMap); 5752 return nullptr; 5753 } 5754 case Intrinsic::gcread: 5755 case Intrinsic::gcwrite: 5756 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5757 case Intrinsic::flt_rounds: 5758 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5759 return nullptr; 5760 5761 case Intrinsic::expect: 5762 // Just replace __builtin_expect(exp, c) with EXP. 5763 setValue(&I, getValue(I.getArgOperand(0))); 5764 return nullptr; 5765 5766 case Intrinsic::debugtrap: 5767 case Intrinsic::trap: { 5768 StringRef TrapFuncName = 5769 I.getAttributes() 5770 .getAttribute(AttributeList::FunctionIndex, "trap-func-name") 5771 .getValueAsString(); 5772 if (TrapFuncName.empty()) { 5773 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5774 ISD::TRAP : ISD::DEBUGTRAP; 5775 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5776 return nullptr; 5777 } 5778 TargetLowering::ArgListTy Args; 5779 5780 TargetLowering::CallLoweringInfo CLI(DAG); 5781 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee( 5782 CallingConv::C, I.getType(), 5783 DAG.getExternalSymbol(TrapFuncName.data(), 5784 TLI.getPointerTy(DAG.getDataLayout())), 5785 std::move(Args)); 5786 5787 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 5788 DAG.setRoot(Result.second); 5789 return nullptr; 5790 } 5791 5792 case Intrinsic::uadd_with_overflow: 5793 case Intrinsic::sadd_with_overflow: 5794 case Intrinsic::usub_with_overflow: 5795 case Intrinsic::ssub_with_overflow: 5796 case Intrinsic::umul_with_overflow: 5797 case Intrinsic::smul_with_overflow: { 5798 ISD::NodeType Op; 5799 switch (Intrinsic) { 5800 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5801 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5802 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5803 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5804 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5805 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5806 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5807 } 5808 SDValue Op1 = getValue(I.getArgOperand(0)); 5809 SDValue Op2 = getValue(I.getArgOperand(1)); 5810 5811 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5812 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5813 return nullptr; 5814 } 5815 case Intrinsic::prefetch: { 5816 SDValue Ops[5]; 5817 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5818 Ops[0] = getRoot(); 5819 Ops[1] = getValue(I.getArgOperand(0)); 5820 Ops[2] = getValue(I.getArgOperand(1)); 5821 Ops[3] = getValue(I.getArgOperand(2)); 5822 Ops[4] = getValue(I.getArgOperand(3)); 5823 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5824 DAG.getVTList(MVT::Other), Ops, 5825 EVT::getIntegerVT(*Context, 8), 5826 MachinePointerInfo(I.getArgOperand(0)), 5827 0, /* align */ 5828 false, /* volatile */ 5829 rw==0, /* read */ 5830 rw==1)); /* write */ 5831 return nullptr; 5832 } 5833 case Intrinsic::lifetime_start: 5834 case Intrinsic::lifetime_end: { 5835 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5836 // Stack coloring is not enabled in O0, discard region information. 5837 if (TM.getOptLevel() == CodeGenOpt::None) 5838 return nullptr; 5839 5840 SmallVector<Value *, 4> Allocas; 5841 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL); 5842 5843 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5844 E = Allocas.end(); Object != E; ++Object) { 5845 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5846 5847 // Could not find an Alloca. 5848 if (!LifetimeObject) 5849 continue; 5850 5851 // First check that the Alloca is static, otherwise it won't have a 5852 // valid frame index. 5853 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject); 5854 if (SI == FuncInfo.StaticAllocaMap.end()) 5855 return nullptr; 5856 5857 int FI = SI->second; 5858 5859 SDValue Ops[2]; 5860 Ops[0] = getRoot(); 5861 Ops[1] = 5862 DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true); 5863 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5864 5865 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops); 5866 DAG.setRoot(Res); 5867 } 5868 return nullptr; 5869 } 5870 case Intrinsic::invariant_start: 5871 // Discard region information. 5872 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout()))); 5873 return nullptr; 5874 case Intrinsic::invariant_end: 5875 // Discard region information. 5876 return nullptr; 5877 case Intrinsic::clear_cache: 5878 return TLI.getClearCacheBuiltinName(); 5879 case Intrinsic::donothing: 5880 // ignore 5881 return nullptr; 5882 case Intrinsic::experimental_stackmap: 5883 visitStackmap(I); 5884 return nullptr; 5885 case Intrinsic::experimental_patchpoint_void: 5886 case Intrinsic::experimental_patchpoint_i64: 5887 visitPatchpoint(&I); 5888 return nullptr; 5889 case Intrinsic::experimental_gc_statepoint: 5890 LowerStatepoint(ImmutableStatepoint(&I)); 5891 return nullptr; 5892 case Intrinsic::experimental_gc_result: 5893 visitGCResult(cast<GCResultInst>(I)); 5894 return nullptr; 5895 case Intrinsic::experimental_gc_relocate: 5896 visitGCRelocate(cast<GCRelocateInst>(I)); 5897 return nullptr; 5898 case Intrinsic::instrprof_increment: 5899 llvm_unreachable("instrprof failed to lower an increment"); 5900 case Intrinsic::instrprof_value_profile: 5901 llvm_unreachable("instrprof failed to lower a value profiling call"); 5902 case Intrinsic::localescape: { 5903 MachineFunction &MF = DAG.getMachineFunction(); 5904 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo(); 5905 5906 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 5907 // is the same on all targets. 5908 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) { 5909 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts(); 5910 if (isa<ConstantPointerNull>(Arg)) 5911 continue; // Skip null pointers. They represent a hole in index space. 5912 AllocaInst *Slot = cast<AllocaInst>(Arg); 5913 assert(FuncInfo.StaticAllocaMap.count(Slot) && 5914 "can only escape static allocas"); 5915 int FI = FuncInfo.StaticAllocaMap[Slot]; 5916 MCSymbol *FrameAllocSym = 5917 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5918 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx); 5919 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl, 5920 TII->get(TargetOpcode::LOCAL_ESCAPE)) 5921 .addSym(FrameAllocSym) 5922 .addFrameIndex(FI); 5923 } 5924 5925 return nullptr; 5926 } 5927 5928 case Intrinsic::localrecover: { 5929 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx) 5930 MachineFunction &MF = DAG.getMachineFunction(); 5931 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0); 5932 5933 // Get the symbol that defines the frame offset. 5934 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts()); 5935 auto *Idx = cast<ConstantInt>(I.getArgOperand(2)); 5936 unsigned IdxVal = 5937 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max())); 5938 MCSymbol *FrameAllocSym = 5939 MF.getMMI().getContext().getOrCreateFrameAllocSymbol( 5940 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal); 5941 5942 // Create a MCSymbol for the label to avoid any target lowering 5943 // that would make this PC relative. 5944 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT); 5945 SDValue OffsetVal = 5946 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym); 5947 5948 // Add the offset to the FP. 5949 Value *FP = I.getArgOperand(1); 5950 SDValue FPVal = getValue(FP); 5951 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal); 5952 setValue(&I, Add); 5953 5954 return nullptr; 5955 } 5956 5957 case Intrinsic::eh_exceptionpointer: 5958 case Intrinsic::eh_exceptioncode: { 5959 // Get the exception pointer vreg, copy from it, and resize it to fit. 5960 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0)); 5961 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout()); 5962 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT); 5963 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC); 5964 SDValue N = 5965 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT); 5966 if (Intrinsic == Intrinsic::eh_exceptioncode) 5967 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32); 5968 setValue(&I, N); 5969 return nullptr; 5970 } 5971 case Intrinsic::xray_customevent: { 5972 // Here we want to make sure that the intrinsic behaves as if it has a 5973 // specific calling convention, and only for x86_64. 5974 // FIXME: Support other platforms later. 5975 const auto &Triple = DAG.getTarget().getTargetTriple(); 5976 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux()) 5977 return nullptr; 5978 5979 SDLoc DL = getCurSDLoc(); 5980 SmallVector<SDValue, 8> Ops; 5981 5982 // We want to say that we always want the arguments in registers. 5983 SDValue LogEntryVal = getValue(I.getArgOperand(0)); 5984 SDValue StrSizeVal = getValue(I.getArgOperand(1)); 5985 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 5986 SDValue Chain = getRoot(); 5987 Ops.push_back(LogEntryVal); 5988 Ops.push_back(StrSizeVal); 5989 Ops.push_back(Chain); 5990 5991 // We need to enforce the calling convention for the callsite, so that 5992 // argument ordering is enforced correctly, and that register allocation can 5993 // see that some registers may be assumed clobbered and have to preserve 5994 // them across calls to the intrinsic. 5995 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL, 5996 DL, NodeTys, Ops); 5997 SDValue patchableNode = SDValue(MN, 0); 5998 DAG.setRoot(patchableNode); 5999 setValue(&I, patchableNode); 6000 return nullptr; 6001 } 6002 case Intrinsic::experimental_deoptimize: 6003 LowerDeoptimizeCall(&I); 6004 return nullptr; 6005 6006 case Intrinsic::experimental_vector_reduce_fadd: 6007 case Intrinsic::experimental_vector_reduce_fmul: 6008 case Intrinsic::experimental_vector_reduce_add: 6009 case Intrinsic::experimental_vector_reduce_mul: 6010 case Intrinsic::experimental_vector_reduce_and: 6011 case Intrinsic::experimental_vector_reduce_or: 6012 case Intrinsic::experimental_vector_reduce_xor: 6013 case Intrinsic::experimental_vector_reduce_smax: 6014 case Intrinsic::experimental_vector_reduce_smin: 6015 case Intrinsic::experimental_vector_reduce_umax: 6016 case Intrinsic::experimental_vector_reduce_umin: 6017 case Intrinsic::experimental_vector_reduce_fmax: 6018 case Intrinsic::experimental_vector_reduce_fmin: 6019 visitVectorReduce(I, Intrinsic); 6020 return nullptr; 6021 } 6022 } 6023 6024 void SelectionDAGBuilder::visitConstrainedFPIntrinsic( 6025 const ConstrainedFPIntrinsic &FPI) { 6026 SDLoc sdl = getCurSDLoc(); 6027 unsigned Opcode; 6028 switch (FPI.getIntrinsicID()) { 6029 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 6030 case Intrinsic::experimental_constrained_fadd: 6031 Opcode = ISD::STRICT_FADD; 6032 break; 6033 case Intrinsic::experimental_constrained_fsub: 6034 Opcode = ISD::STRICT_FSUB; 6035 break; 6036 case Intrinsic::experimental_constrained_fmul: 6037 Opcode = ISD::STRICT_FMUL; 6038 break; 6039 case Intrinsic::experimental_constrained_fdiv: 6040 Opcode = ISD::STRICT_FDIV; 6041 break; 6042 case Intrinsic::experimental_constrained_frem: 6043 Opcode = ISD::STRICT_FREM; 6044 break; 6045 case Intrinsic::experimental_constrained_fma: 6046 Opcode = ISD::STRICT_FMA; 6047 break; 6048 case Intrinsic::experimental_constrained_sqrt: 6049 Opcode = ISD::STRICT_FSQRT; 6050 break; 6051 case Intrinsic::experimental_constrained_pow: 6052 Opcode = ISD::STRICT_FPOW; 6053 break; 6054 case Intrinsic::experimental_constrained_powi: 6055 Opcode = ISD::STRICT_FPOWI; 6056 break; 6057 case Intrinsic::experimental_constrained_sin: 6058 Opcode = ISD::STRICT_FSIN; 6059 break; 6060 case Intrinsic::experimental_constrained_cos: 6061 Opcode = ISD::STRICT_FCOS; 6062 break; 6063 case Intrinsic::experimental_constrained_exp: 6064 Opcode = ISD::STRICT_FEXP; 6065 break; 6066 case Intrinsic::experimental_constrained_exp2: 6067 Opcode = ISD::STRICT_FEXP2; 6068 break; 6069 case Intrinsic::experimental_constrained_log: 6070 Opcode = ISD::STRICT_FLOG; 6071 break; 6072 case Intrinsic::experimental_constrained_log10: 6073 Opcode = ISD::STRICT_FLOG10; 6074 break; 6075 case Intrinsic::experimental_constrained_log2: 6076 Opcode = ISD::STRICT_FLOG2; 6077 break; 6078 case Intrinsic::experimental_constrained_rint: 6079 Opcode = ISD::STRICT_FRINT; 6080 break; 6081 case Intrinsic::experimental_constrained_nearbyint: 6082 Opcode = ISD::STRICT_FNEARBYINT; 6083 break; 6084 } 6085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6086 SDValue Chain = getRoot(); 6087 SmallVector<EVT, 4> ValueVTs; 6088 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs); 6089 ValueVTs.push_back(MVT::Other); // Out chain 6090 6091 SDVTList VTs = DAG.getVTList(ValueVTs); 6092 SDValue Result; 6093 if (FPI.isUnaryOp()) 6094 Result = DAG.getNode(Opcode, sdl, VTs, 6095 { Chain, getValue(FPI.getArgOperand(0)) }); 6096 else if (FPI.isTernaryOp()) 6097 Result = DAG.getNode(Opcode, sdl, VTs, 6098 { Chain, getValue(FPI.getArgOperand(0)), 6099 getValue(FPI.getArgOperand(1)), 6100 getValue(FPI.getArgOperand(2)) }); 6101 else 6102 Result = DAG.getNode(Opcode, sdl, VTs, 6103 { Chain, getValue(FPI.getArgOperand(0)), 6104 getValue(FPI.getArgOperand(1)) }); 6105 6106 assert(Result.getNode()->getNumValues() == 2); 6107 SDValue OutChain = Result.getValue(1); 6108 DAG.setRoot(OutChain); 6109 SDValue FPResult = Result.getValue(0); 6110 setValue(&FPI, FPResult); 6111 } 6112 6113 std::pair<SDValue, SDValue> 6114 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI, 6115 const BasicBlock *EHPadBB) { 6116 MachineFunction &MF = DAG.getMachineFunction(); 6117 MachineModuleInfo &MMI = MF.getMMI(); 6118 MCSymbol *BeginLabel = nullptr; 6119 6120 if (EHPadBB) { 6121 // Insert a label before the invoke call to mark the try range. This can be 6122 // used to detect deletion of the invoke via the MachineModuleInfo. 6123 BeginLabel = MMI.getContext().createTempSymbol(); 6124 6125 // For SjLj, keep track of which landing pads go with which invokes 6126 // so as to maintain the ordering of pads in the LSDA. 6127 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 6128 if (CallSiteIndex) { 6129 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 6130 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex); 6131 6132 // Now that the call site is handled, stop tracking it. 6133 MMI.setCurrentCallSite(0); 6134 } 6135 6136 // Both PendingLoads and PendingExports must be flushed here; 6137 // this call might not return. 6138 (void)getRoot(); 6139 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 6140 6141 CLI.setChain(getRoot()); 6142 } 6143 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6144 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 6145 6146 assert((CLI.IsTailCall || Result.second.getNode()) && 6147 "Non-null chain expected with non-tail call!"); 6148 assert((Result.second.getNode() || !Result.first.getNode()) && 6149 "Null value expected with tail call!"); 6150 6151 if (!Result.second.getNode()) { 6152 // As a special case, a null chain means that a tail call has been emitted 6153 // and the DAG root is already updated. 6154 HasTailCall = true; 6155 6156 // Since there's no actual continuation from this block, nothing can be 6157 // relying on us setting vregs for them. 6158 PendingExports.clear(); 6159 } else { 6160 DAG.setRoot(Result.second); 6161 } 6162 6163 if (EHPadBB) { 6164 // Insert a label at the end of the invoke call to mark the try range. This 6165 // can be used to detect deletion of the invoke via the MachineModuleInfo. 6166 MCSymbol *EndLabel = MMI.getContext().createTempSymbol(); 6167 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 6168 6169 // Inform MachineModuleInfo of range. 6170 if (MF.hasEHFunclets()) { 6171 assert(CLI.CS); 6172 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo(); 6173 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()), 6174 BeginLabel, EndLabel); 6175 } else { 6176 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel); 6177 } 6178 } 6179 6180 return Result; 6181 } 6182 6183 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 6184 bool isTailCall, 6185 const BasicBlock *EHPadBB) { 6186 auto &DL = DAG.getDataLayout(); 6187 FunctionType *FTy = CS.getFunctionType(); 6188 Type *RetTy = CS.getType(); 6189 6190 TargetLowering::ArgListTy Args; 6191 Args.reserve(CS.arg_size()); 6192 6193 const Value *SwiftErrorVal = nullptr; 6194 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6195 6196 // We can't tail call inside a function with a swifterror argument. Lowering 6197 // does not support this yet. It would have to move into the swifterror 6198 // register before the call. 6199 auto *Caller = CS.getInstruction()->getParent()->getParent(); 6200 if (TLI.supportSwiftError() && 6201 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 6202 isTailCall = false; 6203 6204 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 6205 i != e; ++i) { 6206 TargetLowering::ArgListEntry Entry; 6207 const Value *V = *i; 6208 6209 // Skip empty types 6210 if (V->getType()->isEmptyTy()) 6211 continue; 6212 6213 SDValue ArgNode = getValue(V); 6214 Entry.Node = ArgNode; Entry.Ty = V->getType(); 6215 6216 Entry.setAttributes(&CS, i - CS.arg_begin()); 6217 6218 // Use swifterror virtual register as input to the call. 6219 if (Entry.IsSwiftError && TLI.supportSwiftError()) { 6220 SwiftErrorVal = V; 6221 // We find the virtual register for the actual swifterror argument. 6222 // Instead of using the Value, we use the virtual register instead. 6223 Entry.Node = DAG.getRegister(FuncInfo 6224 .getOrCreateSwiftErrorVRegUseAt( 6225 CS.getInstruction(), FuncInfo.MBB, V) 6226 .first, 6227 EVT(TLI.getPointerTy(DL))); 6228 } 6229 6230 Args.push_back(Entry); 6231 6232 // If we have an explicit sret argument that is an Instruction, (i.e., it 6233 // might point to function-local memory), we can't meaningfully tail-call. 6234 if (Entry.IsSRet && isa<Instruction>(V)) 6235 isTailCall = false; 6236 } 6237 6238 // Check if target-independent constraints permit a tail call here. 6239 // Target-dependent constraints are checked within TLI->LowerCallTo. 6240 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget())) 6241 isTailCall = false; 6242 6243 // Disable tail calls if there is an swifterror argument. Targets have not 6244 // been updated to support tail calls. 6245 if (TLI.supportSwiftError() && SwiftErrorVal) 6246 isTailCall = false; 6247 6248 TargetLowering::CallLoweringInfo CLI(DAG); 6249 CLI.setDebugLoc(getCurSDLoc()) 6250 .setChain(getRoot()) 6251 .setCallee(RetTy, FTy, Callee, std::move(Args), CS) 6252 .setTailCall(isTailCall) 6253 .setConvergent(CS.isConvergent()); 6254 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 6255 6256 if (Result.first.getNode()) { 6257 const Instruction *Inst = CS.getInstruction(); 6258 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first); 6259 setValue(Inst, Result.first); 6260 } 6261 6262 // The last element of CLI.InVals has the SDValue for swifterror return. 6263 // Here we copy it to a virtual register and update SwiftErrorMap for 6264 // book-keeping. 6265 if (SwiftErrorVal && TLI.supportSwiftError()) { 6266 // Get the last element of InVals. 6267 SDValue Src = CLI.InVals.back(); 6268 unsigned VReg; bool CreatedVReg; 6269 std::tie(VReg, CreatedVReg) = 6270 FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction()); 6271 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src); 6272 // We update the virtual register for the actual swifterror argument. 6273 if (CreatedVReg) 6274 FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg); 6275 DAG.setRoot(CopyNode); 6276 } 6277 } 6278 6279 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 6280 SelectionDAGBuilder &Builder) { 6281 // Check to see if this load can be trivially constant folded, e.g. if the 6282 // input is from a string literal. 6283 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 6284 // Cast pointer to the type we really want to load. 6285 Type *LoadTy = 6286 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits()); 6287 if (LoadVT.isVector()) 6288 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements()); 6289 6290 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 6291 PointerType::getUnqual(LoadTy)); 6292 6293 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr( 6294 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL)) 6295 return Builder.getValue(LoadCst); 6296 } 6297 6298 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 6299 // still constant memory, the input chain can be the entry node. 6300 SDValue Root; 6301 bool ConstantMemory = false; 6302 6303 // Do not serialize (non-volatile) loads of constant memory with anything. 6304 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) { 6305 Root = Builder.DAG.getEntryNode(); 6306 ConstantMemory = true; 6307 } else { 6308 // Do not serialize non-volatile loads against each other. 6309 Root = Builder.DAG.getRoot(); 6310 } 6311 6312 SDValue Ptr = Builder.getValue(PtrVal); 6313 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 6314 Ptr, MachinePointerInfo(PtrVal), 6315 /* Alignment = */ 1); 6316 6317 if (!ConstantMemory) 6318 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 6319 return LoadVal; 6320 } 6321 6322 /// Record the value for an instruction that produces an integer result, 6323 /// converting the type where necessary. 6324 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 6325 SDValue Value, 6326 bool IsSigned) { 6327 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6328 I.getType(), true); 6329 if (IsSigned) 6330 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 6331 else 6332 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 6333 setValue(&I, Value); 6334 } 6335 6336 /// See if we can lower a memcmp call into an optimized form. If so, return 6337 /// true and lower it. Otherwise return false, and it will be lowered like a 6338 /// normal call. 6339 /// The caller already checked that \p I calls the appropriate LibFunc with a 6340 /// correct prototype. 6341 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 6342 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 6343 const Value *Size = I.getArgOperand(2); 6344 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 6345 if (CSize && CSize->getZExtValue() == 0) { 6346 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(), 6347 I.getType(), true); 6348 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT)); 6349 return true; 6350 } 6351 6352 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6353 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp( 6354 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS), 6355 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS)); 6356 if (Res.first.getNode()) { 6357 processIntegerCallValue(I, Res.first, true); 6358 PendingLoads.push_back(Res.second); 6359 return true; 6360 } 6361 6362 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 6363 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 6364 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I)) 6365 return false; 6366 6367 // If the target has a fast compare for the given size, it will return a 6368 // preferred load type for that size. Require that the load VT is legal and 6369 // that the target supports unaligned loads of that type. Otherwise, return 6370 // INVALID. 6371 auto hasFastLoadsAndCompare = [&](unsigned NumBits) { 6372 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6373 MVT LVT = TLI.hasFastEqualityCompare(NumBits); 6374 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) { 6375 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 6376 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 6377 // TODO: Check alignment of src and dest ptrs. 6378 unsigned DstAS = LHS->getType()->getPointerAddressSpace(); 6379 unsigned SrcAS = RHS->getType()->getPointerAddressSpace(); 6380 if (!TLI.isTypeLegal(LVT) || 6381 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) || 6382 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS)) 6383 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE; 6384 } 6385 6386 return LVT; 6387 }; 6388 6389 // This turns into unaligned loads. We only do this if the target natively 6390 // supports the MVT we'll be loading or if it is small enough (<= 4) that 6391 // we'll only produce a small number of byte loads. 6392 MVT LoadVT; 6393 unsigned NumBitsToCompare = CSize->getZExtValue() * 8; 6394 switch (NumBitsToCompare) { 6395 default: 6396 return false; 6397 case 16: 6398 LoadVT = MVT::i16; 6399 break; 6400 case 32: 6401 LoadVT = MVT::i32; 6402 break; 6403 case 64: 6404 case 128: 6405 case 256: 6406 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare); 6407 break; 6408 } 6409 6410 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE) 6411 return false; 6412 6413 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this); 6414 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this); 6415 6416 // Bitcast to a wide integer type if the loads are vectors. 6417 if (LoadVT.isVector()) { 6418 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits()); 6419 LoadL = DAG.getBitcast(CmpVT, LoadL); 6420 LoadR = DAG.getBitcast(CmpVT, LoadR); 6421 } 6422 6423 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE); 6424 processIntegerCallValue(I, Cmp, false); 6425 return true; 6426 } 6427 6428 /// See if we can lower a memchr call into an optimized form. If so, return 6429 /// true and lower it. Otherwise return false, and it will be lowered like a 6430 /// normal call. 6431 /// The caller already checked that \p I calls the appropriate LibFunc with a 6432 /// correct prototype. 6433 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 6434 const Value *Src = I.getArgOperand(0); 6435 const Value *Char = I.getArgOperand(1); 6436 const Value *Length = I.getArgOperand(2); 6437 6438 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6439 std::pair<SDValue, SDValue> Res = 6440 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 6441 getValue(Src), getValue(Char), getValue(Length), 6442 MachinePointerInfo(Src)); 6443 if (Res.first.getNode()) { 6444 setValue(&I, Res.first); 6445 PendingLoads.push_back(Res.second); 6446 return true; 6447 } 6448 6449 return false; 6450 } 6451 6452 /// See if we can lower a mempcpy call into an optimized form. If so, return 6453 /// true and lower it. Otherwise return false, and it will be lowered like a 6454 /// normal call. 6455 /// The caller already checked that \p I calls the appropriate LibFunc with a 6456 /// correct prototype. 6457 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) { 6458 SDValue Dst = getValue(I.getArgOperand(0)); 6459 SDValue Src = getValue(I.getArgOperand(1)); 6460 SDValue Size = getValue(I.getArgOperand(2)); 6461 6462 unsigned DstAlign = DAG.InferPtrAlignment(Dst); 6463 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 6464 unsigned Align = std::min(DstAlign, SrcAlign); 6465 if (Align == 0) // Alignment of one or both could not be inferred. 6466 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved. 6467 6468 bool isVol = false; 6469 SDLoc sdl = getCurSDLoc(); 6470 6471 // In the mempcpy context we need to pass in a false value for isTailCall 6472 // because the return pointer needs to be adjusted by the size of 6473 // the copied memory. 6474 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol, 6475 false, /*isTailCall=*/false, 6476 MachinePointerInfo(I.getArgOperand(0)), 6477 MachinePointerInfo(I.getArgOperand(1))); 6478 assert(MC.getNode() != nullptr && 6479 "** memcpy should not be lowered as TailCall in mempcpy context **"); 6480 DAG.setRoot(MC); 6481 6482 // Check if Size needs to be truncated or extended. 6483 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType()); 6484 6485 // Adjust return pointer to point just past the last dst byte. 6486 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(), 6487 Dst, Size); 6488 setValue(&I, DstPlusSize); 6489 return true; 6490 } 6491 6492 /// See if we can lower a strcpy call into an optimized form. If so, return 6493 /// true and lower it, otherwise return false and it will be lowered like a 6494 /// normal call. 6495 /// The caller already checked that \p I calls the appropriate LibFunc with a 6496 /// correct prototype. 6497 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 6498 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6499 6500 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6501 std::pair<SDValue, SDValue> Res = 6502 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 6503 getValue(Arg0), getValue(Arg1), 6504 MachinePointerInfo(Arg0), 6505 MachinePointerInfo(Arg1), isStpcpy); 6506 if (Res.first.getNode()) { 6507 setValue(&I, Res.first); 6508 DAG.setRoot(Res.second); 6509 return true; 6510 } 6511 6512 return false; 6513 } 6514 6515 /// See if we can lower a strcmp call into an optimized form. If so, return 6516 /// true and lower it, otherwise return false and it will be lowered like a 6517 /// normal call. 6518 /// The caller already checked that \p I calls the appropriate LibFunc with a 6519 /// correct prototype. 6520 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 6521 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6522 6523 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6524 std::pair<SDValue, SDValue> Res = 6525 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 6526 getValue(Arg0), getValue(Arg1), 6527 MachinePointerInfo(Arg0), 6528 MachinePointerInfo(Arg1)); 6529 if (Res.first.getNode()) { 6530 processIntegerCallValue(I, Res.first, true); 6531 PendingLoads.push_back(Res.second); 6532 return true; 6533 } 6534 6535 return false; 6536 } 6537 6538 /// See if we can lower a strlen call into an optimized form. If so, return 6539 /// true and lower it, otherwise return false and it will be lowered like a 6540 /// normal call. 6541 /// The caller already checked that \p I calls the appropriate LibFunc with a 6542 /// correct prototype. 6543 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 6544 const Value *Arg0 = I.getArgOperand(0); 6545 6546 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6547 std::pair<SDValue, SDValue> Res = 6548 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 6549 getValue(Arg0), MachinePointerInfo(Arg0)); 6550 if (Res.first.getNode()) { 6551 processIntegerCallValue(I, Res.first, false); 6552 PendingLoads.push_back(Res.second); 6553 return true; 6554 } 6555 6556 return false; 6557 } 6558 6559 /// See if we can lower a strnlen call into an optimized form. If so, return 6560 /// true and lower it, otherwise return false and it will be lowered like a 6561 /// normal call. 6562 /// The caller already checked that \p I calls the appropriate LibFunc with a 6563 /// correct prototype. 6564 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 6565 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 6566 6567 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo(); 6568 std::pair<SDValue, SDValue> Res = 6569 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 6570 getValue(Arg0), getValue(Arg1), 6571 MachinePointerInfo(Arg0)); 6572 if (Res.first.getNode()) { 6573 processIntegerCallValue(I, Res.first, false); 6574 PendingLoads.push_back(Res.second); 6575 return true; 6576 } 6577 6578 return false; 6579 } 6580 6581 /// See if we can lower a unary floating-point operation into an SDNode with 6582 /// the specified Opcode. If so, return true and lower it, otherwise return 6583 /// false and it will be lowered like a normal call. 6584 /// The caller already checked that \p I calls the appropriate LibFunc with a 6585 /// correct prototype. 6586 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 6587 unsigned Opcode) { 6588 // We already checked this call's prototype; verify it doesn't modify errno. 6589 if (!I.onlyReadsMemory()) 6590 return false; 6591 6592 SDValue Tmp = getValue(I.getArgOperand(0)); 6593 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 6594 return true; 6595 } 6596 6597 /// See if we can lower a binary floating-point operation into an SDNode with 6598 /// the specified Opcode. If so, return true and lower it. Otherwise return 6599 /// false, and it will be lowered like a normal call. 6600 /// The caller already checked that \p I calls the appropriate LibFunc with a 6601 /// correct prototype. 6602 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I, 6603 unsigned Opcode) { 6604 // We already checked this call's prototype; verify it doesn't modify errno. 6605 if (!I.onlyReadsMemory()) 6606 return false; 6607 6608 SDValue Tmp0 = getValue(I.getArgOperand(0)); 6609 SDValue Tmp1 = getValue(I.getArgOperand(1)); 6610 EVT VT = Tmp0.getValueType(); 6611 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1)); 6612 return true; 6613 } 6614 6615 void SelectionDAGBuilder::visitCall(const CallInst &I) { 6616 // Handle inline assembly differently. 6617 if (isa<InlineAsm>(I.getCalledValue())) { 6618 visitInlineAsm(&I); 6619 return; 6620 } 6621 6622 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 6623 computeUsesVAFloatArgument(I, MMI); 6624 6625 const char *RenameFn = nullptr; 6626 if (Function *F = I.getCalledFunction()) { 6627 if (F->isDeclaration()) { 6628 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 6629 if (unsigned IID = II->getIntrinsicID(F)) { 6630 RenameFn = visitIntrinsicCall(I, IID); 6631 if (!RenameFn) 6632 return; 6633 } 6634 } 6635 if (Intrinsic::ID IID = F->getIntrinsicID()) { 6636 RenameFn = visitIntrinsicCall(I, IID); 6637 if (!RenameFn) 6638 return; 6639 } 6640 } 6641 6642 // Check for well-known libc/libm calls. If the function is internal, it 6643 // can't be a library call. Don't do the check if marked as nobuiltin for 6644 // some reason or the call site requires strict floating point semantics. 6645 LibFunc Func; 6646 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() && 6647 F->hasName() && LibInfo->getLibFunc(*F, Func) && 6648 LibInfo->hasOptimizedCodeGen(Func)) { 6649 switch (Func) { 6650 default: break; 6651 case LibFunc_copysign: 6652 case LibFunc_copysignf: 6653 case LibFunc_copysignl: 6654 // We already checked this call's prototype; verify it doesn't modify 6655 // errno. 6656 if (I.onlyReadsMemory()) { 6657 SDValue LHS = getValue(I.getArgOperand(0)); 6658 SDValue RHS = getValue(I.getArgOperand(1)); 6659 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 6660 LHS.getValueType(), LHS, RHS)); 6661 return; 6662 } 6663 break; 6664 case LibFunc_fabs: 6665 case LibFunc_fabsf: 6666 case LibFunc_fabsl: 6667 if (visitUnaryFloatCall(I, ISD::FABS)) 6668 return; 6669 break; 6670 case LibFunc_fmin: 6671 case LibFunc_fminf: 6672 case LibFunc_fminl: 6673 if (visitBinaryFloatCall(I, ISD::FMINNUM)) 6674 return; 6675 break; 6676 case LibFunc_fmax: 6677 case LibFunc_fmaxf: 6678 case LibFunc_fmaxl: 6679 if (visitBinaryFloatCall(I, ISD::FMAXNUM)) 6680 return; 6681 break; 6682 case LibFunc_sin: 6683 case LibFunc_sinf: 6684 case LibFunc_sinl: 6685 if (visitUnaryFloatCall(I, ISD::FSIN)) 6686 return; 6687 break; 6688 case LibFunc_cos: 6689 case LibFunc_cosf: 6690 case LibFunc_cosl: 6691 if (visitUnaryFloatCall(I, ISD::FCOS)) 6692 return; 6693 break; 6694 case LibFunc_sqrt: 6695 case LibFunc_sqrtf: 6696 case LibFunc_sqrtl: 6697 case LibFunc_sqrt_finite: 6698 case LibFunc_sqrtf_finite: 6699 case LibFunc_sqrtl_finite: 6700 if (visitUnaryFloatCall(I, ISD::FSQRT)) 6701 return; 6702 break; 6703 case LibFunc_floor: 6704 case LibFunc_floorf: 6705 case LibFunc_floorl: 6706 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 6707 return; 6708 break; 6709 case LibFunc_nearbyint: 6710 case LibFunc_nearbyintf: 6711 case LibFunc_nearbyintl: 6712 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 6713 return; 6714 break; 6715 case LibFunc_ceil: 6716 case LibFunc_ceilf: 6717 case LibFunc_ceill: 6718 if (visitUnaryFloatCall(I, ISD::FCEIL)) 6719 return; 6720 break; 6721 case LibFunc_rint: 6722 case LibFunc_rintf: 6723 case LibFunc_rintl: 6724 if (visitUnaryFloatCall(I, ISD::FRINT)) 6725 return; 6726 break; 6727 case LibFunc_round: 6728 case LibFunc_roundf: 6729 case LibFunc_roundl: 6730 if (visitUnaryFloatCall(I, ISD::FROUND)) 6731 return; 6732 break; 6733 case LibFunc_trunc: 6734 case LibFunc_truncf: 6735 case LibFunc_truncl: 6736 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 6737 return; 6738 break; 6739 case LibFunc_log2: 6740 case LibFunc_log2f: 6741 case LibFunc_log2l: 6742 if (visitUnaryFloatCall(I, ISD::FLOG2)) 6743 return; 6744 break; 6745 case LibFunc_exp2: 6746 case LibFunc_exp2f: 6747 case LibFunc_exp2l: 6748 if (visitUnaryFloatCall(I, ISD::FEXP2)) 6749 return; 6750 break; 6751 case LibFunc_memcmp: 6752 if (visitMemCmpCall(I)) 6753 return; 6754 break; 6755 case LibFunc_mempcpy: 6756 if (visitMemPCpyCall(I)) 6757 return; 6758 break; 6759 case LibFunc_memchr: 6760 if (visitMemChrCall(I)) 6761 return; 6762 break; 6763 case LibFunc_strcpy: 6764 if (visitStrCpyCall(I, false)) 6765 return; 6766 break; 6767 case LibFunc_stpcpy: 6768 if (visitStrCpyCall(I, true)) 6769 return; 6770 break; 6771 case LibFunc_strcmp: 6772 if (visitStrCmpCall(I)) 6773 return; 6774 break; 6775 case LibFunc_strlen: 6776 if (visitStrLenCall(I)) 6777 return; 6778 break; 6779 case LibFunc_strnlen: 6780 if (visitStrNLenCall(I)) 6781 return; 6782 break; 6783 } 6784 } 6785 } 6786 6787 SDValue Callee; 6788 if (!RenameFn) 6789 Callee = getValue(I.getCalledValue()); 6790 else 6791 Callee = DAG.getExternalSymbol( 6792 RenameFn, 6793 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout())); 6794 6795 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't 6796 // have to do anything here to lower funclet bundles. 6797 assert(!I.hasOperandBundlesOtherThan( 6798 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && 6799 "Cannot lower calls with arbitrary operand bundles!"); 6800 6801 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 6802 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr); 6803 else 6804 // Check if we can potentially perform a tail call. More detailed checking 6805 // is be done within LowerCallTo, after more information about the call is 6806 // known. 6807 LowerCallTo(&I, Callee, I.isTailCall()); 6808 } 6809 6810 namespace { 6811 6812 /// AsmOperandInfo - This contains information for each constraint that we are 6813 /// lowering. 6814 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 6815 public: 6816 /// CallOperand - If this is the result output operand or a clobber 6817 /// this is null, otherwise it is the incoming operand to the CallInst. 6818 /// This gets modified as the asm is processed. 6819 SDValue CallOperand; 6820 6821 /// AssignedRegs - If this is a register or register class operand, this 6822 /// contains the set of register corresponding to the operand. 6823 RegsForValue AssignedRegs; 6824 6825 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 6826 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) { 6827 } 6828 6829 /// Whether or not this operand accesses memory 6830 bool hasMemory(const TargetLowering &TLI) const { 6831 // Indirect operand accesses access memory. 6832 if (isIndirect) 6833 return true; 6834 6835 for (const auto &Code : Codes) 6836 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory) 6837 return true; 6838 6839 return false; 6840 } 6841 6842 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 6843 /// corresponds to. If there is no Value* for this operand, it returns 6844 /// MVT::Other. 6845 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI, 6846 const DataLayout &DL) const { 6847 if (!CallOperandVal) return MVT::Other; 6848 6849 if (isa<BasicBlock>(CallOperandVal)) 6850 return TLI.getPointerTy(DL); 6851 6852 llvm::Type *OpTy = CallOperandVal->getType(); 6853 6854 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 6855 // If this is an indirect operand, the operand is a pointer to the 6856 // accessed type. 6857 if (isIndirect) { 6858 PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 6859 if (!PtrTy) 6860 report_fatal_error("Indirect operand for inline asm not a pointer!"); 6861 OpTy = PtrTy->getElementType(); 6862 } 6863 6864 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 6865 if (StructType *STy = dyn_cast<StructType>(OpTy)) 6866 if (STy->getNumElements() == 1) 6867 OpTy = STy->getElementType(0); 6868 6869 // If OpTy is not a single value, it may be a struct/union that we 6870 // can tile with integers. 6871 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 6872 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 6873 switch (BitSize) { 6874 default: break; 6875 case 1: 6876 case 8: 6877 case 16: 6878 case 32: 6879 case 64: 6880 case 128: 6881 OpTy = IntegerType::get(Context, BitSize); 6882 break; 6883 } 6884 } 6885 6886 return TLI.getValueType(DL, OpTy, true); 6887 } 6888 }; 6889 6890 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>; 6891 6892 } // end anonymous namespace 6893 6894 /// Make sure that the output operand \p OpInfo and its corresponding input 6895 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error 6896 /// out). 6897 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo, 6898 SDISelAsmOperandInfo &MatchingOpInfo, 6899 SelectionDAG &DAG) { 6900 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT) 6901 return; 6902 6903 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo(); 6904 const auto &TLI = DAG.getTargetLoweringInfo(); 6905 6906 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 6907 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 6908 OpInfo.ConstraintVT); 6909 std::pair<unsigned, const TargetRegisterClass *> InputRC = 6910 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode, 6911 MatchingOpInfo.ConstraintVT); 6912 if ((OpInfo.ConstraintVT.isInteger() != 6913 MatchingOpInfo.ConstraintVT.isInteger()) || 6914 (MatchRC.second != InputRC.second)) { 6915 // FIXME: error out in a more elegant fashion 6916 report_fatal_error("Unsupported asm: input constraint" 6917 " with a matching output constraint of" 6918 " incompatible type!"); 6919 } 6920 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT; 6921 } 6922 6923 /// Get a direct memory input to behave well as an indirect operand. 6924 /// This may introduce stores, hence the need for a \p Chain. 6925 /// \return The (possibly updated) chain. 6926 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location, 6927 SDISelAsmOperandInfo &OpInfo, 6928 SelectionDAG &DAG) { 6929 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6930 6931 // If we don't have an indirect input, put it in the constpool if we can, 6932 // otherwise spill it to a stack slot. 6933 // TODO: This isn't quite right. We need to handle these according to 6934 // the addressing mode that the constraint wants. Also, this may take 6935 // an additional register for the computation and we don't want that 6936 // either. 6937 6938 // If the operand is a float, integer, or vector constant, spill to a 6939 // constant pool entry to get its address. 6940 const Value *OpVal = OpInfo.CallOperandVal; 6941 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 6942 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 6943 OpInfo.CallOperand = DAG.getConstantPool( 6944 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout())); 6945 return Chain; 6946 } 6947 6948 // Otherwise, create a stack slot and emit a store to it before the asm. 6949 Type *Ty = OpVal->getType(); 6950 auto &DL = DAG.getDataLayout(); 6951 uint64_t TySize = DL.getTypeAllocSize(Ty); 6952 unsigned Align = DL.getPrefTypeAlignment(Ty); 6953 MachineFunction &MF = DAG.getMachineFunction(); 6954 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 6955 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL)); 6956 Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot, 6957 MachinePointerInfo::getFixedStack(MF, SSFI)); 6958 OpInfo.CallOperand = StackSlot; 6959 6960 return Chain; 6961 } 6962 6963 /// GetRegistersForValue - Assign registers (virtual or physical) for the 6964 /// specified operand. We prefer to assign virtual registers, to allow the 6965 /// register allocator to handle the assignment process. However, if the asm 6966 /// uses features that we can't model on machineinstrs, we have SDISel do the 6967 /// allocation. This produces generally horrible, but correct, code. 6968 /// 6969 /// OpInfo describes the operand. 6970 static void GetRegistersForValue(SelectionDAG &DAG, const TargetLowering &TLI, 6971 const SDLoc &DL, 6972 SDISelAsmOperandInfo &OpInfo) { 6973 LLVMContext &Context = *DAG.getContext(); 6974 6975 MachineFunction &MF = DAG.getMachineFunction(); 6976 SmallVector<unsigned, 4> Regs; 6977 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 6978 6979 // If this is a constraint for a single physreg, or a constraint for a 6980 // register class, find it. 6981 std::pair<unsigned, const TargetRegisterClass *> PhysReg = 6982 TLI.getRegForInlineAsmConstraint(&TRI, OpInfo.ConstraintCode, 6983 OpInfo.ConstraintVT); 6984 6985 unsigned NumRegs = 1; 6986 if (OpInfo.ConstraintVT != MVT::Other) { 6987 // If this is a FP input in an integer register (or visa versa) insert a bit 6988 // cast of the input value. More generally, handle any case where the input 6989 // value disagrees with the register class we plan to stick this in. 6990 if (OpInfo.Type == InlineAsm::isInput && PhysReg.second && 6991 !TRI.isTypeLegalForClass(*PhysReg.second, OpInfo.ConstraintVT)) { 6992 // Try to convert to the first EVT that the reg class contains. If the 6993 // types are identical size, use a bitcast to convert (e.g. two differing 6994 // vector types). 6995 MVT RegVT = *TRI.legalclasstypes_begin(*PhysReg.second); 6996 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) { 6997 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 6998 RegVT, OpInfo.CallOperand); 6999 OpInfo.ConstraintVT = RegVT; 7000 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 7001 // If the input is a FP value and we want it in FP registers, do a 7002 // bitcast to the corresponding integer type. This turns an f64 value 7003 // into i64, which can be passed with two i32 values on a 32-bit 7004 // machine. 7005 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 7006 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 7007 RegVT, OpInfo.CallOperand); 7008 OpInfo.ConstraintVT = RegVT; 7009 } 7010 } 7011 7012 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 7013 } 7014 7015 MVT RegVT; 7016 EVT ValueVT = OpInfo.ConstraintVT; 7017 7018 // If this is a constraint for a specific physical register, like {r17}, 7019 // assign it now. 7020 if (unsigned AssignedReg = PhysReg.first) { 7021 const TargetRegisterClass *RC = PhysReg.second; 7022 if (OpInfo.ConstraintVT == MVT::Other) 7023 ValueVT = *TRI.legalclasstypes_begin(*RC); 7024 7025 // Get the actual register value type. This is important, because the user 7026 // may have asked for (e.g.) the AX register in i32 type. We need to 7027 // remember that AX is actually i16 to get the right extension. 7028 RegVT = *TRI.legalclasstypes_begin(*RC); 7029 7030 // This is a explicit reference to a physical register. 7031 Regs.push_back(AssignedReg); 7032 7033 // If this is an expanded reference, add the rest of the regs to Regs. 7034 if (NumRegs != 1) { 7035 TargetRegisterClass::iterator I = RC->begin(); 7036 for (; *I != AssignedReg; ++I) 7037 assert(I != RC->end() && "Didn't find reg!"); 7038 7039 // Already added the first reg. 7040 --NumRegs; ++I; 7041 for (; NumRegs; --NumRegs, ++I) { 7042 assert(I != RC->end() && "Ran out of registers to allocate!"); 7043 Regs.push_back(*I); 7044 } 7045 } 7046 7047 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7048 return; 7049 } 7050 7051 // Otherwise, if this was a reference to an LLVM register class, create vregs 7052 // for this reference. 7053 if (const TargetRegisterClass *RC = PhysReg.second) { 7054 RegVT = *TRI.legalclasstypes_begin(*RC); 7055 if (OpInfo.ConstraintVT == MVT::Other) 7056 ValueVT = RegVT; 7057 7058 // Create the appropriate number of virtual registers. 7059 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 7060 for (; NumRegs; --NumRegs) 7061 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7062 7063 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 7064 return; 7065 } 7066 7067 // Otherwise, we couldn't allocate enough registers for this. 7068 } 7069 7070 static unsigned 7071 findMatchingInlineAsmOperand(unsigned OperandNo, 7072 const std::vector<SDValue> &AsmNodeOperands) { 7073 // Scan until we find the definition we already emitted of this operand. 7074 unsigned CurOp = InlineAsm::Op_FirstOperand; 7075 for (; OperandNo; --OperandNo) { 7076 // Advance to the next operand. 7077 unsigned OpFlag = 7078 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7079 assert((InlineAsm::isRegDefKind(OpFlag) || 7080 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 7081 InlineAsm::isMemKind(OpFlag)) && 7082 "Skipped past definitions?"); 7083 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1; 7084 } 7085 return CurOp; 7086 } 7087 7088 /// Fill \p Regs with \p NumRegs new virtual registers of type \p RegVT 7089 /// \return true if it has succeeded, false otherwise 7090 static bool createVirtualRegs(SmallVector<unsigned, 4> &Regs, unsigned NumRegs, 7091 MVT RegVT, SelectionDAG &DAG) { 7092 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7093 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 7094 for (unsigned i = 0, e = NumRegs; i != e; ++i) { 7095 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) 7096 Regs.push_back(RegInfo.createVirtualRegister(RC)); 7097 else 7098 return false; 7099 } 7100 return true; 7101 } 7102 7103 namespace { 7104 7105 class ExtraFlags { 7106 unsigned Flags = 0; 7107 7108 public: 7109 explicit ExtraFlags(ImmutableCallSite CS) { 7110 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7111 if (IA->hasSideEffects()) 7112 Flags |= InlineAsm::Extra_HasSideEffects; 7113 if (IA->isAlignStack()) 7114 Flags |= InlineAsm::Extra_IsAlignStack; 7115 if (CS.isConvergent()) 7116 Flags |= InlineAsm::Extra_IsConvergent; 7117 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 7118 } 7119 7120 void update(const TargetLowering::AsmOperandInfo &OpInfo) { 7121 // Ideally, we would only check against memory constraints. However, the 7122 // meaning of an Other constraint can be target-specific and we can't easily 7123 // reason about it. Therefore, be conservative and set MayLoad/MayStore 7124 // for Other constraints as well. 7125 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 7126 OpInfo.ConstraintType == TargetLowering::C_Other) { 7127 if (OpInfo.Type == InlineAsm::isInput) 7128 Flags |= InlineAsm::Extra_MayLoad; 7129 else if (OpInfo.Type == InlineAsm::isOutput) 7130 Flags |= InlineAsm::Extra_MayStore; 7131 else if (OpInfo.Type == InlineAsm::isClobber) 7132 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 7133 } 7134 } 7135 7136 unsigned get() const { return Flags; } 7137 }; 7138 7139 } // end anonymous namespace 7140 7141 /// visitInlineAsm - Handle a call to an InlineAsm object. 7142 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 7143 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 7144 7145 /// ConstraintOperands - Information about all of the constraints. 7146 SDISelAsmOperandInfoVector ConstraintOperands; 7147 7148 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7149 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints( 7150 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS); 7151 7152 bool hasMemory = false; 7153 7154 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7155 ExtraFlags ExtraInfo(CS); 7156 7157 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 7158 unsigned ResNo = 0; // ResNo - The result number of the next output. 7159 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 7160 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 7161 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 7162 7163 MVT OpVT = MVT::Other; 7164 7165 // Compute the value type for each operand. 7166 if (OpInfo.Type == InlineAsm::isInput || 7167 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) { 7168 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 7169 7170 // Process the call argument. BasicBlocks are labels, currently appearing 7171 // only in asm's. 7172 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 7173 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 7174 } else { 7175 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 7176 } 7177 7178 OpVT = 7179 OpInfo 7180 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout()) 7181 .getSimpleVT(); 7182 } 7183 7184 if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) { 7185 // The return value of the call is this value. As such, there is no 7186 // corresponding argument. 7187 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7188 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 7189 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), 7190 STy->getElementType(ResNo)); 7191 } else { 7192 assert(ResNo == 0 && "Asm only has one result!"); 7193 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType()); 7194 } 7195 ++ResNo; 7196 } 7197 7198 OpInfo.ConstraintVT = OpVT; 7199 7200 if (!hasMemory) 7201 hasMemory = OpInfo.hasMemory(TLI); 7202 7203 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 7204 // FIXME: Could we compute this on OpInfo rather than TargetConstraints[i]? 7205 auto TargetConstraint = TargetConstraints[i]; 7206 7207 // Compute the constraint code and ConstraintType to use. 7208 TLI.ComputeConstraintToUse(TargetConstraint, SDValue()); 7209 7210 ExtraInfo.update(TargetConstraint); 7211 } 7212 7213 SDValue Chain, Flag; 7214 7215 // We won't need to flush pending loads if this asm doesn't touch 7216 // memory and is nonvolatile. 7217 if (hasMemory || IA->hasSideEffects()) 7218 Chain = getRoot(); 7219 else 7220 Chain = DAG.getRoot(); 7221 7222 // Second pass over the constraints: compute which constraint option to use 7223 // and assign registers to constraints that want a specific physreg. 7224 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7225 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7226 7227 // If this is an output operand with a matching input operand, look up the 7228 // matching input. If their types mismatch, e.g. one is an integer, the 7229 // other is floating point, or their sizes are different, flag it as an 7230 // error. 7231 if (OpInfo.hasMatchingInput()) { 7232 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 7233 patchMatchingInput(OpInfo, Input, DAG); 7234 } 7235 7236 // Compute the constraint code and ConstraintType to use. 7237 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 7238 7239 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7240 OpInfo.Type == InlineAsm::isClobber) 7241 continue; 7242 7243 // If this is a memory input, and if the operand is not indirect, do what we 7244 // need to to provide an address for the memory input. 7245 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 7246 !OpInfo.isIndirect) { 7247 assert((OpInfo.isMultipleAlternative || 7248 (OpInfo.Type == InlineAsm::isInput)) && 7249 "Can only indirectify direct input operands!"); 7250 7251 // Memory operands really want the address of the value. 7252 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG); 7253 7254 // There is no longer a Value* corresponding to this operand. 7255 OpInfo.CallOperandVal = nullptr; 7256 7257 // It is now an indirect operand. 7258 OpInfo.isIndirect = true; 7259 } 7260 7261 // If this constraint is for a specific register, allocate it before 7262 // anything else. 7263 if (OpInfo.ConstraintType == TargetLowering::C_Register) 7264 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7265 } 7266 7267 // Third pass - Loop over all of the operands, assigning virtual or physregs 7268 // to register class operands. 7269 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7270 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7271 7272 // C_Register operands have already been allocated, Other/Memory don't need 7273 // to be. 7274 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 7275 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo); 7276 } 7277 7278 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 7279 std::vector<SDValue> AsmNodeOperands; 7280 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 7281 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol( 7282 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout()))); 7283 7284 // If we have a !srcloc metadata node associated with it, we want to attach 7285 // this to the ultimately generated inline asm machineinstr. To do this, we 7286 // pass in the third operand as this (potentially null) inline asm MDNode. 7287 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 7288 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 7289 7290 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 7291 // bits as operand 3. 7292 AsmNodeOperands.push_back(DAG.getTargetConstant( 7293 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7294 7295 // Loop over all of the inputs, copying the operand values into the 7296 // appropriate registers and processing the output regs. 7297 RegsForValue RetValRegs; 7298 7299 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 7300 std::vector<std::pair<RegsForValue, Value *>> IndirectStoresToEmit; 7301 7302 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 7303 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 7304 7305 switch (OpInfo.Type) { 7306 case InlineAsm::isOutput: 7307 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 7308 OpInfo.ConstraintType != TargetLowering::C_Register) { 7309 // Memory output, or 'other' output (e.g. 'X' constraint). 7310 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 7311 7312 unsigned ConstraintID = 7313 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7314 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7315 "Failed to convert memory constraint code to constraint id."); 7316 7317 // Add information to the INLINEASM node to know about this output. 7318 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7319 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID); 7320 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(), 7321 MVT::i32)); 7322 AsmNodeOperands.push_back(OpInfo.CallOperand); 7323 break; 7324 } 7325 7326 // Otherwise, this is a register or register class output. 7327 7328 // Copy the output from the appropriate register. Find a register that 7329 // we can use. 7330 if (OpInfo.AssignedRegs.Regs.empty()) { 7331 emitInlineAsmError( 7332 CS, "couldn't allocate output register for constraint '" + 7333 Twine(OpInfo.ConstraintCode) + "'"); 7334 return; 7335 } 7336 7337 // If this is an indirect operand, store through the pointer after the 7338 // asm. 7339 if (OpInfo.isIndirect) { 7340 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 7341 OpInfo.CallOperandVal)); 7342 } else { 7343 // This is the result value of the call. 7344 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 7345 // Concatenate this output onto the outputs list. 7346 RetValRegs.append(OpInfo.AssignedRegs); 7347 } 7348 7349 // Add information to the INLINEASM node to know that this register is 7350 // set. 7351 OpInfo.AssignedRegs 7352 .AddInlineAsmOperands(OpInfo.isEarlyClobber 7353 ? InlineAsm::Kind_RegDefEarlyClobber 7354 : InlineAsm::Kind_RegDef, 7355 false, 0, getCurSDLoc(), DAG, AsmNodeOperands); 7356 break; 7357 7358 case InlineAsm::isInput: { 7359 SDValue InOperandVal = OpInfo.CallOperand; 7360 7361 if (OpInfo.isMatchingInputConstraint()) { 7362 // If this is required to match an output register we have already set, 7363 // just use its register. 7364 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(), 7365 AsmNodeOperands); 7366 unsigned OpFlag = 7367 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 7368 if (InlineAsm::isRegDefKind(OpFlag) || 7369 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 7370 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 7371 if (OpInfo.isIndirect) { 7372 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 7373 emitInlineAsmError(CS, "inline asm not supported yet:" 7374 " don't know how to handle tied " 7375 "indirect register inputs"); 7376 return; 7377 } 7378 7379 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 7380 SmallVector<unsigned, 4> Regs; 7381 7382 if (!createVirtualRegs(Regs, 7383 InlineAsm::getNumOperandRegisters(OpFlag), 7384 RegVT, DAG)) { 7385 emitInlineAsmError(CS, "inline asm error: This value type register " 7386 "class is not natively supported!"); 7387 return; 7388 } 7389 7390 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType()); 7391 7392 SDLoc dl = getCurSDLoc(); 7393 // Use the produced MatchedRegs object to 7394 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, 7395 CS.getInstruction()); 7396 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 7397 true, OpInfo.getMatchedOperand(), dl, 7398 DAG, AsmNodeOperands); 7399 break; 7400 } 7401 7402 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 7403 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 7404 "Unexpected number of operands"); 7405 // Add information to the INLINEASM node to know about this input. 7406 // See InlineAsm.h isUseOperandTiedToDef. 7407 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag); 7408 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 7409 OpInfo.getMatchedOperand()); 7410 AsmNodeOperands.push_back(DAG.getTargetConstant( 7411 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7412 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 7413 break; 7414 } 7415 7416 // Treat indirect 'X' constraint as memory. 7417 if (OpInfo.ConstraintType == TargetLowering::C_Other && 7418 OpInfo.isIndirect) 7419 OpInfo.ConstraintType = TargetLowering::C_Memory; 7420 7421 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 7422 std::vector<SDValue> Ops; 7423 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 7424 Ops, DAG); 7425 if (Ops.empty()) { 7426 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" + 7427 Twine(OpInfo.ConstraintCode) + "'"); 7428 return; 7429 } 7430 7431 // Add information to the INLINEASM node to know about this input. 7432 unsigned ResOpType = 7433 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 7434 AsmNodeOperands.push_back(DAG.getTargetConstant( 7435 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout()))); 7436 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 7437 break; 7438 } 7439 7440 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 7441 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 7442 assert(InOperandVal.getValueType() == 7443 TLI.getPointerTy(DAG.getDataLayout()) && 7444 "Memory operands expect pointer values"); 7445 7446 unsigned ConstraintID = 7447 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode); 7448 assert(ConstraintID != InlineAsm::Constraint_Unknown && 7449 "Failed to convert memory constraint code to constraint id."); 7450 7451 // Add information to the INLINEASM node to know about this input. 7452 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 7453 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID); 7454 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 7455 getCurSDLoc(), 7456 MVT::i32)); 7457 AsmNodeOperands.push_back(InOperandVal); 7458 break; 7459 } 7460 7461 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 7462 OpInfo.ConstraintType == TargetLowering::C_Register) && 7463 "Unknown constraint type!"); 7464 7465 // TODO: Support this. 7466 if (OpInfo.isIndirect) { 7467 emitInlineAsmError( 7468 CS, "Don't know how to handle indirect register inputs yet " 7469 "for constraint '" + 7470 Twine(OpInfo.ConstraintCode) + "'"); 7471 return; 7472 } 7473 7474 // Copy the input into the appropriate registers. 7475 if (OpInfo.AssignedRegs.Regs.empty()) { 7476 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" + 7477 Twine(OpInfo.ConstraintCode) + "'"); 7478 return; 7479 } 7480 7481 SDLoc dl = getCurSDLoc(); 7482 7483 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, 7484 Chain, &Flag, CS.getInstruction()); 7485 7486 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 7487 dl, DAG, AsmNodeOperands); 7488 break; 7489 } 7490 case InlineAsm::isClobber: 7491 // Add the clobbered value to the operand list, so that the register 7492 // allocator is aware that the physreg got clobbered. 7493 if (!OpInfo.AssignedRegs.Regs.empty()) 7494 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 7495 false, 0, getCurSDLoc(), DAG, 7496 AsmNodeOperands); 7497 break; 7498 } 7499 } 7500 7501 // Finish up input operands. Set the input chain and add the flag last. 7502 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 7503 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 7504 7505 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 7506 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands); 7507 Flag = Chain.getValue(1); 7508 7509 // If this asm returns a register value, copy the result from that register 7510 // and set it as the value of the call. 7511 if (!RetValRegs.Regs.empty()) { 7512 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7513 Chain, &Flag, CS.getInstruction()); 7514 7515 // FIXME: Why don't we do this for inline asms with MRVs? 7516 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 7517 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7518 7519 // If any of the results of the inline asm is a vector, it may have the 7520 // wrong width/num elts. This can happen for register classes that can 7521 // contain multiple different value types. The preg or vreg allocated may 7522 // not have the same VT as was expected. Convert it to the right type 7523 // with bit_convert. 7524 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 7525 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 7526 ResultType, Val); 7527 7528 } else if (ResultType != Val.getValueType() && 7529 ResultType.isInteger() && Val.getValueType().isInteger()) { 7530 // If a result value was tied to an input value, the computed result may 7531 // have a wider width than the expected result. Extract the relevant 7532 // portion. 7533 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 7534 } 7535 7536 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 7537 } 7538 7539 setValue(CS.getInstruction(), Val); 7540 // Don't need to use this as a chain in this case. 7541 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 7542 return; 7543 } 7544 7545 std::vector<std::pair<SDValue, const Value *>> StoresToEmit; 7546 7547 // Process indirect outputs, first output all of the flagged copies out of 7548 // physregs. 7549 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 7550 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 7551 const Value *Ptr = IndirectStoresToEmit[i].second; 7552 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 7553 Chain, &Flag, IA); 7554 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 7555 } 7556 7557 // Emit the non-flagged stores from the physregs. 7558 SmallVector<SDValue, 8> OutChains; 7559 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 7560 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), StoresToEmit[i].first, 7561 getValue(StoresToEmit[i].second), 7562 MachinePointerInfo(StoresToEmit[i].second)); 7563 OutChains.push_back(Val); 7564 } 7565 7566 if (!OutChains.empty()) 7567 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains); 7568 7569 DAG.setRoot(Chain); 7570 } 7571 7572 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS, 7573 const Twine &Message) { 7574 LLVMContext &Ctx = *DAG.getContext(); 7575 Ctx.emitError(CS.getInstruction(), Message); 7576 7577 // Make sure we leave the DAG in a valid state 7578 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7579 auto VT = TLI.getValueType(DAG.getDataLayout(), CS.getType()); 7580 setValue(CS.getInstruction(), DAG.getUNDEF(VT)); 7581 } 7582 7583 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 7584 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 7585 MVT::Other, getRoot(), 7586 getValue(I.getArgOperand(0)), 7587 DAG.getSrcValue(I.getArgOperand(0)))); 7588 } 7589 7590 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 7591 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7592 const DataLayout &DL = DAG.getDataLayout(); 7593 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()), 7594 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)), 7595 DAG.getSrcValue(I.getOperand(0)), 7596 DL.getABITypeAlignment(I.getType())); 7597 setValue(&I, V); 7598 DAG.setRoot(V.getValue(1)); 7599 } 7600 7601 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 7602 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 7603 MVT::Other, getRoot(), 7604 getValue(I.getArgOperand(0)), 7605 DAG.getSrcValue(I.getArgOperand(0)))); 7606 } 7607 7608 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 7609 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 7610 MVT::Other, getRoot(), 7611 getValue(I.getArgOperand(0)), 7612 getValue(I.getArgOperand(1)), 7613 DAG.getSrcValue(I.getArgOperand(0)), 7614 DAG.getSrcValue(I.getArgOperand(1)))); 7615 } 7616 7617 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG, 7618 const Instruction &I, 7619 SDValue Op) { 7620 const MDNode *Range = I.getMetadata(LLVMContext::MD_range); 7621 if (!Range) 7622 return Op; 7623 7624 ConstantRange CR = getConstantRangeFromMetadata(*Range); 7625 if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet()) 7626 return Op; 7627 7628 APInt Lo = CR.getUnsignedMin(); 7629 if (!Lo.isMinValue()) 7630 return Op; 7631 7632 APInt Hi = CR.getUnsignedMax(); 7633 unsigned Bits = Hi.getActiveBits(); 7634 7635 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7636 7637 SDLoc SL = getCurSDLoc(); 7638 7639 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op, 7640 DAG.getValueType(SmallVT)); 7641 unsigned NumVals = Op.getNode()->getNumValues(); 7642 if (NumVals == 1) 7643 return ZExt; 7644 7645 SmallVector<SDValue, 4> Ops; 7646 7647 Ops.push_back(ZExt); 7648 for (unsigned I = 1; I != NumVals; ++I) 7649 Ops.push_back(Op.getValue(I)); 7650 7651 return DAG.getMergeValues(Ops, SL); 7652 } 7653 7654 /// \brief Populate a CallLowerinInfo (into \p CLI) based on the properties of 7655 /// the call being lowered. 7656 /// 7657 /// This is a helper for lowering intrinsics that follow a target calling 7658 /// convention or require stack pointer adjustment. Only a subset of the 7659 /// intrinsic's operands need to participate in the calling convention. 7660 void SelectionDAGBuilder::populateCallLoweringInfo( 7661 TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS, 7662 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy, 7663 bool IsPatchPoint) { 7664 TargetLowering::ArgListTy Args; 7665 Args.reserve(NumArgs); 7666 7667 // Populate the argument list. 7668 // Attributes for args start at offset 1, after the return attribute. 7669 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; 7670 ArgI != ArgE; ++ArgI) { 7671 const Value *V = CS->getOperand(ArgI); 7672 7673 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic."); 7674 7675 TargetLowering::ArgListEntry Entry; 7676 Entry.Node = getValue(V); 7677 Entry.Ty = V->getType(); 7678 Entry.setAttributes(&CS, ArgIdx); 7679 Args.push_back(Entry); 7680 } 7681 7682 CLI.setDebugLoc(getCurSDLoc()) 7683 .setChain(getRoot()) 7684 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args)) 7685 .setDiscardResult(CS->use_empty()) 7686 .setIsPatchPoint(IsPatchPoint); 7687 } 7688 7689 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap 7690 /// or patchpoint target node's operand list. 7691 /// 7692 /// Constants are converted to TargetConstants purely as an optimization to 7693 /// avoid constant materialization and register allocation. 7694 /// 7695 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not 7696 /// generate addess computation nodes, and so ExpandISelPseudo can convert the 7697 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids 7698 /// address materialization and register allocation, but may also be required 7699 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an 7700 /// alloca in the entry block, then the runtime may assume that the alloca's 7701 /// StackMap location can be read immediately after compilation and that the 7702 /// location is valid at any point during execution (this is similar to the 7703 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were 7704 /// only available in a register, then the runtime would need to trap when 7705 /// execution reaches the StackMap in order to read the alloca's location. 7706 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx, 7707 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops, 7708 SelectionDAGBuilder &Builder) { 7709 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) { 7710 SDValue OpVal = Builder.getValue(CS.getArgument(i)); 7711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) { 7712 Ops.push_back( 7713 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64)); 7714 Ops.push_back( 7715 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64)); 7716 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) { 7717 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo(); 7718 Ops.push_back(Builder.DAG.getTargetFrameIndex( 7719 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout()))); 7720 } else 7721 Ops.push_back(OpVal); 7722 } 7723 } 7724 7725 /// \brief Lower llvm.experimental.stackmap directly to its target opcode. 7726 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) { 7727 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>, 7728 // [live variables...]) 7729 7730 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value."); 7731 7732 SDValue Chain, InFlag, Callee, NullPtr; 7733 SmallVector<SDValue, 32> Ops; 7734 7735 SDLoc DL = getCurSDLoc(); 7736 Callee = getValue(CI.getCalledValue()); 7737 NullPtr = DAG.getIntPtrConstant(0, DL, true); 7738 7739 // The stackmap intrinsic only records the live variables (the arguemnts 7740 // passed to it) and emits NOPS (if requested). Unlike the patchpoint 7741 // intrinsic, this won't be lowered to a function call. This means we don't 7742 // have to worry about calling conventions and target specific lowering code. 7743 // Instead we perform the call lowering right here. 7744 // 7745 // chain, flag = CALLSEQ_START(chain, 0, 0) 7746 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag) 7747 // chain, flag = CALLSEQ_END(chain, 0, 0, flag) 7748 // 7749 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL); 7750 InFlag = Chain.getValue(1); 7751 7752 // Add the <id> and <numBytes> constants. 7753 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos)); 7754 Ops.push_back(DAG.getTargetConstant( 7755 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64)); 7756 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos)); 7757 Ops.push_back(DAG.getTargetConstant( 7758 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL, 7759 MVT::i32)); 7760 7761 // Push live variables for the stack map. 7762 addStackMapLiveVars(&CI, 2, DL, Ops, *this); 7763 7764 // We are not pushing any register mask info here on the operands list, 7765 // because the stackmap doesn't clobber anything. 7766 7767 // Push the chain and the glue flag. 7768 Ops.push_back(Chain); 7769 Ops.push_back(InFlag); 7770 7771 // Create the STACKMAP node. 7772 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7773 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops); 7774 Chain = SDValue(SM, 0); 7775 InFlag = Chain.getValue(1); 7776 7777 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL); 7778 7779 // Stackmaps don't generate values, so nothing goes into the NodeMap. 7780 7781 // Set the root to the target-lowered call chain. 7782 DAG.setRoot(Chain); 7783 7784 // Inform the Frame Information that we have a stackmap in this function. 7785 FuncInfo.MF->getFrameInfo().setHasStackMap(); 7786 } 7787 7788 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode. 7789 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS, 7790 const BasicBlock *EHPadBB) { 7791 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>, 7792 // i32 <numBytes>, 7793 // i8* <target>, 7794 // i32 <numArgs>, 7795 // [Args...], 7796 // [live variables...]) 7797 7798 CallingConv::ID CC = CS.getCallingConv(); 7799 bool IsAnyRegCC = CC == CallingConv::AnyReg; 7800 bool HasDef = !CS->getType()->isVoidTy(); 7801 SDLoc dl = getCurSDLoc(); 7802 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos)); 7803 7804 // Handle immediate and symbolic callees. 7805 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee)) 7806 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl, 7807 /*isTarget=*/true); 7808 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee)) 7809 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(), 7810 SDLoc(SymbolicCallee), 7811 SymbolicCallee->getValueType(0)); 7812 7813 // Get the real number of arguments participating in the call <numArgs> 7814 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos)); 7815 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue(); 7816 7817 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs> 7818 // Intrinsics include all meta-operands up to but not including CC. 7819 unsigned NumMetaOpers = PatchPointOpers::CCPos; 7820 assert(CS.arg_size() >= NumMetaOpers + NumArgs && 7821 "Not enough arguments provided to the patchpoint intrinsic"); 7822 7823 // For AnyRegCC the arguments are lowered later on manually. 7824 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs; 7825 Type *ReturnTy = 7826 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType(); 7827 7828 TargetLowering::CallLoweringInfo CLI(DAG); 7829 populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, 7830 true); 7831 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB); 7832 7833 SDNode *CallEnd = Result.second.getNode(); 7834 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg)) 7835 CallEnd = CallEnd->getOperand(0).getNode(); 7836 7837 /// Get a call instruction from the call sequence chain. 7838 /// Tail calls are not allowed. 7839 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END && 7840 "Expected a callseq node."); 7841 SDNode *Call = CallEnd->getOperand(0).getNode(); 7842 bool HasGlue = Call->getGluedNode(); 7843 7844 // Replace the target specific call node with the patchable intrinsic. 7845 SmallVector<SDValue, 8> Ops; 7846 7847 // Add the <id> and <numBytes> constants. 7848 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos)); 7849 Ops.push_back(DAG.getTargetConstant( 7850 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64)); 7851 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos)); 7852 Ops.push_back(DAG.getTargetConstant( 7853 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl, 7854 MVT::i32)); 7855 7856 // Add the callee. 7857 Ops.push_back(Callee); 7858 7859 // Adjust <numArgs> to account for any arguments that have been passed on the 7860 // stack instead. 7861 // Call Node: Chain, Target, {Args}, RegMask, [Glue] 7862 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3); 7863 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs; 7864 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32)); 7865 7866 // Add the calling convention 7867 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32)); 7868 7869 // Add the arguments we omitted previously. The register allocator should 7870 // place these in any free register. 7871 if (IsAnyRegCC) 7872 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) 7873 Ops.push_back(getValue(CS.getArgument(i))); 7874 7875 // Push the arguments from the call instruction up to the register mask. 7876 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1; 7877 Ops.append(Call->op_begin() + 2, e); 7878 7879 // Push live variables for the stack map. 7880 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this); 7881 7882 // Push the register mask info. 7883 if (HasGlue) 7884 Ops.push_back(*(Call->op_end()-2)); 7885 else 7886 Ops.push_back(*(Call->op_end()-1)); 7887 7888 // Push the chain (this is originally the first operand of the call, but 7889 // becomes now the last or second to last operand). 7890 Ops.push_back(*(Call->op_begin())); 7891 7892 // Push the glue flag (last operand). 7893 if (HasGlue) 7894 Ops.push_back(*(Call->op_end()-1)); 7895 7896 SDVTList NodeTys; 7897 if (IsAnyRegCC && HasDef) { 7898 // Create the return types based on the intrinsic definition 7899 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7900 SmallVector<EVT, 3> ValueVTs; 7901 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs); 7902 assert(ValueVTs.size() == 1 && "Expected only one return value type."); 7903 7904 // There is always a chain and a glue type at the end 7905 ValueVTs.push_back(MVT::Other); 7906 ValueVTs.push_back(MVT::Glue); 7907 NodeTys = DAG.getVTList(ValueVTs); 7908 } else 7909 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 7910 7911 // Replace the target specific call node with a PATCHPOINT node. 7912 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT, 7913 dl, NodeTys, Ops); 7914 7915 // Update the NodeMap. 7916 if (HasDef) { 7917 if (IsAnyRegCC) 7918 setValue(CS.getInstruction(), SDValue(MN, 0)); 7919 else 7920 setValue(CS.getInstruction(), Result.first); 7921 } 7922 7923 // Fixup the consumers of the intrinsic. The chain and glue may be used in the 7924 // call sequence. Furthermore the location of the chain and glue can change 7925 // when the AnyReg calling convention is used and the intrinsic returns a 7926 // value. 7927 if (IsAnyRegCC && HasDef) { 7928 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)}; 7929 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)}; 7930 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 7931 } else 7932 DAG.ReplaceAllUsesWith(Call, MN); 7933 DAG.DeleteNode(Call); 7934 7935 // Inform the Frame Information that we have a patchpoint in this function. 7936 FuncInfo.MF->getFrameInfo().setHasPatchPoint(); 7937 } 7938 7939 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I, 7940 unsigned Intrinsic) { 7941 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7942 SDValue Op1 = getValue(I.getArgOperand(0)); 7943 SDValue Op2; 7944 if (I.getNumArgOperands() > 1) 7945 Op2 = getValue(I.getArgOperand(1)); 7946 SDLoc dl = getCurSDLoc(); 7947 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType()); 7948 SDValue Res; 7949 FastMathFlags FMF; 7950 if (isa<FPMathOperator>(I)) 7951 FMF = I.getFastMathFlags(); 7952 SDNodeFlags SDFlags; 7953 SDFlags.setNoNaNs(FMF.noNaNs()); 7954 7955 switch (Intrinsic) { 7956 case Intrinsic::experimental_vector_reduce_fadd: 7957 if (FMF.isFast()) 7958 Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2); 7959 else 7960 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2); 7961 break; 7962 case Intrinsic::experimental_vector_reduce_fmul: 7963 if (FMF.isFast()) 7964 Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2); 7965 else 7966 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2); 7967 break; 7968 case Intrinsic::experimental_vector_reduce_add: 7969 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1); 7970 break; 7971 case Intrinsic::experimental_vector_reduce_mul: 7972 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1); 7973 break; 7974 case Intrinsic::experimental_vector_reduce_and: 7975 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1); 7976 break; 7977 case Intrinsic::experimental_vector_reduce_or: 7978 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1); 7979 break; 7980 case Intrinsic::experimental_vector_reduce_xor: 7981 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1); 7982 break; 7983 case Intrinsic::experimental_vector_reduce_smax: 7984 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1); 7985 break; 7986 case Intrinsic::experimental_vector_reduce_smin: 7987 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1); 7988 break; 7989 case Intrinsic::experimental_vector_reduce_umax: 7990 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1); 7991 break; 7992 case Intrinsic::experimental_vector_reduce_umin: 7993 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1); 7994 break; 7995 case Intrinsic::experimental_vector_reduce_fmax: 7996 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags); 7997 break; 7998 case Intrinsic::experimental_vector_reduce_fmin: 7999 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags); 8000 break; 8001 default: 8002 llvm_unreachable("Unhandled vector reduce intrinsic"); 8003 } 8004 setValue(&I, Res); 8005 } 8006 8007 /// Returns an AttributeList representing the attributes applied to the return 8008 /// value of the given call. 8009 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) { 8010 SmallVector<Attribute::AttrKind, 2> Attrs; 8011 if (CLI.RetSExt) 8012 Attrs.push_back(Attribute::SExt); 8013 if (CLI.RetZExt) 8014 Attrs.push_back(Attribute::ZExt); 8015 if (CLI.IsInReg) 8016 Attrs.push_back(Attribute::InReg); 8017 8018 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex, 8019 Attrs); 8020 } 8021 8022 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 8023 /// implementation, which just calls LowerCall. 8024 /// FIXME: When all targets are 8025 /// migrated to using LowerCall, this hook should be integrated into SDISel. 8026 std::pair<SDValue, SDValue> 8027 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 8028 // Handle the incoming return values from the call. 8029 CLI.Ins.clear(); 8030 Type *OrigRetTy = CLI.RetTy; 8031 SmallVector<EVT, 4> RetTys; 8032 SmallVector<uint64_t, 4> Offsets; 8033 auto &DL = CLI.DAG.getDataLayout(); 8034 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets); 8035 8036 if (CLI.IsPostTypeLegalization) { 8037 // If we are lowering a libcall after legalization, split the return type. 8038 SmallVector<EVT, 4> OldRetTys = std::move(RetTys); 8039 SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets); 8040 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) { 8041 EVT RetVT = OldRetTys[i]; 8042 uint64_t Offset = OldOffsets[i]; 8043 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT); 8044 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT); 8045 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8; 8046 RetTys.append(NumRegs, RegisterVT); 8047 for (unsigned j = 0; j != NumRegs; ++j) 8048 Offsets.push_back(Offset + j * RegisterVTByteSZ); 8049 } 8050 } 8051 8052 SmallVector<ISD::OutputArg, 4> Outs; 8053 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL); 8054 8055 bool CanLowerReturn = 8056 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(), 8057 CLI.IsVarArg, Outs, CLI.RetTy->getContext()); 8058 8059 SDValue DemoteStackSlot; 8060 int DemoteStackIdx = -100; 8061 if (!CanLowerReturn) { 8062 // FIXME: equivalent assert? 8063 // assert(!CS.hasInAllocaArgument() && 8064 // "sret demotion is incompatible with inalloca"); 8065 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy); 8066 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy); 8067 MachineFunction &MF = CLI.DAG.getMachineFunction(); 8068 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false); 8069 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy); 8070 8071 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL)); 8072 ArgListEntry Entry; 8073 Entry.Node = DemoteStackSlot; 8074 Entry.Ty = StackSlotPtrType; 8075 Entry.IsSExt = false; 8076 Entry.IsZExt = false; 8077 Entry.IsInReg = false; 8078 Entry.IsSRet = true; 8079 Entry.IsNest = false; 8080 Entry.IsByVal = false; 8081 Entry.IsReturned = false; 8082 Entry.IsSwiftSelf = false; 8083 Entry.IsSwiftError = false; 8084 Entry.Alignment = Align; 8085 CLI.getArgs().insert(CLI.getArgs().begin(), Entry); 8086 CLI.NumFixedArgs += 1; 8087 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext()); 8088 8089 // sret demotion isn't compatible with tail-calls, since the sret argument 8090 // points into the callers stack frame. 8091 CLI.IsTailCall = false; 8092 } else { 8093 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8094 EVT VT = RetTys[I]; 8095 MVT RegisterVT = 8096 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8097 unsigned NumRegs = 8098 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8099 for (unsigned i = 0; i != NumRegs; ++i) { 8100 ISD::InputArg MyFlags; 8101 MyFlags.VT = RegisterVT; 8102 MyFlags.ArgVT = VT; 8103 MyFlags.Used = CLI.IsReturnValueUsed; 8104 if (CLI.RetSExt) 8105 MyFlags.Flags.setSExt(); 8106 if (CLI.RetZExt) 8107 MyFlags.Flags.setZExt(); 8108 if (CLI.IsInReg) 8109 MyFlags.Flags.setInReg(); 8110 CLI.Ins.push_back(MyFlags); 8111 } 8112 } 8113 } 8114 8115 // We push in swifterror return as the last element of CLI.Ins. 8116 ArgListTy &Args = CLI.getArgs(); 8117 if (supportSwiftError()) { 8118 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8119 if (Args[i].IsSwiftError) { 8120 ISD::InputArg MyFlags; 8121 MyFlags.VT = getPointerTy(DL); 8122 MyFlags.ArgVT = EVT(getPointerTy(DL)); 8123 MyFlags.Flags.setSwiftError(); 8124 CLI.Ins.push_back(MyFlags); 8125 } 8126 } 8127 } 8128 8129 // Handle all of the outgoing arguments. 8130 CLI.Outs.clear(); 8131 CLI.OutVals.clear(); 8132 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 8133 SmallVector<EVT, 4> ValueVTs; 8134 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs); 8135 // FIXME: Split arguments if CLI.IsPostTypeLegalization 8136 Type *FinalType = Args[i].Ty; 8137 if (Args[i].IsByVal) 8138 FinalType = cast<PointerType>(Args[i].Ty)->getElementType(); 8139 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters( 8140 FinalType, CLI.CallConv, CLI.IsVarArg); 8141 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues; 8142 ++Value) { 8143 EVT VT = ValueVTs[Value]; 8144 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 8145 SDValue Op = SDValue(Args[i].Node.getNode(), 8146 Args[i].Node.getResNo() + Value); 8147 ISD::ArgFlagsTy Flags; 8148 8149 // Certain targets (such as MIPS), may have a different ABI alignment 8150 // for a type depending on the context. Give the target a chance to 8151 // specify the alignment it wants. 8152 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL); 8153 8154 if (Args[i].IsZExt) 8155 Flags.setZExt(); 8156 if (Args[i].IsSExt) 8157 Flags.setSExt(); 8158 if (Args[i].IsInReg) { 8159 // If we are using vectorcall calling convention, a structure that is 8160 // passed InReg - is surely an HVA 8161 if (CLI.CallConv == CallingConv::X86_VectorCall && 8162 isa<StructType>(FinalType)) { 8163 // The first value of a structure is marked 8164 if (0 == Value) 8165 Flags.setHvaStart(); 8166 Flags.setHva(); 8167 } 8168 // Set InReg Flag 8169 Flags.setInReg(); 8170 } 8171 if (Args[i].IsSRet) 8172 Flags.setSRet(); 8173 if (Args[i].IsSwiftSelf) 8174 Flags.setSwiftSelf(); 8175 if (Args[i].IsSwiftError) 8176 Flags.setSwiftError(); 8177 if (Args[i].IsByVal) 8178 Flags.setByVal(); 8179 if (Args[i].IsInAlloca) { 8180 Flags.setInAlloca(); 8181 // Set the byval flag for CCAssignFn callbacks that don't know about 8182 // inalloca. This way we can know how many bytes we should've allocated 8183 // and how many bytes a callee cleanup function will pop. If we port 8184 // inalloca to more targets, we'll have to add custom inalloca handling 8185 // in the various CC lowering callbacks. 8186 Flags.setByVal(); 8187 } 8188 if (Args[i].IsByVal || Args[i].IsInAlloca) { 8189 PointerType *Ty = cast<PointerType>(Args[i].Ty); 8190 Type *ElementTy = Ty->getElementType(); 8191 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8192 // For ByVal, alignment should come from FE. BE will guess if this 8193 // info is not there but there are cases it cannot get right. 8194 unsigned FrameAlign; 8195 if (Args[i].Alignment) 8196 FrameAlign = Args[i].Alignment; 8197 else 8198 FrameAlign = getByValTypeAlignment(ElementTy, DL); 8199 Flags.setByValAlign(FrameAlign); 8200 } 8201 if (Args[i].IsNest) 8202 Flags.setNest(); 8203 if (NeedsRegBlock) 8204 Flags.setInConsecutiveRegs(); 8205 Flags.setOrigAlign(OriginalAlignment); 8206 8207 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8208 unsigned NumParts = 8209 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8210 SmallVector<SDValue, 4> Parts(NumParts); 8211 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 8212 8213 if (Args[i].IsSExt) 8214 ExtendKind = ISD::SIGN_EXTEND; 8215 else if (Args[i].IsZExt) 8216 ExtendKind = ISD::ZERO_EXTEND; 8217 8218 // Conservatively only handle 'returned' on non-vectors for now 8219 if (Args[i].IsReturned && !Op.getValueType().isVector()) { 8220 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 8221 "unexpected use of 'returned'"); 8222 // Before passing 'returned' to the target lowering code, ensure that 8223 // either the register MVT and the actual EVT are the same size or that 8224 // the return value and argument are extended in the same way; in these 8225 // cases it's safe to pass the argument register value unchanged as the 8226 // return register value (although it's at the target's option whether 8227 // to do so) 8228 // TODO: allow code generation to take advantage of partially preserved 8229 // registers rather than clobbering the entire register when the 8230 // parameter extension method is not compatible with the return 8231 // extension method 8232 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 8233 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt && 8234 CLI.RetZExt == Args[i].IsZExt)) 8235 Flags.setReturned(); 8236 } 8237 8238 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, 8239 CLI.CS.getInstruction(), ExtendKind, true); 8240 8241 for (unsigned j = 0; j != NumParts; ++j) { 8242 // if it isn't first piece, alignment must be 1 8243 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT, 8244 i < CLI.NumFixedArgs, 8245 i, j*Parts[j].getValueType().getStoreSize()); 8246 if (NumParts > 1 && j == 0) 8247 MyFlags.Flags.setSplit(); 8248 else if (j != 0) { 8249 MyFlags.Flags.setOrigAlign(1); 8250 if (j == NumParts - 1) 8251 MyFlags.Flags.setSplitEnd(); 8252 } 8253 8254 CLI.Outs.push_back(MyFlags); 8255 CLI.OutVals.push_back(Parts[j]); 8256 } 8257 8258 if (NeedsRegBlock && Value == NumValues - 1) 8259 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast(); 8260 } 8261 } 8262 8263 SmallVector<SDValue, 4> InVals; 8264 CLI.Chain = LowerCall(CLI, InVals); 8265 8266 // Update CLI.InVals to use outside of this function. 8267 CLI.InVals = InVals; 8268 8269 // Verify that the target's LowerCall behaved as expected. 8270 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 8271 "LowerCall didn't return a valid chain!"); 8272 assert((!CLI.IsTailCall || InVals.empty()) && 8273 "LowerCall emitted a return value for a tail call!"); 8274 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 8275 "LowerCall didn't emit the correct number of values!"); 8276 8277 // For a tail call, the return value is merely live-out and there aren't 8278 // any nodes in the DAG representing it. Return a special value to 8279 // indicate that a tail call has been emitted and no more Instructions 8280 // should be processed in the current block. 8281 if (CLI.IsTailCall) { 8282 CLI.DAG.setRoot(CLI.Chain); 8283 return std::make_pair(SDValue(), SDValue()); 8284 } 8285 8286 #ifndef NDEBUG 8287 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 8288 assert(InVals[i].getNode() && "LowerCall emitted a null value!"); 8289 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 8290 "LowerCall emitted a value with the wrong type!"); 8291 } 8292 #endif 8293 8294 SmallVector<SDValue, 4> ReturnValues; 8295 if (!CanLowerReturn) { 8296 // The instruction result is the result of loading from the 8297 // hidden sret parameter. 8298 SmallVector<EVT, 1> PVTs; 8299 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace()); 8300 8301 ComputeValueVTs(*this, DL, PtrRetTy, PVTs); 8302 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 8303 EVT PtrVT = PVTs[0]; 8304 8305 unsigned NumValues = RetTys.size(); 8306 ReturnValues.resize(NumValues); 8307 SmallVector<SDValue, 4> Chains(NumValues); 8308 8309 // An aggregate return value cannot wrap around the address space, so 8310 // offsets to its parts don't wrap either. 8311 SDNodeFlags Flags; 8312 Flags.setNoUnsignedWrap(true); 8313 8314 for (unsigned i = 0; i < NumValues; ++i) { 8315 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot, 8316 CLI.DAG.getConstant(Offsets[i], CLI.DL, 8317 PtrVT), Flags); 8318 SDValue L = CLI.DAG.getLoad( 8319 RetTys[i], CLI.DL, CLI.Chain, Add, 8320 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(), 8321 DemoteStackIdx, Offsets[i]), 8322 /* Alignment = */ 1); 8323 ReturnValues[i] = L; 8324 Chains[i] = L.getValue(1); 8325 } 8326 8327 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains); 8328 } else { 8329 // Collect the legal value parts into potentially illegal values 8330 // that correspond to the original function's return values. 8331 Optional<ISD::NodeType> AssertOp; 8332 if (CLI.RetSExt) 8333 AssertOp = ISD::AssertSext; 8334 else if (CLI.RetZExt) 8335 AssertOp = ISD::AssertZext; 8336 unsigned CurReg = 0; 8337 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 8338 EVT VT = RetTys[I]; 8339 MVT RegisterVT = 8340 getRegisterTypeForCallingConv(CLI.RetTy->getContext(), VT); 8341 unsigned NumRegs = 8342 getNumRegistersForCallingConv(CLI.RetTy->getContext(), VT); 8343 8344 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 8345 NumRegs, RegisterVT, VT, nullptr, 8346 AssertOp, true)); 8347 CurReg += NumRegs; 8348 } 8349 8350 // For a function returning void, there is no return value. We can't create 8351 // such a node, so we just return a null return value in that case. In 8352 // that case, nothing will actually look at the value. 8353 if (ReturnValues.empty()) 8354 return std::make_pair(SDValue(), CLI.Chain); 8355 } 8356 8357 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 8358 CLI.DAG.getVTList(RetTys), ReturnValues); 8359 return std::make_pair(Res, CLI.Chain); 8360 } 8361 8362 void TargetLowering::LowerOperationWrapper(SDNode *N, 8363 SmallVectorImpl<SDValue> &Results, 8364 SelectionDAG &DAG) const { 8365 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG)) 8366 Results.push_back(Res); 8367 } 8368 8369 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 8370 llvm_unreachable("LowerOperation not implemented for this target!"); 8371 } 8372 8373 void 8374 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 8375 SDValue Op = getNonRegisterValue(V); 8376 assert((Op.getOpcode() != ISD::CopyFromReg || 8377 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 8378 "Copy from a reg to the same reg!"); 8379 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 8380 8381 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8382 // If this is an InlineAsm we have to match the registers required, not the 8383 // notional registers required by the type. 8384 8385 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, 8386 V->getType(), isABIRegCopy(V)); 8387 SDValue Chain = DAG.getEntryNode(); 8388 8389 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) == 8390 FuncInfo.PreferredExtendType.end()) 8391 ? ISD::ANY_EXTEND 8392 : FuncInfo.PreferredExtendType[V]; 8393 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType); 8394 PendingExports.push_back(Chain); 8395 } 8396 8397 #include "llvm/CodeGen/SelectionDAGISel.h" 8398 8399 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 8400 /// entry block, return true. This includes arguments used by switches, since 8401 /// the switch may expand into multiple basic blocks. 8402 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 8403 // With FastISel active, we may be splitting blocks, so force creation 8404 // of virtual registers for all non-dead arguments. 8405 if (FastISel) 8406 return A->use_empty(); 8407 8408 const BasicBlock &Entry = A->getParent()->front(); 8409 for (const User *U : A->users()) 8410 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U)) 8411 return false; // Use not in entry block. 8412 8413 return true; 8414 } 8415 8416 using ArgCopyElisionMapTy = 8417 DenseMap<const Argument *, 8418 std::pair<const AllocaInst *, const StoreInst *>>; 8419 8420 /// Scan the entry block of the function in FuncInfo for arguments that look 8421 /// like copies into a local alloca. Record any copied arguments in 8422 /// ArgCopyElisionCandidates. 8423 static void 8424 findArgumentCopyElisionCandidates(const DataLayout &DL, 8425 FunctionLoweringInfo *FuncInfo, 8426 ArgCopyElisionMapTy &ArgCopyElisionCandidates) { 8427 // Record the state of every static alloca used in the entry block. Argument 8428 // allocas are all used in the entry block, so we need approximately as many 8429 // entries as we have arguments. 8430 enum StaticAllocaInfo { Unknown, Clobbered, Elidable }; 8431 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas; 8432 unsigned NumArgs = FuncInfo->Fn->arg_size(); 8433 StaticAllocas.reserve(NumArgs * 2); 8434 8435 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * { 8436 if (!V) 8437 return nullptr; 8438 V = V->stripPointerCasts(); 8439 const auto *AI = dyn_cast<AllocaInst>(V); 8440 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI)) 8441 return nullptr; 8442 auto Iter = StaticAllocas.insert({AI, Unknown}); 8443 return &Iter.first->second; 8444 }; 8445 8446 // Look for stores of arguments to static allocas. Look through bitcasts and 8447 // GEPs to handle type coercions, as long as the alloca is fully initialized 8448 // by the store. Any non-store use of an alloca escapes it and any subsequent 8449 // unanalyzed store might write it. 8450 // FIXME: Handle structs initialized with multiple stores. 8451 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) { 8452 // Look for stores, and handle non-store uses conservatively. 8453 const auto *SI = dyn_cast<StoreInst>(&I); 8454 if (!SI) { 8455 // We will look through cast uses, so ignore them completely. 8456 if (I.isCast()) 8457 continue; 8458 // Ignore debug info intrinsics, they don't escape or store to allocas. 8459 if (isa<DbgInfoIntrinsic>(I)) 8460 continue; 8461 // This is an unknown instruction. Assume it escapes or writes to all 8462 // static alloca operands. 8463 for (const Use &U : I.operands()) { 8464 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U)) 8465 *Info = StaticAllocaInfo::Clobbered; 8466 } 8467 continue; 8468 } 8469 8470 // If the stored value is a static alloca, mark it as escaped. 8471 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand())) 8472 *Info = StaticAllocaInfo::Clobbered; 8473 8474 // Check if the destination is a static alloca. 8475 const Value *Dst = SI->getPointerOperand()->stripPointerCasts(); 8476 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst); 8477 if (!Info) 8478 continue; 8479 const AllocaInst *AI = cast<AllocaInst>(Dst); 8480 8481 // Skip allocas that have been initialized or clobbered. 8482 if (*Info != StaticAllocaInfo::Unknown) 8483 continue; 8484 8485 // Check if the stored value is an argument, and that this store fully 8486 // initializes the alloca. Don't elide copies from the same argument twice. 8487 const Value *Val = SI->getValueOperand()->stripPointerCasts(); 8488 const auto *Arg = dyn_cast<Argument>(Val); 8489 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() || 8490 Arg->getType()->isEmptyTy() || 8491 DL.getTypeStoreSize(Arg->getType()) != 8492 DL.getTypeAllocSize(AI->getAllocatedType()) || 8493 ArgCopyElisionCandidates.count(Arg)) { 8494 *Info = StaticAllocaInfo::Clobbered; 8495 continue; 8496 } 8497 8498 DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI << '\n'); 8499 8500 // Mark this alloca and store for argument copy elision. 8501 *Info = StaticAllocaInfo::Elidable; 8502 ArgCopyElisionCandidates.insert({Arg, {AI, SI}}); 8503 8504 // Stop scanning if we've seen all arguments. This will happen early in -O0 8505 // builds, which is useful, because -O0 builds have large entry blocks and 8506 // many allocas. 8507 if (ArgCopyElisionCandidates.size() == NumArgs) 8508 break; 8509 } 8510 } 8511 8512 /// Try to elide argument copies from memory into a local alloca. Succeeds if 8513 /// ArgVal is a load from a suitable fixed stack object. 8514 static void tryToElideArgumentCopy( 8515 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains, 8516 DenseMap<int, int> &ArgCopyElisionFrameIndexMap, 8517 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs, 8518 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg, 8519 SDValue ArgVal, bool &ArgHasUses) { 8520 // Check if this is a load from a fixed stack object. 8521 auto *LNode = dyn_cast<LoadSDNode>(ArgVal); 8522 if (!LNode) 8523 return; 8524 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()); 8525 if (!FINode) 8526 return; 8527 8528 // Check that the fixed stack object is the right size and alignment. 8529 // Look at the alignment that the user wrote on the alloca instead of looking 8530 // at the stack object. 8531 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg); 8532 assert(ArgCopyIter != ArgCopyElisionCandidates.end()); 8533 const AllocaInst *AI = ArgCopyIter->second.first; 8534 int FixedIndex = FINode->getIndex(); 8535 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI]; 8536 int OldIndex = AllocaIndex; 8537 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo(); 8538 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) { 8539 DEBUG(dbgs() << " argument copy elision failed due to bad fixed stack " 8540 "object size\n"); 8541 return; 8542 } 8543 unsigned RequiredAlignment = AI->getAlignment(); 8544 if (!RequiredAlignment) { 8545 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment( 8546 AI->getAllocatedType()); 8547 } 8548 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) { 8549 DEBUG(dbgs() << " argument copy elision failed: alignment of alloca " 8550 "greater than stack argument alignment (" 8551 << RequiredAlignment << " vs " 8552 << MFI.getObjectAlignment(FixedIndex) << ")\n"); 8553 return; 8554 } 8555 8556 // Perform the elision. Delete the old stack object and replace its only use 8557 // in the variable info map. Mark the stack object as mutable. 8558 DEBUG({ 8559 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n' 8560 << " Replacing frame index " << OldIndex << " with " << FixedIndex 8561 << '\n'; 8562 }); 8563 MFI.RemoveStackObject(OldIndex); 8564 MFI.setIsImmutableObjectIndex(FixedIndex, false); 8565 AllocaIndex = FixedIndex; 8566 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex}); 8567 Chains.push_back(ArgVal.getValue(1)); 8568 8569 // Avoid emitting code for the store implementing the copy. 8570 const StoreInst *SI = ArgCopyIter->second.second; 8571 ElidedArgCopyInstrs.insert(SI); 8572 8573 // Check for uses of the argument again so that we can avoid exporting ArgVal 8574 // if it is't used by anything other than the store. 8575 for (const Value *U : Arg.users()) { 8576 if (U != SI) { 8577 ArgHasUses = true; 8578 break; 8579 } 8580 } 8581 } 8582 8583 void SelectionDAGISel::LowerArguments(const Function &F) { 8584 SelectionDAG &DAG = SDB->DAG; 8585 SDLoc dl = SDB->getCurSDLoc(); 8586 const DataLayout &DL = DAG.getDataLayout(); 8587 SmallVector<ISD::InputArg, 16> Ins; 8588 8589 if (!FuncInfo->CanLowerReturn) { 8590 // Put in an sret pointer parameter before all the other parameters. 8591 SmallVector<EVT, 1> ValueVTs; 8592 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8593 PointerType::getUnqual(F.getReturnType()), ValueVTs); 8594 8595 // NOTE: Assuming that a pointer will never break down to more than one VT 8596 // or one register. 8597 ISD::ArgFlagsTy Flags; 8598 Flags.setSRet(); 8599 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 8600 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 8601 ISD::InputArg::NoArgIndex, 0); 8602 Ins.push_back(RetArg); 8603 } 8604 8605 // Look for stores of arguments to static allocas. Mark such arguments with a 8606 // flag to ask the target to give us the memory location of that argument if 8607 // available. 8608 ArgCopyElisionMapTy ArgCopyElisionCandidates; 8609 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates); 8610 8611 // Set up the incoming argument description vector. 8612 for (const Argument &Arg : F.args()) { 8613 unsigned ArgNo = Arg.getArgNo(); 8614 SmallVector<EVT, 4> ValueVTs; 8615 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8616 bool isArgValueUsed = !Arg.use_empty(); 8617 unsigned PartBase = 0; 8618 Type *FinalType = Arg.getType(); 8619 if (Arg.hasAttribute(Attribute::ByVal)) 8620 FinalType = cast<PointerType>(FinalType)->getElementType(); 8621 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters( 8622 FinalType, F.getCallingConv(), F.isVarArg()); 8623 for (unsigned Value = 0, NumValues = ValueVTs.size(); 8624 Value != NumValues; ++Value) { 8625 EVT VT = ValueVTs[Value]; 8626 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 8627 ISD::ArgFlagsTy Flags; 8628 8629 // Certain targets (such as MIPS), may have a different ABI alignment 8630 // for a type depending on the context. Give the target a chance to 8631 // specify the alignment it wants. 8632 unsigned OriginalAlignment = 8633 TLI->getABIAlignmentForCallingConv(ArgTy, DL); 8634 8635 if (Arg.hasAttribute(Attribute::ZExt)) 8636 Flags.setZExt(); 8637 if (Arg.hasAttribute(Attribute::SExt)) 8638 Flags.setSExt(); 8639 if (Arg.hasAttribute(Attribute::InReg)) { 8640 // If we are using vectorcall calling convention, a structure that is 8641 // passed InReg - is surely an HVA 8642 if (F.getCallingConv() == CallingConv::X86_VectorCall && 8643 isa<StructType>(Arg.getType())) { 8644 // The first value of a structure is marked 8645 if (0 == Value) 8646 Flags.setHvaStart(); 8647 Flags.setHva(); 8648 } 8649 // Set InReg Flag 8650 Flags.setInReg(); 8651 } 8652 if (Arg.hasAttribute(Attribute::StructRet)) 8653 Flags.setSRet(); 8654 if (Arg.hasAttribute(Attribute::SwiftSelf)) 8655 Flags.setSwiftSelf(); 8656 if (Arg.hasAttribute(Attribute::SwiftError)) 8657 Flags.setSwiftError(); 8658 if (Arg.hasAttribute(Attribute::ByVal)) 8659 Flags.setByVal(); 8660 if (Arg.hasAttribute(Attribute::InAlloca)) { 8661 Flags.setInAlloca(); 8662 // Set the byval flag for CCAssignFn callbacks that don't know about 8663 // inalloca. This way we can know how many bytes we should've allocated 8664 // and how many bytes a callee cleanup function will pop. If we port 8665 // inalloca to more targets, we'll have to add custom inalloca handling 8666 // in the various CC lowering callbacks. 8667 Flags.setByVal(); 8668 } 8669 if (F.getCallingConv() == CallingConv::X86_INTR) { 8670 // IA Interrupt passes frame (1st parameter) by value in the stack. 8671 if (ArgNo == 0) 8672 Flags.setByVal(); 8673 } 8674 if (Flags.isByVal() || Flags.isInAlloca()) { 8675 PointerType *Ty = cast<PointerType>(Arg.getType()); 8676 Type *ElementTy = Ty->getElementType(); 8677 Flags.setByValSize(DL.getTypeAllocSize(ElementTy)); 8678 // For ByVal, alignment should be passed from FE. BE will guess if 8679 // this info is not there but there are cases it cannot get right. 8680 unsigned FrameAlign; 8681 if (Arg.getParamAlignment()) 8682 FrameAlign = Arg.getParamAlignment(); 8683 else 8684 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL); 8685 Flags.setByValAlign(FrameAlign); 8686 } 8687 if (Arg.hasAttribute(Attribute::Nest)) 8688 Flags.setNest(); 8689 if (NeedsRegBlock) 8690 Flags.setInConsecutiveRegs(); 8691 Flags.setOrigAlign(OriginalAlignment); 8692 if (ArgCopyElisionCandidates.count(&Arg)) 8693 Flags.setCopyElisionCandidate(); 8694 8695 MVT RegisterVT = 8696 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 8697 unsigned NumRegs = 8698 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 8699 for (unsigned i = 0; i != NumRegs; ++i) { 8700 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed, 8701 ArgNo, PartBase+i*RegisterVT.getStoreSize()); 8702 if (NumRegs > 1 && i == 0) 8703 MyFlags.Flags.setSplit(); 8704 // if it isn't first piece, alignment must be 1 8705 else if (i > 0) { 8706 MyFlags.Flags.setOrigAlign(1); 8707 if (i == NumRegs - 1) 8708 MyFlags.Flags.setSplitEnd(); 8709 } 8710 Ins.push_back(MyFlags); 8711 } 8712 if (NeedsRegBlock && Value == NumValues - 1) 8713 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast(); 8714 PartBase += VT.getStoreSize(); 8715 } 8716 } 8717 8718 // Call the target to set up the argument values. 8719 SmallVector<SDValue, 8> InVals; 8720 SDValue NewRoot = TLI->LowerFormalArguments( 8721 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals); 8722 8723 // Verify that the target's LowerFormalArguments behaved as expected. 8724 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 8725 "LowerFormalArguments didn't return a valid chain!"); 8726 assert(InVals.size() == Ins.size() && 8727 "LowerFormalArguments didn't emit the correct number of values!"); 8728 DEBUG({ 8729 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 8730 assert(InVals[i].getNode() && 8731 "LowerFormalArguments emitted a null value!"); 8732 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 8733 "LowerFormalArguments emitted a value with the wrong type!"); 8734 } 8735 }); 8736 8737 // Update the DAG with the new chain value resulting from argument lowering. 8738 DAG.setRoot(NewRoot); 8739 8740 // Set up the argument values. 8741 unsigned i = 0; 8742 if (!FuncInfo->CanLowerReturn) { 8743 // Create a virtual register for the sret pointer, and put in a copy 8744 // from the sret argument into it. 8745 SmallVector<EVT, 1> ValueVTs; 8746 ComputeValueVTs(*TLI, DAG.getDataLayout(), 8747 PointerType::getUnqual(F.getReturnType()), ValueVTs); 8748 MVT VT = ValueVTs[0].getSimpleVT(); 8749 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 8750 Optional<ISD::NodeType> AssertOp = None; 8751 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 8752 RegVT, VT, nullptr, AssertOp); 8753 8754 MachineFunction& MF = SDB->DAG.getMachineFunction(); 8755 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 8756 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 8757 FuncInfo->DemoteRegister = SRetReg; 8758 NewRoot = 8759 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue); 8760 DAG.setRoot(NewRoot); 8761 8762 // i indexes lowered arguments. Bump it past the hidden sret argument. 8763 ++i; 8764 } 8765 8766 SmallVector<SDValue, 4> Chains; 8767 DenseMap<int, int> ArgCopyElisionFrameIndexMap; 8768 for (const Argument &Arg : F.args()) { 8769 SmallVector<SDValue, 4> ArgValues; 8770 SmallVector<EVT, 4> ValueVTs; 8771 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs); 8772 unsigned NumValues = ValueVTs.size(); 8773 if (NumValues == 0) 8774 continue; 8775 8776 bool ArgHasUses = !Arg.use_empty(); 8777 8778 // Elide the copying store if the target loaded this argument from a 8779 // suitable fixed stack object. 8780 if (Ins[i].Flags.isCopyElisionCandidate()) { 8781 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap, 8782 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg, 8783 InVals[i], ArgHasUses); 8784 } 8785 8786 // If this argument is unused then remember its value. It is used to generate 8787 // debugging information. 8788 bool isSwiftErrorArg = 8789 TLI->supportSwiftError() && 8790 Arg.hasAttribute(Attribute::SwiftError); 8791 if (!ArgHasUses && !isSwiftErrorArg) { 8792 SDB->setUnusedArgValue(&Arg, InVals[i]); 8793 8794 // Also remember any frame index for use in FastISel. 8795 if (FrameIndexSDNode *FI = 8796 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 8797 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 8798 } 8799 8800 for (unsigned Val = 0; Val != NumValues; ++Val) { 8801 EVT VT = ValueVTs[Val]; 8802 MVT PartVT = 8803 TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(), VT); 8804 unsigned NumParts = 8805 TLI->getNumRegistersForCallingConv(*CurDAG->getContext(), VT); 8806 8807 // Even an apparant 'unused' swifterror argument needs to be returned. So 8808 // we do generate a copy for it that can be used on return from the 8809 // function. 8810 if (ArgHasUses || isSwiftErrorArg) { 8811 Optional<ISD::NodeType> AssertOp; 8812 if (Arg.hasAttribute(Attribute::SExt)) 8813 AssertOp = ISD::AssertSext; 8814 else if (Arg.hasAttribute(Attribute::ZExt)) 8815 AssertOp = ISD::AssertZext; 8816 8817 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts, 8818 PartVT, VT, nullptr, AssertOp, 8819 true)); 8820 } 8821 8822 i += NumParts; 8823 } 8824 8825 // We don't need to do anything else for unused arguments. 8826 if (ArgValues.empty()) 8827 continue; 8828 8829 // Note down frame index. 8830 if (FrameIndexSDNode *FI = 8831 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 8832 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 8833 8834 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues), 8835 SDB->getCurSDLoc()); 8836 8837 SDB->setValue(&Arg, Res); 8838 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 8839 // We want to associate the argument with the frame index, among 8840 // involved operands, that correspond to the lowest address. The 8841 // getCopyFromParts function, called earlier, is swapping the order of 8842 // the operands to BUILD_PAIR depending on endianness. The result of 8843 // that swapping is that the least significant bits of the argument will 8844 // be in the first operand of the BUILD_PAIR node, and the most 8845 // significant bits will be in the second operand. 8846 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0; 8847 if (LoadSDNode *LNode = 8848 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode())) 8849 if (FrameIndexSDNode *FI = 8850 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 8851 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex()); 8852 } 8853 8854 // Update the SwiftErrorVRegDefMap. 8855 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) { 8856 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 8857 if (TargetRegisterInfo::isVirtualRegister(Reg)) 8858 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, 8859 FuncInfo->SwiftErrorArg, Reg); 8860 } 8861 8862 // If this argument is live outside of the entry block, insert a copy from 8863 // wherever we got it to the vreg that other BB's will reference it as. 8864 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 8865 // If we can, though, try to skip creating an unnecessary vreg. 8866 // FIXME: This isn't very clean... it would be nice to make this more 8867 // general. It's also subtly incompatible with the hacks FastISel 8868 // uses with vregs. 8869 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 8870 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 8871 FuncInfo->ValueMap[&Arg] = Reg; 8872 continue; 8873 } 8874 } 8875 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) { 8876 FuncInfo->InitializeRegForValue(&Arg); 8877 SDB->CopyToExportRegsIfNeeded(&Arg); 8878 } 8879 } 8880 8881 if (!Chains.empty()) { 8882 Chains.push_back(NewRoot); 8883 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains); 8884 } 8885 8886 DAG.setRoot(NewRoot); 8887 8888 assert(i == InVals.size() && "Argument register count mismatch!"); 8889 8890 // If any argument copy elisions occurred and we have debug info, update the 8891 // stale frame indices used in the dbg.declare variable info table. 8892 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo(); 8893 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) { 8894 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) { 8895 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot); 8896 if (I != ArgCopyElisionFrameIndexMap.end()) 8897 VI.Slot = I->second; 8898 } 8899 } 8900 8901 // Finally, if the target has anything special to do, allow it to do so. 8902 EmitFunctionEntryCode(); 8903 } 8904 8905 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 8906 /// ensure constants are generated when needed. Remember the virtual registers 8907 /// that need to be added to the Machine PHI nodes as input. We cannot just 8908 /// directly add them, because expansion might result in multiple MBB's for one 8909 /// BB. As such, the start of the BB might correspond to a different MBB than 8910 /// the end. 8911 void 8912 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 8913 const TerminatorInst *TI = LLVMBB->getTerminator(); 8914 8915 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 8916 8917 // Check PHI nodes in successors that expect a value to be available from this 8918 // block. 8919 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 8920 const BasicBlock *SuccBB = TI->getSuccessor(succ); 8921 if (!isa<PHINode>(SuccBB->begin())) continue; 8922 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 8923 8924 // If this terminator has multiple identical successors (common for 8925 // switches), only handle each succ once. 8926 if (!SuccsHandled.insert(SuccMBB).second) 8927 continue; 8928 8929 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 8930 8931 // At this point we know that there is a 1-1 correspondence between LLVM PHI 8932 // nodes and Machine PHI nodes, but the incoming operands have not been 8933 // emitted yet. 8934 for (BasicBlock::const_iterator I = SuccBB->begin(); 8935 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 8936 // Ignore dead phi's. 8937 if (PN->use_empty()) continue; 8938 8939 // Skip empty types 8940 if (PN->getType()->isEmptyTy()) 8941 continue; 8942 8943 unsigned Reg; 8944 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 8945 8946 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 8947 unsigned &RegOut = ConstantsOut[C]; 8948 if (RegOut == 0) { 8949 RegOut = FuncInfo.CreateRegs(C->getType()); 8950 CopyValueToVirtualRegister(C, RegOut); 8951 } 8952 Reg = RegOut; 8953 } else { 8954 DenseMap<const Value *, unsigned>::iterator I = 8955 FuncInfo.ValueMap.find(PHIOp); 8956 if (I != FuncInfo.ValueMap.end()) 8957 Reg = I->second; 8958 else { 8959 assert(isa<AllocaInst>(PHIOp) && 8960 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 8961 "Didn't codegen value into a register!??"); 8962 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 8963 CopyValueToVirtualRegister(PHIOp, Reg); 8964 } 8965 } 8966 8967 // Remember that this register needs to added to the machine PHI node as 8968 // the input for this MBB. 8969 SmallVector<EVT, 4> ValueVTs; 8970 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8971 ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs); 8972 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 8973 EVT VT = ValueVTs[vti]; 8974 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT); 8975 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 8976 FuncInfo.PHINodesToUpdate.push_back( 8977 std::make_pair(&*MBBI++, Reg + i)); 8978 Reg += NumRegisters; 8979 } 8980 } 8981 } 8982 8983 ConstantsOut.clear(); 8984 } 8985 8986 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 8987 /// is 0. 8988 MachineBasicBlock * 8989 SelectionDAGBuilder::StackProtectorDescriptor:: 8990 AddSuccessorMBB(const BasicBlock *BB, 8991 MachineBasicBlock *ParentMBB, 8992 bool IsLikely, 8993 MachineBasicBlock *SuccMBB) { 8994 // If SuccBB has not been created yet, create it. 8995 if (!SuccMBB) { 8996 MachineFunction *MF = ParentMBB->getParent(); 8997 MachineFunction::iterator BBI(ParentMBB); 8998 SuccMBB = MF->CreateMachineBasicBlock(BB); 8999 MF->insert(++BBI, SuccMBB); 9000 } 9001 // Add it as a successor of ParentMBB. 9002 ParentMBB->addSuccessor( 9003 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely)); 9004 return SuccMBB; 9005 } 9006 9007 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) { 9008 MachineFunction::iterator I(MBB); 9009 if (++I == FuncInfo.MF->end()) 9010 return nullptr; 9011 return &*I; 9012 } 9013 9014 /// During lowering new call nodes can be created (such as memset, etc.). 9015 /// Those will become new roots of the current DAG, but complications arise 9016 /// when they are tail calls. In such cases, the call lowering will update 9017 /// the root, but the builder still needs to know that a tail call has been 9018 /// lowered in order to avoid generating an additional return. 9019 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) { 9020 // If the node is null, we do have a tail call. 9021 if (MaybeTC.getNode() != nullptr) 9022 DAG.setRoot(MaybeTC); 9023 else 9024 HasTailCall = true; 9025 } 9026 9027 uint64_t 9028 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters, 9029 unsigned First, unsigned Last) const { 9030 assert(Last >= First); 9031 const APInt &LowCase = Clusters[First].Low->getValue(); 9032 const APInt &HighCase = Clusters[Last].High->getValue(); 9033 assert(LowCase.getBitWidth() == HighCase.getBitWidth()); 9034 9035 // FIXME: A range of consecutive cases has 100% density, but only requires one 9036 // comparison to lower. We should discriminate against such consecutive ranges 9037 // in jump tables. 9038 9039 return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1; 9040 } 9041 9042 uint64_t SelectionDAGBuilder::getJumpTableNumCases( 9043 const SmallVectorImpl<unsigned> &TotalCases, unsigned First, 9044 unsigned Last) const { 9045 assert(Last >= First); 9046 assert(TotalCases[Last] >= TotalCases[First]); 9047 uint64_t NumCases = 9048 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]); 9049 return NumCases; 9050 } 9051 9052 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters, 9053 unsigned First, unsigned Last, 9054 const SwitchInst *SI, 9055 MachineBasicBlock *DefaultMBB, 9056 CaseCluster &JTCluster) { 9057 assert(First <= Last); 9058 9059 auto Prob = BranchProbability::getZero(); 9060 unsigned NumCmps = 0; 9061 std::vector<MachineBasicBlock*> Table; 9062 DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 9063 9064 // Initialize probabilities in JTProbs. 9065 for (unsigned I = First; I <= Last; ++I) 9066 JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 9067 9068 for (unsigned I = First; I <= Last; ++I) { 9069 assert(Clusters[I].Kind == CC_Range); 9070 Prob += Clusters[I].Prob; 9071 const APInt &Low = Clusters[I].Low->getValue(); 9072 const APInt &High = Clusters[I].High->getValue(); 9073 NumCmps += (Low == High) ? 1 : 2; 9074 if (I != First) { 9075 // Fill the gap between this and the previous cluster. 9076 const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 9077 assert(PreviousHigh.slt(Low)); 9078 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 9079 for (uint64_t J = 0; J < Gap; J++) 9080 Table.push_back(DefaultMBB); 9081 } 9082 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 9083 for (uint64_t J = 0; J < ClusterSize; ++J) 9084 Table.push_back(Clusters[I].MBB); 9085 JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 9086 } 9087 9088 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9089 unsigned NumDests = JTProbs.size(); 9090 if (TLI.isSuitableForBitTests( 9091 NumDests, NumCmps, Clusters[First].Low->getValue(), 9092 Clusters[Last].High->getValue(), DAG.getDataLayout())) { 9093 // Clusters[First..Last] should be lowered as bit tests instead. 9094 return false; 9095 } 9096 9097 // Create the MBB that will load from and jump through the table. 9098 // Note: We create it here, but it's not inserted into the function yet. 9099 MachineFunction *CurMF = FuncInfo.MF; 9100 MachineBasicBlock *JumpTableMBB = 9101 CurMF->CreateMachineBasicBlock(SI->getParent()); 9102 9103 // Add successors. Note: use table order for determinism. 9104 SmallPtrSet<MachineBasicBlock *, 8> Done; 9105 for (MachineBasicBlock *Succ : Table) { 9106 if (Done.count(Succ)) 9107 continue; 9108 addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 9109 Done.insert(Succ); 9110 } 9111 JumpTableMBB->normalizeSuccProbs(); 9112 9113 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding()) 9114 ->createJumpTableIndex(Table); 9115 9116 // Set up the jump table info. 9117 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr); 9118 JumpTableHeader JTH(Clusters[First].Low->getValue(), 9119 Clusters[Last].High->getValue(), SI->getCondition(), 9120 nullptr, false); 9121 JTCases.emplace_back(std::move(JTH), std::move(JT)); 9122 9123 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 9124 JTCases.size() - 1, Prob); 9125 return true; 9126 } 9127 9128 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters, 9129 const SwitchInst *SI, 9130 MachineBasicBlock *DefaultMBB) { 9131 #ifndef NDEBUG 9132 // Clusters must be non-empty, sorted, and only contain Range clusters. 9133 assert(!Clusters.empty()); 9134 for (CaseCluster &C : Clusters) 9135 assert(C.Kind == CC_Range); 9136 for (unsigned i = 1, e = Clusters.size(); i < e; ++i) 9137 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue())); 9138 #endif 9139 9140 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9141 if (!TLI.areJTsAllowed(SI->getParent()->getParent())) 9142 return; 9143 9144 const int64_t N = Clusters.size(); 9145 const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries(); 9146 const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2; 9147 9148 if (N < 2 || N < MinJumpTableEntries) 9149 return; 9150 9151 // TotalCases[i]: Total nbr of cases in Clusters[0..i]. 9152 SmallVector<unsigned, 8> TotalCases(N); 9153 for (unsigned i = 0; i < N; ++i) { 9154 const APInt &Hi = Clusters[i].High->getValue(); 9155 const APInt &Lo = Clusters[i].Low->getValue(); 9156 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1; 9157 if (i != 0) 9158 TotalCases[i] += TotalCases[i - 1]; 9159 } 9160 9161 // Cheap case: the whole range may be suitable for jump table. 9162 uint64_t Range = getJumpTableRange(Clusters,0, N - 1); 9163 uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1); 9164 assert(NumCases < UINT64_MAX / 100); 9165 assert(Range >= NumCases); 9166 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9167 CaseCluster JTCluster; 9168 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) { 9169 Clusters[0] = JTCluster; 9170 Clusters.resize(1); 9171 return; 9172 } 9173 } 9174 9175 // The algorithm below is not suitable for -O0. 9176 if (TM.getOptLevel() == CodeGenOpt::None) 9177 return; 9178 9179 // Split Clusters into minimum number of dense partitions. The algorithm uses 9180 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code 9181 // for the Case Statement'" (1994), but builds the MinPartitions array in 9182 // reverse order to make it easier to reconstruct the partitions in ascending 9183 // order. In the choice between two optimal partitionings, it picks the one 9184 // which yields more jump tables. 9185 9186 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9187 SmallVector<unsigned, 8> MinPartitions(N); 9188 // LastElement[i] is the last element of the partition starting at i. 9189 SmallVector<unsigned, 8> LastElement(N); 9190 // PartitionsScore[i] is used to break ties when choosing between two 9191 // partitionings resulting in the same number of partitions. 9192 SmallVector<unsigned, 8> PartitionsScore(N); 9193 // For PartitionsScore, a small number of comparisons is considered as good as 9194 // a jump table and a single comparison is considered better than a jump 9195 // table. 9196 enum PartitionScores : unsigned { 9197 NoTable = 0, 9198 Table = 1, 9199 FewCases = 1, 9200 SingleCase = 2 9201 }; 9202 9203 // Base case: There is only one way to partition Clusters[N-1]. 9204 MinPartitions[N - 1] = 1; 9205 LastElement[N - 1] = N - 1; 9206 PartitionsScore[N - 1] = PartitionScores::SingleCase; 9207 9208 // Note: loop indexes are signed to avoid underflow. 9209 for (int64_t i = N - 2; i >= 0; i--) { 9210 // Find optimal partitioning of Clusters[i..N-1]. 9211 // Baseline: Put Clusters[i] into a partition on its own. 9212 MinPartitions[i] = MinPartitions[i + 1] + 1; 9213 LastElement[i] = i; 9214 PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 9215 9216 // Search for a solution that results in fewer partitions. 9217 for (int64_t j = N - 1; j > i; j--) { 9218 // Try building a partition from Clusters[i..j]. 9219 uint64_t Range = getJumpTableRange(Clusters, i, j); 9220 uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j); 9221 assert(NumCases < UINT64_MAX / 100); 9222 assert(Range >= NumCases); 9223 if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) { 9224 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9225 unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 9226 int64_t NumEntries = j - i + 1; 9227 9228 if (NumEntries == 1) 9229 Score += PartitionScores::SingleCase; 9230 else if (NumEntries <= SmallNumberOfEntries) 9231 Score += PartitionScores::FewCases; 9232 else if (NumEntries >= MinJumpTableEntries) 9233 Score += PartitionScores::Table; 9234 9235 // If this leads to fewer partitions, or to the same number of 9236 // partitions with better score, it is a better partitioning. 9237 if (NumPartitions < MinPartitions[i] || 9238 (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 9239 MinPartitions[i] = NumPartitions; 9240 LastElement[i] = j; 9241 PartitionsScore[i] = Score; 9242 } 9243 } 9244 } 9245 } 9246 9247 // Iterate over the partitions, replacing some with jump tables in-place. 9248 unsigned DstIndex = 0; 9249 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9250 Last = LastElement[First]; 9251 assert(Last >= First); 9252 assert(DstIndex <= First); 9253 unsigned NumClusters = Last - First + 1; 9254 9255 CaseCluster JTCluster; 9256 if (NumClusters >= MinJumpTableEntries && 9257 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) { 9258 Clusters[DstIndex++] = JTCluster; 9259 } else { 9260 for (unsigned I = First; I <= Last; ++I) 9261 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 9262 } 9263 } 9264 Clusters.resize(DstIndex); 9265 } 9266 9267 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters, 9268 unsigned First, unsigned Last, 9269 const SwitchInst *SI, 9270 CaseCluster &BTCluster) { 9271 assert(First <= Last); 9272 if (First == Last) 9273 return false; 9274 9275 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9276 unsigned NumCmps = 0; 9277 for (int64_t I = First; I <= Last; ++I) { 9278 assert(Clusters[I].Kind == CC_Range); 9279 Dests.set(Clusters[I].MBB->getNumber()); 9280 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 9281 } 9282 unsigned NumDests = Dests.count(); 9283 9284 APInt Low = Clusters[First].Low->getValue(); 9285 APInt High = Clusters[Last].High->getValue(); 9286 assert(Low.slt(High)); 9287 9288 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9289 const DataLayout &DL = DAG.getDataLayout(); 9290 if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL)) 9291 return false; 9292 9293 APInt LowBound; 9294 APInt CmpRange; 9295 9296 const int BitWidth = TLI.getPointerTy(DL).getSizeInBits(); 9297 assert(TLI.rangeFitsInWord(Low, High, DL) && 9298 "Case range must fit in bit mask!"); 9299 9300 // Check if the clusters cover a contiguous range such that no value in the 9301 // range will jump to the default statement. 9302 bool ContiguousRange = true; 9303 for (int64_t I = First + 1; I <= Last; ++I) { 9304 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 9305 ContiguousRange = false; 9306 break; 9307 } 9308 } 9309 9310 if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 9311 // Optimize the case where all the case values fit in a word without having 9312 // to subtract minValue. In this case, we can optimize away the subtraction. 9313 LowBound = APInt::getNullValue(Low.getBitWidth()); 9314 CmpRange = High; 9315 ContiguousRange = false; 9316 } else { 9317 LowBound = Low; 9318 CmpRange = High - Low; 9319 } 9320 9321 CaseBitsVector CBV; 9322 auto TotalProb = BranchProbability::getZero(); 9323 for (unsigned i = First; i <= Last; ++i) { 9324 // Find the CaseBits for this destination. 9325 unsigned j; 9326 for (j = 0; j < CBV.size(); ++j) 9327 if (CBV[j].BB == Clusters[i].MBB) 9328 break; 9329 if (j == CBV.size()) 9330 CBV.push_back( 9331 CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 9332 CaseBits *CB = &CBV[j]; 9333 9334 // Update Mask, Bits and ExtraProb. 9335 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 9336 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 9337 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 9338 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 9339 CB->Bits += Hi - Lo + 1; 9340 CB->ExtraProb += Clusters[i].Prob; 9341 TotalProb += Clusters[i].Prob; 9342 } 9343 9344 BitTestInfo BTI; 9345 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) { 9346 // Sort by probability first, number of bits second, bit mask third. 9347 if (a.ExtraProb != b.ExtraProb) 9348 return a.ExtraProb > b.ExtraProb; 9349 if (a.Bits != b.Bits) 9350 return a.Bits > b.Bits; 9351 return a.Mask < b.Mask; 9352 }); 9353 9354 for (auto &CB : CBV) { 9355 MachineBasicBlock *BitTestBB = 9356 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 9357 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 9358 } 9359 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 9360 SI->getCondition(), -1U, MVT::Other, false, 9361 ContiguousRange, nullptr, nullptr, std::move(BTI), 9362 TotalProb); 9363 9364 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 9365 BitTestCases.size() - 1, TotalProb); 9366 return true; 9367 } 9368 9369 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters, 9370 const SwitchInst *SI) { 9371 // Partition Clusters into as few subsets as possible, where each subset has a 9372 // range that fits in a machine word and has <= 3 unique destinations. 9373 9374 #ifndef NDEBUG 9375 // Clusters must be sorted and contain Range or JumpTable clusters. 9376 assert(!Clusters.empty()); 9377 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 9378 for (const CaseCluster &C : Clusters) 9379 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 9380 for (unsigned i = 1; i < Clusters.size(); ++i) 9381 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 9382 #endif 9383 9384 // The algorithm below is not suitable for -O0. 9385 if (TM.getOptLevel() == CodeGenOpt::None) 9386 return; 9387 9388 // If target does not have legal shift left, do not emit bit tests at all. 9389 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9390 const DataLayout &DL = DAG.getDataLayout(); 9391 9392 EVT PTy = TLI.getPointerTy(DL); 9393 if (!TLI.isOperationLegal(ISD::SHL, PTy)) 9394 return; 9395 9396 int BitWidth = PTy.getSizeInBits(); 9397 const int64_t N = Clusters.size(); 9398 9399 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 9400 SmallVector<unsigned, 8> MinPartitions(N); 9401 // LastElement[i] is the last element of the partition starting at i. 9402 SmallVector<unsigned, 8> LastElement(N); 9403 9404 // FIXME: This might not be the best algorithm for finding bit test clusters. 9405 9406 // Base case: There is only one way to partition Clusters[N-1]. 9407 MinPartitions[N - 1] = 1; 9408 LastElement[N - 1] = N - 1; 9409 9410 // Note: loop indexes are signed to avoid underflow. 9411 for (int64_t i = N - 2; i >= 0; --i) { 9412 // Find optimal partitioning of Clusters[i..N-1]. 9413 // Baseline: Put Clusters[i] into a partition on its own. 9414 MinPartitions[i] = MinPartitions[i + 1] + 1; 9415 LastElement[i] = i; 9416 9417 // Search for a solution that results in fewer partitions. 9418 // Note: the search is limited by BitWidth, reducing time complexity. 9419 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 9420 // Try building a partition from Clusters[i..j]. 9421 9422 // Check the range. 9423 if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(), 9424 Clusters[j].High->getValue(), DL)) 9425 continue; 9426 9427 // Check nbr of destinations and cluster types. 9428 // FIXME: This works, but doesn't seem very efficient. 9429 bool RangesOnly = true; 9430 BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 9431 for (int64_t k = i; k <= j; k++) { 9432 if (Clusters[k].Kind != CC_Range) { 9433 RangesOnly = false; 9434 break; 9435 } 9436 Dests.set(Clusters[k].MBB->getNumber()); 9437 } 9438 if (!RangesOnly || Dests.count() > 3) 9439 break; 9440 9441 // Check if it's a better partition. 9442 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 9443 if (NumPartitions < MinPartitions[i]) { 9444 // Found a better partition. 9445 MinPartitions[i] = NumPartitions; 9446 LastElement[i] = j; 9447 } 9448 } 9449 } 9450 9451 // Iterate over the partitions, replacing with bit-test clusters in-place. 9452 unsigned DstIndex = 0; 9453 for (unsigned First = 0, Last; First < N; First = Last + 1) { 9454 Last = LastElement[First]; 9455 assert(First <= Last); 9456 assert(DstIndex <= First); 9457 9458 CaseCluster BitTestCluster; 9459 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 9460 Clusters[DstIndex++] = BitTestCluster; 9461 } else { 9462 size_t NumClusters = Last - First + 1; 9463 std::memmove(&Clusters[DstIndex], &Clusters[First], 9464 sizeof(Clusters[0]) * NumClusters); 9465 DstIndex += NumClusters; 9466 } 9467 } 9468 Clusters.resize(DstIndex); 9469 } 9470 9471 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond, 9472 MachineBasicBlock *SwitchMBB, 9473 MachineBasicBlock *DefaultMBB) { 9474 MachineFunction *CurMF = FuncInfo.MF; 9475 MachineBasicBlock *NextMBB = nullptr; 9476 MachineFunction::iterator BBI(W.MBB); 9477 if (++BBI != FuncInfo.MF->end()) 9478 NextMBB = &*BBI; 9479 9480 unsigned Size = W.LastCluster - W.FirstCluster + 1; 9481 9482 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9483 9484 if (Size == 2 && W.MBB == SwitchMBB) { 9485 // If any two of the cases has the same destination, and if one value 9486 // is the same as the other, but has one bit unset that the other has set, 9487 // use bit manipulation to do two compares at once. For example: 9488 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 9489 // TODO: This could be extended to merge any 2 cases in switches with 3 9490 // cases. 9491 // TODO: Handle cases where W.CaseBB != SwitchBB. 9492 CaseCluster &Small = *W.FirstCluster; 9493 CaseCluster &Big = *W.LastCluster; 9494 9495 if (Small.Low == Small.High && Big.Low == Big.High && 9496 Small.MBB == Big.MBB) { 9497 const APInt &SmallValue = Small.Low->getValue(); 9498 const APInt &BigValue = Big.Low->getValue(); 9499 9500 // Check that there is only one bit different. 9501 APInt CommonBit = BigValue ^ SmallValue; 9502 if (CommonBit.isPowerOf2()) { 9503 SDValue CondLHS = getValue(Cond); 9504 EVT VT = CondLHS.getValueType(); 9505 SDLoc DL = getCurSDLoc(); 9506 9507 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 9508 DAG.getConstant(CommonBit, DL, VT)); 9509 SDValue Cond = DAG.getSetCC( 9510 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT), 9511 ISD::SETEQ); 9512 9513 // Update successor info. 9514 // Both Small and Big will jump to Small.BB, so we sum up the 9515 // probabilities. 9516 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob); 9517 if (BPI) 9518 addSuccessorWithProb( 9519 SwitchMBB, DefaultMBB, 9520 // The default destination is the first successor in IR. 9521 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0)); 9522 else 9523 addSuccessorWithProb(SwitchMBB, DefaultMBB); 9524 9525 // Insert the true branch. 9526 SDValue BrCond = 9527 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond, 9528 DAG.getBasicBlock(Small.MBB)); 9529 // Insert the false branch. 9530 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 9531 DAG.getBasicBlock(DefaultMBB)); 9532 9533 DAG.setRoot(BrCond); 9534 return; 9535 } 9536 } 9537 } 9538 9539 if (TM.getOptLevel() != CodeGenOpt::None) { 9540 // Here, we order cases by probability so the most likely case will be 9541 // checked first. However, two clusters can have the same probability in 9542 // which case their relative ordering is non-deterministic. So we use Low 9543 // as a tie-breaker as clusters are guaranteed to never overlap. 9544 std::sort(W.FirstCluster, W.LastCluster + 1, 9545 [](const CaseCluster &a, const CaseCluster &b) { 9546 return a.Prob != b.Prob ? 9547 a.Prob > b.Prob : 9548 a.Low->getValue().slt(b.Low->getValue()); 9549 }); 9550 9551 // Rearrange the case blocks so that the last one falls through if possible 9552 // without without changing the order of probabilities. 9553 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) { 9554 --I; 9555 if (I->Prob > W.LastCluster->Prob) 9556 break; 9557 if (I->Kind == CC_Range && I->MBB == NextMBB) { 9558 std::swap(*I, *W.LastCluster); 9559 break; 9560 } 9561 } 9562 } 9563 9564 // Compute total probability. 9565 BranchProbability DefaultProb = W.DefaultProb; 9566 BranchProbability UnhandledProbs = DefaultProb; 9567 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 9568 UnhandledProbs += I->Prob; 9569 9570 MachineBasicBlock *CurMBB = W.MBB; 9571 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 9572 MachineBasicBlock *Fallthrough; 9573 if (I == W.LastCluster) { 9574 // For the last cluster, fall through to the default destination. 9575 Fallthrough = DefaultMBB; 9576 } else { 9577 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 9578 CurMF->insert(BBI, Fallthrough); 9579 // Put Cond in a virtual register to make it available from the new blocks. 9580 ExportFromCurrentBlock(Cond); 9581 } 9582 UnhandledProbs -= I->Prob; 9583 9584 switch (I->Kind) { 9585 case CC_JumpTable: { 9586 // FIXME: Optimize away range check based on pivot comparisons. 9587 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first; 9588 JumpTable *JT = &JTCases[I->JTCasesIndex].second; 9589 9590 // The jump block hasn't been inserted yet; insert it here. 9591 MachineBasicBlock *JumpMBB = JT->MBB; 9592 CurMF->insert(BBI, JumpMBB); 9593 9594 auto JumpProb = I->Prob; 9595 auto FallthroughProb = UnhandledProbs; 9596 9597 // If the default statement is a target of the jump table, we evenly 9598 // distribute the default probability to successors of CurMBB. Also 9599 // update the probability on the edge from JumpMBB to Fallthrough. 9600 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 9601 SE = JumpMBB->succ_end(); 9602 SI != SE; ++SI) { 9603 if (*SI == DefaultMBB) { 9604 JumpProb += DefaultProb / 2; 9605 FallthroughProb -= DefaultProb / 2; 9606 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 9607 JumpMBB->normalizeSuccProbs(); 9608 break; 9609 } 9610 } 9611 9612 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 9613 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 9614 CurMBB->normalizeSuccProbs(); 9615 9616 // The jump table header will be inserted in our current block, do the 9617 // range check, and fall through to our fallthrough block. 9618 JTH->HeaderBB = CurMBB; 9619 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 9620 9621 // If we're in the right place, emit the jump table header right now. 9622 if (CurMBB == SwitchMBB) { 9623 visitJumpTableHeader(*JT, *JTH, SwitchMBB); 9624 JTH->Emitted = true; 9625 } 9626 break; 9627 } 9628 case CC_BitTests: { 9629 // FIXME: Optimize away range check based on pivot comparisons. 9630 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex]; 9631 9632 // The bit test blocks haven't been inserted yet; insert them here. 9633 for (BitTestCase &BTC : BTB->Cases) 9634 CurMF->insert(BBI, BTC.ThisBB); 9635 9636 // Fill in fields of the BitTestBlock. 9637 BTB->Parent = CurMBB; 9638 BTB->Default = Fallthrough; 9639 9640 BTB->DefaultProb = UnhandledProbs; 9641 // If the cases in bit test don't form a contiguous range, we evenly 9642 // distribute the probability on the edge to Fallthrough to two 9643 // successors of CurMBB. 9644 if (!BTB->ContiguousRange) { 9645 BTB->Prob += DefaultProb / 2; 9646 BTB->DefaultProb -= DefaultProb / 2; 9647 } 9648 9649 // If we're in the right place, emit the bit test header right now. 9650 if (CurMBB == SwitchMBB) { 9651 visitBitTestHeader(*BTB, SwitchMBB); 9652 BTB->Emitted = true; 9653 } 9654 break; 9655 } 9656 case CC_Range: { 9657 const Value *RHS, *LHS, *MHS; 9658 ISD::CondCode CC; 9659 if (I->Low == I->High) { 9660 // Check Cond == I->Low. 9661 CC = ISD::SETEQ; 9662 LHS = Cond; 9663 RHS=I->Low; 9664 MHS = nullptr; 9665 } else { 9666 // Check I->Low <= Cond <= I->High. 9667 CC = ISD::SETLE; 9668 LHS = I->Low; 9669 MHS = Cond; 9670 RHS = I->High; 9671 } 9672 9673 // The false probability is the sum of all unhandled cases. 9674 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, 9675 getCurSDLoc(), I->Prob, UnhandledProbs); 9676 9677 if (CurMBB == SwitchMBB) 9678 visitSwitchCase(CB, SwitchMBB); 9679 else 9680 SwitchCases.push_back(CB); 9681 9682 break; 9683 } 9684 } 9685 CurMBB = Fallthrough; 9686 } 9687 } 9688 9689 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC, 9690 CaseClusterIt First, 9691 CaseClusterIt Last) { 9692 return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 9693 if (X.Prob != CC.Prob) 9694 return X.Prob > CC.Prob; 9695 9696 // Ties are broken by comparing the case value. 9697 return X.Low->getValue().slt(CC.Low->getValue()); 9698 }); 9699 } 9700 9701 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList, 9702 const SwitchWorkListItem &W, 9703 Value *Cond, 9704 MachineBasicBlock *SwitchMBB) { 9705 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) && 9706 "Clusters not sorted?"); 9707 9708 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!"); 9709 9710 // Balance the tree based on branch probabilities to create a near-optimal (in 9711 // terms of search time given key frequency) binary search tree. See e.g. Kurt 9712 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975). 9713 CaseClusterIt LastLeft = W.FirstCluster; 9714 CaseClusterIt FirstRight = W.LastCluster; 9715 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 9716 auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 9717 9718 // Move LastLeft and FirstRight towards each other from opposite directions to 9719 // find a partitioning of the clusters which balances the probability on both 9720 // sides. If LeftProb and RightProb are equal, alternate which side is 9721 // taken to ensure 0-probability nodes are distributed evenly. 9722 unsigned I = 0; 9723 while (LastLeft + 1 < FirstRight) { 9724 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 9725 LeftProb += (++LastLeft)->Prob; 9726 else 9727 RightProb += (--FirstRight)->Prob; 9728 I++; 9729 } 9730 9731 while (true) { 9732 // Our binary search tree differs from a typical BST in that ours can have up 9733 // to three values in each leaf. The pivot selection above doesn't take that 9734 // into account, which means the tree might require more nodes and be less 9735 // efficient. We compensate for this here. 9736 9737 unsigned NumLeft = LastLeft - W.FirstCluster + 1; 9738 unsigned NumRight = W.LastCluster - FirstRight + 1; 9739 9740 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 9741 // If one side has less than 3 clusters, and the other has more than 3, 9742 // consider taking a cluster from the other side. 9743 9744 if (NumLeft < NumRight) { 9745 // Consider moving the first cluster on the right to the left side. 9746 CaseCluster &CC = *FirstRight; 9747 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9748 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9749 if (LeftSideRank <= RightSideRank) { 9750 // Moving the cluster to the left does not demote it. 9751 ++LastLeft; 9752 ++FirstRight; 9753 continue; 9754 } 9755 } else { 9756 assert(NumRight < NumLeft); 9757 // Consider moving the last element on the left to the right side. 9758 CaseCluster &CC = *LastLeft; 9759 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 9760 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 9761 if (RightSideRank <= LeftSideRank) { 9762 // Moving the cluster to the right does not demot it. 9763 --LastLeft; 9764 --FirstRight; 9765 continue; 9766 } 9767 } 9768 } 9769 break; 9770 } 9771 9772 assert(LastLeft + 1 == FirstRight); 9773 assert(LastLeft >= W.FirstCluster); 9774 assert(FirstRight <= W.LastCluster); 9775 9776 // Use the first element on the right as pivot since we will make less-than 9777 // comparisons against it. 9778 CaseClusterIt PivotCluster = FirstRight; 9779 assert(PivotCluster > W.FirstCluster); 9780 assert(PivotCluster <= W.LastCluster); 9781 9782 CaseClusterIt FirstLeft = W.FirstCluster; 9783 CaseClusterIt LastRight = W.LastCluster; 9784 9785 const ConstantInt *Pivot = PivotCluster->Low; 9786 9787 // New blocks will be inserted immediately after the current one. 9788 MachineFunction::iterator BBI(W.MBB); 9789 ++BBI; 9790 9791 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster, 9792 // we can branch to its destination directly if it's squeezed exactly in 9793 // between the known lower bound and Pivot - 1. 9794 MachineBasicBlock *LeftMBB; 9795 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range && 9796 FirstLeft->Low == W.GE && 9797 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) { 9798 LeftMBB = FirstLeft->MBB; 9799 } else { 9800 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 9801 FuncInfo.MF->insert(BBI, LeftMBB); 9802 WorkList.push_back( 9803 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2}); 9804 // Put Cond in a virtual register to make it available from the new blocks. 9805 ExportFromCurrentBlock(Cond); 9806 } 9807 9808 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a 9809 // single cluster, RHS.Low == Pivot, and we can branch to its destination 9810 // directly if RHS.High equals the current upper bound. 9811 MachineBasicBlock *RightMBB; 9812 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && 9813 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) { 9814 RightMBB = FirstRight->MBB; 9815 } else { 9816 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock()); 9817 FuncInfo.MF->insert(BBI, RightMBB); 9818 WorkList.push_back( 9819 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2}); 9820 // Put Cond in a virtual register to make it available from the new blocks. 9821 ExportFromCurrentBlock(Cond); 9822 } 9823 9824 // Create the CaseBlock record that will be used to lower the branch. 9825 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB, 9826 getCurSDLoc(), LeftProb, RightProb); 9827 9828 if (W.MBB == SwitchMBB) 9829 visitSwitchCase(CB, SwitchMBB); 9830 else 9831 SwitchCases.push_back(CB); 9832 } 9833 9834 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb 9835 // from the swith statement. 9836 static BranchProbability scaleCaseProbality(BranchProbability CaseProb, 9837 BranchProbability PeeledCaseProb) { 9838 if (PeeledCaseProb == BranchProbability::getOne()) 9839 return BranchProbability::getZero(); 9840 BranchProbability SwitchProb = PeeledCaseProb.getCompl(); 9841 9842 uint32_t Numerator = CaseProb.getNumerator(); 9843 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator()); 9844 return BranchProbability(Numerator, std::max(Numerator, Denominator)); 9845 } 9846 9847 // Try to peel the top probability case if it exceeds the threshold. 9848 // Return current MachineBasicBlock for the switch statement if the peeling 9849 // does not occur. 9850 // If the peeling is performed, return the newly created MachineBasicBlock 9851 // for the peeled switch statement. Also update Clusters to remove the peeled 9852 // case. PeeledCaseProb is the BranchProbability for the peeled case. 9853 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster( 9854 const SwitchInst &SI, CaseClusterVector &Clusters, 9855 BranchProbability &PeeledCaseProb) { 9856 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 9857 // Don't perform if there is only one cluster or optimizing for size. 9858 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 || 9859 TM.getOptLevel() == CodeGenOpt::None || 9860 SwitchMBB->getParent()->getFunction()->optForMinSize()) 9861 return SwitchMBB; 9862 9863 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100); 9864 unsigned PeeledCaseIndex = 0; 9865 bool SwitchPeeled = false; 9866 for (unsigned Index = 0; Index < Clusters.size(); ++Index) { 9867 CaseCluster &CC = Clusters[Index]; 9868 if (CC.Prob < TopCaseProb) 9869 continue; 9870 TopCaseProb = CC.Prob; 9871 PeeledCaseIndex = Index; 9872 SwitchPeeled = true; 9873 } 9874 if (!SwitchPeeled) 9875 return SwitchMBB; 9876 9877 DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: " << TopCaseProb 9878 << "\n"); 9879 9880 // Record the MBB for the peeled switch statement. 9881 MachineFunction::iterator BBI(SwitchMBB); 9882 ++BBI; 9883 MachineBasicBlock *PeeledSwitchMBB = 9884 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock()); 9885 FuncInfo.MF->insert(BBI, PeeledSwitchMBB); 9886 9887 ExportFromCurrentBlock(SI.getCondition()); 9888 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex; 9889 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt, 9890 nullptr, nullptr, TopCaseProb.getCompl()}; 9891 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB); 9892 9893 Clusters.erase(PeeledCaseIt); 9894 for (CaseCluster &CC : Clusters) { 9895 DEBUG(dbgs() << "Scale the probablity for one cluster, before scaling: " 9896 << CC.Prob << "\n"); 9897 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb); 9898 DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n"); 9899 } 9900 PeeledCaseProb = TopCaseProb; 9901 return PeeledSwitchMBB; 9902 } 9903 9904 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 9905 // Extract cases from the switch. 9906 BranchProbabilityInfo *BPI = FuncInfo.BPI; 9907 CaseClusterVector Clusters; 9908 Clusters.reserve(SI.getNumCases()); 9909 for (auto I : SI.cases()) { 9910 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()]; 9911 const ConstantInt *CaseVal = I.getCaseValue(); 9912 BranchProbability Prob = 9913 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 9914 : BranchProbability(1, SI.getNumCases() + 1); 9915 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 9916 } 9917 9918 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()]; 9919 9920 // Cluster adjacent cases with the same destination. We do this at all 9921 // optimization levels because it's cheap to do and will make codegen faster 9922 // if there are many clusters. 9923 sortAndRangeify(Clusters); 9924 9925 if (TM.getOptLevel() != CodeGenOpt::None) { 9926 // Replace an unreachable default with the most popular destination. 9927 // FIXME: Exploit unreachable default more aggressively. 9928 bool UnreachableDefault = 9929 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()); 9930 if (UnreachableDefault && !Clusters.empty()) { 9931 DenseMap<const BasicBlock *, unsigned> Popularity; 9932 unsigned MaxPop = 0; 9933 const BasicBlock *MaxBB = nullptr; 9934 for (auto I : SI.cases()) { 9935 const BasicBlock *BB = I.getCaseSuccessor(); 9936 if (++Popularity[BB] > MaxPop) { 9937 MaxPop = Popularity[BB]; 9938 MaxBB = BB; 9939 } 9940 } 9941 // Set new default. 9942 assert(MaxPop > 0 && MaxBB); 9943 DefaultMBB = FuncInfo.MBBMap[MaxBB]; 9944 9945 // Remove cases that were pointing to the destination that is now the 9946 // default. 9947 CaseClusterVector New; 9948 New.reserve(Clusters.size()); 9949 for (CaseCluster &CC : Clusters) { 9950 if (CC.MBB != DefaultMBB) 9951 New.push_back(CC); 9952 } 9953 Clusters = std::move(New); 9954 } 9955 } 9956 9957 // The branch probablity of the peeled case. 9958 BranchProbability PeeledCaseProb = BranchProbability::getZero(); 9959 MachineBasicBlock *PeeledSwitchMBB = 9960 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb); 9961 9962 // If there is only the default destination, jump there directly. 9963 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 9964 if (Clusters.empty()) { 9965 assert(PeeledSwitchMBB == SwitchMBB); 9966 SwitchMBB->addSuccessor(DefaultMBB); 9967 if (DefaultMBB != NextBlock(SwitchMBB)) { 9968 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, 9969 getControlRoot(), DAG.getBasicBlock(DefaultMBB))); 9970 } 9971 return; 9972 } 9973 9974 findJumpTables(Clusters, &SI, DefaultMBB); 9975 findBitTestClusters(Clusters, &SI); 9976 9977 DEBUG({ 9978 dbgs() << "Case clusters: "; 9979 for (const CaseCluster &C : Clusters) { 9980 if (C.Kind == CC_JumpTable) dbgs() << "JT:"; 9981 if (C.Kind == CC_BitTests) dbgs() << "BT:"; 9982 9983 C.Low->getValue().print(dbgs(), true); 9984 if (C.Low != C.High) { 9985 dbgs() << '-'; 9986 C.High->getValue().print(dbgs(), true); 9987 } 9988 dbgs() << ' '; 9989 } 9990 dbgs() << '\n'; 9991 }); 9992 9993 assert(!Clusters.empty()); 9994 SwitchWorkList WorkList; 9995 CaseClusterIt First = Clusters.begin(); 9996 CaseClusterIt Last = Clusters.end() - 1; 9997 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB); 9998 // Scale the branchprobability for DefaultMBB if the peel occurs and 9999 // DefaultMBB is not replaced. 10000 if (PeeledCaseProb != BranchProbability::getZero() && 10001 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()]) 10002 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb); 10003 WorkList.push_back( 10004 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 10005 10006 while (!WorkList.empty()) { 10007 SwitchWorkListItem W = WorkList.back(); 10008 WorkList.pop_back(); 10009 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1; 10010 10011 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None && 10012 !DefaultMBB->getParent()->getFunction()->optForMinSize()) { 10013 // For optimized builds, lower large range as a balanced binary tree. 10014 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB); 10015 continue; 10016 } 10017 10018 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB); 10019 } 10020 } 10021