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 #define DEBUG_TYPE "isel" 15 #include "SelectionDAGBuilder.h" 16 #include "SDNodeDbgValue.h" 17 #include "llvm/ADT/BitVector.h" 18 #include "llvm/ADT/Optional.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/BranchProbabilityInfo.h" 22 #include "llvm/Analysis/ConstantFolding.h" 23 #include "llvm/Analysis/ValueTracking.h" 24 #include "llvm/CodeGen/Analysis.h" 25 #include "llvm/CodeGen/FastISel.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GCMetadata.h" 28 #include "llvm/CodeGen/GCStrategy.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineInstrBuilder.h" 32 #include "llvm/CodeGen/MachineJumpTableInfo.h" 33 #include "llvm/CodeGen/MachineModuleInfo.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/SelectionDAG.h" 36 #include "llvm/DebugInfo.h" 37 #include "llvm/IR/CallingConv.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/DataLayout.h" 40 #include "llvm/IR/DerivedTypes.h" 41 #include "llvm/IR/Function.h" 42 #include "llvm/IR/GlobalVariable.h" 43 #include "llvm/IR/InlineAsm.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/IntrinsicInst.h" 46 #include "llvm/IR/Intrinsics.h" 47 #include "llvm/IR/LLVMContext.h" 48 #include "llvm/IR/Module.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/ErrorHandling.h" 52 #include "llvm/Support/IntegersSubsetMapping.h" 53 #include "llvm/Support/MathExtras.h" 54 #include "llvm/Support/raw_ostream.h" 55 #include "llvm/Target/TargetFrameLowering.h" 56 #include "llvm/Target/TargetInstrInfo.h" 57 #include "llvm/Target/TargetIntrinsicInfo.h" 58 #include "llvm/Target/TargetLibraryInfo.h" 59 #include "llvm/Target/TargetLowering.h" 60 #include "llvm/Target/TargetOptions.h" 61 #include "llvm/Target/TargetSelectionDAGInfo.h" 62 #include <algorithm> 63 using namespace llvm; 64 65 /// LimitFloatPrecision - Generate low-precision inline sequences for 66 /// some float libcalls (6, 8 or 12 bits). 67 static unsigned LimitFloatPrecision; 68 69 static cl::opt<unsigned, true> 70 LimitFPPrecision("limit-float-precision", 71 cl::desc("Generate low-precision inline sequences " 72 "for some float libcalls"), 73 cl::location(LimitFloatPrecision), 74 cl::init(0)); 75 76 // Limit the width of DAG chains. This is important in general to prevent 77 // prevent DAG-based analysis from blowing up. For example, alias analysis and 78 // load clustering may not complete in reasonable time. It is difficult to 79 // recognize and avoid this situation within each individual analysis, and 80 // future analyses are likely to have the same behavior. Limiting DAG width is 81 // the safe approach, and will be especially important with global DAGs. 82 // 83 // MaxParallelChains default is arbitrarily high to avoid affecting 84 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st 85 // sequence over this should have been converted to llvm.memcpy by the 86 // frontend. It easy to induce this behavior with .ll code such as: 87 // %buffer = alloca [4096 x i8] 88 // %data = load [4096 x i8]* %argPtr 89 // store [4096 x i8] %data, [4096 x i8]* %buffer 90 static const unsigned MaxParallelChains = 64; 91 92 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL, 93 const SDValue *Parts, unsigned NumParts, 94 MVT PartVT, EVT ValueVT, const Value *V); 95 96 /// getCopyFromParts - Create a value that contains the specified legal parts 97 /// combined into the value they represent. If the parts combine to a type 98 /// larger then ValueVT then AssertOp can be used to specify whether the extra 99 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT 100 /// (ISD::AssertSext). 101 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL, 102 const SDValue *Parts, 103 unsigned NumParts, MVT PartVT, EVT ValueVT, 104 const Value *V, 105 ISD::NodeType AssertOp = ISD::DELETED_NODE) { 106 if (ValueVT.isVector()) 107 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, 108 PartVT, ValueVT, V); 109 110 assert(NumParts > 0 && "No parts to assemble!"); 111 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 112 SDValue Val = Parts[0]; 113 114 if (NumParts > 1) { 115 // Assemble the value from multiple parts. 116 if (ValueVT.isInteger()) { 117 unsigned PartBits = PartVT.getSizeInBits(); 118 unsigned ValueBits = ValueVT.getSizeInBits(); 119 120 // Assemble the power of 2 part. 121 unsigned RoundParts = NumParts & (NumParts - 1) ? 122 1 << Log2_32(NumParts) : NumParts; 123 unsigned RoundBits = PartBits * RoundParts; 124 EVT RoundVT = RoundBits == ValueBits ? 125 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits); 126 SDValue Lo, Hi; 127 128 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2); 129 130 if (RoundParts > 2) { 131 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, 132 PartVT, HalfVT, V); 133 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, 134 RoundParts / 2, PartVT, HalfVT, V); 135 } else { 136 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]); 137 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]); 138 } 139 140 if (TLI.isBigEndian()) 141 std::swap(Lo, Hi); 142 143 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi); 144 145 if (RoundParts < NumParts) { 146 // Assemble the trailing non-power-of-2 part. 147 unsigned OddParts = NumParts - RoundParts; 148 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits); 149 Hi = getCopyFromParts(DAG, DL, 150 Parts + RoundParts, OddParts, PartVT, OddVT, V); 151 152 // Combine the round and odd parts. 153 Lo = Val; 154 if (TLI.isBigEndian()) 155 std::swap(Lo, Hi); 156 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 157 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi); 158 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi, 159 DAG.getConstant(Lo.getValueType().getSizeInBits(), 160 TLI.getPointerTy())); 161 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo); 162 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi); 163 } 164 } else if (PartVT.isFloatingPoint()) { 165 // FP split into multiple FP parts (for ppcf128) 166 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && 167 "Unexpected split"); 168 SDValue Lo, Hi; 169 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]); 170 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]); 171 if (TLI.isBigEndian()) 172 std::swap(Lo, Hi); 173 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi); 174 } else { 175 // FP split into integer parts (soft fp) 176 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() && 177 !PartVT.isVector() && "Unexpected split"); 178 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()); 179 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V); 180 } 181 } 182 183 // There is now one part, held in Val. Correct it to match ValueVT. 184 EVT PartEVT = Val.getValueType(); 185 186 if (PartEVT == ValueVT) 187 return Val; 188 189 if (PartEVT.isInteger() && ValueVT.isInteger()) { 190 if (ValueVT.bitsLT(PartEVT)) { 191 // For a truncate, see if we have any information to 192 // indicate whether the truncated bits will always be 193 // zero or sign-extension. 194 if (AssertOp != ISD::DELETED_NODE) 195 Val = DAG.getNode(AssertOp, DL, PartEVT, Val, 196 DAG.getValueType(ValueVT)); 197 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 198 } 199 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val); 200 } 201 202 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 203 // FP_ROUND's are always exact here. 204 if (ValueVT.bitsLT(Val.getValueType())) 205 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, 206 DAG.getTargetConstant(1, TLI.getPointerTy())); 207 208 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val); 209 } 210 211 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits()) 212 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 213 214 llvm_unreachable("Unknown mismatch!"); 215 } 216 217 /// getCopyFromPartsVector - Create a value that contains the specified legal 218 /// parts combined into the value they represent. If the parts combine to a 219 /// type larger then ValueVT then AssertOp can be used to specify whether the 220 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from 221 /// ValueVT (ISD::AssertSext). 222 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL, 223 const SDValue *Parts, unsigned NumParts, 224 MVT PartVT, EVT ValueVT, const Value *V) { 225 assert(ValueVT.isVector() && "Not a vector value"); 226 assert(NumParts > 0 && "No parts to assemble!"); 227 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 228 SDValue Val = Parts[0]; 229 230 // Handle a multi-element vector. 231 if (NumParts > 1) { 232 EVT IntermediateVT; 233 MVT RegisterVT; 234 unsigned NumIntermediates; 235 unsigned NumRegs = 236 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT, 237 NumIntermediates, RegisterVT); 238 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 239 NumParts = NumRegs; // Silence a compiler warning. 240 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 241 assert(RegisterVT == Parts[0].getSimpleValueType() && 242 "Part type doesn't match part!"); 243 244 // Assemble the parts into intermediate operands. 245 SmallVector<SDValue, 8> Ops(NumIntermediates); 246 if (NumIntermediates == NumParts) { 247 // If the register was not expanded, truncate or copy the value, 248 // as appropriate. 249 for (unsigned i = 0; i != NumParts; ++i) 250 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, 251 PartVT, IntermediateVT, V); 252 } else if (NumParts > 0) { 253 // If the intermediate type was expanded, build the intermediate 254 // operands from the parts. 255 assert(NumParts % NumIntermediates == 0 && 256 "Must expand into a divisible number of parts!"); 257 unsigned Factor = NumParts / NumIntermediates; 258 for (unsigned i = 0; i != NumIntermediates; ++i) 259 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, 260 PartVT, IntermediateVT, V); 261 } 262 263 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the 264 // intermediate operands. 265 Val = DAG.getNode(IntermediateVT.isVector() ? 266 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL, 267 ValueVT, &Ops[0], NumIntermediates); 268 } 269 270 // There is now one part, held in Val. Correct it to match ValueVT. 271 EVT PartEVT = Val.getValueType(); 272 273 if (PartEVT == ValueVT) 274 return Val; 275 276 if (PartEVT.isVector()) { 277 // If the element type of the source/dest vectors are the same, but the 278 // parts vector has more elements than the value vector, then we have a 279 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the 280 // elements we want. 281 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) { 282 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() && 283 "Cannot narrow, it would be a lossy transformation"); 284 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 285 DAG.getConstant(0, TLI.getVectorIdxTy())); 286 } 287 288 // Vector/Vector bitcast. 289 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) 290 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 291 292 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() && 293 "Cannot handle this kind of promotion"); 294 // Promoted vector extract 295 bool Smaller = ValueVT.bitsLE(PartEVT); 296 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 297 DL, ValueVT, Val); 298 299 } 300 301 // Trivial bitcast if the types are the same size and the destination 302 // vector type is legal. 303 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() && 304 TLI.isTypeLegal(ValueVT)) 305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val); 306 307 // Handle cases such as i8 -> <1 x i1> 308 if (ValueVT.getVectorNumElements() != 1) { 309 LLVMContext &Ctx = *DAG.getContext(); 310 Twine ErrMsg("non-trivial scalar-to-vector conversion"); 311 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) { 312 if (const CallInst *CI = dyn_cast<CallInst>(I)) 313 if (isa<InlineAsm>(CI->getCalledValue())) 314 ErrMsg = ErrMsg + ", possible invalid constraint for vector type"; 315 Ctx.emitError(I, ErrMsg); 316 } else { 317 Ctx.emitError(ErrMsg); 318 } 319 return DAG.getUNDEF(ValueVT); 320 } 321 322 if (ValueVT.getVectorNumElements() == 1 && 323 ValueVT.getVectorElementType() != PartEVT) { 324 bool Smaller = ValueVT.bitsLE(PartEVT); 325 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 326 DL, ValueVT.getScalarType(), Val); 327 } 328 329 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val); 330 } 331 332 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl, 333 SDValue Val, SDValue *Parts, unsigned NumParts, 334 MVT PartVT, const Value *V); 335 336 /// getCopyToParts - Create a series of nodes that contain the specified value 337 /// split into legal parts. If the parts contain more bits than Val, then, for 338 /// integers, ExtendKind can be used to specify how to generate the extra bits. 339 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL, 340 SDValue Val, SDValue *Parts, unsigned NumParts, 341 MVT PartVT, const Value *V, 342 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) { 343 EVT ValueVT = Val.getValueType(); 344 345 // Handle the vector case separately. 346 if (ValueVT.isVector()) 347 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V); 348 349 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 350 unsigned PartBits = PartVT.getSizeInBits(); 351 unsigned OrigNumParts = NumParts; 352 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!"); 353 354 if (NumParts == 0) 355 return; 356 357 assert(!ValueVT.isVector() && "Vector case handled elsewhere"); 358 EVT PartEVT = PartVT; 359 if (PartEVT == ValueVT) { 360 assert(NumParts == 1 && "No-op copy with multiple parts!"); 361 Parts[0] = Val; 362 return; 363 } 364 365 if (NumParts * PartBits > ValueVT.getSizeInBits()) { 366 // If the parts cover more bits than the value has, promote the value. 367 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) { 368 assert(NumParts == 1 && "Do not know what to promote to!"); 369 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val); 370 } else { 371 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 372 ValueVT.isInteger() && 373 "Unknown mismatch!"); 374 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 375 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val); 376 if (PartVT == MVT::x86mmx) 377 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 378 } 379 } else if (PartBits == ValueVT.getSizeInBits()) { 380 // Different types of the same size. 381 assert(NumParts == 1 && PartEVT != ValueVT); 382 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 383 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) { 384 // If the parts cover less bits than value has, truncate the value. 385 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) && 386 ValueVT.isInteger() && 387 "Unknown mismatch!"); 388 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 389 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 390 if (PartVT == MVT::x86mmx) 391 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 392 } 393 394 // The value may have changed - recompute ValueVT. 395 ValueVT = Val.getValueType(); 396 assert(NumParts * PartBits == ValueVT.getSizeInBits() && 397 "Failed to tile the value with PartVT!"); 398 399 if (NumParts == 1) { 400 if (PartEVT != ValueVT) { 401 LLVMContext &Ctx = *DAG.getContext(); 402 Twine ErrMsg("scalar-to-vector conversion failed"); 403 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) { 404 if (const CallInst *CI = dyn_cast<CallInst>(I)) 405 if (isa<InlineAsm>(CI->getCalledValue())) 406 ErrMsg = ErrMsg + ", possible invalid constraint for vector type"; 407 Ctx.emitError(I, ErrMsg); 408 } else { 409 Ctx.emitError(ErrMsg); 410 } 411 } 412 413 Parts[0] = Val; 414 return; 415 } 416 417 // Expand the value into multiple parts. 418 if (NumParts & (NumParts - 1)) { 419 // The number of parts is not a power of 2. Split off and copy the tail. 420 assert(PartVT.isInteger() && ValueVT.isInteger() && 421 "Do not know what to expand to!"); 422 unsigned RoundParts = 1 << Log2_32(NumParts); 423 unsigned RoundBits = RoundParts * PartBits; 424 unsigned OddParts = NumParts - RoundParts; 425 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val, 426 DAG.getIntPtrConstant(RoundBits)); 427 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V); 428 429 if (TLI.isBigEndian()) 430 // The odd parts were reversed by getCopyToParts - unreverse them. 431 std::reverse(Parts + RoundParts, Parts + NumParts); 432 433 NumParts = RoundParts; 434 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits); 435 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val); 436 } 437 438 // The number of parts is a power of 2. Repeatedly bisect the value using 439 // EXTRACT_ELEMENT. 440 Parts[0] = DAG.getNode(ISD::BITCAST, DL, 441 EVT::getIntegerVT(*DAG.getContext(), 442 ValueVT.getSizeInBits()), 443 Val); 444 445 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) { 446 for (unsigned i = 0; i < NumParts; i += StepSize) { 447 unsigned ThisBits = StepSize * PartBits / 2; 448 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits); 449 SDValue &Part0 = Parts[i]; 450 SDValue &Part1 = Parts[i+StepSize/2]; 451 452 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 453 ThisVT, Part0, DAG.getIntPtrConstant(1)); 454 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, 455 ThisVT, Part0, DAG.getIntPtrConstant(0)); 456 457 if (ThisBits == PartBits && ThisVT != PartVT) { 458 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0); 459 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1); 460 } 461 } 462 } 463 464 if (TLI.isBigEndian()) 465 std::reverse(Parts, Parts + OrigNumParts); 466 } 467 468 469 /// getCopyToPartsVector - Create a series of nodes that contain the specified 470 /// value split into legal parts. 471 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL, 472 SDValue Val, SDValue *Parts, unsigned NumParts, 473 MVT PartVT, const Value *V) { 474 EVT ValueVT = Val.getValueType(); 475 assert(ValueVT.isVector() && "Not a vector"); 476 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 477 478 if (NumParts == 1) { 479 EVT PartEVT = PartVT; 480 if (PartEVT == ValueVT) { 481 // Nothing to do. 482 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) { 483 // Bitconvert vector->vector case. 484 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 485 } else if (PartVT.isVector() && 486 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() && 487 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) { 488 EVT ElementVT = PartVT.getVectorElementType(); 489 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in 490 // undef elements. 491 SmallVector<SDValue, 16> Ops; 492 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i) 493 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 494 ElementVT, Val, DAG.getConstant(i, 495 TLI.getVectorIdxTy()))); 496 497 for (unsigned i = ValueVT.getVectorNumElements(), 498 e = PartVT.getVectorNumElements(); i != e; ++i) 499 Ops.push_back(DAG.getUNDEF(ElementVT)); 500 501 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size()); 502 503 // FIXME: Use CONCAT for 2x -> 4x. 504 505 //SDValue UndefElts = DAG.getUNDEF(VectorTy); 506 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts); 507 } else if (PartVT.isVector() && 508 PartEVT.getVectorElementType().bitsGE( 509 ValueVT.getVectorElementType()) && 510 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) { 511 512 // Promoted vector extract 513 bool Smaller = PartEVT.bitsLE(ValueVT); 514 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 515 DL, PartVT, Val); 516 } else{ 517 // Vector -> scalar conversion. 518 assert(ValueVT.getVectorNumElements() == 1 && 519 "Only trivial vector-to-scalar conversions should get here!"); 520 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 521 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy())); 522 523 bool Smaller = ValueVT.bitsLE(PartVT); 524 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND), 525 DL, PartVT, Val); 526 } 527 528 Parts[0] = Val; 529 return; 530 } 531 532 // Handle a multi-element vector. 533 EVT IntermediateVT; 534 MVT RegisterVT; 535 unsigned NumIntermediates; 536 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, 537 IntermediateVT, 538 NumIntermediates, RegisterVT); 539 unsigned NumElements = ValueVT.getVectorNumElements(); 540 541 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!"); 542 NumParts = NumRegs; // Silence a compiler warning. 543 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!"); 544 545 // Split the vector into intermediate operands. 546 SmallVector<SDValue, 8> Ops(NumIntermediates); 547 for (unsigned i = 0; i != NumIntermediates; ++i) { 548 if (IntermediateVT.isVector()) 549 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, 550 IntermediateVT, Val, 551 DAG.getConstant(i * (NumElements / NumIntermediates), 552 TLI.getVectorIdxTy())); 553 else 554 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, 555 IntermediateVT, Val, 556 DAG.getConstant(i, TLI.getVectorIdxTy())); 557 } 558 559 // Split the intermediate operands into legal parts. 560 if (NumParts == NumIntermediates) { 561 // If the register was not expanded, promote or copy the value, 562 // as appropriate. 563 for (unsigned i = 0; i != NumParts; ++i) 564 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V); 565 } else if (NumParts > 0) { 566 // If the intermediate type was expanded, split each the value into 567 // legal parts. 568 assert(NumParts % NumIntermediates == 0 && 569 "Must expand into a divisible number of parts!"); 570 unsigned Factor = NumParts / NumIntermediates; 571 for (unsigned i = 0; i != NumIntermediates; ++i) 572 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V); 573 } 574 } 575 576 namespace { 577 /// RegsForValue - This struct represents the registers (physical or virtual) 578 /// that a particular set of values is assigned, and the type information 579 /// about the value. The most common situation is to represent one value at a 580 /// time, but struct or array values are handled element-wise as multiple 581 /// values. The splitting of aggregates is performed recursively, so that we 582 /// never have aggregate-typed registers. The values at this point do not 583 /// necessarily have legal types, so each value may require one or more 584 /// registers of some legal type. 585 /// 586 struct RegsForValue { 587 /// ValueVTs - The value types of the values, which may not be legal, and 588 /// may need be promoted or synthesized from one or more registers. 589 /// 590 SmallVector<EVT, 4> ValueVTs; 591 592 /// RegVTs - The value types of the registers. This is the same size as 593 /// ValueVTs and it records, for each value, what the type of the assigned 594 /// register or registers are. (Individual values are never synthesized 595 /// from more than one type of register.) 596 /// 597 /// With virtual registers, the contents of RegVTs is redundant with TLI's 598 /// getRegisterType member function, however when with physical registers 599 /// it is necessary to have a separate record of the types. 600 /// 601 SmallVector<MVT, 4> RegVTs; 602 603 /// Regs - This list holds the registers assigned to the values. 604 /// Each legal or promoted value requires one register, and each 605 /// expanded value requires multiple registers. 606 /// 607 SmallVector<unsigned, 4> Regs; 608 609 RegsForValue() {} 610 611 RegsForValue(const SmallVector<unsigned, 4> ®s, 612 MVT regvt, EVT valuevt) 613 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {} 614 615 RegsForValue(LLVMContext &Context, const TargetLowering &tli, 616 unsigned Reg, Type *Ty) { 617 ComputeValueVTs(tli, Ty, ValueVTs); 618 619 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 620 EVT ValueVT = ValueVTs[Value]; 621 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT); 622 MVT RegisterVT = tli.getRegisterType(Context, ValueVT); 623 for (unsigned i = 0; i != NumRegs; ++i) 624 Regs.push_back(Reg + i); 625 RegVTs.push_back(RegisterVT); 626 Reg += NumRegs; 627 } 628 } 629 630 /// areValueTypesLegal - Return true if types of all the values are legal. 631 bool areValueTypesLegal(const TargetLowering &TLI) { 632 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) { 633 MVT RegisterVT = RegVTs[Value]; 634 if (!TLI.isTypeLegal(RegisterVT)) 635 return false; 636 } 637 return true; 638 } 639 640 /// append - Add the specified values to this one. 641 void append(const RegsForValue &RHS) { 642 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end()); 643 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end()); 644 Regs.append(RHS.Regs.begin(), RHS.Regs.end()); 645 } 646 647 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 648 /// this value and returns the result as a ValueVTs value. This uses 649 /// Chain/Flag as the input and updates them for the output Chain/Flag. 650 /// If the Flag pointer is NULL, no flag is used. 651 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo, 652 SDLoc dl, 653 SDValue &Chain, SDValue *Flag, 654 const Value *V = 0) const; 655 656 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 657 /// specified value into the registers specified by this object. This uses 658 /// Chain/Flag as the input and updates them for the output Chain/Flag. 659 /// If the Flag pointer is NULL, no flag is used. 660 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, 661 SDValue &Chain, SDValue *Flag, const Value *V) const; 662 663 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 664 /// operand list. This adds the code marker, matching input operand index 665 /// (if applicable), and includes the number of values added into it. 666 void AddInlineAsmOperands(unsigned Kind, 667 bool HasMatching, unsigned MatchingIdx, 668 SelectionDAG &DAG, 669 std::vector<SDValue> &Ops) const; 670 }; 671 } 672 673 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from 674 /// this value and returns the result as a ValueVT value. This uses 675 /// Chain/Flag as the input and updates them for the output Chain/Flag. 676 /// If the Flag pointer is NULL, no flag is used. 677 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 678 FunctionLoweringInfo &FuncInfo, 679 SDLoc dl, 680 SDValue &Chain, SDValue *Flag, 681 const Value *V) const { 682 // A Value with type {} or [0 x %t] needs no registers. 683 if (ValueVTs.empty()) 684 return SDValue(); 685 686 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 687 688 // Assemble the legal parts into the final values. 689 SmallVector<SDValue, 4> Values(ValueVTs.size()); 690 SmallVector<SDValue, 8> Parts; 691 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 692 // Copy the legal parts from the registers. 693 EVT ValueVT = ValueVTs[Value]; 694 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 695 MVT RegisterVT = RegVTs[Value]; 696 697 Parts.resize(NumRegs); 698 for (unsigned i = 0; i != NumRegs; ++i) { 699 SDValue P; 700 if (Flag == 0) { 701 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT); 702 } else { 703 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag); 704 *Flag = P.getValue(2); 705 } 706 707 Chain = P.getValue(1); 708 Parts[i] = P; 709 710 // If the source register was virtual and if we know something about it, 711 // add an assert node. 712 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) || 713 !RegisterVT.isInteger() || RegisterVT.isVector()) 714 continue; 715 716 const FunctionLoweringInfo::LiveOutInfo *LOI = 717 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]); 718 if (!LOI) 719 continue; 720 721 unsigned RegSize = RegisterVT.getSizeInBits(); 722 unsigned NumSignBits = LOI->NumSignBits; 723 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes(); 724 725 if (NumZeroBits == RegSize) { 726 // The current value is a zero. 727 // Explicitly express that as it would be easier for 728 // optimizations to kick in. 729 Parts[i] = DAG.getConstant(0, RegisterVT); 730 continue; 731 } 732 733 // FIXME: We capture more information than the dag can represent. For 734 // now, just use the tightest assertzext/assertsext possible. 735 bool isSExt = true; 736 EVT FromVT(MVT::Other); 737 if (NumSignBits == RegSize) 738 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1 739 else if (NumZeroBits >= RegSize-1) 740 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1 741 else if (NumSignBits > RegSize-8) 742 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8 743 else if (NumZeroBits >= RegSize-8) 744 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8 745 else if (NumSignBits > RegSize-16) 746 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16 747 else if (NumZeroBits >= RegSize-16) 748 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16 749 else if (NumSignBits > RegSize-32) 750 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32 751 else if (NumZeroBits >= RegSize-32) 752 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32 753 else 754 continue; 755 756 // Add an assertion node. 757 assert(FromVT != MVT::Other); 758 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl, 759 RegisterVT, P, DAG.getValueType(FromVT)); 760 } 761 762 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), 763 NumRegs, RegisterVT, ValueVT, V); 764 Part += NumRegs; 765 Parts.clear(); 766 } 767 768 return DAG.getNode(ISD::MERGE_VALUES, dl, 769 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 770 &Values[0], ValueVTs.size()); 771 } 772 773 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the 774 /// specified value into the registers specified by this object. This uses 775 /// Chain/Flag as the input and updates them for the output Chain/Flag. 776 /// If the Flag pointer is NULL, no flag is used. 777 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, 778 SDValue &Chain, SDValue *Flag, 779 const Value *V) const { 780 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 781 782 // Get the list of the values's legal parts. 783 unsigned NumRegs = Regs.size(); 784 SmallVector<SDValue, 8> Parts(NumRegs); 785 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) { 786 EVT ValueVT = ValueVTs[Value]; 787 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT); 788 MVT RegisterVT = RegVTs[Value]; 789 ISD::NodeType ExtendKind = 790 TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND; 791 792 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), 793 &Parts[Part], NumParts, RegisterVT, V, ExtendKind); 794 Part += NumParts; 795 } 796 797 // Copy the parts into the registers. 798 SmallVector<SDValue, 8> Chains(NumRegs); 799 for (unsigned i = 0; i != NumRegs; ++i) { 800 SDValue Part; 801 if (Flag == 0) { 802 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]); 803 } else { 804 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag); 805 *Flag = Part.getValue(1); 806 } 807 808 Chains[i] = Part.getValue(0); 809 } 810 811 if (NumRegs == 1 || Flag) 812 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 813 // flagged to it. That is the CopyToReg nodes and the user are considered 814 // a single scheduling unit. If we create a TokenFactor and return it as 815 // chain, then the TokenFactor is both a predecessor (operand) of the 816 // user as well as a successor (the TF operands are flagged to the user). 817 // c1, f1 = CopyToReg 818 // c2, f2 = CopyToReg 819 // c3 = TokenFactor c1, c2 820 // ... 821 // = op c3, ..., f2 822 Chain = Chains[NumRegs-1]; 823 else 824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs); 825 } 826 827 /// AddInlineAsmOperands - Add this value to the specified inlineasm node 828 /// operand list. This adds the code marker and includes the number of 829 /// values added into it. 830 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching, 831 unsigned MatchingIdx, 832 SelectionDAG &DAG, 833 std::vector<SDValue> &Ops) const { 834 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 835 836 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size()); 837 if (HasMatching) 838 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx); 839 else if (!Regs.empty() && 840 TargetRegisterInfo::isVirtualRegister(Regs.front())) { 841 // Put the register class of the virtual registers in the flag word. That 842 // way, later passes can recompute register class constraints for inline 843 // assembly as well as normal instructions. 844 // Don't do this for tied operands that can use the regclass information 845 // from the def. 846 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 847 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front()); 848 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID()); 849 } 850 851 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32); 852 Ops.push_back(Res); 853 854 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) { 855 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]); 856 MVT RegisterVT = RegVTs[Value]; 857 for (unsigned i = 0; i != NumRegs; ++i) { 858 assert(Reg < Regs.size() && "Mismatch in # registers expected"); 859 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT)); 860 } 861 } 862 } 863 864 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa, 865 const TargetLibraryInfo *li) { 866 AA = &aa; 867 GFI = gfi; 868 LibInfo = li; 869 TD = DAG.getTarget().getDataLayout(); 870 Context = DAG.getContext(); 871 LPadToCallSiteMap.clear(); 872 } 873 874 /// clear - Clear out the current SelectionDAG and the associated 875 /// state and prepare this SelectionDAGBuilder object to be used 876 /// for a new block. This doesn't clear out information about 877 /// additional blocks that are needed to complete switch lowering 878 /// or PHI node updating; that information is cleared out as it is 879 /// consumed. 880 void SelectionDAGBuilder::clear() { 881 NodeMap.clear(); 882 UnusedArgNodeMap.clear(); 883 PendingLoads.clear(); 884 PendingExports.clear(); 885 CurInst = NULL; 886 HasTailCall = false; 887 } 888 889 /// clearDanglingDebugInfo - Clear the dangling debug information 890 /// map. This function is separated from the clear so that debug 891 /// information that is dangling in a basic block can be properly 892 /// resolved in a different basic block. This allows the 893 /// SelectionDAG to resolve dangling debug information attached 894 /// to PHI nodes. 895 void SelectionDAGBuilder::clearDanglingDebugInfo() { 896 DanglingDebugInfoMap.clear(); 897 } 898 899 /// getRoot - Return the current virtual root of the Selection DAG, 900 /// flushing any PendingLoad items. This must be done before emitting 901 /// a store or any other node that may need to be ordered after any 902 /// prior load instructions. 903 /// 904 SDValue SelectionDAGBuilder::getRoot() { 905 if (PendingLoads.empty()) 906 return DAG.getRoot(); 907 908 if (PendingLoads.size() == 1) { 909 SDValue Root = PendingLoads[0]; 910 DAG.setRoot(Root); 911 PendingLoads.clear(); 912 return Root; 913 } 914 915 // Otherwise, we have to make a token factor node. 916 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 917 &PendingLoads[0], PendingLoads.size()); 918 PendingLoads.clear(); 919 DAG.setRoot(Root); 920 return Root; 921 } 922 923 /// getControlRoot - Similar to getRoot, but instead of flushing all the 924 /// PendingLoad items, flush all the PendingExports items. It is necessary 925 /// to do this before emitting a terminator instruction. 926 /// 927 SDValue SelectionDAGBuilder::getControlRoot() { 928 SDValue Root = DAG.getRoot(); 929 930 if (PendingExports.empty()) 931 return Root; 932 933 // Turn all of the CopyToReg chains into one factored node. 934 if (Root.getOpcode() != ISD::EntryToken) { 935 unsigned i = 0, e = PendingExports.size(); 936 for (; i != e; ++i) { 937 assert(PendingExports[i].getNode()->getNumOperands() > 1); 938 if (PendingExports[i].getNode()->getOperand(0) == Root) 939 break; // Don't add the root if we already indirectly depend on it. 940 } 941 942 if (i == e) 943 PendingExports.push_back(Root); 944 } 945 946 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 947 &PendingExports[0], 948 PendingExports.size()); 949 PendingExports.clear(); 950 DAG.setRoot(Root); 951 return Root; 952 } 953 954 void SelectionDAGBuilder::visit(const Instruction &I) { 955 // Set up outgoing PHI node register values before emitting the terminator. 956 if (isa<TerminatorInst>(&I)) 957 HandlePHINodesInSuccessorBlocks(I.getParent()); 958 959 ++SDNodeOrder; 960 961 CurInst = &I; 962 963 visit(I.getOpcode(), I); 964 965 if (!isa<TerminatorInst>(&I) && !HasTailCall) 966 CopyToExportRegsIfNeeded(&I); 967 968 CurInst = NULL; 969 } 970 971 void SelectionDAGBuilder::visitPHI(const PHINode &) { 972 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!"); 973 } 974 975 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) { 976 // Note: this doesn't use InstVisitor, because it has to work with 977 // ConstantExpr's in addition to instructions. 978 switch (Opcode) { 979 default: llvm_unreachable("Unknown instruction type encountered!"); 980 // Build the switch statement using the Instruction.def file. 981 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 982 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break; 983 #include "llvm/IR/Instruction.def" 984 } 985 } 986 987 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V, 988 // generate the debug data structures now that we've seen its definition. 989 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V, 990 SDValue Val) { 991 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V]; 992 if (DDI.getDI()) { 993 const DbgValueInst *DI = DDI.getDI(); 994 DebugLoc dl = DDI.getdl(); 995 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder(); 996 MDNode *Variable = DI->getVariable(); 997 uint64_t Offset = DI->getOffset(); 998 SDDbgValue *SDV; 999 if (Val.getNode()) { 1000 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) { 1001 SDV = DAG.getDbgValue(Variable, Val.getNode(), 1002 Val.getResNo(), Offset, dl, DbgSDNodeOrder); 1003 DAG.AddDbgValue(SDV, Val.getNode(), false); 1004 } 1005 } else 1006 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n"); 1007 DanglingDebugInfoMap[V] = DanglingDebugInfo(); 1008 } 1009 } 1010 1011 /// getValue - Return an SDValue for the given Value. 1012 SDValue SelectionDAGBuilder::getValue(const Value *V) { 1013 // If we already have an SDValue for this value, use it. It's important 1014 // to do this first, so that we don't create a CopyFromReg if we already 1015 // have a regular SDValue. 1016 SDValue &N = NodeMap[V]; 1017 if (N.getNode()) return N; 1018 1019 // If there's a virtual register allocated and initialized for this 1020 // value, use it. 1021 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V); 1022 if (It != FuncInfo.ValueMap.end()) { 1023 unsigned InReg = It->second; 1024 RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(), 1025 InReg, V->getType()); 1026 SDValue Chain = DAG.getEntryNode(); 1027 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V); 1028 resolveDanglingDebugInfo(V, N); 1029 return N; 1030 } 1031 1032 // Otherwise create a new SDValue and remember it. 1033 SDValue Val = getValueImpl(V); 1034 NodeMap[V] = Val; 1035 resolveDanglingDebugInfo(V, Val); 1036 return Val; 1037 } 1038 1039 /// getNonRegisterValue - Return an SDValue for the given Value, but 1040 /// don't look in FuncInfo.ValueMap for a virtual register. 1041 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) { 1042 // If we already have an SDValue for this value, use it. 1043 SDValue &N = NodeMap[V]; 1044 if (N.getNode()) return N; 1045 1046 // Otherwise create a new SDValue and remember it. 1047 SDValue Val = getValueImpl(V); 1048 NodeMap[V] = Val; 1049 resolveDanglingDebugInfo(V, Val); 1050 return Val; 1051 } 1052 1053 /// getValueImpl - Helper function for getValue and getNonRegisterValue. 1054 /// Create an SDValue for the given value. 1055 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) { 1056 const TargetLowering *TLI = TM.getTargetLowering(); 1057 1058 if (const Constant *C = dyn_cast<Constant>(V)) { 1059 EVT VT = TLI->getValueType(V->getType(), true); 1060 1061 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1062 return DAG.getConstant(*CI, VT); 1063 1064 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C)) 1065 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT); 1066 1067 if (isa<ConstantPointerNull>(C)) 1068 return DAG.getConstant(0, TLI->getPointerTy()); 1069 1070 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) 1071 return DAG.getConstantFP(*CFP, VT); 1072 1073 if (isa<UndefValue>(C) && !V->getType()->isAggregateType()) 1074 return DAG.getUNDEF(VT); 1075 1076 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 1077 visit(CE->getOpcode(), *CE); 1078 SDValue N1 = NodeMap[V]; 1079 assert(N1.getNode() && "visit didn't populate the NodeMap!"); 1080 return N1; 1081 } 1082 1083 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) { 1084 SmallVector<SDValue, 4> Constants; 1085 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end(); 1086 OI != OE; ++OI) { 1087 SDNode *Val = getValue(*OI).getNode(); 1088 // If the operand is an empty aggregate, there are no values. 1089 if (!Val) continue; 1090 // Add each leaf value from the operand to the Constants list 1091 // to form a flattened list of all the values. 1092 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1093 Constants.push_back(SDValue(Val, i)); 1094 } 1095 1096 return DAG.getMergeValues(&Constants[0], Constants.size(), 1097 getCurSDLoc()); 1098 } 1099 1100 if (const ConstantDataSequential *CDS = 1101 dyn_cast<ConstantDataSequential>(C)) { 1102 SmallVector<SDValue, 4> Ops; 1103 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1104 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode(); 1105 // Add each leaf value from the operand to the Constants list 1106 // to form a flattened list of all the values. 1107 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) 1108 Ops.push_back(SDValue(Val, i)); 1109 } 1110 1111 if (isa<ArrayType>(CDS->getType())) 1112 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc()); 1113 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), 1114 VT, &Ops[0], Ops.size()); 1115 } 1116 1117 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) { 1118 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && 1119 "Unknown struct or array constant!"); 1120 1121 SmallVector<EVT, 4> ValueVTs; 1122 ComputeValueVTs(*TLI, C->getType(), ValueVTs); 1123 unsigned NumElts = ValueVTs.size(); 1124 if (NumElts == 0) 1125 return SDValue(); // empty struct 1126 SmallVector<SDValue, 4> Constants(NumElts); 1127 for (unsigned i = 0; i != NumElts; ++i) { 1128 EVT EltVT = ValueVTs[i]; 1129 if (isa<UndefValue>(C)) 1130 Constants[i] = DAG.getUNDEF(EltVT); 1131 else if (EltVT.isFloatingPoint()) 1132 Constants[i] = DAG.getConstantFP(0, EltVT); 1133 else 1134 Constants[i] = DAG.getConstant(0, EltVT); 1135 } 1136 1137 return DAG.getMergeValues(&Constants[0], NumElts, 1138 getCurSDLoc()); 1139 } 1140 1141 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 1142 return DAG.getBlockAddress(BA, VT); 1143 1144 VectorType *VecTy = cast<VectorType>(V->getType()); 1145 unsigned NumElements = VecTy->getNumElements(); 1146 1147 // Now that we know the number and type of the elements, get that number of 1148 // elements into the Ops array based on what kind of constant it is. 1149 SmallVector<SDValue, 16> Ops; 1150 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) { 1151 for (unsigned i = 0; i != NumElements; ++i) 1152 Ops.push_back(getValue(CV->getOperand(i))); 1153 } else { 1154 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!"); 1155 EVT EltVT = TLI->getValueType(VecTy->getElementType()); 1156 1157 SDValue Op; 1158 if (EltVT.isFloatingPoint()) 1159 Op = DAG.getConstantFP(0, EltVT); 1160 else 1161 Op = DAG.getConstant(0, EltVT); 1162 Ops.assign(NumElements, Op); 1163 } 1164 1165 // Create a BUILD_VECTOR node. 1166 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), 1167 VT, &Ops[0], Ops.size()); 1168 } 1169 1170 // If this is a static alloca, generate it as the frameindex instead of 1171 // computation. 1172 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) { 1173 DenseMap<const AllocaInst*, int>::iterator SI = 1174 FuncInfo.StaticAllocaMap.find(AI); 1175 if (SI != FuncInfo.StaticAllocaMap.end()) 1176 return DAG.getFrameIndex(SI->second, TLI->getPointerTy()); 1177 } 1178 1179 // If this is an instruction which fast-isel has deferred, select it now. 1180 if (const Instruction *Inst = dyn_cast<Instruction>(V)) { 1181 unsigned InReg = FuncInfo.InitializeRegForValue(Inst); 1182 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType()); 1183 SDValue Chain = DAG.getEntryNode(); 1184 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V); 1185 } 1186 1187 llvm_unreachable("Can't get register for value!"); 1188 } 1189 1190 void SelectionDAGBuilder::visitRet(const ReturnInst &I) { 1191 const TargetLowering *TLI = TM.getTargetLowering(); 1192 SDValue Chain = getControlRoot(); 1193 SmallVector<ISD::OutputArg, 8> Outs; 1194 SmallVector<SDValue, 8> OutVals; 1195 1196 if (!FuncInfo.CanLowerReturn) { 1197 unsigned DemoteReg = FuncInfo.DemoteRegister; 1198 const Function *F = I.getParent()->getParent(); 1199 1200 // Emit a store of the return value through the virtual register. 1201 // Leave Outs empty so that LowerReturn won't try to load return 1202 // registers the usual way. 1203 SmallVector<EVT, 1> PtrValueVTs; 1204 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()), 1205 PtrValueVTs); 1206 1207 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]); 1208 SDValue RetOp = getValue(I.getOperand(0)); 1209 1210 SmallVector<EVT, 4> ValueVTs; 1211 SmallVector<uint64_t, 4> Offsets; 1212 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets); 1213 unsigned NumValues = ValueVTs.size(); 1214 1215 SmallVector<SDValue, 4> Chains(NumValues); 1216 for (unsigned i = 0; i != NumValues; ++i) { 1217 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), 1218 RetPtr.getValueType(), RetPtr, 1219 DAG.getIntPtrConstant(Offsets[i])); 1220 Chains[i] = 1221 DAG.getStore(Chain, getCurSDLoc(), 1222 SDValue(RetOp.getNode(), RetOp.getResNo() + i), 1223 // FIXME: better loc info would be nice. 1224 Add, MachinePointerInfo(), false, false, 0); 1225 } 1226 1227 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 1228 MVT::Other, &Chains[0], NumValues); 1229 } else if (I.getNumOperands() != 0) { 1230 SmallVector<EVT, 4> ValueVTs; 1231 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs); 1232 unsigned NumValues = ValueVTs.size(); 1233 if (NumValues) { 1234 SDValue RetOp = getValue(I.getOperand(0)); 1235 for (unsigned j = 0, f = NumValues; j != f; ++j) { 1236 EVT VT = ValueVTs[j]; 1237 1238 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 1239 1240 const Function *F = I.getParent()->getParent(); 1241 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1242 Attribute::SExt)) 1243 ExtendKind = ISD::SIGN_EXTEND; 1244 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1245 Attribute::ZExt)) 1246 ExtendKind = ISD::ZERO_EXTEND; 1247 1248 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) 1249 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind); 1250 1251 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT); 1252 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT); 1253 SmallVector<SDValue, 4> Parts(NumParts); 1254 getCopyToParts(DAG, getCurSDLoc(), 1255 SDValue(RetOp.getNode(), RetOp.getResNo() + j), 1256 &Parts[0], NumParts, PartVT, &I, ExtendKind); 1257 1258 // 'inreg' on function refers to return value 1259 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy(); 1260 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex, 1261 Attribute::InReg)) 1262 Flags.setInReg(); 1263 1264 // Propagate extension type if any 1265 if (ExtendKind == ISD::SIGN_EXTEND) 1266 Flags.setSExt(); 1267 else if (ExtendKind == ISD::ZERO_EXTEND) 1268 Flags.setZExt(); 1269 1270 for (unsigned i = 0; i < NumParts; ++i) { 1271 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(), 1272 /*isfixed=*/true, 0, 0)); 1273 OutVals.push_back(Parts[i]); 1274 } 1275 } 1276 } 1277 } 1278 1279 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg(); 1280 CallingConv::ID CallConv = 1281 DAG.getMachineFunction().getFunction()->getCallingConv(); 1282 Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg, 1283 Outs, OutVals, getCurSDLoc(), 1284 DAG); 1285 1286 // Verify that the target's LowerReturn behaved as expected. 1287 assert(Chain.getNode() && Chain.getValueType() == MVT::Other && 1288 "LowerReturn didn't return a valid chain!"); 1289 1290 // Update the DAG with the new chain value resulting from return lowering. 1291 DAG.setRoot(Chain); 1292 } 1293 1294 /// CopyToExportRegsIfNeeded - If the given value has virtual registers 1295 /// created for it, emit nodes to copy the value into the virtual 1296 /// registers. 1297 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) { 1298 // Skip empty types 1299 if (V->getType()->isEmptyTy()) 1300 return; 1301 1302 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 1303 if (VMI != FuncInfo.ValueMap.end()) { 1304 assert(!V->use_empty() && "Unused value assigned virtual registers!"); 1305 CopyValueToVirtualRegister(V, VMI->second); 1306 } 1307 } 1308 1309 /// ExportFromCurrentBlock - If this condition isn't known to be exported from 1310 /// the current basic block, add it to ValueMap now so that we'll get a 1311 /// CopyTo/FromReg. 1312 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) { 1313 // No need to export constants. 1314 if (!isa<Instruction>(V) && !isa<Argument>(V)) return; 1315 1316 // Already exported? 1317 if (FuncInfo.isExportedInst(V)) return; 1318 1319 unsigned Reg = FuncInfo.InitializeRegForValue(V); 1320 CopyValueToVirtualRegister(V, Reg); 1321 } 1322 1323 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V, 1324 const BasicBlock *FromBB) { 1325 // The operands of the setcc have to be in this block. We don't know 1326 // how to export them from some other block. 1327 if (const Instruction *VI = dyn_cast<Instruction>(V)) { 1328 // Can export from current BB. 1329 if (VI->getParent() == FromBB) 1330 return true; 1331 1332 // Is already exported, noop. 1333 return FuncInfo.isExportedInst(V); 1334 } 1335 1336 // If this is an argument, we can export it if the BB is the entry block or 1337 // if it is already exported. 1338 if (isa<Argument>(V)) { 1339 if (FromBB == &FromBB->getParent()->getEntryBlock()) 1340 return true; 1341 1342 // Otherwise, can only export this if it is already exported. 1343 return FuncInfo.isExportedInst(V); 1344 } 1345 1346 // Otherwise, constants can always be exported. 1347 return true; 1348 } 1349 1350 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks. 1351 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src, 1352 const MachineBasicBlock *Dst) const { 1353 BranchProbabilityInfo *BPI = FuncInfo.BPI; 1354 if (!BPI) 1355 return 0; 1356 const BasicBlock *SrcBB = Src->getBasicBlock(); 1357 const BasicBlock *DstBB = Dst->getBasicBlock(); 1358 return BPI->getEdgeWeight(SrcBB, DstBB); 1359 } 1360 1361 void SelectionDAGBuilder:: 1362 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst, 1363 uint32_t Weight /* = 0 */) { 1364 if (!Weight) 1365 Weight = getEdgeWeight(Src, Dst); 1366 Src->addSuccessor(Dst, Weight); 1367 } 1368 1369 1370 static bool InBlock(const Value *V, const BasicBlock *BB) { 1371 if (const Instruction *I = dyn_cast<Instruction>(V)) 1372 return I->getParent() == BB; 1373 return true; 1374 } 1375 1376 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions. 1377 /// This function emits a branch and is used at the leaves of an OR or an 1378 /// AND operator tree. 1379 /// 1380 void 1381 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond, 1382 MachineBasicBlock *TBB, 1383 MachineBasicBlock *FBB, 1384 MachineBasicBlock *CurBB, 1385 MachineBasicBlock *SwitchBB) { 1386 const BasicBlock *BB = CurBB->getBasicBlock(); 1387 1388 // If the leaf of the tree is a comparison, merge the condition into 1389 // the caseblock. 1390 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 1391 // The operands of the cmp have to be in this block. We don't know 1392 // how to export them from some other block. If this is the first block 1393 // of the sequence, no exporting is needed. 1394 if (CurBB == SwitchBB || 1395 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) && 1396 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) { 1397 ISD::CondCode Condition; 1398 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 1399 Condition = getICmpCondCode(IC->getPredicate()); 1400 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) { 1401 Condition = getFCmpCondCode(FC->getPredicate()); 1402 if (TM.Options.NoNaNsFPMath) 1403 Condition = getFCmpCodeWithoutNaN(Condition); 1404 } else { 1405 Condition = ISD::SETEQ; // silence warning. 1406 llvm_unreachable("Unknown compare instruction"); 1407 } 1408 1409 CaseBlock CB(Condition, BOp->getOperand(0), 1410 BOp->getOperand(1), NULL, TBB, FBB, CurBB); 1411 SwitchCases.push_back(CB); 1412 return; 1413 } 1414 } 1415 1416 // Create a CaseBlock record representing this branch. 1417 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()), 1418 NULL, TBB, FBB, CurBB); 1419 SwitchCases.push_back(CB); 1420 } 1421 1422 /// FindMergedConditions - If Cond is an expression like 1423 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond, 1424 MachineBasicBlock *TBB, 1425 MachineBasicBlock *FBB, 1426 MachineBasicBlock *CurBB, 1427 MachineBasicBlock *SwitchBB, 1428 unsigned Opc) { 1429 // If this node is not part of the or/and tree, emit it as a branch. 1430 const Instruction *BOp = dyn_cast<Instruction>(Cond); 1431 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 1432 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() || 1433 BOp->getParent() != CurBB->getBasicBlock() || 1434 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 1435 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 1436 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB); 1437 return; 1438 } 1439 1440 // Create TmpBB after CurBB. 1441 MachineFunction::iterator BBI = CurBB; 1442 MachineFunction &MF = DAG.getMachineFunction(); 1443 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock()); 1444 CurBB->getParent()->insert(++BBI, TmpBB); 1445 1446 if (Opc == Instruction::Or) { 1447 // Codegen X | Y as: 1448 // jmp_if_X TBB 1449 // jmp TmpBB 1450 // TmpBB: 1451 // jmp_if_Y TBB 1452 // jmp FBB 1453 // 1454 1455 // Emit the LHS condition. 1456 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc); 1457 1458 // Emit the RHS condition into TmpBB. 1459 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1460 } else { 1461 assert(Opc == Instruction::And && "Unknown merge op!"); 1462 // Codegen X & Y as: 1463 // jmp_if_X TmpBB 1464 // jmp FBB 1465 // TmpBB: 1466 // jmp_if_Y TBB 1467 // jmp FBB 1468 // 1469 // This requires creation of TmpBB after CurBB. 1470 1471 // Emit the LHS condition. 1472 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc); 1473 1474 // Emit the RHS condition into TmpBB. 1475 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc); 1476 } 1477 } 1478 1479 /// If the set of cases should be emitted as a series of branches, return true. 1480 /// If we should emit this as a bunch of and/or'd together conditions, return 1481 /// false. 1482 bool 1483 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) { 1484 if (Cases.size() != 2) return true; 1485 1486 // If this is two comparisons of the same values or'd or and'd together, they 1487 // will get folded into a single comparison, so don't emit two blocks. 1488 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 1489 Cases[0].CmpRHS == Cases[1].CmpRHS) || 1490 (Cases[0].CmpRHS == Cases[1].CmpLHS && 1491 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 1492 return false; 1493 } 1494 1495 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 1496 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 1497 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 1498 Cases[0].CC == Cases[1].CC && 1499 isa<Constant>(Cases[0].CmpRHS) && 1500 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 1501 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB) 1502 return false; 1503 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB) 1504 return false; 1505 } 1506 1507 return true; 1508 } 1509 1510 void SelectionDAGBuilder::visitBr(const BranchInst &I) { 1511 MachineBasicBlock *BrMBB = FuncInfo.MBB; 1512 1513 // Update machine-CFG edges. 1514 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)]; 1515 1516 // Figure out which block is immediately after the current one. 1517 MachineBasicBlock *NextBlock = 0; 1518 MachineFunction::iterator BBI = BrMBB; 1519 if (++BBI != FuncInfo.MF->end()) 1520 NextBlock = BBI; 1521 1522 if (I.isUnconditional()) { 1523 // Update machine-CFG edges. 1524 BrMBB->addSuccessor(Succ0MBB); 1525 1526 // If this is not a fall-through branch, emit the branch. 1527 if (Succ0MBB != NextBlock) 1528 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1529 MVT::Other, getControlRoot(), 1530 DAG.getBasicBlock(Succ0MBB))); 1531 1532 return; 1533 } 1534 1535 // If this condition is one of the special cases we handle, do special stuff 1536 // now. 1537 const Value *CondVal = I.getCondition(); 1538 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)]; 1539 1540 // If this is a series of conditions that are or'd or and'd together, emit 1541 // this as a sequence of branches instead of setcc's with and/or operations. 1542 // As long as jumps are not expensive, this should improve performance. 1543 // For example, instead of something like: 1544 // cmp A, B 1545 // C = seteq 1546 // cmp D, E 1547 // F = setle 1548 // or C, F 1549 // jnz foo 1550 // Emit: 1551 // cmp A, B 1552 // je foo 1553 // cmp D, E 1554 // jle foo 1555 // 1556 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 1557 if (!TM.getTargetLowering()->isJumpExpensive() && 1558 BOp->hasOneUse() && 1559 (BOp->getOpcode() == Instruction::And || 1560 BOp->getOpcode() == Instruction::Or)) { 1561 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, 1562 BOp->getOpcode()); 1563 // If the compares in later blocks need to use values not currently 1564 // exported from this block, export them now. This block should always 1565 // be the first entry. 1566 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!"); 1567 1568 // Allow some cases to be rejected. 1569 if (ShouldEmitAsBranches(SwitchCases)) { 1570 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) { 1571 ExportFromCurrentBlock(SwitchCases[i].CmpLHS); 1572 ExportFromCurrentBlock(SwitchCases[i].CmpRHS); 1573 } 1574 1575 // Emit the branch for this block. 1576 visitSwitchCase(SwitchCases[0], BrMBB); 1577 SwitchCases.erase(SwitchCases.begin()); 1578 return; 1579 } 1580 1581 // Okay, we decided not to do this, remove any inserted MBB's and clear 1582 // SwitchCases. 1583 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) 1584 FuncInfo.MF->erase(SwitchCases[i].ThisBB); 1585 1586 SwitchCases.clear(); 1587 } 1588 } 1589 1590 // Create a CaseBlock record representing this branch. 1591 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()), 1592 NULL, Succ0MBB, Succ1MBB, BrMBB); 1593 1594 // Use visitSwitchCase to actually insert the fast branch sequence for this 1595 // cond branch. 1596 visitSwitchCase(CB, BrMBB); 1597 } 1598 1599 /// visitSwitchCase - Emits the necessary code to represent a single node in 1600 /// the binary search tree resulting from lowering a switch instruction. 1601 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB, 1602 MachineBasicBlock *SwitchBB) { 1603 SDValue Cond; 1604 SDValue CondLHS = getValue(CB.CmpLHS); 1605 SDLoc dl = getCurSDLoc(); 1606 1607 // Build the setcc now. 1608 if (CB.CmpMHS == NULL) { 1609 // Fold "(X == true)" to X and "(X == false)" to !X to 1610 // handle common cases produced by branch lowering. 1611 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) && 1612 CB.CC == ISD::SETEQ) 1613 Cond = CondLHS; 1614 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) && 1615 CB.CC == ISD::SETEQ) { 1616 SDValue True = DAG.getConstant(1, CondLHS.getValueType()); 1617 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True); 1618 } else 1619 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC); 1620 } else { 1621 assert(CB.CC == ISD::SETCC_INVALID && 1622 "Condition is undefined for to-the-range belonging check."); 1623 1624 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 1625 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 1626 1627 SDValue CmpOp = getValue(CB.CmpMHS); 1628 EVT VT = CmpOp.getValueType(); 1629 1630 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(false)) { 1631 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT), 1632 ISD::SETULE); 1633 } else { 1634 SDValue SUB = DAG.getNode(ISD::SUB, dl, 1635 VT, CmpOp, DAG.getConstant(Low, VT)); 1636 Cond = DAG.getSetCC(dl, MVT::i1, SUB, 1637 DAG.getConstant(High-Low, VT), ISD::SETULE); 1638 } 1639 } 1640 1641 // Update successor info 1642 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight); 1643 // TrueBB and FalseBB are always different unless the incoming IR is 1644 // degenerate. This only happens when running llc on weird IR. 1645 if (CB.TrueBB != CB.FalseBB) 1646 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight); 1647 1648 // Set NextBlock to be the MBB immediately after the current one, if any. 1649 // This is used to avoid emitting unnecessary branches to the next block. 1650 MachineBasicBlock *NextBlock = 0; 1651 MachineFunction::iterator BBI = SwitchBB; 1652 if (++BBI != FuncInfo.MF->end()) 1653 NextBlock = BBI; 1654 1655 // If the lhs block is the next block, invert the condition so that we can 1656 // fall through to the lhs instead of the rhs block. 1657 if (CB.TrueBB == NextBlock) { 1658 std::swap(CB.TrueBB, CB.FalseBB); 1659 SDValue True = DAG.getConstant(1, Cond.getValueType()); 1660 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True); 1661 } 1662 1663 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, 1664 MVT::Other, getControlRoot(), Cond, 1665 DAG.getBasicBlock(CB.TrueBB)); 1666 1667 // Insert the false branch. Do this even if it's a fall through branch, 1668 // this makes it easier to do DAG optimizations which require inverting 1669 // the branch condition. 1670 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond, 1671 DAG.getBasicBlock(CB.FalseBB)); 1672 1673 DAG.setRoot(BrCond); 1674 } 1675 1676 /// visitJumpTable - Emit JumpTable node in the current MBB 1677 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) { 1678 // Emit the code for the jump table 1679 assert(JT.Reg != -1U && "Should lower JT Header first!"); 1680 EVT PTy = TM.getTargetLowering()->getPointerTy(); 1681 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 1682 JT.Reg, PTy); 1683 SDValue Table = DAG.getJumpTable(JT.JTI, PTy); 1684 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(), 1685 MVT::Other, Index.getValue(1), 1686 Table, Index); 1687 DAG.setRoot(BrJumpTable); 1688 } 1689 1690 /// visitJumpTableHeader - This function emits necessary code to produce index 1691 /// in the JumpTable from switch case. 1692 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT, 1693 JumpTableHeader &JTH, 1694 MachineBasicBlock *SwitchBB) { 1695 // Subtract the lowest switch case value from the value being switched on and 1696 // conditional branch to default mbb if the result is greater than the 1697 // difference between smallest and largest cases. 1698 SDValue SwitchOp = getValue(JTH.SValue); 1699 EVT VT = SwitchOp.getValueType(); 1700 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp, 1701 DAG.getConstant(JTH.First, VT)); 1702 1703 // The SDNode we just created, which holds the value being switched on minus 1704 // the smallest case value, needs to be copied to a virtual register so it 1705 // can be used as an index into the jump table in a subsequent basic block. 1706 // This value may be smaller or larger than the target's pointer type, and 1707 // therefore require extension or truncating. 1708 const TargetLowering *TLI = TM.getTargetLowering(); 1709 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy()); 1710 1711 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy()); 1712 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(), 1713 JumpTableReg, SwitchOp); 1714 JT.Reg = JumpTableReg; 1715 1716 // Emit the range check for the jump table, and branch to the default block 1717 // for the switch statement if the value being switched on exceeds the largest 1718 // case in the switch. 1719 SDValue CMP = DAG.getSetCC(getCurSDLoc(), 1720 TLI->getSetCCResultType(*DAG.getContext(), 1721 Sub.getValueType()), 1722 Sub, 1723 DAG.getConstant(JTH.Last - JTH.First,VT), 1724 ISD::SETUGT); 1725 1726 // Set NextBlock to be the MBB immediately after the current one, if any. 1727 // This is used to avoid emitting unnecessary branches to the next block. 1728 MachineBasicBlock *NextBlock = 0; 1729 MachineFunction::iterator BBI = SwitchBB; 1730 1731 if (++BBI != FuncInfo.MF->end()) 1732 NextBlock = BBI; 1733 1734 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(), 1735 MVT::Other, CopyTo, CMP, 1736 DAG.getBasicBlock(JT.Default)); 1737 1738 if (JT.MBB != NextBlock) 1739 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond, 1740 DAG.getBasicBlock(JT.MBB)); 1741 1742 DAG.setRoot(BrCond); 1743 } 1744 1745 /// Codegen a new tail for a stack protector check ParentMBB which has had its 1746 /// tail spliced into a stack protector check success bb. 1747 /// 1748 /// For a high level explanation of how this fits into the stack protector 1749 /// generation see the comment on the declaration of class 1750 /// StackProtectorDescriptor. 1751 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD, 1752 MachineBasicBlock *ParentBB) { 1753 1754 // First create the loads to the guard/stack slot for the comparison. 1755 const TargetLowering *TLI = TM.getTargetLowering(); 1756 EVT PtrTy = TLI->getPointerTy(); 1757 1758 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo(); 1759 int FI = MFI->getStackProtectorIndex(); 1760 1761 const Value *IRGuard = SPD.getGuard(); 1762 SDValue GuardPtr = getValue(IRGuard); 1763 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy); 1764 1765 unsigned Align = 1766 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType()); 1767 SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(), 1768 GuardPtr, MachinePointerInfo(IRGuard, 0), 1769 true, false, false, Align); 1770 1771 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(), 1772 StackSlotPtr, 1773 MachinePointerInfo::getFixedStack(FI), 1774 true, false, false, Align); 1775 1776 // Perform the comparison via a subtract/getsetcc. 1777 EVT VT = Guard.getValueType(); 1778 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot); 1779 1780 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), 1781 TLI->getSetCCResultType(*DAG.getContext(), 1782 Sub.getValueType()), 1783 Sub, DAG.getConstant(0, VT), 1784 ISD::SETNE); 1785 1786 // If the sub is not 0, then we know the guard/stackslot do not equal, so 1787 // branch to failure MBB. 1788 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(), 1789 MVT::Other, StackSlot.getOperand(0), 1790 Cmp, DAG.getBasicBlock(SPD.getFailureMBB())); 1791 // Otherwise branch to success MBB. 1792 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(), 1793 MVT::Other, BrCond, 1794 DAG.getBasicBlock(SPD.getSuccessMBB())); 1795 1796 DAG.setRoot(Br); 1797 } 1798 1799 /// Codegen the failure basic block for a stack protector check. 1800 /// 1801 /// A failure stack protector machine basic block consists simply of a call to 1802 /// __stack_chk_fail(). 1803 /// 1804 /// For a high level explanation of how this fits into the stack protector 1805 /// generation see the comment on the declaration of class 1806 /// StackProtectorDescriptor. 1807 void 1808 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) { 1809 const TargetLowering *TLI = TM.getTargetLowering(); 1810 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, 1811 MVT::isVoid, 0, 0, false, getCurSDLoc(), 1812 false, false).second; 1813 DAG.setRoot(Chain); 1814 } 1815 1816 /// visitBitTestHeader - This function emits necessary code to produce value 1817 /// suitable for "bit tests" 1818 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B, 1819 MachineBasicBlock *SwitchBB) { 1820 // Subtract the minimum value 1821 SDValue SwitchOp = getValue(B.SValue); 1822 EVT VT = SwitchOp.getValueType(); 1823 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp, 1824 DAG.getConstant(B.First, VT)); 1825 1826 // Check range 1827 const TargetLowering *TLI = TM.getTargetLowering(); 1828 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(), 1829 TLI->getSetCCResultType(*DAG.getContext(), 1830 Sub.getValueType()), 1831 Sub, DAG.getConstant(B.Range, VT), 1832 ISD::SETUGT); 1833 1834 // Determine the type of the test operands. 1835 bool UsePtrType = false; 1836 if (!TLI->isTypeLegal(VT)) 1837 UsePtrType = true; 1838 else { 1839 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i) 1840 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) { 1841 // Switch table case range are encoded into series of masks. 1842 // Just use pointer type, it's guaranteed to fit. 1843 UsePtrType = true; 1844 break; 1845 } 1846 } 1847 if (UsePtrType) { 1848 VT = TLI->getPointerTy(); 1849 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT); 1850 } 1851 1852 B.RegVT = VT.getSimpleVT(); 1853 B.Reg = FuncInfo.CreateReg(B.RegVT); 1854 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(), 1855 B.Reg, Sub); 1856 1857 // Set NextBlock to be the MBB immediately after the current one, if any. 1858 // This is used to avoid emitting unnecessary branches to the next block. 1859 MachineBasicBlock *NextBlock = 0; 1860 MachineFunction::iterator BBI = SwitchBB; 1861 if (++BBI != FuncInfo.MF->end()) 1862 NextBlock = BBI; 1863 1864 MachineBasicBlock* MBB = B.Cases[0].ThisBB; 1865 1866 addSuccessorWithWeight(SwitchBB, B.Default); 1867 addSuccessorWithWeight(SwitchBB, MBB); 1868 1869 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(), 1870 MVT::Other, CopyTo, RangeCmp, 1871 DAG.getBasicBlock(B.Default)); 1872 1873 if (MBB != NextBlock) 1874 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo, 1875 DAG.getBasicBlock(MBB)); 1876 1877 DAG.setRoot(BrRange); 1878 } 1879 1880 /// visitBitTestCase - this function produces one "bit test" 1881 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB, 1882 MachineBasicBlock* NextMBB, 1883 uint32_t BranchWeightToNext, 1884 unsigned Reg, 1885 BitTestCase &B, 1886 MachineBasicBlock *SwitchBB) { 1887 MVT VT = BB.RegVT; 1888 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(), 1889 Reg, VT); 1890 SDValue Cmp; 1891 unsigned PopCount = CountPopulation_64(B.Mask); 1892 const TargetLowering *TLI = TM.getTargetLowering(); 1893 if (PopCount == 1) { 1894 // Testing for a single bit; just compare the shift count with what it 1895 // would need to be to shift a 1 bit in that position. 1896 Cmp = DAG.getSetCC(getCurSDLoc(), 1897 TLI->getSetCCResultType(*DAG.getContext(), VT), 1898 ShiftOp, 1899 DAG.getConstant(countTrailingZeros(B.Mask), VT), 1900 ISD::SETEQ); 1901 } else if (PopCount == BB.Range) { 1902 // There is only one zero bit in the range, test for it directly. 1903 Cmp = DAG.getSetCC(getCurSDLoc(), 1904 TLI->getSetCCResultType(*DAG.getContext(), VT), 1905 ShiftOp, 1906 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), 1907 ISD::SETNE); 1908 } else { 1909 // Make desired shift 1910 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT, 1911 DAG.getConstant(1, VT), ShiftOp); 1912 1913 // Emit bit tests and jumps 1914 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(), 1915 VT, SwitchVal, DAG.getConstant(B.Mask, VT)); 1916 Cmp = DAG.getSetCC(getCurSDLoc(), 1917 TLI->getSetCCResultType(*DAG.getContext(), VT), 1918 AndOp, DAG.getConstant(0, VT), 1919 ISD::SETNE); 1920 } 1921 1922 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight. 1923 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight); 1924 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext. 1925 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext); 1926 1927 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(), 1928 MVT::Other, getControlRoot(), 1929 Cmp, DAG.getBasicBlock(B.TargetBB)); 1930 1931 // Set NextBlock to be the MBB immediately after the current one, if any. 1932 // This is used to avoid emitting unnecessary branches to the next block. 1933 MachineBasicBlock *NextBlock = 0; 1934 MachineFunction::iterator BBI = SwitchBB; 1935 if (++BBI != FuncInfo.MF->end()) 1936 NextBlock = BBI; 1937 1938 if (NextMBB != NextBlock) 1939 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd, 1940 DAG.getBasicBlock(NextMBB)); 1941 1942 DAG.setRoot(BrAnd); 1943 } 1944 1945 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) { 1946 MachineBasicBlock *InvokeMBB = FuncInfo.MBB; 1947 1948 // Retrieve successors. 1949 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)]; 1950 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)]; 1951 1952 const Value *Callee(I.getCalledValue()); 1953 const Function *Fn = dyn_cast<Function>(Callee); 1954 if (isa<InlineAsm>(Callee)) 1955 visitInlineAsm(&I); 1956 else if (Fn && Fn->isIntrinsic()) { 1957 assert(Fn->getIntrinsicID() == Intrinsic::donothing); 1958 // Ignore invokes to @llvm.donothing: jump directly to the next BB. 1959 } else 1960 LowerCallTo(&I, getValue(Callee), false, LandingPad); 1961 1962 // If the value of the invoke is used outside of its defining block, make it 1963 // available as a virtual register. 1964 CopyToExportRegsIfNeeded(&I); 1965 1966 // Update successor info 1967 addSuccessorWithWeight(InvokeMBB, Return); 1968 addSuccessorWithWeight(InvokeMBB, LandingPad); 1969 1970 // Drop into normal successor. 1971 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 1972 MVT::Other, getControlRoot(), 1973 DAG.getBasicBlock(Return))); 1974 } 1975 1976 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) { 1977 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!"); 1978 } 1979 1980 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) { 1981 assert(FuncInfo.MBB->isLandingPad() && 1982 "Call to landingpad not in landing pad!"); 1983 1984 MachineBasicBlock *MBB = FuncInfo.MBB; 1985 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 1986 AddLandingPadInfo(LP, MMI, MBB); 1987 1988 // If there aren't registers to copy the values into (e.g., during SjLj 1989 // exceptions), then don't bother to create these DAG nodes. 1990 const TargetLowering *TLI = TM.getTargetLowering(); 1991 if (TLI->getExceptionPointerRegister() == 0 && 1992 TLI->getExceptionSelectorRegister() == 0) 1993 return; 1994 1995 SmallVector<EVT, 2> ValueVTs; 1996 ComputeValueVTs(*TLI, LP.getType(), ValueVTs); 1997 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported"); 1998 1999 // Get the two live-in registers as SDValues. The physregs have already been 2000 // copied into virtual registers. 2001 SDValue Ops[2]; 2002 Ops[0] = DAG.getZExtOrTrunc( 2003 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 2004 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()), 2005 getCurSDLoc(), ValueVTs[0]); 2006 Ops[1] = DAG.getZExtOrTrunc( 2007 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), 2008 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()), 2009 getCurSDLoc(), ValueVTs[1]); 2010 2011 // Merge into one. 2012 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2013 DAG.getVTList(&ValueVTs[0], ValueVTs.size()), 2014 &Ops[0], 2); 2015 setValue(&LP, Res); 2016 } 2017 2018 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for 2019 /// small case ranges). 2020 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR, 2021 CaseRecVector& WorkList, 2022 const Value* SV, 2023 MachineBasicBlock *Default, 2024 MachineBasicBlock *SwitchBB) { 2025 // Size is the number of Cases represented by this range. 2026 size_t Size = CR.Range.second - CR.Range.first; 2027 if (Size > 3) 2028 return false; 2029 2030 // Get the MachineFunction which holds the current MBB. This is used when 2031 // inserting any additional MBBs necessary to represent the switch. 2032 MachineFunction *CurMF = FuncInfo.MF; 2033 2034 // Figure out which block is immediately after the current one. 2035 MachineBasicBlock *NextBlock = 0; 2036 MachineFunction::iterator BBI = CR.CaseBB; 2037 2038 if (++BBI != FuncInfo.MF->end()) 2039 NextBlock = BBI; 2040 2041 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2042 // If any two of the cases has the same destination, and if one value 2043 // is the same as the other, but has one bit unset that the other has set, 2044 // use bit manipulation to do two compares at once. For example: 2045 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)" 2046 // TODO: This could be extended to merge any 2 cases in switches with 3 cases. 2047 // TODO: Handle cases where CR.CaseBB != SwitchBB. 2048 if (Size == 2 && CR.CaseBB == SwitchBB) { 2049 Case &Small = *CR.Range.first; 2050 Case &Big = *(CR.Range.second-1); 2051 2052 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) { 2053 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue(); 2054 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue(); 2055 2056 // Check that there is only one bit different. 2057 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 && 2058 (SmallValue | BigValue) == BigValue) { 2059 // Isolate the common bit. 2060 APInt CommonBit = BigValue & ~SmallValue; 2061 assert((SmallValue | CommonBit) == BigValue && 2062 CommonBit.countPopulation() == 1 && "Not a common bit?"); 2063 2064 SDValue CondLHS = getValue(SV); 2065 EVT VT = CondLHS.getValueType(); 2066 SDLoc DL = getCurSDLoc(); 2067 2068 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS, 2069 DAG.getConstant(CommonBit, VT)); 2070 SDValue Cond = DAG.getSetCC(DL, MVT::i1, 2071 Or, DAG.getConstant(BigValue, VT), 2072 ISD::SETEQ); 2073 2074 // Update successor info. 2075 // Both Small and Big will jump to Small.BB, so we sum up the weights. 2076 addSuccessorWithWeight(SwitchBB, Small.BB, 2077 Small.ExtraWeight + Big.ExtraWeight); 2078 addSuccessorWithWeight(SwitchBB, Default, 2079 // The default destination is the first successor in IR. 2080 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0); 2081 2082 // Insert the true branch. 2083 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other, 2084 getControlRoot(), Cond, 2085 DAG.getBasicBlock(Small.BB)); 2086 2087 // Insert the false branch. 2088 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond, 2089 DAG.getBasicBlock(Default)); 2090 2091 DAG.setRoot(BrCond); 2092 return true; 2093 } 2094 } 2095 } 2096 2097 // Order cases by weight so the most likely case will be checked first. 2098 uint32_t UnhandledWeights = 0; 2099 if (BPI) { 2100 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) { 2101 uint32_t IWeight = I->ExtraWeight; 2102 UnhandledWeights += IWeight; 2103 for (CaseItr J = CR.Range.first; J < I; ++J) { 2104 uint32_t JWeight = J->ExtraWeight; 2105 if (IWeight > JWeight) 2106 std::swap(*I, *J); 2107 } 2108 } 2109 } 2110 // Rearrange the case blocks so that the last one falls through if possible. 2111 Case &BackCase = *(CR.Range.second-1); 2112 if (Size > 1 && 2113 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) { 2114 // The last case block won't fall through into 'NextBlock' if we emit the 2115 // branches in this order. See if rearranging a case value would help. 2116 // We start at the bottom as it's the case with the least weight. 2117 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I) 2118 if (I->BB == NextBlock) { 2119 std::swap(*I, BackCase); 2120 break; 2121 } 2122 } 2123 2124 // Create a CaseBlock record representing a conditional branch to 2125 // the Case's target mbb if the value being switched on SV is equal 2126 // to C. 2127 MachineBasicBlock *CurBlock = CR.CaseBB; 2128 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 2129 MachineBasicBlock *FallThrough; 2130 if (I != E-1) { 2131 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock()); 2132 CurMF->insert(BBI, FallThrough); 2133 2134 // Put SV in a virtual register to make it available from the new blocks. 2135 ExportFromCurrentBlock(SV); 2136 } else { 2137 // If the last case doesn't match, go to the default block. 2138 FallThrough = Default; 2139 } 2140 2141 const Value *RHS, *LHS, *MHS; 2142 ISD::CondCode CC; 2143 if (I->High == I->Low) { 2144 // This is just small small case range :) containing exactly 1 case 2145 CC = ISD::SETEQ; 2146 LHS = SV; RHS = I->High; MHS = NULL; 2147 } else { 2148 CC = ISD::SETCC_INVALID; 2149 LHS = I->Low; MHS = SV; RHS = I->High; 2150 } 2151 2152 // The false weight should be sum of all un-handled cases. 2153 UnhandledWeights -= I->ExtraWeight; 2154 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough, 2155 /* me */ CurBlock, 2156 /* trueweight */ I->ExtraWeight, 2157 /* falseweight */ UnhandledWeights); 2158 2159 // If emitting the first comparison, just call visitSwitchCase to emit the 2160 // code into the current block. Otherwise, push the CaseBlock onto the 2161 // vector to be later processed by SDISel, and insert the node's MBB 2162 // before the next MBB. 2163 if (CurBlock == SwitchBB) 2164 visitSwitchCase(CB, SwitchBB); 2165 else 2166 SwitchCases.push_back(CB); 2167 2168 CurBlock = FallThrough; 2169 } 2170 2171 return true; 2172 } 2173 2174 static inline bool areJTsAllowed(const TargetLowering &TLI) { 2175 return TLI.supportJumpTables() && 2176 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) || 2177 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other)); 2178 } 2179 2180 static APInt ComputeRange(const APInt &First, const APInt &Last) { 2181 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1; 2182 APInt LastExt = Last.zext(BitWidth), FirstExt = First.zext(BitWidth); 2183 return (LastExt - FirstExt + 1ULL); 2184 } 2185 2186 /// handleJTSwitchCase - Emit jumptable for current switch case range 2187 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR, 2188 CaseRecVector &WorkList, 2189 const Value *SV, 2190 MachineBasicBlock *Default, 2191 MachineBasicBlock *SwitchBB) { 2192 Case& FrontCase = *CR.Range.first; 2193 Case& BackCase = *(CR.Range.second-1); 2194 2195 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 2196 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 2197 2198 APInt TSize(First.getBitWidth(), 0); 2199 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) 2200 TSize += I->size(); 2201 2202 const TargetLowering *TLI = TM.getTargetLowering(); 2203 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries())) 2204 return false; 2205 2206 APInt Range = ComputeRange(First, Last); 2207 // The density is TSize / Range. Require at least 40%. 2208 // It should not be possible for IntTSize to saturate for sane code, but make 2209 // sure we handle Range saturation correctly. 2210 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10); 2211 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10); 2212 if (IntTSize * 10 < IntRange * 4) 2213 return false; 2214 2215 DEBUG(dbgs() << "Lowering jump table\n" 2216 << "First entry: " << First << ". Last entry: " << Last << '\n' 2217 << "Range: " << Range << ". Size: " << TSize << ".\n\n"); 2218 2219 // Get the MachineFunction which holds the current MBB. This is used when 2220 // inserting any additional MBBs necessary to represent the switch. 2221 MachineFunction *CurMF = FuncInfo.MF; 2222 2223 // Figure out which block is immediately after the current one. 2224 MachineFunction::iterator BBI = CR.CaseBB; 2225 ++BBI; 2226 2227 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2228 2229 // Create a new basic block to hold the code for loading the address 2230 // of the jump table, and jumping to it. Update successor information; 2231 // we will either branch to the default case for the switch, or the jump 2232 // table. 2233 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2234 CurMF->insert(BBI, JumpTableBB); 2235 2236 addSuccessorWithWeight(CR.CaseBB, Default); 2237 addSuccessorWithWeight(CR.CaseBB, JumpTableBB); 2238 2239 // Build a vector of destination BBs, corresponding to each target 2240 // of the jump table. If the value of the jump table slot corresponds to 2241 // a case statement, push the case's BB onto the vector, otherwise, push 2242 // the default BB. 2243 std::vector<MachineBasicBlock*> DestBBs; 2244 APInt TEI = First; 2245 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) { 2246 const APInt &Low = cast<ConstantInt>(I->Low)->getValue(); 2247 const APInt &High = cast<ConstantInt>(I->High)->getValue(); 2248 2249 if (Low.ule(TEI) && TEI.ule(High)) { 2250 DestBBs.push_back(I->BB); 2251 if (TEI==High) 2252 ++I; 2253 } else { 2254 DestBBs.push_back(Default); 2255 } 2256 } 2257 2258 // Calculate weight for each unique destination in CR. 2259 DenseMap<MachineBasicBlock*, uint32_t> DestWeights; 2260 if (FuncInfo.BPI) 2261 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) { 2262 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr = 2263 DestWeights.find(I->BB); 2264 if (Itr != DestWeights.end()) 2265 Itr->second += I->ExtraWeight; 2266 else 2267 DestWeights[I->BB] = I->ExtraWeight; 2268 } 2269 2270 // Update successor info. Add one edge to each unique successor. 2271 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs()); 2272 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 2273 E = DestBBs.end(); I != E; ++I) { 2274 if (!SuccsHandled[(*I)->getNumber()]) { 2275 SuccsHandled[(*I)->getNumber()] = true; 2276 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr = 2277 DestWeights.find(*I); 2278 addSuccessorWithWeight(JumpTableBB, *I, 2279 Itr != DestWeights.end() ? Itr->second : 0); 2280 } 2281 } 2282 2283 // Create a jump table index for this jump table. 2284 unsigned JTEncoding = TLI->getJumpTableEncoding(); 2285 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding) 2286 ->createJumpTableIndex(DestBBs); 2287 2288 // Set the jump table information so that we can codegen it as a second 2289 // MachineBasicBlock 2290 JumpTable JT(-1U, JTI, JumpTableBB, Default); 2291 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB)); 2292 if (CR.CaseBB == SwitchBB) 2293 visitJumpTableHeader(JT, JTH, SwitchBB); 2294 2295 JTCases.push_back(JumpTableBlock(JTH, JT)); 2296 return true; 2297 } 2298 2299 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into 2300 /// 2 subtrees. 2301 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR, 2302 CaseRecVector& WorkList, 2303 const Value* SV, 2304 MachineBasicBlock* Default, 2305 MachineBasicBlock* SwitchBB) { 2306 // Get the MachineFunction which holds the current MBB. This is used when 2307 // inserting any additional MBBs necessary to represent the switch. 2308 MachineFunction *CurMF = FuncInfo.MF; 2309 2310 // Figure out which block is immediately after the current one. 2311 MachineFunction::iterator BBI = CR.CaseBB; 2312 ++BBI; 2313 2314 Case& FrontCase = *CR.Range.first; 2315 Case& BackCase = *(CR.Range.second-1); 2316 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2317 2318 // Size is the number of Cases represented by this range. 2319 unsigned Size = CR.Range.second - CR.Range.first; 2320 2321 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue(); 2322 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue(); 2323 double FMetric = 0; 2324 CaseItr Pivot = CR.Range.first + Size/2; 2325 2326 // Select optimal pivot, maximizing sum density of LHS and RHS. This will 2327 // (heuristically) allow us to emit JumpTable's later. 2328 APInt TSize(First.getBitWidth(), 0); 2329 for (CaseItr I = CR.Range.first, E = CR.Range.second; 2330 I!=E; ++I) 2331 TSize += I->size(); 2332 2333 APInt LSize = FrontCase.size(); 2334 APInt RSize = TSize-LSize; 2335 DEBUG(dbgs() << "Selecting best pivot: \n" 2336 << "First: " << First << ", Last: " << Last <<'\n' 2337 << "LSize: " << LSize << ", RSize: " << RSize << '\n'); 2338 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second; 2339 J!=E; ++I, ++J) { 2340 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue(); 2341 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue(); 2342 APInt Range = ComputeRange(LEnd, RBegin); 2343 assert((Range - 2ULL).isNonNegative() && 2344 "Invalid case distance"); 2345 // Use volatile double here to avoid excess precision issues on some hosts, 2346 // e.g. that use 80-bit X87 registers. 2347 volatile double LDensity = 2348 (double)LSize.roundToDouble() / 2349 (LEnd - First + 1ULL).roundToDouble(); 2350 volatile double RDensity = 2351 (double)RSize.roundToDouble() / 2352 (Last - RBegin + 1ULL).roundToDouble(); 2353 double Metric = Range.logBase2()*(LDensity+RDensity); 2354 // Should always split in some non-trivial place 2355 DEBUG(dbgs() <<"=>Step\n" 2356 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n' 2357 << "LDensity: " << LDensity 2358 << ", RDensity: " << RDensity << '\n' 2359 << "Metric: " << Metric << '\n'); 2360 if (FMetric < Metric) { 2361 Pivot = J; 2362 FMetric = Metric; 2363 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n'); 2364 } 2365 2366 LSize += J->size(); 2367 RSize -= J->size(); 2368 } 2369 2370 const TargetLowering *TLI = TM.getTargetLowering(); 2371 if (areJTsAllowed(*TLI)) { 2372 // If our case is dense we *really* should handle it earlier! 2373 assert((FMetric > 0) && "Should handle dense range earlier!"); 2374 } else { 2375 Pivot = CR.Range.first + Size/2; 2376 } 2377 2378 CaseRange LHSR(CR.Range.first, Pivot); 2379 CaseRange RHSR(Pivot, CR.Range.second); 2380 const Constant *C = Pivot->Low; 2381 MachineBasicBlock *FalseBB = 0, *TrueBB = 0; 2382 2383 // We know that we branch to the LHS if the Value being switched on is 2384 // less than the Pivot value, C. We use this to optimize our binary 2385 // tree a bit, by recognizing that if SV is greater than or equal to the 2386 // LHS's Case Value, and that Case Value is exactly one less than the 2387 // Pivot's Value, then we can branch directly to the LHS's Target, 2388 // rather than creating a leaf node for it. 2389 if ((LHSR.second - LHSR.first) == 1 && 2390 LHSR.first->High == CR.GE && 2391 cast<ConstantInt>(C)->getValue() == 2392 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) { 2393 TrueBB = LHSR.first->BB; 2394 } else { 2395 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2396 CurMF->insert(BBI, TrueBB); 2397 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR)); 2398 2399 // Put SV in a virtual register to make it available from the new blocks. 2400 ExportFromCurrentBlock(SV); 2401 } 2402 2403 // Similar to the optimization above, if the Value being switched on is 2404 // known to be less than the Constant CR.LT, and the current Case Value 2405 // is CR.LT - 1, then we can branch directly to the target block for 2406 // the current Case Value, rather than emitting a RHS leaf node for it. 2407 if ((RHSR.second - RHSR.first) == 1 && CR.LT && 2408 cast<ConstantInt>(RHSR.first->Low)->getValue() == 2409 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) { 2410 FalseBB = RHSR.first->BB; 2411 } else { 2412 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2413 CurMF->insert(BBI, FalseBB); 2414 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR)); 2415 2416 // Put SV in a virtual register to make it available from the new blocks. 2417 ExportFromCurrentBlock(SV); 2418 } 2419 2420 // Create a CaseBlock record representing a conditional branch to 2421 // the LHS node if the value being switched on SV is less than C. 2422 // Otherwise, branch to LHS. 2423 CaseBlock CB(ISD::SETULT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB); 2424 2425 if (CR.CaseBB == SwitchBB) 2426 visitSwitchCase(CB, SwitchBB); 2427 else 2428 SwitchCases.push_back(CB); 2429 2430 return true; 2431 } 2432 2433 /// handleBitTestsSwitchCase - if current case range has few destination and 2434 /// range span less, than machine word bitwidth, encode case range into series 2435 /// of masks and emit bit tests with these masks. 2436 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR, 2437 CaseRecVector& WorkList, 2438 const Value* SV, 2439 MachineBasicBlock* Default, 2440 MachineBasicBlock* SwitchBB) { 2441 const TargetLowering *TLI = TM.getTargetLowering(); 2442 EVT PTy = TLI->getPointerTy(); 2443 unsigned IntPtrBits = PTy.getSizeInBits(); 2444 2445 Case& FrontCase = *CR.Range.first; 2446 Case& BackCase = *(CR.Range.second-1); 2447 2448 // Get the MachineFunction which holds the current MBB. This is used when 2449 // inserting any additional MBBs necessary to represent the switch. 2450 MachineFunction *CurMF = FuncInfo.MF; 2451 2452 // If target does not have legal shift left, do not emit bit tests at all. 2453 if (!TLI->isOperationLegal(ISD::SHL, TLI->getPointerTy())) 2454 return false; 2455 2456 size_t numCmps = 0; 2457 for (CaseItr I = CR.Range.first, E = CR.Range.second; 2458 I!=E; ++I) { 2459 // Single case counts one, case range - two. 2460 numCmps += (I->Low == I->High ? 1 : 2); 2461 } 2462 2463 // Count unique destinations 2464 SmallSet<MachineBasicBlock*, 4> Dests; 2465 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2466 Dests.insert(I->BB); 2467 if (Dests.size() > 3) 2468 // Don't bother the code below, if there are too much unique destinations 2469 return false; 2470 } 2471 DEBUG(dbgs() << "Total number of unique destinations: " 2472 << Dests.size() << '\n' 2473 << "Total number of comparisons: " << numCmps << '\n'); 2474 2475 // Compute span of values. 2476 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue(); 2477 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue(); 2478 APInt cmpRange = maxValue - minValue; 2479 2480 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n' 2481 << "Low bound: " << minValue << '\n' 2482 << "High bound: " << maxValue << '\n'); 2483 2484 if (cmpRange.uge(IntPtrBits) || 2485 (!(Dests.size() == 1 && numCmps >= 3) && 2486 !(Dests.size() == 2 && numCmps >= 5) && 2487 !(Dests.size() >= 3 && numCmps >= 6))) 2488 return false; 2489 2490 DEBUG(dbgs() << "Emitting bit tests\n"); 2491 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth()); 2492 2493 // Optimize the case where all the case values fit in a 2494 // word without having to subtract minValue. In this case, 2495 // we can optimize away the subtraction. 2496 if (maxValue.ult(IntPtrBits)) { 2497 cmpRange = maxValue; 2498 } else { 2499 lowBound = minValue; 2500 } 2501 2502 CaseBitsVector CasesBits; 2503 unsigned i, count = 0; 2504 2505 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) { 2506 MachineBasicBlock* Dest = I->BB; 2507 for (i = 0; i < count; ++i) 2508 if (Dest == CasesBits[i].BB) 2509 break; 2510 2511 if (i == count) { 2512 assert((count < 3) && "Too much destinations to test!"); 2513 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/)); 2514 count++; 2515 } 2516 2517 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue(); 2518 const APInt& highValue = cast<ConstantInt>(I->High)->getValue(); 2519 2520 uint64_t lo = (lowValue - lowBound).getZExtValue(); 2521 uint64_t hi = (highValue - lowBound).getZExtValue(); 2522 CasesBits[i].ExtraWeight += I->ExtraWeight; 2523 2524 for (uint64_t j = lo; j <= hi; j++) { 2525 CasesBits[i].Mask |= 1ULL << j; 2526 CasesBits[i].Bits++; 2527 } 2528 2529 } 2530 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp()); 2531 2532 BitTestInfo BTC; 2533 2534 // Figure out which block is immediately after the current one. 2535 MachineFunction::iterator BBI = CR.CaseBB; 2536 ++BBI; 2537 2538 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock(); 2539 2540 DEBUG(dbgs() << "Cases:\n"); 2541 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) { 2542 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask 2543 << ", Bits: " << CasesBits[i].Bits 2544 << ", BB: " << CasesBits[i].BB << '\n'); 2545 2546 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB); 2547 CurMF->insert(BBI, CaseBB); 2548 BTC.push_back(BitTestCase(CasesBits[i].Mask, 2549 CaseBB, 2550 CasesBits[i].BB, CasesBits[i].ExtraWeight)); 2551 2552 // Put SV in a virtual register to make it available from the new blocks. 2553 ExportFromCurrentBlock(SV); 2554 } 2555 2556 BitTestBlock BTB(lowBound, cmpRange, SV, 2557 -1U, MVT::Other, (CR.CaseBB == SwitchBB), 2558 CR.CaseBB, Default, BTC); 2559 2560 if (CR.CaseBB == SwitchBB) 2561 visitBitTestHeader(BTB, SwitchBB); 2562 2563 BitTestCases.push_back(BTB); 2564 2565 return true; 2566 } 2567 2568 /// Clusterify - Transform simple list of Cases into list of CaseRange's 2569 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases, 2570 const SwitchInst& SI) { 2571 2572 /// Use a shorter form of declaration, and also 2573 /// show the we want to use CRSBuilder as Clusterifier. 2574 typedef IntegersSubsetMapping<MachineBasicBlock> Clusterifier; 2575 2576 Clusterifier TheClusterifier; 2577 2578 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2579 // Start with "simple" cases 2580 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end(); 2581 i != e; ++i) { 2582 const BasicBlock *SuccBB = i.getCaseSuccessor(); 2583 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB]; 2584 2585 TheClusterifier.add(i.getCaseValueEx(), SMBB, 2586 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0); 2587 } 2588 2589 TheClusterifier.optimize(); 2590 2591 size_t numCmps = 0; 2592 for (Clusterifier::RangeIterator i = TheClusterifier.begin(), 2593 e = TheClusterifier.end(); i != e; ++i, ++numCmps) { 2594 Clusterifier::Cluster &C = *i; 2595 // Update edge weight for the cluster. 2596 unsigned W = C.first.Weight; 2597 2598 // FIXME: Currently work with ConstantInt based numbers. 2599 // Changing it to APInt based is a pretty heavy for this commit. 2600 Cases.push_back(Case(C.first.getLow().toConstantInt(), 2601 C.first.getHigh().toConstantInt(), C.second, W)); 2602 2603 if (C.first.getLow() != C.first.getHigh()) 2604 // A range counts double, since it requires two compares. 2605 ++numCmps; 2606 } 2607 2608 return numCmps; 2609 } 2610 2611 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First, 2612 MachineBasicBlock *Last) { 2613 // Update JTCases. 2614 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) 2615 if (JTCases[i].first.HeaderBB == First) 2616 JTCases[i].first.HeaderBB = Last; 2617 2618 // Update BitTestCases. 2619 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) 2620 if (BitTestCases[i].Parent == First) 2621 BitTestCases[i].Parent = Last; 2622 } 2623 2624 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) { 2625 MachineBasicBlock *SwitchMBB = FuncInfo.MBB; 2626 2627 // Figure out which block is immediately after the current one. 2628 MachineBasicBlock *NextBlock = 0; 2629 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()]; 2630 2631 // If there is only the default destination, branch to it if it is not the 2632 // next basic block. Otherwise, just fall through. 2633 if (!SI.getNumCases()) { 2634 // Update machine-CFG edges. 2635 2636 // If this is not a fall-through branch, emit the branch. 2637 SwitchMBB->addSuccessor(Default); 2638 if (Default != NextBlock) 2639 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), 2640 MVT::Other, getControlRoot(), 2641 DAG.getBasicBlock(Default))); 2642 2643 return; 2644 } 2645 2646 // If there are any non-default case statements, create a vector of Cases 2647 // representing each one, and sort the vector so that we can efficiently 2648 // create a binary search tree from them. 2649 CaseVector Cases; 2650 size_t numCmps = Clusterify(Cases, SI); 2651 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size() 2652 << ". Total compares: " << numCmps << '\n'); 2653 (void)numCmps; 2654 2655 // Get the Value to be switched on and default basic blocks, which will be 2656 // inserted into CaseBlock records, representing basic blocks in the binary 2657 // search tree. 2658 const Value *SV = SI.getCondition(); 2659 2660 // Push the initial CaseRec onto the worklist 2661 CaseRecVector WorkList; 2662 WorkList.push_back(CaseRec(SwitchMBB,0,0, 2663 CaseRange(Cases.begin(),Cases.end()))); 2664 2665 while (!WorkList.empty()) { 2666 // Grab a record representing a case range to process off the worklist 2667 CaseRec CR = WorkList.back(); 2668 WorkList.pop_back(); 2669 2670 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2671 continue; 2672 2673 // If the range has few cases (two or less) emit a series of specific 2674 // tests. 2675 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB)) 2676 continue; 2677 2678 // If the switch has more than N blocks, and is at least 40% dense, and the 2679 // target supports indirect branches, then emit a jump table rather than 2680 // lowering the switch to a binary tree of conditional branches. 2681 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries(). 2682 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB)) 2683 continue; 2684 2685 // Emit binary tree. We need to pick a pivot, and push left and right ranges 2686 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call. 2687 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB); 2688 } 2689 } 2690 2691 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) { 2692 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB; 2693 2694 // Update machine-CFG edges with unique successors. 2695 SmallSet<BasicBlock*, 32> Done; 2696 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) { 2697 BasicBlock *BB = I.getSuccessor(i); 2698 bool Inserted = Done.insert(BB); 2699 if (!Inserted) 2700 continue; 2701 2702 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB]; 2703 addSuccessorWithWeight(IndirectBrMBB, Succ); 2704 } 2705 2706 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(), 2707 MVT::Other, getControlRoot(), 2708 getValue(I.getAddress()))); 2709 } 2710 2711 void SelectionDAGBuilder::visitFSub(const User &I) { 2712 // -0.0 - X --> fneg 2713 Type *Ty = I.getType(); 2714 if (isa<Constant>(I.getOperand(0)) && 2715 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) { 2716 SDValue Op2 = getValue(I.getOperand(1)); 2717 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(), 2718 Op2.getValueType(), Op2)); 2719 return; 2720 } 2721 2722 visitBinary(I, ISD::FSUB); 2723 } 2724 2725 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) { 2726 SDValue Op1 = getValue(I.getOperand(0)); 2727 SDValue Op2 = getValue(I.getOperand(1)); 2728 setValue(&I, DAG.getNode(OpCode, getCurSDLoc(), 2729 Op1.getValueType(), Op1, Op2)); 2730 } 2731 2732 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) { 2733 SDValue Op1 = getValue(I.getOperand(0)); 2734 SDValue Op2 = getValue(I.getOperand(1)); 2735 2736 EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType()); 2737 2738 // Coerce the shift amount to the right type if we can. 2739 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) { 2740 unsigned ShiftSize = ShiftTy.getSizeInBits(); 2741 unsigned Op2Size = Op2.getValueType().getSizeInBits(); 2742 SDLoc DL = getCurSDLoc(); 2743 2744 // If the operand is smaller than the shift count type, promote it. 2745 if (ShiftSize > Op2Size) 2746 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2); 2747 2748 // If the operand is larger than the shift count type but the shift 2749 // count type has enough bits to represent any shift value, truncate 2750 // it now. This is a common case and it exposes the truncate to 2751 // optimization early. 2752 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits())) 2753 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2); 2754 // Otherwise we'll need to temporarily settle for some other convenient 2755 // type. Type legalization will make adjustments once the shiftee is split. 2756 else 2757 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32); 2758 } 2759 2760 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), 2761 Op1.getValueType(), Op1, Op2)); 2762 } 2763 2764 void SelectionDAGBuilder::visitSDiv(const User &I) { 2765 SDValue Op1 = getValue(I.getOperand(0)); 2766 SDValue Op2 = getValue(I.getOperand(1)); 2767 2768 // Turn exact SDivs into multiplications. 2769 // FIXME: This should be in DAGCombiner, but it doesn't have access to the 2770 // exact bit. 2771 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() && 2772 !isa<ConstantSDNode>(Op1) && 2773 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue()) 2774 setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2, 2775 getCurSDLoc(), DAG)); 2776 else 2777 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), 2778 Op1, Op2)); 2779 } 2780 2781 void SelectionDAGBuilder::visitICmp(const User &I) { 2782 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE; 2783 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I)) 2784 predicate = IC->getPredicate(); 2785 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I)) 2786 predicate = ICmpInst::Predicate(IC->getPredicate()); 2787 SDValue Op1 = getValue(I.getOperand(0)); 2788 SDValue Op2 = getValue(I.getOperand(1)); 2789 ISD::CondCode Opcode = getICmpCondCode(predicate); 2790 2791 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2792 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode)); 2793 } 2794 2795 void SelectionDAGBuilder::visitFCmp(const User &I) { 2796 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE; 2797 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I)) 2798 predicate = FC->getPredicate(); 2799 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I)) 2800 predicate = FCmpInst::Predicate(FC->getPredicate()); 2801 SDValue Op1 = getValue(I.getOperand(0)); 2802 SDValue Op2 = getValue(I.getOperand(1)); 2803 ISD::CondCode Condition = getFCmpCondCode(predicate); 2804 if (TM.Options.NoNaNsFPMath) 2805 Condition = getFCmpCodeWithoutNaN(Condition); 2806 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2807 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition)); 2808 } 2809 2810 void SelectionDAGBuilder::visitSelect(const User &I) { 2811 SmallVector<EVT, 4> ValueVTs; 2812 ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs); 2813 unsigned NumValues = ValueVTs.size(); 2814 if (NumValues == 0) return; 2815 2816 SmallVector<SDValue, 4> Values(NumValues); 2817 SDValue Cond = getValue(I.getOperand(0)); 2818 SDValue TrueVal = getValue(I.getOperand(1)); 2819 SDValue FalseVal = getValue(I.getOperand(2)); 2820 ISD::NodeType OpCode = Cond.getValueType().isVector() ? 2821 ISD::VSELECT : ISD::SELECT; 2822 2823 for (unsigned i = 0; i != NumValues; ++i) 2824 Values[i] = DAG.getNode(OpCode, getCurSDLoc(), 2825 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i), 2826 Cond, 2827 SDValue(TrueVal.getNode(), 2828 TrueVal.getResNo() + i), 2829 SDValue(FalseVal.getNode(), 2830 FalseVal.getResNo() + i)); 2831 2832 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 2833 DAG.getVTList(&ValueVTs[0], NumValues), 2834 &Values[0], NumValues)); 2835 } 2836 2837 void SelectionDAGBuilder::visitTrunc(const User &I) { 2838 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest). 2839 SDValue N = getValue(I.getOperand(0)); 2840 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2841 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N)); 2842 } 2843 2844 void SelectionDAGBuilder::visitZExt(const User &I) { 2845 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2846 // ZExt also can't be a cast to bool for same reason. So, nothing much to do 2847 SDValue N = getValue(I.getOperand(0)); 2848 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2849 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N)); 2850 } 2851 2852 void SelectionDAGBuilder::visitSExt(const User &I) { 2853 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest). 2854 // SExt also can't be a cast to bool for same reason. So, nothing much to do 2855 SDValue N = getValue(I.getOperand(0)); 2856 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2857 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N)); 2858 } 2859 2860 void SelectionDAGBuilder::visitFPTrunc(const User &I) { 2861 // FPTrunc is never a no-op cast, no need to check 2862 SDValue N = getValue(I.getOperand(0)); 2863 const TargetLowering *TLI = TM.getTargetLowering(); 2864 EVT DestVT = TLI->getValueType(I.getType()); 2865 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), 2866 DestVT, N, 2867 DAG.getTargetConstant(0, TLI->getPointerTy()))); 2868 } 2869 2870 void SelectionDAGBuilder::visitFPExt(const User &I) { 2871 // FPExt is never a no-op cast, no need to check 2872 SDValue N = getValue(I.getOperand(0)); 2873 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2874 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N)); 2875 } 2876 2877 void SelectionDAGBuilder::visitFPToUI(const User &I) { 2878 // FPToUI is never a no-op cast, no need to check 2879 SDValue N = getValue(I.getOperand(0)); 2880 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2881 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N)); 2882 } 2883 2884 void SelectionDAGBuilder::visitFPToSI(const User &I) { 2885 // FPToSI is never a no-op cast, no need to check 2886 SDValue N = getValue(I.getOperand(0)); 2887 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2888 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N)); 2889 } 2890 2891 void SelectionDAGBuilder::visitUIToFP(const User &I) { 2892 // UIToFP is never a no-op cast, no need to check 2893 SDValue N = getValue(I.getOperand(0)); 2894 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2895 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N)); 2896 } 2897 2898 void SelectionDAGBuilder::visitSIToFP(const User &I) { 2899 // SIToFP is never a no-op cast, no need to check 2900 SDValue N = getValue(I.getOperand(0)); 2901 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2902 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N)); 2903 } 2904 2905 void SelectionDAGBuilder::visitPtrToInt(const User &I) { 2906 // What to do depends on the size of the integer and the size of the pointer. 2907 // We can either truncate, zero extend, or no-op, accordingly. 2908 SDValue N = getValue(I.getOperand(0)); 2909 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2910 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2911 } 2912 2913 void SelectionDAGBuilder::visitIntToPtr(const User &I) { 2914 // What to do depends on the size of the integer and the size of the pointer. 2915 // We can either truncate, zero extend, or no-op, accordingly. 2916 SDValue N = getValue(I.getOperand(0)); 2917 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2918 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT)); 2919 } 2920 2921 void SelectionDAGBuilder::visitBitCast(const User &I) { 2922 SDValue N = getValue(I.getOperand(0)); 2923 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType()); 2924 2925 // BitCast assures us that source and destination are the same size so this is 2926 // either a BITCAST or a no-op. 2927 if (DestVT != N.getValueType()) 2928 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(), 2929 DestVT, N)); // convert types. 2930 else 2931 setValue(&I, N); // noop cast. 2932 } 2933 2934 void SelectionDAGBuilder::visitInsertElement(const User &I) { 2935 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2936 SDValue InVec = getValue(I.getOperand(0)); 2937 SDValue InVal = getValue(I.getOperand(1)); 2938 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), 2939 getCurSDLoc(), TLI.getVectorIdxTy()); 2940 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(), 2941 TM.getTargetLowering()->getValueType(I.getType()), 2942 InVec, InVal, InIdx)); 2943 } 2944 2945 void SelectionDAGBuilder::visitExtractElement(const User &I) { 2946 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2947 SDValue InVec = getValue(I.getOperand(0)); 2948 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), 2949 getCurSDLoc(), TLI.getVectorIdxTy()); 2950 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 2951 TM.getTargetLowering()->getValueType(I.getType()), 2952 InVec, InIdx)); 2953 } 2954 2955 // Utility for visitShuffleVector - Return true if every element in Mask, 2956 // beginning from position Pos and ending in Pos+Size, falls within the 2957 // specified sequential range [L, L+Pos). or is undef. 2958 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask, 2959 unsigned Pos, unsigned Size, int Low) { 2960 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low) 2961 if (Mask[i] >= 0 && Mask[i] != Low) 2962 return false; 2963 return true; 2964 } 2965 2966 void SelectionDAGBuilder::visitShuffleVector(const User &I) { 2967 SDValue Src1 = getValue(I.getOperand(0)); 2968 SDValue Src2 = getValue(I.getOperand(1)); 2969 2970 SmallVector<int, 8> Mask; 2971 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask); 2972 unsigned MaskNumElts = Mask.size(); 2973 2974 const TargetLowering *TLI = TM.getTargetLowering(); 2975 EVT VT = TLI->getValueType(I.getType()); 2976 EVT SrcVT = Src1.getValueType(); 2977 unsigned SrcNumElts = SrcVT.getVectorNumElements(); 2978 2979 if (SrcNumElts == MaskNumElts) { 2980 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 2981 &Mask[0])); 2982 return; 2983 } 2984 2985 // Normalize the shuffle vector since mask and vector length don't match. 2986 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) { 2987 // Mask is longer than the source vectors and is a multiple of the source 2988 // vectors. We can use concatenate vector to make the mask and vectors 2989 // lengths match. 2990 if (SrcNumElts*2 == MaskNumElts) { 2991 // First check for Src1 in low and Src2 in high 2992 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) && 2993 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) { 2994 // The shuffle is concatenating two vectors together. 2995 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(), 2996 VT, Src1, Src2)); 2997 return; 2998 } 2999 // Then check for Src2 in low and Src1 in high 3000 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) && 3001 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) { 3002 // The shuffle is concatenating two vectors together. 3003 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(), 3004 VT, Src2, Src1)); 3005 return; 3006 } 3007 } 3008 3009 // Pad both vectors with undefs to make them the same length as the mask. 3010 unsigned NumConcat = MaskNumElts / SrcNumElts; 3011 bool Src1U = Src1.getOpcode() == ISD::UNDEF; 3012 bool Src2U = Src2.getOpcode() == ISD::UNDEF; 3013 SDValue UndefVal = DAG.getUNDEF(SrcVT); 3014 3015 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal); 3016 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal); 3017 MOps1[0] = Src1; 3018 MOps2[0] = Src2; 3019 3020 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 3021 getCurSDLoc(), VT, 3022 &MOps1[0], NumConcat); 3023 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS, 3024 getCurSDLoc(), VT, 3025 &MOps2[0], NumConcat); 3026 3027 // Readjust mask for new input vector length. 3028 SmallVector<int, 8> MappedOps; 3029 for (unsigned i = 0; i != MaskNumElts; ++i) { 3030 int Idx = Mask[i]; 3031 if (Idx >= (int)SrcNumElts) 3032 Idx -= SrcNumElts - MaskNumElts; 3033 MappedOps.push_back(Idx); 3034 } 3035 3036 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 3037 &MappedOps[0])); 3038 return; 3039 } 3040 3041 if (SrcNumElts > MaskNumElts) { 3042 // Analyze the access pattern of the vector to see if we can extract 3043 // two subvectors and do the shuffle. The analysis is done by calculating 3044 // the range of elements the mask access on both vectors. 3045 int MinRange[2] = { static_cast<int>(SrcNumElts), 3046 static_cast<int>(SrcNumElts)}; 3047 int MaxRange[2] = {-1, -1}; 3048 3049 for (unsigned i = 0; i != MaskNumElts; ++i) { 3050 int Idx = Mask[i]; 3051 unsigned Input = 0; 3052 if (Idx < 0) 3053 continue; 3054 3055 if (Idx >= (int)SrcNumElts) { 3056 Input = 1; 3057 Idx -= SrcNumElts; 3058 } 3059 if (Idx > MaxRange[Input]) 3060 MaxRange[Input] = Idx; 3061 if (Idx < MinRange[Input]) 3062 MinRange[Input] = Idx; 3063 } 3064 3065 // Check if the access is smaller than the vector size and can we find 3066 // a reasonable extract index. 3067 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not 3068 // Extract. 3069 int StartIdx[2]; // StartIdx to extract from 3070 for (unsigned Input = 0; Input < 2; ++Input) { 3071 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) { 3072 RangeUse[Input] = 0; // Unused 3073 StartIdx[Input] = 0; 3074 continue; 3075 } 3076 3077 // Find a good start index that is a multiple of the mask length. Then 3078 // see if the rest of the elements are in range. 3079 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts; 3080 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts && 3081 StartIdx[Input] + MaskNumElts <= SrcNumElts) 3082 RangeUse[Input] = 1; // Extract from a multiple of the mask length. 3083 } 3084 3085 if (RangeUse[0] == 0 && RangeUse[1] == 0) { 3086 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used. 3087 return; 3088 } 3089 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) { 3090 // Extract appropriate subvector and generate a vector shuffle 3091 for (unsigned Input = 0; Input < 2; ++Input) { 3092 SDValue &Src = Input == 0 ? Src1 : Src2; 3093 if (RangeUse[Input] == 0) 3094 Src = DAG.getUNDEF(VT); 3095 else 3096 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, 3097 Src, DAG.getConstant(StartIdx[Input], 3098 TLI->getVectorIdxTy())); 3099 } 3100 3101 // Calculate new mask. 3102 SmallVector<int, 8> MappedOps; 3103 for (unsigned i = 0; i != MaskNumElts; ++i) { 3104 int Idx = Mask[i]; 3105 if (Idx >= 0) { 3106 if (Idx < (int)SrcNumElts) 3107 Idx -= StartIdx[0]; 3108 else 3109 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts; 3110 } 3111 MappedOps.push_back(Idx); 3112 } 3113 3114 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2, 3115 &MappedOps[0])); 3116 return; 3117 } 3118 } 3119 3120 // We can't use either concat vectors or extract subvectors so fall back to 3121 // replacing the shuffle with extract and build vector. 3122 // to insert and build vector. 3123 EVT EltVT = VT.getVectorElementType(); 3124 EVT IdxVT = TLI->getVectorIdxTy(); 3125 SmallVector<SDValue,8> Ops; 3126 for (unsigned i = 0; i != MaskNumElts; ++i) { 3127 int Idx = Mask[i]; 3128 SDValue Res; 3129 3130 if (Idx < 0) { 3131 Res = DAG.getUNDEF(EltVT); 3132 } else { 3133 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2; 3134 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts; 3135 3136 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(), 3137 EltVT, Src, DAG.getConstant(Idx, IdxVT)); 3138 } 3139 3140 Ops.push_back(Res); 3141 } 3142 3143 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), 3144 VT, &Ops[0], Ops.size())); 3145 } 3146 3147 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) { 3148 const Value *Op0 = I.getOperand(0); 3149 const Value *Op1 = I.getOperand(1); 3150 Type *AggTy = I.getType(); 3151 Type *ValTy = Op1->getType(); 3152 bool IntoUndef = isa<UndefValue>(Op0); 3153 bool FromUndef = isa<UndefValue>(Op1); 3154 3155 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 3156 3157 const TargetLowering *TLI = TM.getTargetLowering(); 3158 SmallVector<EVT, 4> AggValueVTs; 3159 ComputeValueVTs(*TLI, AggTy, AggValueVTs); 3160 SmallVector<EVT, 4> ValValueVTs; 3161 ComputeValueVTs(*TLI, ValTy, ValValueVTs); 3162 3163 unsigned NumAggValues = AggValueVTs.size(); 3164 unsigned NumValValues = ValValueVTs.size(); 3165 SmallVector<SDValue, 4> Values(NumAggValues); 3166 3167 SDValue Agg = getValue(Op0); 3168 unsigned i = 0; 3169 // Copy the beginning value(s) from the original aggregate. 3170 for (; i != LinearIndex; ++i) 3171 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3172 SDValue(Agg.getNode(), Agg.getResNo() + i); 3173 // Copy values from the inserted value(s). 3174 if (NumValValues) { 3175 SDValue Val = getValue(Op1); 3176 for (; i != LinearIndex + NumValValues; ++i) 3177 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3178 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex); 3179 } 3180 // Copy remaining value(s) from the original aggregate. 3181 for (; i != NumAggValues; ++i) 3182 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) : 3183 SDValue(Agg.getNode(), Agg.getResNo() + i); 3184 3185 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3186 DAG.getVTList(&AggValueVTs[0], NumAggValues), 3187 &Values[0], NumAggValues)); 3188 } 3189 3190 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) { 3191 const Value *Op0 = I.getOperand(0); 3192 Type *AggTy = Op0->getType(); 3193 Type *ValTy = I.getType(); 3194 bool OutOfUndef = isa<UndefValue>(Op0); 3195 3196 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices()); 3197 3198 const TargetLowering *TLI = TM.getTargetLowering(); 3199 SmallVector<EVT, 4> ValValueVTs; 3200 ComputeValueVTs(*TLI, ValTy, ValValueVTs); 3201 3202 unsigned NumValValues = ValValueVTs.size(); 3203 3204 // Ignore a extractvalue that produces an empty object 3205 if (!NumValValues) { 3206 setValue(&I, DAG.getUNDEF(MVT(MVT::Other))); 3207 return; 3208 } 3209 3210 SmallVector<SDValue, 4> Values(NumValValues); 3211 3212 SDValue Agg = getValue(Op0); 3213 // Copy out the selected value(s). 3214 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i) 3215 Values[i - LinearIndex] = 3216 OutOfUndef ? 3217 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) : 3218 SDValue(Agg.getNode(), Agg.getResNo() + i); 3219 3220 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3221 DAG.getVTList(&ValValueVTs[0], NumValValues), 3222 &Values[0], NumValValues)); 3223 } 3224 3225 void SelectionDAGBuilder::visitGetElementPtr(const User &I) { 3226 SDValue N = getValue(I.getOperand(0)); 3227 // Note that the pointer operand may be a vector of pointers. Take the scalar 3228 // element which holds a pointer. 3229 Type *Ty = I.getOperand(0)->getType()->getScalarType(); 3230 3231 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end(); 3232 OI != E; ++OI) { 3233 const Value *Idx = *OI; 3234 if (StructType *StTy = dyn_cast<StructType>(Ty)) { 3235 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 3236 if (Field) { 3237 // N = N + Offset 3238 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field); 3239 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N, 3240 DAG.getConstant(Offset, N.getValueType())); 3241 } 3242 3243 Ty = StTy->getElementType(Field); 3244 } else { 3245 uint32_t AS = 0; 3246 if (PointerType *PtrType = dyn_cast<PointerType>(Ty)) { 3247 AS = PtrType->getAddressSpace(); 3248 } 3249 Ty = cast<SequentialType>(Ty)->getElementType(); 3250 3251 // If this is a constant subscript, handle it quickly. 3252 const TargetLowering *TLI = TM.getTargetLowering(); 3253 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) { 3254 if (CI->isZero()) continue; 3255 uint64_t Offs = 3256 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue(); 3257 SDValue OffsVal; 3258 EVT PTy = TLI->getPointerTy(AS); 3259 unsigned PtrBits = PTy.getSizeInBits(); 3260 if (PtrBits < 64) 3261 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy, 3262 DAG.getConstant(Offs, MVT::i64)); 3263 else 3264 OffsVal = DAG.getConstant(Offs, PTy); 3265 3266 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N, 3267 OffsVal); 3268 continue; 3269 } 3270 3271 // N = N + Idx * ElementSize; 3272 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS), 3273 TD->getTypeAllocSize(Ty)); 3274 SDValue IdxN = getValue(Idx); 3275 3276 // If the index is smaller or larger than intptr_t, truncate or extend 3277 // it. 3278 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType()); 3279 3280 // If this is a multiply by a power of two, turn it into a shl 3281 // immediately. This is a very common case. 3282 if (ElementSize != 1) { 3283 if (ElementSize.isPowerOf2()) { 3284 unsigned Amt = ElementSize.logBase2(); 3285 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(), 3286 N.getValueType(), IdxN, 3287 DAG.getConstant(Amt, IdxN.getValueType())); 3288 } else { 3289 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType()); 3290 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(), 3291 N.getValueType(), IdxN, Scale); 3292 } 3293 } 3294 3295 N = DAG.getNode(ISD::ADD, getCurSDLoc(), 3296 N.getValueType(), N, IdxN); 3297 } 3298 } 3299 3300 setValue(&I, N); 3301 } 3302 3303 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) { 3304 // If this is a fixed sized alloca in the entry block of the function, 3305 // allocate it statically on the stack. 3306 if (FuncInfo.StaticAllocaMap.count(&I)) 3307 return; // getValue will auto-populate this. 3308 3309 Type *Ty = I.getAllocatedType(); 3310 const TargetLowering *TLI = TM.getTargetLowering(); 3311 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty); 3312 unsigned Align = 3313 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty), 3314 I.getAlignment()); 3315 3316 SDValue AllocSize = getValue(I.getArraySize()); 3317 3318 EVT IntPtr = TLI->getPointerTy(); 3319 if (AllocSize.getValueType() != IntPtr) 3320 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr); 3321 3322 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr, 3323 AllocSize, 3324 DAG.getConstant(TySize, IntPtr)); 3325 3326 // Handle alignment. If the requested alignment is less than or equal to 3327 // the stack alignment, ignore it. If the size is greater than or equal to 3328 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node. 3329 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment(); 3330 if (Align <= StackAlign) 3331 Align = 0; 3332 3333 // Round the size of the allocation up to the stack alignment size 3334 // by add SA-1 to the size. 3335 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(), 3336 AllocSize.getValueType(), AllocSize, 3337 DAG.getIntPtrConstant(StackAlign-1)); 3338 3339 // Mask out the low bits for alignment purposes. 3340 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(), 3341 AllocSize.getValueType(), AllocSize, 3342 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1))); 3343 3344 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) }; 3345 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other); 3346 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), 3347 VTs, Ops, 3); 3348 setValue(&I, DSA); 3349 DAG.setRoot(DSA.getValue(1)); 3350 3351 // Inform the Frame Information that we have just allocated a variable-sized 3352 // object. 3353 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1); 3354 } 3355 3356 void SelectionDAGBuilder::visitLoad(const LoadInst &I) { 3357 if (I.isAtomic()) 3358 return visitAtomicLoad(I); 3359 3360 const Value *SV = I.getOperand(0); 3361 SDValue Ptr = getValue(SV); 3362 3363 Type *Ty = I.getType(); 3364 3365 bool isVolatile = I.isVolatile(); 3366 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 3367 bool isInvariant = I.getMetadata("invariant.load") != 0; 3368 unsigned Alignment = I.getAlignment(); 3369 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa); 3370 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range); 3371 3372 SmallVector<EVT, 4> ValueVTs; 3373 SmallVector<uint64_t, 4> Offsets; 3374 ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets); 3375 unsigned NumValues = ValueVTs.size(); 3376 if (NumValues == 0) 3377 return; 3378 3379 SDValue Root; 3380 bool ConstantMemory = false; 3381 if (I.isVolatile() || NumValues > MaxParallelChains) 3382 // Serialize volatile loads with other side effects. 3383 Root = getRoot(); 3384 else if (AA->pointsToConstantMemory( 3385 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) { 3386 // Do not serialize (non-volatile) loads of constant memory with anything. 3387 Root = DAG.getEntryNode(); 3388 ConstantMemory = true; 3389 } else { 3390 // Do not serialize non-volatile loads against each other. 3391 Root = DAG.getRoot(); 3392 } 3393 3394 SmallVector<SDValue, 4> Values(NumValues); 3395 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains), 3396 NumValues)); 3397 EVT PtrVT = Ptr.getValueType(); 3398 unsigned ChainI = 0; 3399 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3400 // Serializing loads here may result in excessive register pressure, and 3401 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling 3402 // could recover a bit by hoisting nodes upward in the chain by recognizing 3403 // they are side-effect free or do not alias. The optimizer should really 3404 // avoid this case by converting large object/array copies to llvm.memcpy 3405 // (MaxParallelChains should always remain as failsafe). 3406 if (ChainI == MaxParallelChains) { 3407 assert(PendingLoads.empty() && "PendingLoads must be serialized first"); 3408 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 3409 MVT::Other, &Chains[0], ChainI); 3410 Root = Chain; 3411 ChainI = 0; 3412 } 3413 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(), 3414 PtrVT, Ptr, 3415 DAG.getConstant(Offsets[i], PtrVT)); 3416 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root, 3417 A, MachinePointerInfo(SV, Offsets[i]), isVolatile, 3418 isNonTemporal, isInvariant, Alignment, TBAAInfo, 3419 Ranges); 3420 3421 Values[i] = L; 3422 Chains[ChainI] = L.getValue(1); 3423 } 3424 3425 if (!ConstantMemory) { 3426 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 3427 MVT::Other, &Chains[0], ChainI); 3428 if (isVolatile) 3429 DAG.setRoot(Chain); 3430 else 3431 PendingLoads.push_back(Chain); 3432 } 3433 3434 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 3435 DAG.getVTList(&ValueVTs[0], NumValues), 3436 &Values[0], NumValues)); 3437 } 3438 3439 void SelectionDAGBuilder::visitStore(const StoreInst &I) { 3440 if (I.isAtomic()) 3441 return visitAtomicStore(I); 3442 3443 const Value *SrcV = I.getOperand(0); 3444 const Value *PtrV = I.getOperand(1); 3445 3446 SmallVector<EVT, 4> ValueVTs; 3447 SmallVector<uint64_t, 4> Offsets; 3448 ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets); 3449 unsigned NumValues = ValueVTs.size(); 3450 if (NumValues == 0) 3451 return; 3452 3453 // Get the lowered operands. Note that we do this after 3454 // checking if NumResults is zero, because with zero results 3455 // the operands won't have values in the map. 3456 SDValue Src = getValue(SrcV); 3457 SDValue Ptr = getValue(PtrV); 3458 3459 SDValue Root = getRoot(); 3460 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains), 3461 NumValues)); 3462 EVT PtrVT = Ptr.getValueType(); 3463 bool isVolatile = I.isVolatile(); 3464 bool isNonTemporal = I.getMetadata("nontemporal") != 0; 3465 unsigned Alignment = I.getAlignment(); 3466 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa); 3467 3468 unsigned ChainI = 0; 3469 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) { 3470 // See visitLoad comments. 3471 if (ChainI == MaxParallelChains) { 3472 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 3473 MVT::Other, &Chains[0], ChainI); 3474 Root = Chain; 3475 ChainI = 0; 3476 } 3477 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr, 3478 DAG.getConstant(Offsets[i], PtrVT)); 3479 SDValue St = DAG.getStore(Root, getCurSDLoc(), 3480 SDValue(Src.getNode(), Src.getResNo() + i), 3481 Add, MachinePointerInfo(PtrV, Offsets[i]), 3482 isVolatile, isNonTemporal, Alignment, TBAAInfo); 3483 Chains[ChainI] = St; 3484 } 3485 3486 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 3487 MVT::Other, &Chains[0], ChainI); 3488 DAG.setRoot(StoreNode); 3489 } 3490 3491 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order, 3492 SynchronizationScope Scope, 3493 bool Before, SDLoc dl, 3494 SelectionDAG &DAG, 3495 const TargetLowering &TLI) { 3496 // Fence, if necessary 3497 if (Before) { 3498 if (Order == AcquireRelease || Order == SequentiallyConsistent) 3499 Order = Release; 3500 else if (Order == Acquire || Order == Monotonic) 3501 return Chain; 3502 } else { 3503 if (Order == AcquireRelease) 3504 Order = Acquire; 3505 else if (Order == Release || Order == Monotonic) 3506 return Chain; 3507 } 3508 SDValue Ops[3]; 3509 Ops[0] = Chain; 3510 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy()); 3511 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy()); 3512 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3); 3513 } 3514 3515 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) { 3516 SDLoc dl = getCurSDLoc(); 3517 AtomicOrdering Order = I.getOrdering(); 3518 SynchronizationScope Scope = I.getSynchScope(); 3519 3520 SDValue InChain = getRoot(); 3521 3522 const TargetLowering *TLI = TM.getTargetLowering(); 3523 if (TLI->getInsertFencesForAtomic()) 3524 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl, 3525 DAG, *TLI); 3526 3527 SDValue L = 3528 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, 3529 getValue(I.getCompareOperand()).getSimpleValueType(), 3530 InChain, 3531 getValue(I.getPointerOperand()), 3532 getValue(I.getCompareOperand()), 3533 getValue(I.getNewValOperand()), 3534 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */, 3535 TLI->getInsertFencesForAtomic() ? Monotonic : Order, 3536 Scope); 3537 3538 SDValue OutChain = L.getValue(1); 3539 3540 if (TLI->getInsertFencesForAtomic()) 3541 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl, 3542 DAG, *TLI); 3543 3544 setValue(&I, L); 3545 DAG.setRoot(OutChain); 3546 } 3547 3548 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) { 3549 SDLoc dl = getCurSDLoc(); 3550 ISD::NodeType NT; 3551 switch (I.getOperation()) { 3552 default: llvm_unreachable("Unknown atomicrmw operation"); 3553 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break; 3554 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break; 3555 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break; 3556 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break; 3557 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break; 3558 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break; 3559 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break; 3560 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break; 3561 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break; 3562 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break; 3563 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break; 3564 } 3565 AtomicOrdering Order = I.getOrdering(); 3566 SynchronizationScope Scope = I.getSynchScope(); 3567 3568 SDValue InChain = getRoot(); 3569 3570 const TargetLowering *TLI = TM.getTargetLowering(); 3571 if (TLI->getInsertFencesForAtomic()) 3572 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl, 3573 DAG, *TLI); 3574 3575 SDValue L = 3576 DAG.getAtomic(NT, dl, 3577 getValue(I.getValOperand()).getSimpleValueType(), 3578 InChain, 3579 getValue(I.getPointerOperand()), 3580 getValue(I.getValOperand()), 3581 I.getPointerOperand(), 0 /* Alignment */, 3582 TLI->getInsertFencesForAtomic() ? Monotonic : Order, 3583 Scope); 3584 3585 SDValue OutChain = L.getValue(1); 3586 3587 if (TLI->getInsertFencesForAtomic()) 3588 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl, 3589 DAG, *TLI); 3590 3591 setValue(&I, L); 3592 DAG.setRoot(OutChain); 3593 } 3594 3595 void SelectionDAGBuilder::visitFence(const FenceInst &I) { 3596 SDLoc dl = getCurSDLoc(); 3597 const TargetLowering *TLI = TM.getTargetLowering(); 3598 SDValue Ops[3]; 3599 Ops[0] = getRoot(); 3600 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy()); 3601 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy()); 3602 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3)); 3603 } 3604 3605 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) { 3606 SDLoc dl = getCurSDLoc(); 3607 AtomicOrdering Order = I.getOrdering(); 3608 SynchronizationScope Scope = I.getSynchScope(); 3609 3610 SDValue InChain = getRoot(); 3611 3612 const TargetLowering *TLI = TM.getTargetLowering(); 3613 EVT VT = TLI->getValueType(I.getType()); 3614 3615 if (I.getAlignment() < VT.getSizeInBits() / 8) 3616 report_fatal_error("Cannot generate unaligned atomic load"); 3617 3618 SDValue L = 3619 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain, 3620 getValue(I.getPointerOperand()), 3621 I.getPointerOperand(), I.getAlignment(), 3622 TLI->getInsertFencesForAtomic() ? Monotonic : Order, 3623 Scope); 3624 3625 SDValue OutChain = L.getValue(1); 3626 3627 if (TLI->getInsertFencesForAtomic()) 3628 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl, 3629 DAG, *TLI); 3630 3631 setValue(&I, L); 3632 DAG.setRoot(OutChain); 3633 } 3634 3635 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) { 3636 SDLoc dl = getCurSDLoc(); 3637 3638 AtomicOrdering Order = I.getOrdering(); 3639 SynchronizationScope Scope = I.getSynchScope(); 3640 3641 SDValue InChain = getRoot(); 3642 3643 const TargetLowering *TLI = TM.getTargetLowering(); 3644 EVT VT = TLI->getValueType(I.getValueOperand()->getType()); 3645 3646 if (I.getAlignment() < VT.getSizeInBits() / 8) 3647 report_fatal_error("Cannot generate unaligned atomic store"); 3648 3649 if (TLI->getInsertFencesForAtomic()) 3650 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl, 3651 DAG, *TLI); 3652 3653 SDValue OutChain = 3654 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, 3655 InChain, 3656 getValue(I.getPointerOperand()), 3657 getValue(I.getValueOperand()), 3658 I.getPointerOperand(), I.getAlignment(), 3659 TLI->getInsertFencesForAtomic() ? Monotonic : Order, 3660 Scope); 3661 3662 if (TLI->getInsertFencesForAtomic()) 3663 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl, 3664 DAG, *TLI); 3665 3666 DAG.setRoot(OutChain); 3667 } 3668 3669 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC 3670 /// node. 3671 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I, 3672 unsigned Intrinsic) { 3673 bool HasChain = !I.doesNotAccessMemory(); 3674 bool OnlyLoad = HasChain && I.onlyReadsMemory(); 3675 3676 // Build the operand list. 3677 SmallVector<SDValue, 8> Ops; 3678 if (HasChain) { // If this intrinsic has side-effects, chainify it. 3679 if (OnlyLoad) { 3680 // We don't need to serialize loads against other loads. 3681 Ops.push_back(DAG.getRoot()); 3682 } else { 3683 Ops.push_back(getRoot()); 3684 } 3685 } 3686 3687 // Info is set by getTgtMemInstrinsic 3688 TargetLowering::IntrinsicInfo Info; 3689 const TargetLowering *TLI = TM.getTargetLowering(); 3690 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic); 3691 3692 // Add the intrinsic ID as an integer operand if it's not a target intrinsic. 3693 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID || 3694 Info.opc == ISD::INTRINSIC_W_CHAIN) 3695 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy())); 3696 3697 // Add all operands of the call to the operand list. 3698 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 3699 SDValue Op = getValue(I.getArgOperand(i)); 3700 Ops.push_back(Op); 3701 } 3702 3703 SmallVector<EVT, 4> ValueVTs; 3704 ComputeValueVTs(*TLI, I.getType(), ValueVTs); 3705 3706 if (HasChain) 3707 ValueVTs.push_back(MVT::Other); 3708 3709 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size()); 3710 3711 // Create the node. 3712 SDValue Result; 3713 if (IsTgtIntrinsic) { 3714 // This is target intrinsic that touches memory 3715 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), 3716 VTs, &Ops[0], Ops.size(), 3717 Info.memVT, 3718 MachinePointerInfo(Info.ptrVal, Info.offset), 3719 Info.align, Info.vol, 3720 Info.readMem, Info.writeMem); 3721 } else if (!HasChain) { 3722 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), 3723 VTs, &Ops[0], Ops.size()); 3724 } else if (!I.getType()->isVoidTy()) { 3725 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), 3726 VTs, &Ops[0], Ops.size()); 3727 } else { 3728 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), 3729 VTs, &Ops[0], Ops.size()); 3730 } 3731 3732 if (HasChain) { 3733 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1); 3734 if (OnlyLoad) 3735 PendingLoads.push_back(Chain); 3736 else 3737 DAG.setRoot(Chain); 3738 } 3739 3740 if (!I.getType()->isVoidTy()) { 3741 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) { 3742 EVT VT = TLI->getValueType(PTy); 3743 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result); 3744 } 3745 3746 setValue(&I, Result); 3747 } 3748 } 3749 3750 /// GetSignificand - Get the significand and build it into a floating-point 3751 /// number with exponent of 1: 3752 /// 3753 /// Op = (Op & 0x007fffff) | 0x3f800000; 3754 /// 3755 /// where Op is the hexadecimal representation of floating point value. 3756 static SDValue 3757 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) { 3758 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3759 DAG.getConstant(0x007fffff, MVT::i32)); 3760 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1, 3761 DAG.getConstant(0x3f800000, MVT::i32)); 3762 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2); 3763 } 3764 3765 /// GetExponent - Get the exponent: 3766 /// 3767 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127); 3768 /// 3769 /// where Op is the hexadecimal representation of floating point value. 3770 static SDValue 3771 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI, 3772 SDLoc dl) { 3773 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op, 3774 DAG.getConstant(0x7f800000, MVT::i32)); 3775 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0, 3776 DAG.getConstant(23, TLI.getPointerTy())); 3777 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1, 3778 DAG.getConstant(127, MVT::i32)); 3779 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2); 3780 } 3781 3782 /// getF32Constant - Get 32-bit floating point constant. 3783 static SDValue 3784 getF32Constant(SelectionDAG &DAG, unsigned Flt) { 3785 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), 3786 MVT::f32); 3787 } 3788 3789 /// expandExp - Lower an exp intrinsic. Handles the special sequences for 3790 /// limited-precision mode. 3791 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3792 const TargetLowering &TLI) { 3793 if (Op.getValueType() == MVT::f32 && 3794 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3795 3796 // Put the exponent in the right bit position for later addition to the 3797 // final result: 3798 // 3799 // #define LOG2OFe 1.4426950f 3800 // IntegerPartOfX = ((int32_t)(X * LOG2OFe)); 3801 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op, 3802 getF32Constant(DAG, 0x3fb8aa3b)); 3803 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 3804 3805 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX; 3806 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 3807 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 3808 3809 // IntegerPartOfX <<= 23; 3810 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 3811 DAG.getConstant(23, TLI.getPointerTy())); 3812 3813 SDValue TwoToFracPartOfX; 3814 if (LimitFloatPrecision <= 6) { 3815 // For floating-point precision of 6: 3816 // 3817 // TwoToFractionalPartOfX = 3818 // 0.997535578f + 3819 // (0.735607626f + 0.252464424f * x) * x; 3820 // 3821 // error 0.0144103317, which is 6 bits 3822 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3823 getF32Constant(DAG, 0x3e814304)); 3824 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3825 getF32Constant(DAG, 0x3f3c50c8)); 3826 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3827 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3828 getF32Constant(DAG, 0x3f7f5e7e)); 3829 } else if (LimitFloatPrecision <= 12) { 3830 // For floating-point precision of 12: 3831 // 3832 // TwoToFractionalPartOfX = 3833 // 0.999892986f + 3834 // (0.696457318f + 3835 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 3836 // 3837 // 0.000107046256 error, which is 13 to 14 bits 3838 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3839 getF32Constant(DAG, 0x3da235e3)); 3840 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3841 getF32Constant(DAG, 0x3e65b8f3)); 3842 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3843 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3844 getF32Constant(DAG, 0x3f324b07)); 3845 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3846 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3847 getF32Constant(DAG, 0x3f7ff8fd)); 3848 } else { // LimitFloatPrecision <= 18 3849 // For floating-point precision of 18: 3850 // 3851 // TwoToFractionalPartOfX = 3852 // 0.999999982f + 3853 // (0.693148872f + 3854 // (0.240227044f + 3855 // (0.554906021e-1f + 3856 // (0.961591928e-2f + 3857 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 3858 // 3859 // error 2.47208000*10^(-7), which is better than 18 bits 3860 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3861 getF32Constant(DAG, 0x3924b03e)); 3862 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 3863 getF32Constant(DAG, 0x3ab24b87)); 3864 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3865 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3866 getF32Constant(DAG, 0x3c1d8c17)); 3867 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3868 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 3869 getF32Constant(DAG, 0x3d634a1d)); 3870 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3871 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3872 getF32Constant(DAG, 0x3e75fe14)); 3873 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3874 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 3875 getF32Constant(DAG, 0x3f317234)); 3876 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 3877 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 3878 getF32Constant(DAG, 0x3f800000)); 3879 } 3880 3881 // Add the exponent into the result in integer domain. 3882 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX); 3883 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 3884 DAG.getNode(ISD::ADD, dl, MVT::i32, 3885 t13, IntegerPartOfX)); 3886 } 3887 3888 // No special expansion. 3889 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op); 3890 } 3891 3892 /// expandLog - Lower a log intrinsic. Handles the special sequences for 3893 /// limited-precision mode. 3894 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3895 const TargetLowering &TLI) { 3896 if (Op.getValueType() == MVT::f32 && 3897 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3898 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3899 3900 // Scale the exponent by log(2) [0.69314718f]. 3901 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 3902 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 3903 getF32Constant(DAG, 0x3f317218)); 3904 3905 // Get the significand and build it into a floating-point number with 3906 // exponent of 1. 3907 SDValue X = GetSignificand(DAG, Op1, dl); 3908 3909 SDValue LogOfMantissa; 3910 if (LimitFloatPrecision <= 6) { 3911 // For floating-point precision of 6: 3912 // 3913 // LogofMantissa = 3914 // -1.1609546f + 3915 // (1.4034025f - 0.23903021f * x) * x; 3916 // 3917 // error 0.0034276066, which is better than 8 bits 3918 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3919 getF32Constant(DAG, 0xbe74c456)); 3920 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3921 getF32Constant(DAG, 0x3fb3a2b1)); 3922 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3923 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3924 getF32Constant(DAG, 0x3f949a29)); 3925 } else if (LimitFloatPrecision <= 12) { 3926 // For floating-point precision of 12: 3927 // 3928 // LogOfMantissa = 3929 // -1.7417939f + 3930 // (2.8212026f + 3931 // (-1.4699568f + 3932 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x; 3933 // 3934 // error 0.000061011436, which is 14 bits 3935 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3936 getF32Constant(DAG, 0xbd67b6d6)); 3937 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3938 getF32Constant(DAG, 0x3ee4f4b8)); 3939 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3940 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3941 getF32Constant(DAG, 0x3fbc278b)); 3942 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3943 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3944 getF32Constant(DAG, 0x40348e95)); 3945 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3946 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3947 getF32Constant(DAG, 0x3fdef31a)); 3948 } else { // LimitFloatPrecision <= 18 3949 // For floating-point precision of 18: 3950 // 3951 // LogOfMantissa = 3952 // -2.1072184f + 3953 // (4.2372794f + 3954 // (-3.7029485f + 3955 // (2.2781945f + 3956 // (-0.87823314f + 3957 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x; 3958 // 3959 // error 0.0000023660568, which is better than 18 bits 3960 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 3961 getF32Constant(DAG, 0xbc91e5ac)); 3962 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 3963 getF32Constant(DAG, 0x3e4350aa)); 3964 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 3965 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 3966 getF32Constant(DAG, 0x3f60d3e3)); 3967 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 3968 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 3969 getF32Constant(DAG, 0x4011cdf0)); 3970 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 3971 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 3972 getF32Constant(DAG, 0x406cfd1c)); 3973 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 3974 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 3975 getF32Constant(DAG, 0x408797cb)); 3976 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 3977 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 3978 getF32Constant(DAG, 0x4006dcab)); 3979 } 3980 3981 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa); 3982 } 3983 3984 // No special expansion. 3985 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op); 3986 } 3987 3988 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for 3989 /// limited-precision mode. 3990 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG, 3991 const TargetLowering &TLI) { 3992 if (Op.getValueType() == MVT::f32 && 3993 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 3994 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 3995 3996 // Get the exponent. 3997 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl); 3998 3999 // Get the significand and build it into a floating-point number with 4000 // exponent of 1. 4001 SDValue X = GetSignificand(DAG, Op1, dl); 4002 4003 // Different possible minimax approximations of significand in 4004 // floating-point for various degrees of accuracy over [1,2]. 4005 SDValue Log2ofMantissa; 4006 if (LimitFloatPrecision <= 6) { 4007 // For floating-point precision of 6: 4008 // 4009 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x; 4010 // 4011 // error 0.0049451742, which is more than 7 bits 4012 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4013 getF32Constant(DAG, 0xbeb08fe0)); 4014 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4015 getF32Constant(DAG, 0x40019463)); 4016 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4017 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4018 getF32Constant(DAG, 0x3fd6633d)); 4019 } else if (LimitFloatPrecision <= 12) { 4020 // For floating-point precision of 12: 4021 // 4022 // Log2ofMantissa = 4023 // -2.51285454f + 4024 // (4.07009056f + 4025 // (-2.12067489f + 4026 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x; 4027 // 4028 // error 0.0000876136000, which is better than 13 bits 4029 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4030 getF32Constant(DAG, 0xbda7262e)); 4031 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4032 getF32Constant(DAG, 0x3f25280b)); 4033 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4034 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4035 getF32Constant(DAG, 0x4007b923)); 4036 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4037 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4038 getF32Constant(DAG, 0x40823e2f)); 4039 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4040 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4041 getF32Constant(DAG, 0x4020d29c)); 4042 } else { // LimitFloatPrecision <= 18 4043 // For floating-point precision of 18: 4044 // 4045 // Log2ofMantissa = 4046 // -3.0400495f + 4047 // (6.1129976f + 4048 // (-5.3420409f + 4049 // (3.2865683f + 4050 // (-1.2669343f + 4051 // (0.27515199f - 4052 // 0.25691327e-1f * x) * x) * x) * x) * x) * x; 4053 // 4054 // error 0.0000018516, which is better than 18 bits 4055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4056 getF32Constant(DAG, 0xbcd2769e)); 4057 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4058 getF32Constant(DAG, 0x3e8ce0b9)); 4059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4060 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4061 getF32Constant(DAG, 0x3fa22ae7)); 4062 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4063 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4064 getF32Constant(DAG, 0x40525723)); 4065 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4066 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6, 4067 getF32Constant(DAG, 0x40aaf200)); 4068 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4069 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4070 getF32Constant(DAG, 0x40c39dad)); 4071 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4072 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10, 4073 getF32Constant(DAG, 0x4042902c)); 4074 } 4075 4076 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa); 4077 } 4078 4079 // No special expansion. 4080 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op); 4081 } 4082 4083 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for 4084 /// limited-precision mode. 4085 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG, 4086 const TargetLowering &TLI) { 4087 if (Op.getValueType() == MVT::f32 && 4088 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4089 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op); 4090 4091 // Scale the exponent by log10(2) [0.30102999f]. 4092 SDValue Exp = GetExponent(DAG, Op1, TLI, dl); 4093 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp, 4094 getF32Constant(DAG, 0x3e9a209a)); 4095 4096 // Get the significand and build it into a floating-point number with 4097 // exponent of 1. 4098 SDValue X = GetSignificand(DAG, Op1, dl); 4099 4100 SDValue Log10ofMantissa; 4101 if (LimitFloatPrecision <= 6) { 4102 // For floating-point precision of 6: 4103 // 4104 // Log10ofMantissa = 4105 // -0.50419619f + 4106 // (0.60948995f - 0.10380950f * x) * x; 4107 // 4108 // error 0.0014886165, which is 6 bits 4109 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4110 getF32Constant(DAG, 0xbdd49a13)); 4111 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0, 4112 getF32Constant(DAG, 0x3f1c0789)); 4113 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4114 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2, 4115 getF32Constant(DAG, 0x3f011300)); 4116 } else if (LimitFloatPrecision <= 12) { 4117 // For floating-point precision of 12: 4118 // 4119 // Log10ofMantissa = 4120 // -0.64831180f + 4121 // (0.91751397f + 4122 // (-0.31664806f + 0.47637168e-1f * x) * x) * x; 4123 // 4124 // error 0.00019228036, which is better than 12 bits 4125 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4126 getF32Constant(DAG, 0x3d431f31)); 4127 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4128 getF32Constant(DAG, 0x3ea21fb2)); 4129 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4130 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4131 getF32Constant(DAG, 0x3f6ae232)); 4132 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4133 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4134 getF32Constant(DAG, 0x3f25f7c3)); 4135 } else { // LimitFloatPrecision <= 18 4136 // For floating-point precision of 18: 4137 // 4138 // Log10ofMantissa = 4139 // -0.84299375f + 4140 // (1.5327582f + 4141 // (-1.0688956f + 4142 // (0.49102474f + 4143 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x; 4144 // 4145 // error 0.0000037995730, which is better than 18 bits 4146 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4147 getF32Constant(DAG, 0x3c5d51ce)); 4148 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, 4149 getF32Constant(DAG, 0x3e00685a)); 4150 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X); 4151 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4152 getF32Constant(DAG, 0x3efb6798)); 4153 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4154 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4, 4155 getF32Constant(DAG, 0x3f88d192)); 4156 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4157 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4158 getF32Constant(DAG, 0x3fc4316c)); 4159 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4160 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8, 4161 getF32Constant(DAG, 0x3f57ce70)); 4162 } 4163 4164 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa); 4165 } 4166 4167 // No special expansion. 4168 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op); 4169 } 4170 4171 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for 4172 /// limited-precision mode. 4173 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG, 4174 const TargetLowering &TLI) { 4175 if (Op.getValueType() == MVT::f32 && 4176 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4177 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op); 4178 4179 // FractionalPartOfX = x - (float)IntegerPartOfX; 4180 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4181 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1); 4182 4183 // IntegerPartOfX <<= 23; 4184 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4185 DAG.getConstant(23, TLI.getPointerTy())); 4186 4187 SDValue TwoToFractionalPartOfX; 4188 if (LimitFloatPrecision <= 6) { 4189 // For floating-point precision of 6: 4190 // 4191 // TwoToFractionalPartOfX = 4192 // 0.997535578f + 4193 // (0.735607626f + 0.252464424f * x) * x; 4194 // 4195 // error 0.0144103317, which is 6 bits 4196 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4197 getF32Constant(DAG, 0x3e814304)); 4198 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4199 getF32Constant(DAG, 0x3f3c50c8)); 4200 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4201 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4202 getF32Constant(DAG, 0x3f7f5e7e)); 4203 } else if (LimitFloatPrecision <= 12) { 4204 // For floating-point precision of 12: 4205 // 4206 // TwoToFractionalPartOfX = 4207 // 0.999892986f + 4208 // (0.696457318f + 4209 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4210 // 4211 // error 0.000107046256, which is 13 to 14 bits 4212 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4213 getF32Constant(DAG, 0x3da235e3)); 4214 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4215 getF32Constant(DAG, 0x3e65b8f3)); 4216 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4217 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4218 getF32Constant(DAG, 0x3f324b07)); 4219 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4220 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4221 getF32Constant(DAG, 0x3f7ff8fd)); 4222 } else { // LimitFloatPrecision <= 18 4223 // For floating-point precision of 18: 4224 // 4225 // TwoToFractionalPartOfX = 4226 // 0.999999982f + 4227 // (0.693148872f + 4228 // (0.240227044f + 4229 // (0.554906021e-1f + 4230 // (0.961591928e-2f + 4231 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4232 // error 2.47208000*10^(-7), which is better than 18 bits 4233 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4234 getF32Constant(DAG, 0x3924b03e)); 4235 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4236 getF32Constant(DAG, 0x3ab24b87)); 4237 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4238 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4239 getF32Constant(DAG, 0x3c1d8c17)); 4240 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4241 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4242 getF32Constant(DAG, 0x3d634a1d)); 4243 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4244 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4245 getF32Constant(DAG, 0x3e75fe14)); 4246 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4247 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4248 getF32Constant(DAG, 0x3f317234)); 4249 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4250 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4251 getF32Constant(DAG, 0x3f800000)); 4252 } 4253 4254 // Add the exponent into the result in integer domain. 4255 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, 4256 TwoToFractionalPartOfX); 4257 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4258 DAG.getNode(ISD::ADD, dl, MVT::i32, 4259 t13, IntegerPartOfX)); 4260 } 4261 4262 // No special expansion. 4263 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op); 4264 } 4265 4266 /// visitPow - Lower a pow intrinsic. Handles the special sequences for 4267 /// limited-precision mode with x == 10.0f. 4268 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS, 4269 SelectionDAG &DAG, const TargetLowering &TLI) { 4270 bool IsExp10 = false; 4271 if (LHS.getValueType() == MVT::f32 && LHS.getValueType() == MVT::f32 && 4272 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) { 4273 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) { 4274 APFloat Ten(10.0f); 4275 IsExp10 = LHSC->isExactlyValue(Ten); 4276 } 4277 } 4278 4279 if (IsExp10) { 4280 // Put the exponent in the right bit position for later addition to the 4281 // final result: 4282 // 4283 // #define LOG2OF10 3.3219281f 4284 // IntegerPartOfX = (int32_t)(x * LOG2OF10); 4285 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS, 4286 getF32Constant(DAG, 0x40549a78)); 4287 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0); 4288 4289 // FractionalPartOfX = x - (float)IntegerPartOfX; 4290 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX); 4291 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1); 4292 4293 // IntegerPartOfX <<= 23; 4294 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX, 4295 DAG.getConstant(23, TLI.getPointerTy())); 4296 4297 SDValue TwoToFractionalPartOfX; 4298 if (LimitFloatPrecision <= 6) { 4299 // For floating-point precision of 6: 4300 // 4301 // twoToFractionalPartOfX = 4302 // 0.997535578f + 4303 // (0.735607626f + 0.252464424f * x) * x; 4304 // 4305 // error 0.0144103317, which is 6 bits 4306 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4307 getF32Constant(DAG, 0x3e814304)); 4308 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4309 getF32Constant(DAG, 0x3f3c50c8)); 4310 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4311 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4312 getF32Constant(DAG, 0x3f7f5e7e)); 4313 } else if (LimitFloatPrecision <= 12) { 4314 // For floating-point precision of 12: 4315 // 4316 // TwoToFractionalPartOfX = 4317 // 0.999892986f + 4318 // (0.696457318f + 4319 // (0.224338339f + 0.792043434e-1f * x) * x) * x; 4320 // 4321 // error 0.000107046256, which is 13 to 14 bits 4322 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4323 getF32Constant(DAG, 0x3da235e3)); 4324 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4325 getF32Constant(DAG, 0x3e65b8f3)); 4326 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4327 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4328 getF32Constant(DAG, 0x3f324b07)); 4329 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4330 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4331 getF32Constant(DAG, 0x3f7ff8fd)); 4332 } else { // LimitFloatPrecision <= 18 4333 // For floating-point precision of 18: 4334 // 4335 // TwoToFractionalPartOfX = 4336 // 0.999999982f + 4337 // (0.693148872f + 4338 // (0.240227044f + 4339 // (0.554906021e-1f + 4340 // (0.961591928e-2f + 4341 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x; 4342 // error 2.47208000*10^(-7), which is better than 18 bits 4343 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X, 4344 getF32Constant(DAG, 0x3924b03e)); 4345 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2, 4346 getF32Constant(DAG, 0x3ab24b87)); 4347 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X); 4348 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4, 4349 getF32Constant(DAG, 0x3c1d8c17)); 4350 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X); 4351 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6, 4352 getF32Constant(DAG, 0x3d634a1d)); 4353 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X); 4354 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8, 4355 getF32Constant(DAG, 0x3e75fe14)); 4356 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X); 4357 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10, 4358 getF32Constant(DAG, 0x3f317234)); 4359 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X); 4360 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12, 4361 getF32Constant(DAG, 0x3f800000)); 4362 } 4363 4364 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX); 4365 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, 4366 DAG.getNode(ISD::ADD, dl, MVT::i32, 4367 t13, IntegerPartOfX)); 4368 } 4369 4370 // No special expansion. 4371 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS); 4372 } 4373 4374 4375 /// ExpandPowI - Expand a llvm.powi intrinsic. 4376 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS, 4377 SelectionDAG &DAG) { 4378 // If RHS is a constant, we can expand this out to a multiplication tree, 4379 // otherwise we end up lowering to a call to __powidf2 (for example). When 4380 // optimizing for size, we only want to do this if the expansion would produce 4381 // a small number of multiplies, otherwise we do the full expansion. 4382 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) { 4383 // Get the exponent as a positive value. 4384 unsigned Val = RHSC->getSExtValue(); 4385 if ((int)Val < 0) Val = -Val; 4386 4387 // powi(x, 0) -> 1.0 4388 if (Val == 0) 4389 return DAG.getConstantFP(1.0, LHS.getValueType()); 4390 4391 const Function *F = DAG.getMachineFunction().getFunction(); 4392 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 4393 Attribute::OptimizeForSize) || 4394 // If optimizing for size, don't insert too many multiplies. This 4395 // inserts up to 5 multiplies. 4396 CountPopulation_32(Val)+Log2_32(Val) < 7) { 4397 // We use the simple binary decomposition method to generate the multiply 4398 // sequence. There are more optimal ways to do this (for example, 4399 // powi(x,15) generates one more multiply than it should), but this has 4400 // the benefit of being both really simple and much better than a libcall. 4401 SDValue Res; // Logically starts equal to 1.0 4402 SDValue CurSquare = LHS; 4403 while (Val) { 4404 if (Val & 1) { 4405 if (Res.getNode()) 4406 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare); 4407 else 4408 Res = CurSquare; // 1.0*CurSquare. 4409 } 4410 4411 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(), 4412 CurSquare, CurSquare); 4413 Val >>= 1; 4414 } 4415 4416 // If the original was negative, invert the result, producing 1/(x*x*x). 4417 if (RHSC->getSExtValue() < 0) 4418 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(), 4419 DAG.getConstantFP(1.0, LHS.getValueType()), Res); 4420 return Res; 4421 } 4422 } 4423 4424 // Otherwise, expand to a libcall. 4425 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS); 4426 } 4427 4428 // getTruncatedArgReg - Find underlying register used for an truncated 4429 // argument. 4430 static unsigned getTruncatedArgReg(const SDValue &N) { 4431 if (N.getOpcode() != ISD::TRUNCATE) 4432 return 0; 4433 4434 const SDValue &Ext = N.getOperand(0); 4435 if (Ext.getOpcode() == ISD::AssertZext || 4436 Ext.getOpcode() == ISD::AssertSext) { 4437 const SDValue &CFR = Ext.getOperand(0); 4438 if (CFR.getOpcode() == ISD::CopyFromReg) 4439 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg(); 4440 if (CFR.getOpcode() == ISD::TRUNCATE) 4441 return getTruncatedArgReg(CFR); 4442 } 4443 return 0; 4444 } 4445 4446 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function 4447 /// argument, create the corresponding DBG_VALUE machine instruction for it now. 4448 /// At the end of instruction selection, they will be inserted to the entry BB. 4449 bool 4450 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable, 4451 int64_t Offset, 4452 const SDValue &N) { 4453 const Argument *Arg = dyn_cast<Argument>(V); 4454 if (!Arg) 4455 return false; 4456 4457 MachineFunction &MF = DAG.getMachineFunction(); 4458 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo(); 4459 4460 // Ignore inlined function arguments here. 4461 DIVariable DV(Variable); 4462 if (DV.isInlinedFnArgument(MF.getFunction())) 4463 return false; 4464 4465 Optional<MachineOperand> Op; 4466 // Some arguments' frame index is recorded during argument lowering. 4467 if (int FI = FuncInfo.getArgumentFrameIndex(Arg)) 4468 Op = MachineOperand::CreateFI(FI); 4469 4470 if (!Op && N.getNode()) { 4471 unsigned Reg; 4472 if (N.getOpcode() == ISD::CopyFromReg) 4473 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg(); 4474 else 4475 Reg = getTruncatedArgReg(N); 4476 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) { 4477 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 4478 unsigned PR = RegInfo.getLiveInPhysReg(Reg); 4479 if (PR) 4480 Reg = PR; 4481 } 4482 if (Reg) 4483 Op = MachineOperand::CreateReg(Reg, false); 4484 } 4485 4486 if (!Op) { 4487 // Check if ValueMap has reg number. 4488 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V); 4489 if (VMI != FuncInfo.ValueMap.end()) 4490 Op = MachineOperand::CreateReg(VMI->second, false); 4491 } 4492 4493 if (!Op && N.getNode()) 4494 // Check if frame index is available. 4495 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode())) 4496 if (FrameIndexSDNode *FINode = 4497 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 4498 Op = MachineOperand::CreateFI(FINode->getIndex()); 4499 4500 if (!Op) 4501 return false; 4502 4503 // FIXME: This does not handle register-indirect values at offset 0. 4504 bool IsIndirect = Offset != 0; 4505 if (Op->isReg()) 4506 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(), 4507 TII->get(TargetOpcode::DBG_VALUE), 4508 IsIndirect, 4509 Op->getReg(), Offset, Variable)); 4510 else 4511 FuncInfo.ArgDbgValues.push_back( 4512 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE)) 4513 .addOperand(*Op).addImm(Offset).addMetadata(Variable)); 4514 4515 return true; 4516 } 4517 4518 // VisualStudio defines setjmp as _setjmp 4519 #if defined(_MSC_VER) && defined(setjmp) && \ 4520 !defined(setjmp_undefined_for_msvc) 4521 # pragma push_macro("setjmp") 4522 # undef setjmp 4523 # define setjmp_undefined_for_msvc 4524 #endif 4525 4526 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If 4527 /// we want to emit this as a call to a named external function, return the name 4528 /// otherwise lower it and return null. 4529 const char * 4530 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) { 4531 const TargetLowering *TLI = TM.getTargetLowering(); 4532 SDLoc sdl = getCurSDLoc(); 4533 DebugLoc dl = getCurDebugLoc(); 4534 SDValue Res; 4535 4536 switch (Intrinsic) { 4537 default: 4538 // By default, turn this into a target intrinsic node. 4539 visitTargetIntrinsic(I, Intrinsic); 4540 return 0; 4541 case Intrinsic::vastart: visitVAStart(I); return 0; 4542 case Intrinsic::vaend: visitVAEnd(I); return 0; 4543 case Intrinsic::vacopy: visitVACopy(I); return 0; 4544 case Intrinsic::returnaddress: 4545 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(), 4546 getValue(I.getArgOperand(0)))); 4547 return 0; 4548 case Intrinsic::frameaddress: 4549 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(), 4550 getValue(I.getArgOperand(0)))); 4551 return 0; 4552 case Intrinsic::setjmp: 4553 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()]; 4554 case Intrinsic::longjmp: 4555 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()]; 4556 case Intrinsic::memcpy: { 4557 // Assert for address < 256 since we support only user defined address 4558 // spaces. 4559 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4560 < 256 && 4561 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4562 < 256 && 4563 "Unknown address space"); 4564 SDValue Op1 = getValue(I.getArgOperand(0)); 4565 SDValue Op2 = getValue(I.getArgOperand(1)); 4566 SDValue Op3 = getValue(I.getArgOperand(2)); 4567 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4568 if (!Align) 4569 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment. 4570 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4571 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false, 4572 MachinePointerInfo(I.getArgOperand(0)), 4573 MachinePointerInfo(I.getArgOperand(1)))); 4574 return 0; 4575 } 4576 case Intrinsic::memset: { 4577 // Assert for address < 256 since we support only user defined address 4578 // spaces. 4579 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4580 < 256 && 4581 "Unknown address space"); 4582 SDValue Op1 = getValue(I.getArgOperand(0)); 4583 SDValue Op2 = getValue(I.getArgOperand(1)); 4584 SDValue Op3 = getValue(I.getArgOperand(2)); 4585 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4586 if (!Align) 4587 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment. 4588 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4589 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4590 MachinePointerInfo(I.getArgOperand(0)))); 4591 return 0; 4592 } 4593 case Intrinsic::memmove: { 4594 // Assert for address < 256 since we support only user defined address 4595 // spaces. 4596 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace() 4597 < 256 && 4598 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace() 4599 < 256 && 4600 "Unknown address space"); 4601 SDValue Op1 = getValue(I.getArgOperand(0)); 4602 SDValue Op2 = getValue(I.getArgOperand(1)); 4603 SDValue Op3 = getValue(I.getArgOperand(2)); 4604 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue(); 4605 if (!Align) 4606 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment. 4607 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue(); 4608 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, 4609 MachinePointerInfo(I.getArgOperand(0)), 4610 MachinePointerInfo(I.getArgOperand(1)))); 4611 return 0; 4612 } 4613 case Intrinsic::dbg_declare: { 4614 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I); 4615 MDNode *Variable = DI.getVariable(); 4616 const Value *Address = DI.getAddress(); 4617 DIVariable DIVar(Variable); 4618 assert((!DIVar || DIVar.isVariable()) && 4619 "Variable in DbgDeclareInst should be either null or a DIVariable."); 4620 if (!Address || !DIVar) { 4621 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4622 return 0; 4623 } 4624 4625 // Check if address has undef value. 4626 if (isa<UndefValue>(Address) || 4627 (Address->use_empty() && !isa<Argument>(Address))) { 4628 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4629 return 0; 4630 } 4631 4632 SDValue &N = NodeMap[Address]; 4633 if (!N.getNode() && isa<Argument>(Address)) 4634 // Check unused arguments map. 4635 N = UnusedArgNodeMap[Address]; 4636 SDDbgValue *SDV; 4637 if (N.getNode()) { 4638 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address)) 4639 Address = BCI->getOperand(0); 4640 // Parameters are handled specially. 4641 bool isParameter = 4642 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable || 4643 isa<Argument>(Address)); 4644 4645 const AllocaInst *AI = dyn_cast<AllocaInst>(Address); 4646 4647 if (isParameter && !AI) { 4648 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode()); 4649 if (FINode) 4650 // Byval parameter. We have a frame index at this point. 4651 SDV = DAG.getDbgValue(Variable, FINode->getIndex(), 4652 0, dl, SDNodeOrder); 4653 else { 4654 // Address is an argument, so try to emit its dbg value using 4655 // virtual register info from the FuncInfo.ValueMap. 4656 EmitFuncArgumentDbgValue(Address, Variable, 0, N); 4657 return 0; 4658 } 4659 } else if (AI) 4660 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(), 4661 0, dl, SDNodeOrder); 4662 else { 4663 // Can't do anything with other non-AI cases yet. 4664 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4665 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t"); 4666 DEBUG(Address->dump()); 4667 return 0; 4668 } 4669 DAG.AddDbgValue(SDV, N.getNode(), isParameter); 4670 } else { 4671 // If Address is an argument then try to emit its dbg value using 4672 // virtual register info from the FuncInfo.ValueMap. 4673 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) { 4674 // If variable is pinned by a alloca in dominating bb then 4675 // use StaticAllocaMap. 4676 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) { 4677 if (AI->getParent() != DI.getParent()) { 4678 DenseMap<const AllocaInst*, int>::iterator SI = 4679 FuncInfo.StaticAllocaMap.find(AI); 4680 if (SI != FuncInfo.StaticAllocaMap.end()) { 4681 SDV = DAG.getDbgValue(Variable, SI->second, 4682 0, dl, SDNodeOrder); 4683 DAG.AddDbgValue(SDV, 0, false); 4684 return 0; 4685 } 4686 } 4687 } 4688 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4689 } 4690 } 4691 return 0; 4692 } 4693 case Intrinsic::dbg_value: { 4694 const DbgValueInst &DI = cast<DbgValueInst>(I); 4695 DIVariable DIVar(DI.getVariable()); 4696 assert((!DIVar || DIVar.isVariable()) && 4697 "Variable in DbgValueInst should be either null or a DIVariable."); 4698 if (!DIVar) 4699 return 0; 4700 4701 MDNode *Variable = DI.getVariable(); 4702 uint64_t Offset = DI.getOffset(); 4703 const Value *V = DI.getValue(); 4704 if (!V) 4705 return 0; 4706 4707 SDDbgValue *SDV; 4708 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) { 4709 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder); 4710 DAG.AddDbgValue(SDV, 0, false); 4711 } else { 4712 // Do not use getValue() in here; we don't want to generate code at 4713 // this point if it hasn't been done yet. 4714 SDValue N = NodeMap[V]; 4715 if (!N.getNode() && isa<Argument>(V)) 4716 // Check unused arguments map. 4717 N = UnusedArgNodeMap[V]; 4718 if (N.getNode()) { 4719 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) { 4720 SDV = DAG.getDbgValue(Variable, N.getNode(), 4721 N.getResNo(), Offset, dl, SDNodeOrder); 4722 DAG.AddDbgValue(SDV, N.getNode(), false); 4723 } 4724 } else if (!V->use_empty() ) { 4725 // Do not call getValue(V) yet, as we don't want to generate code. 4726 // Remember it for later. 4727 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder); 4728 DanglingDebugInfoMap[V] = DDI; 4729 } else { 4730 // We may expand this to cover more cases. One case where we have no 4731 // data available is an unreferenced parameter. 4732 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 4733 } 4734 } 4735 4736 // Build a debug info table entry. 4737 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V)) 4738 V = BCI->getOperand(0); 4739 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 4740 // Don't handle byval struct arguments or VLAs, for example. 4741 if (!AI) { 4742 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n"); 4743 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n"); 4744 return 0; 4745 } 4746 DenseMap<const AllocaInst*, int>::iterator SI = 4747 FuncInfo.StaticAllocaMap.find(AI); 4748 if (SI == FuncInfo.StaticAllocaMap.end()) 4749 return 0; // VLAs. 4750 int FI = SI->second; 4751 4752 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4753 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo()) 4754 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc()); 4755 return 0; 4756 } 4757 4758 case Intrinsic::eh_typeid_for: { 4759 // Find the type id for the given typeinfo. 4760 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0)); 4761 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV); 4762 Res = DAG.getConstant(TypeID, MVT::i32); 4763 setValue(&I, Res); 4764 return 0; 4765 } 4766 4767 case Intrinsic::eh_return_i32: 4768 case Intrinsic::eh_return_i64: 4769 DAG.getMachineFunction().getMMI().setCallsEHReturn(true); 4770 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl, 4771 MVT::Other, 4772 getControlRoot(), 4773 getValue(I.getArgOperand(0)), 4774 getValue(I.getArgOperand(1)))); 4775 return 0; 4776 case Intrinsic::eh_unwind_init: 4777 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true); 4778 return 0; 4779 case Intrinsic::eh_dwarf_cfa: { 4780 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl, 4781 TLI->getPointerTy()); 4782 SDValue Offset = DAG.getNode(ISD::ADD, sdl, 4783 CfaArg.getValueType(), 4784 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl, 4785 CfaArg.getValueType()), 4786 CfaArg); 4787 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, 4788 TLI->getPointerTy(), 4789 DAG.getConstant(0, TLI->getPointerTy())); 4790 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(), 4791 FA, Offset)); 4792 return 0; 4793 } 4794 case Intrinsic::eh_sjlj_callsite: { 4795 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 4796 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0)); 4797 assert(CI && "Non-constant call site value in eh.sjlj.callsite!"); 4798 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!"); 4799 4800 MMI.setCurrentCallSite(CI->getZExtValue()); 4801 return 0; 4802 } 4803 case Intrinsic::eh_sjlj_functioncontext: { 4804 // Get and store the index of the function context. 4805 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 4806 AllocaInst *FnCtx = 4807 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts()); 4808 int FI = FuncInfo.StaticAllocaMap[FnCtx]; 4809 MFI->setFunctionContextIndex(FI); 4810 return 0; 4811 } 4812 case Intrinsic::eh_sjlj_setjmp: { 4813 SDValue Ops[2]; 4814 Ops[0] = getRoot(); 4815 Ops[1] = getValue(I.getArgOperand(0)); 4816 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl, 4817 DAG.getVTList(MVT::i32, MVT::Other), 4818 Ops, 2); 4819 setValue(&I, Op.getValue(0)); 4820 DAG.setRoot(Op.getValue(1)); 4821 return 0; 4822 } 4823 case Intrinsic::eh_sjlj_longjmp: { 4824 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other, 4825 getRoot(), getValue(I.getArgOperand(0)))); 4826 return 0; 4827 } 4828 4829 case Intrinsic::x86_mmx_pslli_w: 4830 case Intrinsic::x86_mmx_pslli_d: 4831 case Intrinsic::x86_mmx_pslli_q: 4832 case Intrinsic::x86_mmx_psrli_w: 4833 case Intrinsic::x86_mmx_psrli_d: 4834 case Intrinsic::x86_mmx_psrli_q: 4835 case Intrinsic::x86_mmx_psrai_w: 4836 case Intrinsic::x86_mmx_psrai_d: { 4837 SDValue ShAmt = getValue(I.getArgOperand(1)); 4838 if (isa<ConstantSDNode>(ShAmt)) { 4839 visitTargetIntrinsic(I, Intrinsic); 4840 return 0; 4841 } 4842 unsigned NewIntrinsic = 0; 4843 EVT ShAmtVT = MVT::v2i32; 4844 switch (Intrinsic) { 4845 case Intrinsic::x86_mmx_pslli_w: 4846 NewIntrinsic = Intrinsic::x86_mmx_psll_w; 4847 break; 4848 case Intrinsic::x86_mmx_pslli_d: 4849 NewIntrinsic = Intrinsic::x86_mmx_psll_d; 4850 break; 4851 case Intrinsic::x86_mmx_pslli_q: 4852 NewIntrinsic = Intrinsic::x86_mmx_psll_q; 4853 break; 4854 case Intrinsic::x86_mmx_psrli_w: 4855 NewIntrinsic = Intrinsic::x86_mmx_psrl_w; 4856 break; 4857 case Intrinsic::x86_mmx_psrli_d: 4858 NewIntrinsic = Intrinsic::x86_mmx_psrl_d; 4859 break; 4860 case Intrinsic::x86_mmx_psrli_q: 4861 NewIntrinsic = Intrinsic::x86_mmx_psrl_q; 4862 break; 4863 case Intrinsic::x86_mmx_psrai_w: 4864 NewIntrinsic = Intrinsic::x86_mmx_psra_w; 4865 break; 4866 case Intrinsic::x86_mmx_psrai_d: 4867 NewIntrinsic = Intrinsic::x86_mmx_psra_d; 4868 break; 4869 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4870 } 4871 4872 // The vector shift intrinsics with scalars uses 32b shift amounts but 4873 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits 4874 // to be zero. 4875 // We must do this early because v2i32 is not a legal type. 4876 SDValue ShOps[2]; 4877 ShOps[0] = ShAmt; 4878 ShOps[1] = DAG.getConstant(0, MVT::i32); 4879 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2); 4880 EVT DestVT = TLI->getValueType(I.getType()); 4881 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt); 4882 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT, 4883 DAG.getConstant(NewIntrinsic, MVT::i32), 4884 getValue(I.getArgOperand(0)), ShAmt); 4885 setValue(&I, Res); 4886 return 0; 4887 } 4888 case Intrinsic::x86_avx_vinsertf128_pd_256: 4889 case Intrinsic::x86_avx_vinsertf128_ps_256: 4890 case Intrinsic::x86_avx_vinsertf128_si_256: 4891 case Intrinsic::x86_avx2_vinserti128: { 4892 EVT DestVT = TLI->getValueType(I.getType()); 4893 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType()); 4894 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) * 4895 ElVT.getVectorNumElements(); 4896 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT, 4897 getValue(I.getArgOperand(0)), 4898 getValue(I.getArgOperand(1)), 4899 DAG.getConstant(Idx, TLI->getVectorIdxTy())); 4900 setValue(&I, Res); 4901 return 0; 4902 } 4903 case Intrinsic::x86_avx_vextractf128_pd_256: 4904 case Intrinsic::x86_avx_vextractf128_ps_256: 4905 case Intrinsic::x86_avx_vextractf128_si_256: 4906 case Intrinsic::x86_avx2_vextracti128: { 4907 EVT DestVT = TLI->getValueType(I.getType()); 4908 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) * 4909 DestVT.getVectorNumElements(); 4910 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT, 4911 getValue(I.getArgOperand(0)), 4912 DAG.getConstant(Idx, TLI->getVectorIdxTy())); 4913 setValue(&I, Res); 4914 return 0; 4915 } 4916 case Intrinsic::convertff: 4917 case Intrinsic::convertfsi: 4918 case Intrinsic::convertfui: 4919 case Intrinsic::convertsif: 4920 case Intrinsic::convertuif: 4921 case Intrinsic::convertss: 4922 case Intrinsic::convertsu: 4923 case Intrinsic::convertus: 4924 case Intrinsic::convertuu: { 4925 ISD::CvtCode Code = ISD::CVT_INVALID; 4926 switch (Intrinsic) { 4927 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4928 case Intrinsic::convertff: Code = ISD::CVT_FF; break; 4929 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break; 4930 case Intrinsic::convertfui: Code = ISD::CVT_FU; break; 4931 case Intrinsic::convertsif: Code = ISD::CVT_SF; break; 4932 case Intrinsic::convertuif: Code = ISD::CVT_UF; break; 4933 case Intrinsic::convertss: Code = ISD::CVT_SS; break; 4934 case Intrinsic::convertsu: Code = ISD::CVT_SU; break; 4935 case Intrinsic::convertus: Code = ISD::CVT_US; break; 4936 case Intrinsic::convertuu: Code = ISD::CVT_UU; break; 4937 } 4938 EVT DestVT = TLI->getValueType(I.getType()); 4939 const Value *Op1 = I.getArgOperand(0); 4940 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1), 4941 DAG.getValueType(DestVT), 4942 DAG.getValueType(getValue(Op1).getValueType()), 4943 getValue(I.getArgOperand(1)), 4944 getValue(I.getArgOperand(2)), 4945 Code); 4946 setValue(&I, Res); 4947 return 0; 4948 } 4949 case Intrinsic::powi: 4950 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)), 4951 getValue(I.getArgOperand(1)), DAG)); 4952 return 0; 4953 case Intrinsic::log: 4954 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI)); 4955 return 0; 4956 case Intrinsic::log2: 4957 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI)); 4958 return 0; 4959 case Intrinsic::log10: 4960 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI)); 4961 return 0; 4962 case Intrinsic::exp: 4963 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI)); 4964 return 0; 4965 case Intrinsic::exp2: 4966 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI)); 4967 return 0; 4968 case Intrinsic::pow: 4969 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)), 4970 getValue(I.getArgOperand(1)), DAG, *TLI)); 4971 return 0; 4972 case Intrinsic::sqrt: 4973 case Intrinsic::fabs: 4974 case Intrinsic::sin: 4975 case Intrinsic::cos: 4976 case Intrinsic::floor: 4977 case Intrinsic::ceil: 4978 case Intrinsic::trunc: 4979 case Intrinsic::rint: 4980 case Intrinsic::nearbyint: 4981 case Intrinsic::round: { 4982 unsigned Opcode; 4983 switch (Intrinsic) { 4984 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 4985 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break; 4986 case Intrinsic::fabs: Opcode = ISD::FABS; break; 4987 case Intrinsic::sin: Opcode = ISD::FSIN; break; 4988 case Intrinsic::cos: Opcode = ISD::FCOS; break; 4989 case Intrinsic::floor: Opcode = ISD::FFLOOR; break; 4990 case Intrinsic::ceil: Opcode = ISD::FCEIL; break; 4991 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break; 4992 case Intrinsic::rint: Opcode = ISD::FRINT; break; 4993 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break; 4994 case Intrinsic::round: Opcode = ISD::FROUND; break; 4995 } 4996 4997 setValue(&I, DAG.getNode(Opcode, sdl, 4998 getValue(I.getArgOperand(0)).getValueType(), 4999 getValue(I.getArgOperand(0)))); 5000 return 0; 5001 } 5002 case Intrinsic::copysign: 5003 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl, 5004 getValue(I.getArgOperand(0)).getValueType(), 5005 getValue(I.getArgOperand(0)), 5006 getValue(I.getArgOperand(1)))); 5007 return 0; 5008 case Intrinsic::fma: 5009 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5010 getValue(I.getArgOperand(0)).getValueType(), 5011 getValue(I.getArgOperand(0)), 5012 getValue(I.getArgOperand(1)), 5013 getValue(I.getArgOperand(2)))); 5014 return 0; 5015 case Intrinsic::fmuladd: { 5016 EVT VT = TLI->getValueType(I.getType()); 5017 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 5018 TLI->isFMAFasterThanFMulAndFAdd(VT)) { 5019 setValue(&I, DAG.getNode(ISD::FMA, sdl, 5020 getValue(I.getArgOperand(0)).getValueType(), 5021 getValue(I.getArgOperand(0)), 5022 getValue(I.getArgOperand(1)), 5023 getValue(I.getArgOperand(2)))); 5024 } else { 5025 SDValue Mul = DAG.getNode(ISD::FMUL, sdl, 5026 getValue(I.getArgOperand(0)).getValueType(), 5027 getValue(I.getArgOperand(0)), 5028 getValue(I.getArgOperand(1))); 5029 SDValue Add = DAG.getNode(ISD::FADD, sdl, 5030 getValue(I.getArgOperand(0)).getValueType(), 5031 Mul, 5032 getValue(I.getArgOperand(2))); 5033 setValue(&I, Add); 5034 } 5035 return 0; 5036 } 5037 case Intrinsic::convert_to_fp16: 5038 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl, 5039 MVT::i16, getValue(I.getArgOperand(0)))); 5040 return 0; 5041 case Intrinsic::convert_from_fp16: 5042 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl, 5043 MVT::f32, getValue(I.getArgOperand(0)))); 5044 return 0; 5045 case Intrinsic::pcmarker: { 5046 SDValue Tmp = getValue(I.getArgOperand(0)); 5047 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp)); 5048 return 0; 5049 } 5050 case Intrinsic::readcyclecounter: { 5051 SDValue Op = getRoot(); 5052 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl, 5053 DAG.getVTList(MVT::i64, MVT::Other), 5054 &Op, 1); 5055 setValue(&I, Res); 5056 DAG.setRoot(Res.getValue(1)); 5057 return 0; 5058 } 5059 case Intrinsic::bswap: 5060 setValue(&I, DAG.getNode(ISD::BSWAP, sdl, 5061 getValue(I.getArgOperand(0)).getValueType(), 5062 getValue(I.getArgOperand(0)))); 5063 return 0; 5064 case Intrinsic::cttz: { 5065 SDValue Arg = getValue(I.getArgOperand(0)); 5066 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5067 EVT Ty = Arg.getValueType(); 5068 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF, 5069 sdl, Ty, Arg)); 5070 return 0; 5071 } 5072 case Intrinsic::ctlz: { 5073 SDValue Arg = getValue(I.getArgOperand(0)); 5074 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1)); 5075 EVT Ty = Arg.getValueType(); 5076 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF, 5077 sdl, Ty, Arg)); 5078 return 0; 5079 } 5080 case Intrinsic::ctpop: { 5081 SDValue Arg = getValue(I.getArgOperand(0)); 5082 EVT Ty = Arg.getValueType(); 5083 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg)); 5084 return 0; 5085 } 5086 case Intrinsic::stacksave: { 5087 SDValue Op = getRoot(); 5088 Res = DAG.getNode(ISD::STACKSAVE, sdl, 5089 DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1); 5090 setValue(&I, Res); 5091 DAG.setRoot(Res.getValue(1)); 5092 return 0; 5093 } 5094 case Intrinsic::stackrestore: { 5095 Res = getValue(I.getArgOperand(0)); 5096 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res)); 5097 return 0; 5098 } 5099 case Intrinsic::stackprotector: { 5100 // Emit code into the DAG to store the stack guard onto the stack. 5101 MachineFunction &MF = DAG.getMachineFunction(); 5102 MachineFrameInfo *MFI = MF.getFrameInfo(); 5103 EVT PtrTy = TLI->getPointerTy(); 5104 5105 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value. 5106 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1)); 5107 5108 int FI = FuncInfo.StaticAllocaMap[Slot]; 5109 MFI->setStackProtectorIndex(FI); 5110 5111 SDValue FIN = DAG.getFrameIndex(FI, PtrTy); 5112 5113 // Store the stack protector onto the stack. 5114 Res = DAG.getStore(getRoot(), sdl, Src, FIN, 5115 MachinePointerInfo::getFixedStack(FI), 5116 true, false, 0); 5117 setValue(&I, Res); 5118 DAG.setRoot(Res); 5119 return 0; 5120 } 5121 case Intrinsic::objectsize: { 5122 // If we don't know by now, we're never going to know. 5123 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1)); 5124 5125 assert(CI && "Non-constant type in __builtin_object_size?"); 5126 5127 SDValue Arg = getValue(I.getCalledValue()); 5128 EVT Ty = Arg.getValueType(); 5129 5130 if (CI->isZero()) 5131 Res = DAG.getConstant(-1ULL, Ty); 5132 else 5133 Res = DAG.getConstant(0, Ty); 5134 5135 setValue(&I, Res); 5136 return 0; 5137 } 5138 case Intrinsic::annotation: 5139 case Intrinsic::ptr_annotation: 5140 // Drop the intrinsic, but forward the value 5141 setValue(&I, getValue(I.getOperand(0))); 5142 return 0; 5143 case Intrinsic::var_annotation: 5144 // Discard annotate attributes 5145 return 0; 5146 5147 case Intrinsic::init_trampoline: { 5148 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts()); 5149 5150 SDValue Ops[6]; 5151 Ops[0] = getRoot(); 5152 Ops[1] = getValue(I.getArgOperand(0)); 5153 Ops[2] = getValue(I.getArgOperand(1)); 5154 Ops[3] = getValue(I.getArgOperand(2)); 5155 Ops[4] = DAG.getSrcValue(I.getArgOperand(0)); 5156 Ops[5] = DAG.getSrcValue(F); 5157 5158 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6); 5159 5160 DAG.setRoot(Res); 5161 return 0; 5162 } 5163 case Intrinsic::adjust_trampoline: { 5164 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl, 5165 TLI->getPointerTy(), 5166 getValue(I.getArgOperand(0)))); 5167 return 0; 5168 } 5169 case Intrinsic::gcroot: 5170 if (GFI) { 5171 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts(); 5172 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1)); 5173 5174 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode()); 5175 GFI->addStackRoot(FI->getIndex(), TypeMap); 5176 } 5177 return 0; 5178 case Intrinsic::gcread: 5179 case Intrinsic::gcwrite: 5180 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!"); 5181 case Intrinsic::flt_rounds: 5182 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32)); 5183 return 0; 5184 5185 case Intrinsic::expect: { 5186 // Just replace __builtin_expect(exp, c) with EXP. 5187 setValue(&I, getValue(I.getArgOperand(0))); 5188 return 0; 5189 } 5190 5191 case Intrinsic::debugtrap: 5192 case Intrinsic::trap: { 5193 StringRef TrapFuncName = TM.Options.getTrapFunctionName(); 5194 if (TrapFuncName.empty()) { 5195 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ? 5196 ISD::TRAP : ISD::DEBUGTRAP; 5197 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot())); 5198 return 0; 5199 } 5200 TargetLowering::ArgListTy Args; 5201 TargetLowering:: 5202 CallLoweringInfo CLI(getRoot(), I.getType(), 5203 false, false, false, false, 0, CallingConv::C, 5204 /*isTailCall=*/false, 5205 /*doesNotRet=*/false, /*isReturnValueUsed=*/true, 5206 DAG.getExternalSymbol(TrapFuncName.data(), 5207 TLI->getPointerTy()), 5208 Args, DAG, sdl); 5209 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI); 5210 DAG.setRoot(Result.second); 5211 return 0; 5212 } 5213 5214 case Intrinsic::uadd_with_overflow: 5215 case Intrinsic::sadd_with_overflow: 5216 case Intrinsic::usub_with_overflow: 5217 case Intrinsic::ssub_with_overflow: 5218 case Intrinsic::umul_with_overflow: 5219 case Intrinsic::smul_with_overflow: { 5220 ISD::NodeType Op; 5221 switch (Intrinsic) { 5222 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here. 5223 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break; 5224 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break; 5225 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break; 5226 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break; 5227 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break; 5228 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break; 5229 } 5230 SDValue Op1 = getValue(I.getArgOperand(0)); 5231 SDValue Op2 = getValue(I.getArgOperand(1)); 5232 5233 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1); 5234 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2)); 5235 return 0; 5236 } 5237 case Intrinsic::prefetch: { 5238 SDValue Ops[5]; 5239 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue(); 5240 Ops[0] = getRoot(); 5241 Ops[1] = getValue(I.getArgOperand(0)); 5242 Ops[2] = getValue(I.getArgOperand(1)); 5243 Ops[3] = getValue(I.getArgOperand(2)); 5244 Ops[4] = getValue(I.getArgOperand(3)); 5245 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl, 5246 DAG.getVTList(MVT::Other), 5247 &Ops[0], 5, 5248 EVT::getIntegerVT(*Context, 8), 5249 MachinePointerInfo(I.getArgOperand(0)), 5250 0, /* align */ 5251 false, /* volatile */ 5252 rw==0, /* read */ 5253 rw==1)); /* write */ 5254 return 0; 5255 } 5256 case Intrinsic::lifetime_start: 5257 case Intrinsic::lifetime_end: { 5258 bool IsStart = (Intrinsic == Intrinsic::lifetime_start); 5259 // Stack coloring is not enabled in O0, discard region information. 5260 if (TM.getOptLevel() == CodeGenOpt::None) 5261 return 0; 5262 5263 SmallVector<Value *, 4> Allocas; 5264 GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD); 5265 5266 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(), 5267 E = Allocas.end(); Object != E; ++Object) { 5268 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object); 5269 5270 // Could not find an Alloca. 5271 if (!LifetimeObject) 5272 continue; 5273 5274 int FI = FuncInfo.StaticAllocaMap[LifetimeObject]; 5275 5276 SDValue Ops[2]; 5277 Ops[0] = getRoot(); 5278 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true); 5279 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END); 5280 5281 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2); 5282 DAG.setRoot(Res); 5283 } 5284 return 0; 5285 } 5286 case Intrinsic::invariant_start: 5287 // Discard region information. 5288 setValue(&I, DAG.getUNDEF(TLI->getPointerTy())); 5289 return 0; 5290 case Intrinsic::invariant_end: 5291 // Discard region information. 5292 return 0; 5293 case Intrinsic::stackprotectorcheck: { 5294 // Do not actually emit anything for this basic block. Instead we initialize 5295 // the stack protector descriptor and export the guard variable so we can 5296 // access it in FinishBasicBlock. 5297 const BasicBlock *BB = I.getParent(); 5298 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I); 5299 ExportFromCurrentBlock(SPDescriptor.getGuard()); 5300 5301 // Flush our exports since we are going to process a terminator. 5302 (void)getControlRoot(); 5303 return 0; 5304 } 5305 case Intrinsic::donothing: 5306 // ignore 5307 return 0; 5308 } 5309 } 5310 5311 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee, 5312 bool isTailCall, 5313 MachineBasicBlock *LandingPad) { 5314 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType()); 5315 FunctionType *FTy = cast<FunctionType>(PT->getElementType()); 5316 Type *RetTy = FTy->getReturnType(); 5317 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5318 MCSymbol *BeginLabel = 0; 5319 5320 TargetLowering::ArgListTy Args; 5321 TargetLowering::ArgListEntry Entry; 5322 Args.reserve(CS.arg_size()); 5323 5324 // Check whether the function can return without sret-demotion. 5325 SmallVector<ISD::OutputArg, 4> Outs; 5326 const TargetLowering *TLI = TM.getTargetLowering(); 5327 GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI); 5328 5329 bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(), 5330 DAG.getMachineFunction(), 5331 FTy->isVarArg(), Outs, 5332 FTy->getContext()); 5333 5334 SDValue DemoteStackSlot; 5335 int DemoteStackIdx = -100; 5336 5337 if (!CanLowerReturn) { 5338 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize( 5339 FTy->getReturnType()); 5340 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment( 5341 FTy->getReturnType()); 5342 MachineFunction &MF = DAG.getMachineFunction(); 5343 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 5344 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType()); 5345 5346 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy()); 5347 Entry.Node = DemoteStackSlot; 5348 Entry.Ty = StackSlotPtrType; 5349 Entry.isSExt = false; 5350 Entry.isZExt = false; 5351 Entry.isInReg = false; 5352 Entry.isSRet = true; 5353 Entry.isNest = false; 5354 Entry.isByVal = false; 5355 Entry.isReturned = false; 5356 Entry.Alignment = Align; 5357 Args.push_back(Entry); 5358 RetTy = Type::getVoidTy(FTy->getContext()); 5359 } 5360 5361 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); 5362 i != e; ++i) { 5363 const Value *V = *i; 5364 5365 // Skip empty types 5366 if (V->getType()->isEmptyTy()) 5367 continue; 5368 5369 SDValue ArgNode = getValue(V); 5370 Entry.Node = ArgNode; Entry.Ty = V->getType(); 5371 5372 unsigned attrInd = i - CS.arg_begin() + 1; 5373 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt); 5374 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt); 5375 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg); 5376 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet); 5377 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest); 5378 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal); 5379 Entry.isReturned = CS.paramHasAttr(attrInd, Attribute::Returned); 5380 Entry.Alignment = CS.getParamAlignment(attrInd); 5381 Args.push_back(Entry); 5382 } 5383 5384 if (LandingPad) { 5385 // Insert a label before the invoke call to mark the try range. This can be 5386 // used to detect deletion of the invoke via the MachineModuleInfo. 5387 BeginLabel = MMI.getContext().CreateTempSymbol(); 5388 5389 // For SjLj, keep track of which landing pads go with which invokes 5390 // so as to maintain the ordering of pads in the LSDA. 5391 unsigned CallSiteIndex = MMI.getCurrentCallSite(); 5392 if (CallSiteIndex) { 5393 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex); 5394 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex); 5395 5396 // Now that the call site is handled, stop tracking it. 5397 MMI.setCurrentCallSite(0); 5398 } 5399 5400 // Both PendingLoads and PendingExports must be flushed here; 5401 // this call might not return. 5402 (void)getRoot(); 5403 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel)); 5404 } 5405 5406 // Check if target-independent constraints permit a tail call here. 5407 // Target-dependent constraints are checked within TLI->LowerCallTo. 5408 if (isTailCall && !isInTailCallPosition(CS, *TLI)) 5409 isTailCall = false; 5410 5411 TargetLowering:: 5412 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG, 5413 getCurSDLoc(), CS); 5414 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI); 5415 assert((isTailCall || Result.second.getNode()) && 5416 "Non-null chain expected with non-tail call!"); 5417 assert((Result.second.getNode() || !Result.first.getNode()) && 5418 "Null value expected with tail call!"); 5419 if (Result.first.getNode()) { 5420 setValue(CS.getInstruction(), Result.first); 5421 } else if (!CanLowerReturn && Result.second.getNode()) { 5422 // The instruction result is the result of loading from the 5423 // hidden sret parameter. 5424 SmallVector<EVT, 1> PVTs; 5425 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType()); 5426 5427 ComputeValueVTs(*TLI, PtrRetTy, PVTs); 5428 assert(PVTs.size() == 1 && "Pointers should fit in one register"); 5429 EVT PtrVT = PVTs[0]; 5430 5431 SmallVector<EVT, 4> RetTys; 5432 SmallVector<uint64_t, 4> Offsets; 5433 RetTy = FTy->getReturnType(); 5434 ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets); 5435 5436 unsigned NumValues = RetTys.size(); 5437 SmallVector<SDValue, 4> Values(NumValues); 5438 SmallVector<SDValue, 4> Chains(NumValues); 5439 5440 for (unsigned i = 0; i < NumValues; ++i) { 5441 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, 5442 DemoteStackSlot, 5443 DAG.getConstant(Offsets[i], PtrVT)); 5444 SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add, 5445 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), 5446 false, false, false, 1); 5447 Values[i] = L; 5448 Chains[i] = L.getValue(1); 5449 } 5450 5451 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), 5452 MVT::Other, &Chains[0], NumValues); 5453 PendingLoads.push_back(Chain); 5454 5455 setValue(CS.getInstruction(), 5456 DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(), 5457 DAG.getVTList(&RetTys[0], RetTys.size()), 5458 &Values[0], Values.size())); 5459 } 5460 5461 if (!Result.second.getNode()) { 5462 // As a special case, a null chain means that a tail call has been emitted and 5463 // the DAG root is already updated. 5464 HasTailCall = true; 5465 5466 // Since there's no actual continuation from this block, nothing can be 5467 // relying on us setting vregs for them. 5468 PendingExports.clear(); 5469 } else { 5470 DAG.setRoot(Result.second); 5471 } 5472 5473 if (LandingPad) { 5474 // Insert a label at the end of the invoke call to mark the try range. This 5475 // can be used to detect deletion of the invoke via the MachineModuleInfo. 5476 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol(); 5477 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel)); 5478 5479 // Inform MachineModuleInfo of range. 5480 MMI.addInvoke(LandingPad, BeginLabel, EndLabel); 5481 } 5482 } 5483 5484 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the 5485 /// value is equal or not-equal to zero. 5486 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) { 5487 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); 5488 UI != E; ++UI) { 5489 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI)) 5490 if (IC->isEquality()) 5491 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1))) 5492 if (C->isNullValue()) 5493 continue; 5494 // Unknown instruction. 5495 return false; 5496 } 5497 return true; 5498 } 5499 5500 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT, 5501 Type *LoadTy, 5502 SelectionDAGBuilder &Builder) { 5503 5504 // Check to see if this load can be trivially constant folded, e.g. if the 5505 // input is from a string literal. 5506 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) { 5507 // Cast pointer to the type we really want to load. 5508 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput), 5509 PointerType::getUnqual(LoadTy)); 5510 5511 if (const Constant *LoadCst = 5512 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput), 5513 Builder.TD)) 5514 return Builder.getValue(LoadCst); 5515 } 5516 5517 // Otherwise, we have to emit the load. If the pointer is to unfoldable but 5518 // still constant memory, the input chain can be the entry node. 5519 SDValue Root; 5520 bool ConstantMemory = false; 5521 5522 // Do not serialize (non-volatile) loads of constant memory with anything. 5523 if (Builder.AA->pointsToConstantMemory(PtrVal)) { 5524 Root = Builder.DAG.getEntryNode(); 5525 ConstantMemory = true; 5526 } else { 5527 // Do not serialize non-volatile loads against each other. 5528 Root = Builder.DAG.getRoot(); 5529 } 5530 5531 SDValue Ptr = Builder.getValue(PtrVal); 5532 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, 5533 Ptr, MachinePointerInfo(PtrVal), 5534 false /*volatile*/, 5535 false /*nontemporal*/, 5536 false /*isinvariant*/, 1 /* align=1 */); 5537 5538 if (!ConstantMemory) 5539 Builder.PendingLoads.push_back(LoadVal.getValue(1)); 5540 return LoadVal; 5541 } 5542 5543 /// processIntegerCallValue - Record the value for an instruction that 5544 /// produces an integer result, converting the type where necessary. 5545 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I, 5546 SDValue Value, 5547 bool IsSigned) { 5548 EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true); 5549 if (IsSigned) 5550 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT); 5551 else 5552 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT); 5553 setValue(&I, Value); 5554 } 5555 5556 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form. 5557 /// If so, return true and lower it, otherwise return false and it will be 5558 /// lowered like a normal call. 5559 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) { 5560 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t) 5561 if (I.getNumArgOperands() != 3) 5562 return false; 5563 5564 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1); 5565 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() || 5566 !I.getArgOperand(2)->getType()->isIntegerTy() || 5567 !I.getType()->isIntegerTy()) 5568 return false; 5569 5570 const Value *Size = I.getArgOperand(2); 5571 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size); 5572 if (CSize && CSize->getZExtValue() == 0) { 5573 EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true); 5574 setValue(&I, DAG.getConstant(0, CallVT)); 5575 return true; 5576 } 5577 5578 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5579 std::pair<SDValue, SDValue> Res = 5580 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5581 getValue(LHS), getValue(RHS), getValue(Size), 5582 MachinePointerInfo(LHS), 5583 MachinePointerInfo(RHS)); 5584 if (Res.first.getNode()) { 5585 processIntegerCallValue(I, Res.first, true); 5586 PendingLoads.push_back(Res.second); 5587 return true; 5588 } 5589 5590 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0 5591 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0 5592 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) { 5593 bool ActuallyDoIt = true; 5594 MVT LoadVT; 5595 Type *LoadTy; 5596 switch (CSize->getZExtValue()) { 5597 default: 5598 LoadVT = MVT::Other; 5599 LoadTy = 0; 5600 ActuallyDoIt = false; 5601 break; 5602 case 2: 5603 LoadVT = MVT::i16; 5604 LoadTy = Type::getInt16Ty(CSize->getContext()); 5605 break; 5606 case 4: 5607 LoadVT = MVT::i32; 5608 LoadTy = Type::getInt32Ty(CSize->getContext()); 5609 break; 5610 case 8: 5611 LoadVT = MVT::i64; 5612 LoadTy = Type::getInt64Ty(CSize->getContext()); 5613 break; 5614 /* 5615 case 16: 5616 LoadVT = MVT::v4i32; 5617 LoadTy = Type::getInt32Ty(CSize->getContext()); 5618 LoadTy = VectorType::get(LoadTy, 4); 5619 break; 5620 */ 5621 } 5622 5623 // This turns into unaligned loads. We only do this if the target natively 5624 // supports the MVT we'll be loading or if it is small enough (<= 4) that 5625 // we'll only produce a small number of byte loads. 5626 5627 // Require that we can find a legal MVT, and only do this if the target 5628 // supports unaligned loads of that type. Expanding into byte loads would 5629 // bloat the code. 5630 const TargetLowering *TLI = TM.getTargetLowering(); 5631 if (ActuallyDoIt && CSize->getZExtValue() > 4) { 5632 // TODO: Handle 5 byte compare as 4-byte + 1 byte. 5633 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads. 5634 if (!TLI->isTypeLegal(LoadVT) ||!TLI->allowsUnalignedMemoryAccesses(LoadVT)) 5635 ActuallyDoIt = false; 5636 } 5637 5638 if (ActuallyDoIt) { 5639 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this); 5640 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this); 5641 5642 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal, 5643 ISD::SETNE); 5644 processIntegerCallValue(I, Res, false); 5645 return true; 5646 } 5647 } 5648 5649 5650 return false; 5651 } 5652 5653 /// visitMemChrCall -- See if we can lower a memchr call into an optimized 5654 /// form. If so, return true and lower it, otherwise return false and it 5655 /// will be lowered like a normal call. 5656 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) { 5657 // Verify that the prototype makes sense. void *memchr(void *, int, size_t) 5658 if (I.getNumArgOperands() != 3) 5659 return false; 5660 5661 const Value *Src = I.getArgOperand(0); 5662 const Value *Char = I.getArgOperand(1); 5663 const Value *Length = I.getArgOperand(2); 5664 if (!Src->getType()->isPointerTy() || 5665 !Char->getType()->isIntegerTy() || 5666 !Length->getType()->isIntegerTy() || 5667 !I.getType()->isPointerTy()) 5668 return false; 5669 5670 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5671 std::pair<SDValue, SDValue> Res = 5672 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(), 5673 getValue(Src), getValue(Char), getValue(Length), 5674 MachinePointerInfo(Src)); 5675 if (Res.first.getNode()) { 5676 setValue(&I, Res.first); 5677 PendingLoads.push_back(Res.second); 5678 return true; 5679 } 5680 5681 return false; 5682 } 5683 5684 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an 5685 /// optimized form. If so, return true and lower it, otherwise return false 5686 /// and it will be lowered like a normal call. 5687 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) { 5688 // Verify that the prototype makes sense. char *strcpy(char *, char *) 5689 if (I.getNumArgOperands() != 2) 5690 return false; 5691 5692 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5693 if (!Arg0->getType()->isPointerTy() || 5694 !Arg1->getType()->isPointerTy() || 5695 !I.getType()->isPointerTy()) 5696 return false; 5697 5698 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5699 std::pair<SDValue, SDValue> Res = 5700 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(), 5701 getValue(Arg0), getValue(Arg1), 5702 MachinePointerInfo(Arg0), 5703 MachinePointerInfo(Arg1), isStpcpy); 5704 if (Res.first.getNode()) { 5705 setValue(&I, Res.first); 5706 DAG.setRoot(Res.second); 5707 return true; 5708 } 5709 5710 return false; 5711 } 5712 5713 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form. 5714 /// If so, return true and lower it, otherwise return false and it will be 5715 /// lowered like a normal call. 5716 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) { 5717 // Verify that the prototype makes sense. int strcmp(void*,void*) 5718 if (I.getNumArgOperands() != 2) 5719 return false; 5720 5721 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5722 if (!Arg0->getType()->isPointerTy() || 5723 !Arg1->getType()->isPointerTy() || 5724 !I.getType()->isIntegerTy()) 5725 return false; 5726 5727 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5728 std::pair<SDValue, SDValue> Res = 5729 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(), 5730 getValue(Arg0), getValue(Arg1), 5731 MachinePointerInfo(Arg0), 5732 MachinePointerInfo(Arg1)); 5733 if (Res.first.getNode()) { 5734 processIntegerCallValue(I, Res.first, true); 5735 PendingLoads.push_back(Res.second); 5736 return true; 5737 } 5738 5739 return false; 5740 } 5741 5742 /// visitStrLenCall -- See if we can lower a strlen call into an optimized 5743 /// form. If so, return true and lower it, otherwise return false and it 5744 /// will be lowered like a normal call. 5745 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) { 5746 // Verify that the prototype makes sense. size_t strlen(char *) 5747 if (I.getNumArgOperands() != 1) 5748 return false; 5749 5750 const Value *Arg0 = I.getArgOperand(0); 5751 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy()) 5752 return false; 5753 5754 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5755 std::pair<SDValue, SDValue> Res = 5756 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(), 5757 getValue(Arg0), MachinePointerInfo(Arg0)); 5758 if (Res.first.getNode()) { 5759 processIntegerCallValue(I, Res.first, false); 5760 PendingLoads.push_back(Res.second); 5761 return true; 5762 } 5763 5764 return false; 5765 } 5766 5767 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized 5768 /// form. If so, return true and lower it, otherwise return false and it 5769 /// will be lowered like a normal call. 5770 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) { 5771 // Verify that the prototype makes sense. size_t strnlen(char *, size_t) 5772 if (I.getNumArgOperands() != 2) 5773 return false; 5774 5775 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1); 5776 if (!Arg0->getType()->isPointerTy() || 5777 !Arg1->getType()->isIntegerTy() || 5778 !I.getType()->isIntegerTy()) 5779 return false; 5780 5781 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo(); 5782 std::pair<SDValue, SDValue> Res = 5783 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(), 5784 getValue(Arg0), getValue(Arg1), 5785 MachinePointerInfo(Arg0)); 5786 if (Res.first.getNode()) { 5787 processIntegerCallValue(I, Res.first, false); 5788 PendingLoads.push_back(Res.second); 5789 return true; 5790 } 5791 5792 return false; 5793 } 5794 5795 /// visitUnaryFloatCall - If a call instruction is a unary floating-point 5796 /// operation (as expected), translate it to an SDNode with the specified opcode 5797 /// and return true. 5798 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I, 5799 unsigned Opcode) { 5800 // Sanity check that it really is a unary floating-point call. 5801 if (I.getNumArgOperands() != 1 || 5802 !I.getArgOperand(0)->getType()->isFloatingPointTy() || 5803 I.getType() != I.getArgOperand(0)->getType() || 5804 !I.onlyReadsMemory()) 5805 return false; 5806 5807 SDValue Tmp = getValue(I.getArgOperand(0)); 5808 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp)); 5809 return true; 5810 } 5811 5812 void SelectionDAGBuilder::visitCall(const CallInst &I) { 5813 // Handle inline assembly differently. 5814 if (isa<InlineAsm>(I.getCalledValue())) { 5815 visitInlineAsm(&I); 5816 return; 5817 } 5818 5819 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI(); 5820 ComputeUsesVAFloatArgument(I, &MMI); 5821 5822 const char *RenameFn = 0; 5823 if (Function *F = I.getCalledFunction()) { 5824 if (F->isDeclaration()) { 5825 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) { 5826 if (unsigned IID = II->getIntrinsicID(F)) { 5827 RenameFn = visitIntrinsicCall(I, IID); 5828 if (!RenameFn) 5829 return; 5830 } 5831 } 5832 if (unsigned IID = F->getIntrinsicID()) { 5833 RenameFn = visitIntrinsicCall(I, IID); 5834 if (!RenameFn) 5835 return; 5836 } 5837 } 5838 5839 // Check for well-known libc/libm calls. If the function is internal, it 5840 // can't be a library call. 5841 LibFunc::Func Func; 5842 if (!F->hasLocalLinkage() && F->hasName() && 5843 LibInfo->getLibFunc(F->getName(), Func) && 5844 LibInfo->hasOptimizedCodeGen(Func)) { 5845 switch (Func) { 5846 default: break; 5847 case LibFunc::copysign: 5848 case LibFunc::copysignf: 5849 case LibFunc::copysignl: 5850 if (I.getNumArgOperands() == 2 && // Basic sanity checks. 5851 I.getArgOperand(0)->getType()->isFloatingPointTy() && 5852 I.getType() == I.getArgOperand(0)->getType() && 5853 I.getType() == I.getArgOperand(1)->getType() && 5854 I.onlyReadsMemory()) { 5855 SDValue LHS = getValue(I.getArgOperand(0)); 5856 SDValue RHS = getValue(I.getArgOperand(1)); 5857 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(), 5858 LHS.getValueType(), LHS, RHS)); 5859 return; 5860 } 5861 break; 5862 case LibFunc::fabs: 5863 case LibFunc::fabsf: 5864 case LibFunc::fabsl: 5865 if (visitUnaryFloatCall(I, ISD::FABS)) 5866 return; 5867 break; 5868 case LibFunc::sin: 5869 case LibFunc::sinf: 5870 case LibFunc::sinl: 5871 if (visitUnaryFloatCall(I, ISD::FSIN)) 5872 return; 5873 break; 5874 case LibFunc::cos: 5875 case LibFunc::cosf: 5876 case LibFunc::cosl: 5877 if (visitUnaryFloatCall(I, ISD::FCOS)) 5878 return; 5879 break; 5880 case LibFunc::sqrt: 5881 case LibFunc::sqrtf: 5882 case LibFunc::sqrtl: 5883 case LibFunc::sqrt_finite: 5884 case LibFunc::sqrtf_finite: 5885 case LibFunc::sqrtl_finite: 5886 if (visitUnaryFloatCall(I, ISD::FSQRT)) 5887 return; 5888 break; 5889 case LibFunc::floor: 5890 case LibFunc::floorf: 5891 case LibFunc::floorl: 5892 if (visitUnaryFloatCall(I, ISD::FFLOOR)) 5893 return; 5894 break; 5895 case LibFunc::nearbyint: 5896 case LibFunc::nearbyintf: 5897 case LibFunc::nearbyintl: 5898 if (visitUnaryFloatCall(I, ISD::FNEARBYINT)) 5899 return; 5900 break; 5901 case LibFunc::ceil: 5902 case LibFunc::ceilf: 5903 case LibFunc::ceill: 5904 if (visitUnaryFloatCall(I, ISD::FCEIL)) 5905 return; 5906 break; 5907 case LibFunc::rint: 5908 case LibFunc::rintf: 5909 case LibFunc::rintl: 5910 if (visitUnaryFloatCall(I, ISD::FRINT)) 5911 return; 5912 break; 5913 case LibFunc::round: 5914 case LibFunc::roundf: 5915 case LibFunc::roundl: 5916 if (visitUnaryFloatCall(I, ISD::FROUND)) 5917 return; 5918 break; 5919 case LibFunc::trunc: 5920 case LibFunc::truncf: 5921 case LibFunc::truncl: 5922 if (visitUnaryFloatCall(I, ISD::FTRUNC)) 5923 return; 5924 break; 5925 case LibFunc::log2: 5926 case LibFunc::log2f: 5927 case LibFunc::log2l: 5928 if (visitUnaryFloatCall(I, ISD::FLOG2)) 5929 return; 5930 break; 5931 case LibFunc::exp2: 5932 case LibFunc::exp2f: 5933 case LibFunc::exp2l: 5934 if (visitUnaryFloatCall(I, ISD::FEXP2)) 5935 return; 5936 break; 5937 case LibFunc::memcmp: 5938 if (visitMemCmpCall(I)) 5939 return; 5940 break; 5941 case LibFunc::memchr: 5942 if (visitMemChrCall(I)) 5943 return; 5944 break; 5945 case LibFunc::strcpy: 5946 if (visitStrCpyCall(I, false)) 5947 return; 5948 break; 5949 case LibFunc::stpcpy: 5950 if (visitStrCpyCall(I, true)) 5951 return; 5952 break; 5953 case LibFunc::strcmp: 5954 if (visitStrCmpCall(I)) 5955 return; 5956 break; 5957 case LibFunc::strlen: 5958 if (visitStrLenCall(I)) 5959 return; 5960 break; 5961 case LibFunc::strnlen: 5962 if (visitStrNLenCall(I)) 5963 return; 5964 break; 5965 } 5966 } 5967 } 5968 5969 SDValue Callee; 5970 if (!RenameFn) 5971 Callee = getValue(I.getCalledValue()); 5972 else 5973 Callee = DAG.getExternalSymbol(RenameFn, 5974 TM.getTargetLowering()->getPointerTy()); 5975 5976 // Check if we can potentially perform a tail call. More detailed checking is 5977 // be done within LowerCallTo, after more information about the call is known. 5978 LowerCallTo(&I, Callee, I.isTailCall()); 5979 } 5980 5981 namespace { 5982 5983 /// AsmOperandInfo - This contains information for each constraint that we are 5984 /// lowering. 5985 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo { 5986 public: 5987 /// CallOperand - If this is the result output operand or a clobber 5988 /// this is null, otherwise it is the incoming operand to the CallInst. 5989 /// This gets modified as the asm is processed. 5990 SDValue CallOperand; 5991 5992 /// AssignedRegs - If this is a register or register class operand, this 5993 /// contains the set of register corresponding to the operand. 5994 RegsForValue AssignedRegs; 5995 5996 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info) 5997 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) { 5998 } 5999 6000 /// getCallOperandValEVT - Return the EVT of the Value* that this operand 6001 /// corresponds to. If there is no Value* for this operand, it returns 6002 /// MVT::Other. 6003 EVT getCallOperandValEVT(LLVMContext &Context, 6004 const TargetLowering &TLI, 6005 const DataLayout *TD) const { 6006 if (CallOperandVal == 0) return MVT::Other; 6007 6008 if (isa<BasicBlock>(CallOperandVal)) 6009 return TLI.getPointerTy(); 6010 6011 llvm::Type *OpTy = CallOperandVal->getType(); 6012 6013 // FIXME: code duplicated from TargetLowering::ParseConstraints(). 6014 // If this is an indirect operand, the operand is a pointer to the 6015 // accessed type. 6016 if (isIndirect) { 6017 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 6018 if (!PtrTy) 6019 report_fatal_error("Indirect operand for inline asm not a pointer!"); 6020 OpTy = PtrTy->getElementType(); 6021 } 6022 6023 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 6024 if (StructType *STy = dyn_cast<StructType>(OpTy)) 6025 if (STy->getNumElements() == 1) 6026 OpTy = STy->getElementType(0); 6027 6028 // If OpTy is not a single value, it may be a struct/union that we 6029 // can tile with integers. 6030 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 6031 unsigned BitSize = TD->getTypeSizeInBits(OpTy); 6032 switch (BitSize) { 6033 default: break; 6034 case 1: 6035 case 8: 6036 case 16: 6037 case 32: 6038 case 64: 6039 case 128: 6040 OpTy = IntegerType::get(Context, BitSize); 6041 break; 6042 } 6043 } 6044 6045 return TLI.getValueType(OpTy, true); 6046 } 6047 }; 6048 6049 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector; 6050 6051 } // end anonymous namespace 6052 6053 /// GetRegistersForValue - Assign registers (virtual or physical) for the 6054 /// specified operand. We prefer to assign virtual registers, to allow the 6055 /// register allocator to handle the assignment process. However, if the asm 6056 /// uses features that we can't model on machineinstrs, we have SDISel do the 6057 /// allocation. This produces generally horrible, but correct, code. 6058 /// 6059 /// OpInfo describes the operand. 6060 /// 6061 static void GetRegistersForValue(SelectionDAG &DAG, 6062 const TargetLowering &TLI, 6063 SDLoc DL, 6064 SDISelAsmOperandInfo &OpInfo) { 6065 LLVMContext &Context = *DAG.getContext(); 6066 6067 MachineFunction &MF = DAG.getMachineFunction(); 6068 SmallVector<unsigned, 4> Regs; 6069 6070 // If this is a constraint for a single physreg, or a constraint for a 6071 // register class, find it. 6072 std::pair<unsigned, const TargetRegisterClass*> PhysReg = 6073 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 6074 OpInfo.ConstraintVT); 6075 6076 unsigned NumRegs = 1; 6077 if (OpInfo.ConstraintVT != MVT::Other) { 6078 // If this is a FP input in an integer register (or visa versa) insert a bit 6079 // cast of the input value. More generally, handle any case where the input 6080 // value disagrees with the register class we plan to stick this in. 6081 if (OpInfo.Type == InlineAsm::isInput && 6082 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) { 6083 // Try to convert to the first EVT that the reg class contains. If the 6084 // types are identical size, use a bitcast to convert (e.g. two differing 6085 // vector types). 6086 MVT RegVT = *PhysReg.second->vt_begin(); 6087 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) { 6088 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 6089 RegVT, OpInfo.CallOperand); 6090 OpInfo.ConstraintVT = RegVT; 6091 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) { 6092 // If the input is a FP value and we want it in FP registers, do a 6093 // bitcast to the corresponding integer type. This turns an f64 value 6094 // into i64, which can be passed with two i32 values on a 32-bit 6095 // machine. 6096 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits()); 6097 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL, 6098 RegVT, OpInfo.CallOperand); 6099 OpInfo.ConstraintVT = RegVT; 6100 } 6101 } 6102 6103 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT); 6104 } 6105 6106 MVT RegVT; 6107 EVT ValueVT = OpInfo.ConstraintVT; 6108 6109 // If this is a constraint for a specific physical register, like {r17}, 6110 // assign it now. 6111 if (unsigned AssignedReg = PhysReg.first) { 6112 const TargetRegisterClass *RC = PhysReg.second; 6113 if (OpInfo.ConstraintVT == MVT::Other) 6114 ValueVT = *RC->vt_begin(); 6115 6116 // Get the actual register value type. This is important, because the user 6117 // may have asked for (e.g.) the AX register in i32 type. We need to 6118 // remember that AX is actually i16 to get the right extension. 6119 RegVT = *RC->vt_begin(); 6120 6121 // This is a explicit reference to a physical register. 6122 Regs.push_back(AssignedReg); 6123 6124 // If this is an expanded reference, add the rest of the regs to Regs. 6125 if (NumRegs != 1) { 6126 TargetRegisterClass::iterator I = RC->begin(); 6127 for (; *I != AssignedReg; ++I) 6128 assert(I != RC->end() && "Didn't find reg!"); 6129 6130 // Already added the first reg. 6131 --NumRegs; ++I; 6132 for (; NumRegs; --NumRegs, ++I) { 6133 assert(I != RC->end() && "Ran out of registers to allocate!"); 6134 Regs.push_back(*I); 6135 } 6136 } 6137 6138 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 6139 return; 6140 } 6141 6142 // Otherwise, if this was a reference to an LLVM register class, create vregs 6143 // for this reference. 6144 if (const TargetRegisterClass *RC = PhysReg.second) { 6145 RegVT = *RC->vt_begin(); 6146 if (OpInfo.ConstraintVT == MVT::Other) 6147 ValueVT = RegVT; 6148 6149 // Create the appropriate number of virtual registers. 6150 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 6151 for (; NumRegs; --NumRegs) 6152 Regs.push_back(RegInfo.createVirtualRegister(RC)); 6153 6154 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT); 6155 return; 6156 } 6157 6158 // Otherwise, we couldn't allocate enough registers for this. 6159 } 6160 6161 /// visitInlineAsm - Handle a call to an InlineAsm object. 6162 /// 6163 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) { 6164 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 6165 6166 /// ConstraintOperands - Information about all of the constraints. 6167 SDISelAsmOperandInfoVector ConstraintOperands; 6168 6169 const TargetLowering *TLI = TM.getTargetLowering(); 6170 TargetLowering::AsmOperandInfoVector 6171 TargetConstraints = TLI->ParseConstraints(CS); 6172 6173 bool hasMemory = false; 6174 6175 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 6176 unsigned ResNo = 0; // ResNo - The result number of the next output. 6177 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 6178 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i])); 6179 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back(); 6180 6181 MVT OpVT = MVT::Other; 6182 6183 // Compute the value type for each operand. 6184 switch (OpInfo.Type) { 6185 case InlineAsm::isOutput: 6186 // Indirect outputs just consume an argument. 6187 if (OpInfo.isIndirect) { 6188 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 6189 break; 6190 } 6191 6192 // The return value of the call is this value. As such, there is no 6193 // corresponding argument. 6194 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6195 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 6196 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo)); 6197 } else { 6198 assert(ResNo == 0 && "Asm only has one result!"); 6199 OpVT = TLI->getSimpleValueType(CS.getType()); 6200 } 6201 ++ResNo; 6202 break; 6203 case InlineAsm::isInput: 6204 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 6205 break; 6206 case InlineAsm::isClobber: 6207 // Nothing to do. 6208 break; 6209 } 6210 6211 // If this is an input or an indirect output, process the call argument. 6212 // BasicBlocks are labels, currently appearing only in asm's. 6213 if (OpInfo.CallOperandVal) { 6214 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) { 6215 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]); 6216 } else { 6217 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal); 6218 } 6219 6220 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, TD). 6221 getSimpleVT(); 6222 } 6223 6224 OpInfo.ConstraintVT = OpVT; 6225 6226 // Indirect operand accesses access memory. 6227 if (OpInfo.isIndirect) 6228 hasMemory = true; 6229 else { 6230 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) { 6231 TargetLowering::ConstraintType 6232 CType = TLI->getConstraintType(OpInfo.Codes[j]); 6233 if (CType == TargetLowering::C_Memory) { 6234 hasMemory = true; 6235 break; 6236 } 6237 } 6238 } 6239 } 6240 6241 SDValue Chain, Flag; 6242 6243 // We won't need to flush pending loads if this asm doesn't touch 6244 // memory and is nonvolatile. 6245 if (hasMemory || IA->hasSideEffects()) 6246 Chain = getRoot(); 6247 else 6248 Chain = DAG.getRoot(); 6249 6250 // Second pass over the constraints: compute which constraint option to use 6251 // and assign registers to constraints that want a specific physreg. 6252 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6253 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6254 6255 // If this is an output operand with a matching input operand, look up the 6256 // matching input. If their types mismatch, e.g. one is an integer, the 6257 // other is floating point, or their sizes are different, flag it as an 6258 // error. 6259 if (OpInfo.hasMatchingInput()) { 6260 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 6261 6262 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 6263 std::pair<unsigned, const TargetRegisterClass*> MatchRC = 6264 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 6265 OpInfo.ConstraintVT); 6266 std::pair<unsigned, const TargetRegisterClass*> InputRC = 6267 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode, 6268 Input.ConstraintVT); 6269 if ((OpInfo.ConstraintVT.isInteger() != 6270 Input.ConstraintVT.isInteger()) || 6271 (MatchRC.second != InputRC.second)) { 6272 report_fatal_error("Unsupported asm: input constraint" 6273 " with a matching output constraint of" 6274 " incompatible type!"); 6275 } 6276 Input.ConstraintVT = OpInfo.ConstraintVT; 6277 } 6278 } 6279 6280 // Compute the constraint code and ConstraintType to use. 6281 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG); 6282 6283 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6284 OpInfo.Type == InlineAsm::isClobber) 6285 continue; 6286 6287 // If this is a memory input, and if the operand is not indirect, do what we 6288 // need to to provide an address for the memory input. 6289 if (OpInfo.ConstraintType == TargetLowering::C_Memory && 6290 !OpInfo.isIndirect) { 6291 assert((OpInfo.isMultipleAlternative || 6292 (OpInfo.Type == InlineAsm::isInput)) && 6293 "Can only indirectify direct input operands!"); 6294 6295 // Memory operands really want the address of the value. If we don't have 6296 // an indirect input, put it in the constpool if we can, otherwise spill 6297 // it to a stack slot. 6298 // TODO: This isn't quite right. We need to handle these according to 6299 // the addressing mode that the constraint wants. Also, this may take 6300 // an additional register for the computation and we don't want that 6301 // either. 6302 6303 // If the operand is a float, integer, or vector constant, spill to a 6304 // constant pool entry to get its address. 6305 const Value *OpVal = OpInfo.CallOperandVal; 6306 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) || 6307 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) { 6308 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal), 6309 TLI->getPointerTy()); 6310 } else { 6311 // Otherwise, create a stack slot and emit a store to it before the 6312 // asm. 6313 Type *Ty = OpVal->getType(); 6314 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty); 6315 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty); 6316 MachineFunction &MF = DAG.getMachineFunction(); 6317 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false); 6318 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy()); 6319 Chain = DAG.getStore(Chain, getCurSDLoc(), 6320 OpInfo.CallOperand, StackSlot, 6321 MachinePointerInfo::getFixedStack(SSFI), 6322 false, false, 0); 6323 OpInfo.CallOperand = StackSlot; 6324 } 6325 6326 // There is no longer a Value* corresponding to this operand. 6327 OpInfo.CallOperandVal = 0; 6328 6329 // It is now an indirect operand. 6330 OpInfo.isIndirect = true; 6331 } 6332 6333 // If this constraint is for a specific register, allocate it before 6334 // anything else. 6335 if (OpInfo.ConstraintType == TargetLowering::C_Register) 6336 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo); 6337 } 6338 6339 // Second pass - Loop over all of the operands, assigning virtual or physregs 6340 // to register class operands. 6341 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6342 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6343 6344 // C_Register operands have already been allocated, Other/Memory don't need 6345 // to be. 6346 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass) 6347 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo); 6348 } 6349 6350 // AsmNodeOperands - The operands for the ISD::INLINEASM node. 6351 std::vector<SDValue> AsmNodeOperands; 6352 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain 6353 AsmNodeOperands.push_back( 6354 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), 6355 TLI->getPointerTy())); 6356 6357 // If we have a !srcloc metadata node associated with it, we want to attach 6358 // this to the ultimately generated inline asm machineinstr. To do this, we 6359 // pass in the third operand as this (potentially null) inline asm MDNode. 6360 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc"); 6361 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc)); 6362 6363 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore 6364 // bits as operand 3. 6365 unsigned ExtraInfo = 0; 6366 if (IA->hasSideEffects()) 6367 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 6368 if (IA->isAlignStack()) 6369 ExtraInfo |= InlineAsm::Extra_IsAlignStack; 6370 // Set the asm dialect. 6371 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect; 6372 6373 // Determine if this InlineAsm MayLoad or MayStore based on the constraints. 6374 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { 6375 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; 6376 6377 // Compute the constraint code and ConstraintType to use. 6378 TLI->ComputeConstraintToUse(OpInfo, SDValue()); 6379 6380 // Ideally, we would only check against memory constraints. However, the 6381 // meaning of an other constraint can be target-specific and we can't easily 6382 // reason about it. Therefore, be conservative and set MayLoad/MayStore 6383 // for other constriants as well. 6384 if (OpInfo.ConstraintType == TargetLowering::C_Memory || 6385 OpInfo.ConstraintType == TargetLowering::C_Other) { 6386 if (OpInfo.Type == InlineAsm::isInput) 6387 ExtraInfo |= InlineAsm::Extra_MayLoad; 6388 else if (OpInfo.Type == InlineAsm::isOutput) 6389 ExtraInfo |= InlineAsm::Extra_MayStore; 6390 else if (OpInfo.Type == InlineAsm::isClobber) 6391 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore); 6392 } 6393 } 6394 6395 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo, 6396 TLI->getPointerTy())); 6397 6398 // Loop over all of the inputs, copying the operand values into the 6399 // appropriate registers and processing the output regs. 6400 RegsForValue RetValRegs; 6401 6402 // IndirectStoresToEmit - The set of stores to emit after the inline asm node. 6403 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit; 6404 6405 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) { 6406 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i]; 6407 6408 switch (OpInfo.Type) { 6409 case InlineAsm::isOutput: { 6410 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass && 6411 OpInfo.ConstraintType != TargetLowering::C_Register) { 6412 // Memory output, or 'other' output (e.g. 'X' constraint). 6413 assert(OpInfo.isIndirect && "Memory output must be indirect operand"); 6414 6415 // Add information to the INLINEASM node to know about this output. 6416 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6417 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, 6418 TLI->getPointerTy())); 6419 AsmNodeOperands.push_back(OpInfo.CallOperand); 6420 break; 6421 } 6422 6423 // Otherwise, this is a register or register class output. 6424 6425 // Copy the output from the appropriate register. Find a register that 6426 // we can use. 6427 if (OpInfo.AssignedRegs.Regs.empty()) { 6428 LLVMContext &Ctx = *DAG.getContext(); 6429 Ctx.emitError(CS.getInstruction(), 6430 "couldn't allocate output register for constraint '" + 6431 Twine(OpInfo.ConstraintCode) + "'"); 6432 return; 6433 } 6434 6435 // If this is an indirect operand, store through the pointer after the 6436 // asm. 6437 if (OpInfo.isIndirect) { 6438 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs, 6439 OpInfo.CallOperandVal)); 6440 } else { 6441 // This is the result value of the call. 6442 assert(!CS.getType()->isVoidTy() && "Bad inline asm!"); 6443 // Concatenate this output onto the outputs list. 6444 RetValRegs.append(OpInfo.AssignedRegs); 6445 } 6446 6447 // Add information to the INLINEASM node to know that this register is 6448 // set. 6449 OpInfo.AssignedRegs 6450 .AddInlineAsmOperands(OpInfo.isEarlyClobber 6451 ? InlineAsm::Kind_RegDefEarlyClobber 6452 : InlineAsm::Kind_RegDef, 6453 false, 0, DAG, AsmNodeOperands); 6454 break; 6455 } 6456 case InlineAsm::isInput: { 6457 SDValue InOperandVal = OpInfo.CallOperand; 6458 6459 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint? 6460 // If this is required to match an output register we have already set, 6461 // just use its register. 6462 unsigned OperandNo = OpInfo.getMatchedOperand(); 6463 6464 // Scan until we find the definition we already emitted of this operand. 6465 // When we find it, create a RegsForValue operand. 6466 unsigned CurOp = InlineAsm::Op_FirstOperand; 6467 for (; OperandNo; --OperandNo) { 6468 // Advance to the next operand. 6469 unsigned OpFlag = 6470 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6471 assert((InlineAsm::isRegDefKind(OpFlag) || 6472 InlineAsm::isRegDefEarlyClobberKind(OpFlag) || 6473 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?"); 6474 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1; 6475 } 6476 6477 unsigned OpFlag = 6478 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue(); 6479 if (InlineAsm::isRegDefKind(OpFlag) || 6480 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) { 6481 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs. 6482 if (OpInfo.isIndirect) { 6483 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c 6484 LLVMContext &Ctx = *DAG.getContext(); 6485 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:" 6486 " don't know how to handle tied " 6487 "indirect register inputs"); 6488 return; 6489 } 6490 6491 RegsForValue MatchedRegs; 6492 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType()); 6493 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType(); 6494 MatchedRegs.RegVTs.push_back(RegVT); 6495 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo(); 6496 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag); 6497 i != e; ++i) { 6498 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT)) 6499 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC)); 6500 else { 6501 LLVMContext &Ctx = *DAG.getContext(); 6502 Ctx.emitError(CS.getInstruction(), 6503 "inline asm error: This value" 6504 " type register class is not natively supported!"); 6505 return; 6506 } 6507 } 6508 // Use the produced MatchedRegs object to 6509 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(), 6510 Chain, &Flag, CS.getInstruction()); 6511 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, 6512 true, OpInfo.getMatchedOperand(), 6513 DAG, AsmNodeOperands); 6514 break; 6515 } 6516 6517 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!"); 6518 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 && 6519 "Unexpected number of operands"); 6520 // Add information to the INLINEASM node to know about this input. 6521 // See InlineAsm.h isUseOperandTiedToDef. 6522 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag, 6523 OpInfo.getMatchedOperand()); 6524 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, 6525 TLI->getPointerTy())); 6526 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]); 6527 break; 6528 } 6529 6530 // Treat indirect 'X' constraint as memory. 6531 if (OpInfo.ConstraintType == TargetLowering::C_Other && 6532 OpInfo.isIndirect) 6533 OpInfo.ConstraintType = TargetLowering::C_Memory; 6534 6535 if (OpInfo.ConstraintType == TargetLowering::C_Other) { 6536 std::vector<SDValue> Ops; 6537 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode, 6538 Ops, DAG); 6539 if (Ops.empty()) { 6540 LLVMContext &Ctx = *DAG.getContext(); 6541 Ctx.emitError(CS.getInstruction(), 6542 "invalid operand for inline asm constraint '" + 6543 Twine(OpInfo.ConstraintCode) + "'"); 6544 return; 6545 } 6546 6547 // Add information to the INLINEASM node to know about this input. 6548 unsigned ResOpType = 6549 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size()); 6550 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 6551 TLI->getPointerTy())); 6552 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end()); 6553 break; 6554 } 6555 6556 if (OpInfo.ConstraintType == TargetLowering::C_Memory) { 6557 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!"); 6558 assert(InOperandVal.getValueType() == TLI->getPointerTy() && 6559 "Memory operands expect pointer values"); 6560 6561 // Add information to the INLINEASM node to know about this input. 6562 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1); 6563 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 6564 TLI->getPointerTy())); 6565 AsmNodeOperands.push_back(InOperandVal); 6566 break; 6567 } 6568 6569 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass || 6570 OpInfo.ConstraintType == TargetLowering::C_Register) && 6571 "Unknown constraint type!"); 6572 6573 // TODO: Support this. 6574 if (OpInfo.isIndirect) { 6575 LLVMContext &Ctx = *DAG.getContext(); 6576 Ctx.emitError(CS.getInstruction(), 6577 "Don't know how to handle indirect register inputs yet " 6578 "for constraint '" + 6579 Twine(OpInfo.ConstraintCode) + "'"); 6580 return; 6581 } 6582 6583 // Copy the input into the appropriate registers. 6584 if (OpInfo.AssignedRegs.Regs.empty()) { 6585 LLVMContext &Ctx = *DAG.getContext(); 6586 Ctx.emitError(CS.getInstruction(), 6587 "couldn't allocate input reg for constraint '" + 6588 Twine(OpInfo.ConstraintCode) + "'"); 6589 return; 6590 } 6591 6592 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(), 6593 Chain, &Flag, CS.getInstruction()); 6594 6595 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0, 6596 DAG, AsmNodeOperands); 6597 break; 6598 } 6599 case InlineAsm::isClobber: { 6600 // Add the clobbered value to the operand list, so that the register 6601 // allocator is aware that the physreg got clobbered. 6602 if (!OpInfo.AssignedRegs.Regs.empty()) 6603 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber, 6604 false, 0, DAG, 6605 AsmNodeOperands); 6606 break; 6607 } 6608 } 6609 } 6610 6611 // Finish up input operands. Set the input chain and add the flag last. 6612 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain; 6613 if (Flag.getNode()) AsmNodeOperands.push_back(Flag); 6614 6615 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(), 6616 DAG.getVTList(MVT::Other, MVT::Glue), 6617 &AsmNodeOperands[0], AsmNodeOperands.size()); 6618 Flag = Chain.getValue(1); 6619 6620 // If this asm returns a register value, copy the result from that register 6621 // and set it as the value of the call. 6622 if (!RetValRegs.Regs.empty()) { 6623 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 6624 Chain, &Flag, CS.getInstruction()); 6625 6626 // FIXME: Why don't we do this for inline asms with MRVs? 6627 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) { 6628 EVT ResultType = TLI->getValueType(CS.getType()); 6629 6630 // If any of the results of the inline asm is a vector, it may have the 6631 // wrong width/num elts. This can happen for register classes that can 6632 // contain multiple different value types. The preg or vreg allocated may 6633 // not have the same VT as was expected. Convert it to the right type 6634 // with bit_convert. 6635 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) { 6636 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(), 6637 ResultType, Val); 6638 6639 } else if (ResultType != Val.getValueType() && 6640 ResultType.isInteger() && Val.getValueType().isInteger()) { 6641 // If a result value was tied to an input value, the computed result may 6642 // have a wider width than the expected result. Extract the relevant 6643 // portion. 6644 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val); 6645 } 6646 6647 assert(ResultType == Val.getValueType() && "Asm result value mismatch!"); 6648 } 6649 6650 setValue(CS.getInstruction(), Val); 6651 // Don't need to use this as a chain in this case. 6652 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty()) 6653 return; 6654 } 6655 6656 std::vector<std::pair<SDValue, const Value *> > StoresToEmit; 6657 6658 // Process indirect outputs, first output all of the flagged copies out of 6659 // physregs. 6660 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) { 6661 RegsForValue &OutRegs = IndirectStoresToEmit[i].first; 6662 const Value *Ptr = IndirectStoresToEmit[i].second; 6663 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), 6664 Chain, &Flag, IA); 6665 StoresToEmit.push_back(std::make_pair(OutVal, Ptr)); 6666 } 6667 6668 // Emit the non-flagged stores from the physregs. 6669 SmallVector<SDValue, 8> OutChains; 6670 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) { 6671 SDValue Val = DAG.getStore(Chain, getCurSDLoc(), 6672 StoresToEmit[i].first, 6673 getValue(StoresToEmit[i].second), 6674 MachinePointerInfo(StoresToEmit[i].second), 6675 false, false, 0); 6676 OutChains.push_back(Val); 6677 } 6678 6679 if (!OutChains.empty()) 6680 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, 6681 &OutChains[0], OutChains.size()); 6682 6683 DAG.setRoot(Chain); 6684 } 6685 6686 void SelectionDAGBuilder::visitVAStart(const CallInst &I) { 6687 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(), 6688 MVT::Other, getRoot(), 6689 getValue(I.getArgOperand(0)), 6690 DAG.getSrcValue(I.getArgOperand(0)))); 6691 } 6692 6693 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) { 6694 const TargetLowering *TLI = TM.getTargetLowering(); 6695 const DataLayout &TD = *TLI->getDataLayout(); 6696 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(), 6697 getRoot(), getValue(I.getOperand(0)), 6698 DAG.getSrcValue(I.getOperand(0)), 6699 TD.getABITypeAlignment(I.getType())); 6700 setValue(&I, V); 6701 DAG.setRoot(V.getValue(1)); 6702 } 6703 6704 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) { 6705 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(), 6706 MVT::Other, getRoot(), 6707 getValue(I.getArgOperand(0)), 6708 DAG.getSrcValue(I.getArgOperand(0)))); 6709 } 6710 6711 void SelectionDAGBuilder::visitVACopy(const CallInst &I) { 6712 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(), 6713 MVT::Other, getRoot(), 6714 getValue(I.getArgOperand(0)), 6715 getValue(I.getArgOperand(1)), 6716 DAG.getSrcValue(I.getArgOperand(0)), 6717 DAG.getSrcValue(I.getArgOperand(1)))); 6718 } 6719 6720 /// TargetLowering::LowerCallTo - This is the default LowerCallTo 6721 /// implementation, which just calls LowerCall. 6722 /// FIXME: When all targets are 6723 /// migrated to using LowerCall, this hook should be integrated into SDISel. 6724 std::pair<SDValue, SDValue> 6725 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const { 6726 // Handle the incoming return values from the call. 6727 CLI.Ins.clear(); 6728 SmallVector<EVT, 4> RetTys; 6729 ComputeValueVTs(*this, CLI.RetTy, RetTys); 6730 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6731 EVT VT = RetTys[I]; 6732 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 6733 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 6734 for (unsigned i = 0; i != NumRegs; ++i) { 6735 ISD::InputArg MyFlags; 6736 MyFlags.VT = RegisterVT; 6737 MyFlags.Used = CLI.IsReturnValueUsed; 6738 if (CLI.RetSExt) 6739 MyFlags.Flags.setSExt(); 6740 if (CLI.RetZExt) 6741 MyFlags.Flags.setZExt(); 6742 if (CLI.IsInReg) 6743 MyFlags.Flags.setInReg(); 6744 CLI.Ins.push_back(MyFlags); 6745 } 6746 } 6747 6748 // Handle all of the outgoing arguments. 6749 CLI.Outs.clear(); 6750 CLI.OutVals.clear(); 6751 ArgListTy &Args = CLI.Args; 6752 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 6753 SmallVector<EVT, 4> ValueVTs; 6754 ComputeValueVTs(*this, Args[i].Ty, ValueVTs); 6755 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6756 Value != NumValues; ++Value) { 6757 EVT VT = ValueVTs[Value]; 6758 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext()); 6759 SDValue Op = SDValue(Args[i].Node.getNode(), 6760 Args[i].Node.getResNo() + Value); 6761 ISD::ArgFlagsTy Flags; 6762 unsigned OriginalAlignment = 6763 getDataLayout()->getABITypeAlignment(ArgTy); 6764 6765 if (Args[i].isZExt) 6766 Flags.setZExt(); 6767 if (Args[i].isSExt) 6768 Flags.setSExt(); 6769 if (Args[i].isInReg) 6770 Flags.setInReg(); 6771 if (Args[i].isSRet) 6772 Flags.setSRet(); 6773 if (Args[i].isByVal) { 6774 Flags.setByVal(); 6775 PointerType *Ty = cast<PointerType>(Args[i].Ty); 6776 Type *ElementTy = Ty->getElementType(); 6777 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy)); 6778 // For ByVal, alignment should come from FE. BE will guess if this 6779 // info is not there but there are cases it cannot get right. 6780 unsigned FrameAlign; 6781 if (Args[i].Alignment) 6782 FrameAlign = Args[i].Alignment; 6783 else 6784 FrameAlign = getByValTypeAlignment(ElementTy); 6785 Flags.setByValAlign(FrameAlign); 6786 } 6787 if (Args[i].isNest) 6788 Flags.setNest(); 6789 Flags.setOrigAlign(OriginalAlignment); 6790 6791 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT); 6792 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT); 6793 SmallVector<SDValue, 4> Parts(NumParts); 6794 ISD::NodeType ExtendKind = ISD::ANY_EXTEND; 6795 6796 if (Args[i].isSExt) 6797 ExtendKind = ISD::SIGN_EXTEND; 6798 else if (Args[i].isZExt) 6799 ExtendKind = ISD::ZERO_EXTEND; 6800 6801 // Conservatively only handle 'returned' on non-vectors for now 6802 if (Args[i].isReturned && !Op.getValueType().isVector()) { 6803 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues && 6804 "unexpected use of 'returned'"); 6805 // Before passing 'returned' to the target lowering code, ensure that 6806 // either the register MVT and the actual EVT are the same size or that 6807 // the return value and argument are extended in the same way; in these 6808 // cases it's safe to pass the argument register value unchanged as the 6809 // return register value (although it's at the target's option whether 6810 // to do so) 6811 // TODO: allow code generation to take advantage of partially preserved 6812 // registers rather than clobbering the entire register when the 6813 // parameter extension method is not compatible with the return 6814 // extension method 6815 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) || 6816 (ExtendKind != ISD::ANY_EXTEND && 6817 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt)) 6818 Flags.setReturned(); 6819 } 6820 6821 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, 6822 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind); 6823 6824 for (unsigned j = 0; j != NumParts; ++j) { 6825 // if it isn't first piece, alignment must be 1 6826 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), 6827 i < CLI.NumFixedArgs, 6828 i, j*Parts[j].getValueType().getStoreSize()); 6829 if (NumParts > 1 && j == 0) 6830 MyFlags.Flags.setSplit(); 6831 else if (j != 0) 6832 MyFlags.Flags.setOrigAlign(1); 6833 6834 CLI.Outs.push_back(MyFlags); 6835 CLI.OutVals.push_back(Parts[j]); 6836 } 6837 } 6838 } 6839 6840 SmallVector<SDValue, 4> InVals; 6841 CLI.Chain = LowerCall(CLI, InVals); 6842 6843 // Verify that the target's LowerCall behaved as expected. 6844 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other && 6845 "LowerCall didn't return a valid chain!"); 6846 assert((!CLI.IsTailCall || InVals.empty()) && 6847 "LowerCall emitted a return value for a tail call!"); 6848 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) && 6849 "LowerCall didn't emit the correct number of values!"); 6850 6851 // For a tail call, the return value is merely live-out and there aren't 6852 // any nodes in the DAG representing it. Return a special value to 6853 // indicate that a tail call has been emitted and no more Instructions 6854 // should be processed in the current block. 6855 if (CLI.IsTailCall) { 6856 CLI.DAG.setRoot(CLI.Chain); 6857 return std::make_pair(SDValue(), SDValue()); 6858 } 6859 6860 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) { 6861 assert(InVals[i].getNode() && 6862 "LowerCall emitted a null value!"); 6863 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() && 6864 "LowerCall emitted a value with the wrong type!"); 6865 }); 6866 6867 // Collect the legal value parts into potentially illegal values 6868 // that correspond to the original function's return values. 6869 ISD::NodeType AssertOp = ISD::DELETED_NODE; 6870 if (CLI.RetSExt) 6871 AssertOp = ISD::AssertSext; 6872 else if (CLI.RetZExt) 6873 AssertOp = ISD::AssertZext; 6874 SmallVector<SDValue, 4> ReturnValues; 6875 unsigned CurReg = 0; 6876 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) { 6877 EVT VT = RetTys[I]; 6878 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT); 6879 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT); 6880 6881 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg], 6882 NumRegs, RegisterVT, VT, NULL, 6883 AssertOp)); 6884 CurReg += NumRegs; 6885 } 6886 6887 // For a function returning void, there is no return value. We can't create 6888 // such a node, so we just return a null return value in that case. In 6889 // that case, nothing will actually look at the value. 6890 if (ReturnValues.empty()) 6891 return std::make_pair(SDValue(), CLI.Chain); 6892 6893 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL, 6894 CLI.DAG.getVTList(&RetTys[0], RetTys.size()), 6895 &ReturnValues[0], ReturnValues.size()); 6896 return std::make_pair(Res, CLI.Chain); 6897 } 6898 6899 void TargetLowering::LowerOperationWrapper(SDNode *N, 6900 SmallVectorImpl<SDValue> &Results, 6901 SelectionDAG &DAG) const { 6902 SDValue Res = LowerOperation(SDValue(N, 0), DAG); 6903 if (Res.getNode()) 6904 Results.push_back(Res); 6905 } 6906 6907 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 6908 llvm_unreachable("LowerOperation not implemented for this target!"); 6909 } 6910 6911 void 6912 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) { 6913 SDValue Op = getNonRegisterValue(V); 6914 assert((Op.getOpcode() != ISD::CopyFromReg || 6915 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) && 6916 "Copy from a reg to the same reg!"); 6917 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg"); 6918 6919 const TargetLowering *TLI = TM.getTargetLowering(); 6920 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType()); 6921 SDValue Chain = DAG.getEntryNode(); 6922 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V); 6923 PendingExports.push_back(Chain); 6924 } 6925 6926 #include "llvm/CodeGen/SelectionDAGISel.h" 6927 6928 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the 6929 /// entry block, return true. This includes arguments used by switches, since 6930 /// the switch may expand into multiple basic blocks. 6931 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) { 6932 // With FastISel active, we may be splitting blocks, so force creation 6933 // of virtual registers for all non-dead arguments. 6934 if (FastISel) 6935 return A->use_empty(); 6936 6937 const BasicBlock *Entry = A->getParent()->begin(); 6938 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end(); 6939 UI != E; ++UI) { 6940 const User *U = *UI; 6941 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U)) 6942 return false; // Use not in entry block. 6943 } 6944 return true; 6945 } 6946 6947 void SelectionDAGISel::LowerArguments(const Function &F) { 6948 SelectionDAG &DAG = SDB->DAG; 6949 SDLoc dl = SDB->getCurSDLoc(); 6950 const TargetLowering *TLI = getTargetLowering(); 6951 const DataLayout *TD = TLI->getDataLayout(); 6952 SmallVector<ISD::InputArg, 16> Ins; 6953 6954 if (!FuncInfo->CanLowerReturn) { 6955 // Put in an sret pointer parameter before all the other parameters. 6956 SmallVector<EVT, 1> ValueVTs; 6957 ComputeValueVTs(*getTargetLowering(), 6958 PointerType::getUnqual(F.getReturnType()), ValueVTs); 6959 6960 // NOTE: Assuming that a pointer will never break down to more than one VT 6961 // or one register. 6962 ISD::ArgFlagsTy Flags; 6963 Flags.setSRet(); 6964 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]); 6965 ISD::InputArg RetArg(Flags, RegisterVT, true, 0, 0); 6966 Ins.push_back(RetArg); 6967 } 6968 6969 // Set up the incoming argument description vector. 6970 unsigned Idx = 1; 6971 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); 6972 I != E; ++I, ++Idx) { 6973 SmallVector<EVT, 4> ValueVTs; 6974 ComputeValueVTs(*TLI, I->getType(), ValueVTs); 6975 bool isArgValueUsed = !I->use_empty(); 6976 for (unsigned Value = 0, NumValues = ValueVTs.size(); 6977 Value != NumValues; ++Value) { 6978 EVT VT = ValueVTs[Value]; 6979 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 6980 ISD::ArgFlagsTy Flags; 6981 unsigned OriginalAlignment = 6982 TD->getABITypeAlignment(ArgTy); 6983 6984 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 6985 Flags.setZExt(); 6986 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 6987 Flags.setSExt(); 6988 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg)) 6989 Flags.setInReg(); 6990 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet)) 6991 Flags.setSRet(); 6992 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) { 6993 Flags.setByVal(); 6994 PointerType *Ty = cast<PointerType>(I->getType()); 6995 Type *ElementTy = Ty->getElementType(); 6996 Flags.setByValSize(TD->getTypeAllocSize(ElementTy)); 6997 // For ByVal, alignment should be passed from FE. BE will guess if 6998 // this info is not there but there are cases it cannot get right. 6999 unsigned FrameAlign; 7000 if (F.getParamAlignment(Idx)) 7001 FrameAlign = F.getParamAlignment(Idx); 7002 else 7003 FrameAlign = TLI->getByValTypeAlignment(ElementTy); 7004 Flags.setByValAlign(FrameAlign); 7005 } 7006 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest)) 7007 Flags.setNest(); 7008 Flags.setOrigAlign(OriginalAlignment); 7009 7010 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7011 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT); 7012 for (unsigned i = 0; i != NumRegs; ++i) { 7013 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed, 7014 Idx-1, i*RegisterVT.getStoreSize()); 7015 if (NumRegs > 1 && i == 0) 7016 MyFlags.Flags.setSplit(); 7017 // if it isn't first piece, alignment must be 1 7018 else if (i > 0) 7019 MyFlags.Flags.setOrigAlign(1); 7020 Ins.push_back(MyFlags); 7021 } 7022 } 7023 } 7024 7025 // Call the target to set up the argument values. 7026 SmallVector<SDValue, 8> InVals; 7027 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(), 7028 F.isVarArg(), Ins, 7029 dl, DAG, InVals); 7030 7031 // Verify that the target's LowerFormalArguments behaved as expected. 7032 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other && 7033 "LowerFormalArguments didn't return a valid chain!"); 7034 assert(InVals.size() == Ins.size() && 7035 "LowerFormalArguments didn't emit the correct number of values!"); 7036 DEBUG({ 7037 for (unsigned i = 0, e = Ins.size(); i != e; ++i) { 7038 assert(InVals[i].getNode() && 7039 "LowerFormalArguments emitted a null value!"); 7040 assert(EVT(Ins[i].VT) == InVals[i].getValueType() && 7041 "LowerFormalArguments emitted a value with the wrong type!"); 7042 } 7043 }); 7044 7045 // Update the DAG with the new chain value resulting from argument lowering. 7046 DAG.setRoot(NewRoot); 7047 7048 // Set up the argument values. 7049 unsigned i = 0; 7050 Idx = 1; 7051 if (!FuncInfo->CanLowerReturn) { 7052 // Create a virtual register for the sret pointer, and put in a copy 7053 // from the sret argument into it. 7054 SmallVector<EVT, 1> ValueVTs; 7055 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs); 7056 MVT VT = ValueVTs[0].getSimpleVT(); 7057 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7058 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7059 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, 7060 RegVT, VT, NULL, AssertOp); 7061 7062 MachineFunction& MF = SDB->DAG.getMachineFunction(); 7063 MachineRegisterInfo& RegInfo = MF.getRegInfo(); 7064 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT)); 7065 FuncInfo->DemoteRegister = SRetReg; 7066 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), 7067 SRetReg, ArgValue); 7068 DAG.setRoot(NewRoot); 7069 7070 // i indexes lowered arguments. Bump it past the hidden sret argument. 7071 // Idx indexes LLVM arguments. Don't touch it. 7072 ++i; 7073 } 7074 7075 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 7076 ++I, ++Idx) { 7077 SmallVector<SDValue, 4> ArgValues; 7078 SmallVector<EVT, 4> ValueVTs; 7079 ComputeValueVTs(*TLI, I->getType(), ValueVTs); 7080 unsigned NumValues = ValueVTs.size(); 7081 7082 // If this argument is unused then remember its value. It is used to generate 7083 // debugging information. 7084 if (I->use_empty() && NumValues) { 7085 SDB->setUnusedArgValue(I, InVals[i]); 7086 7087 // Also remember any frame index for use in FastISel. 7088 if (FrameIndexSDNode *FI = 7089 dyn_cast<FrameIndexSDNode>(InVals[i].getNode())) 7090 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7091 } 7092 7093 for (unsigned Val = 0; Val != NumValues; ++Val) { 7094 EVT VT = ValueVTs[Val]; 7095 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT); 7096 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT); 7097 7098 if (!I->use_empty()) { 7099 ISD::NodeType AssertOp = ISD::DELETED_NODE; 7100 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt)) 7101 AssertOp = ISD::AssertSext; 7102 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt)) 7103 AssertOp = ISD::AssertZext; 7104 7105 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], 7106 NumParts, PartVT, VT, 7107 NULL, AssertOp)); 7108 } 7109 7110 i += NumParts; 7111 } 7112 7113 // We don't need to do anything else for unused arguments. 7114 if (ArgValues.empty()) 7115 continue; 7116 7117 // Note down frame index. 7118 if (FrameIndexSDNode *FI = 7119 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode())) 7120 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7121 7122 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues, 7123 SDB->getCurSDLoc()); 7124 7125 SDB->setValue(I, Res); 7126 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) { 7127 if (LoadSDNode *LNode = 7128 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode())) 7129 if (FrameIndexSDNode *FI = 7130 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) 7131 FuncInfo->setArgumentFrameIndex(I, FI->getIndex()); 7132 } 7133 7134 // If this argument is live outside of the entry block, insert a copy from 7135 // wherever we got it to the vreg that other BB's will reference it as. 7136 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) { 7137 // If we can, though, try to skip creating an unnecessary vreg. 7138 // FIXME: This isn't very clean... it would be nice to make this more 7139 // general. It's also subtly incompatible with the hacks FastISel 7140 // uses with vregs. 7141 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg(); 7142 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 7143 FuncInfo->ValueMap[I] = Reg; 7144 continue; 7145 } 7146 } 7147 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) { 7148 FuncInfo->InitializeRegForValue(I); 7149 SDB->CopyToExportRegsIfNeeded(I); 7150 } 7151 } 7152 7153 assert(i == InVals.size() && "Argument register count mismatch!"); 7154 7155 // Finally, if the target has anything special to do, allow it to do so. 7156 // FIXME: this should insert code into the DAG! 7157 EmitFunctionEntryCode(); 7158 } 7159 7160 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to 7161 /// ensure constants are generated when needed. Remember the virtual registers 7162 /// that need to be added to the Machine PHI nodes as input. We cannot just 7163 /// directly add them, because expansion might result in multiple MBB's for one 7164 /// BB. As such, the start of the BB might correspond to a different MBB than 7165 /// the end. 7166 /// 7167 void 7168 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) { 7169 const TerminatorInst *TI = LLVMBB->getTerminator(); 7170 7171 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled; 7172 7173 // Check successor nodes' PHI nodes that expect a constant to be available 7174 // from this block. 7175 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) { 7176 const BasicBlock *SuccBB = TI->getSuccessor(succ); 7177 if (!isa<PHINode>(SuccBB->begin())) continue; 7178 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB]; 7179 7180 // If this terminator has multiple identical successors (common for 7181 // switches), only handle each succ once. 7182 if (!SuccsHandled.insert(SuccMBB)) continue; 7183 7184 MachineBasicBlock::iterator MBBI = SuccMBB->begin(); 7185 7186 // At this point we know that there is a 1-1 correspondence between LLVM PHI 7187 // nodes and Machine PHI nodes, but the incoming operands have not been 7188 // emitted yet. 7189 for (BasicBlock::const_iterator I = SuccBB->begin(); 7190 const PHINode *PN = dyn_cast<PHINode>(I); ++I) { 7191 // Ignore dead phi's. 7192 if (PN->use_empty()) continue; 7193 7194 // Skip empty types 7195 if (PN->getType()->isEmptyTy()) 7196 continue; 7197 7198 unsigned Reg; 7199 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB); 7200 7201 if (const Constant *C = dyn_cast<Constant>(PHIOp)) { 7202 unsigned &RegOut = ConstantsOut[C]; 7203 if (RegOut == 0) { 7204 RegOut = FuncInfo.CreateRegs(C->getType()); 7205 CopyValueToVirtualRegister(C, RegOut); 7206 } 7207 Reg = RegOut; 7208 } else { 7209 DenseMap<const Value *, unsigned>::iterator I = 7210 FuncInfo.ValueMap.find(PHIOp); 7211 if (I != FuncInfo.ValueMap.end()) 7212 Reg = I->second; 7213 else { 7214 assert(isa<AllocaInst>(PHIOp) && 7215 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) && 7216 "Didn't codegen value into a register!??"); 7217 Reg = FuncInfo.CreateRegs(PHIOp->getType()); 7218 CopyValueToVirtualRegister(PHIOp, Reg); 7219 } 7220 } 7221 7222 // Remember that this register needs to added to the machine PHI node as 7223 // the input for this MBB. 7224 SmallVector<EVT, 4> ValueVTs; 7225 const TargetLowering *TLI = TM.getTargetLowering(); 7226 ComputeValueVTs(*TLI, PN->getType(), ValueVTs); 7227 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) { 7228 EVT VT = ValueVTs[vti]; 7229 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT); 7230 for (unsigned i = 0, e = NumRegisters; i != e; ++i) 7231 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i)); 7232 Reg += NumRegisters; 7233 } 7234 } 7235 } 7236 7237 ConstantsOut.clear(); 7238 } 7239 7240 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB 7241 /// is 0. 7242 MachineBasicBlock * 7243 SelectionDAGBuilder::StackProtectorDescriptor:: 7244 AddSuccessorMBB(const BasicBlock *BB, 7245 MachineBasicBlock *ParentMBB, 7246 MachineBasicBlock *SuccMBB) { 7247 // If SuccBB has not been created yet, create it. 7248 if (!SuccMBB) { 7249 MachineFunction *MF = ParentMBB->getParent(); 7250 MachineFunction::iterator BBI = ParentMBB; 7251 SuccMBB = MF->CreateMachineBasicBlock(BB); 7252 MF->insert(++BBI, SuccMBB); 7253 } 7254 // Add it as a successor of ParentMBB. 7255 ParentMBB->addSuccessor(SuccMBB); 7256 return SuccMBB; 7257 } 7258