TargetLowering.h revision 100c83341676d8aae8fc34b5452563ed08b14f3e
1//===-- llvm/Target/TargetLowering.h - Target Lowering Info -----*- C++ -*-===// 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 file describes how to lower LLVM code to machine code. This has two 11// main components: 12// 13// 1. Which ValueTypes are natively supported by the target. 14// 2. Which operations are supported for supported ValueTypes. 15// 3. Cost thresholds for alternative implementations of certain operations. 16// 17// In addition it has a few other components, like information about FP 18// immediates. 19// 20//===----------------------------------------------------------------------===// 21 22#ifndef LLVM_TARGET_TARGETLOWERING_H 23#define LLVM_TARGET_TARGETLOWERING_H 24 25#include "llvm/CallingConv.h" 26#include "llvm/InlineAsm.h" 27#include "llvm/Attributes.h" 28#include "llvm/ADT/SmallPtrSet.h" 29#include "llvm/CodeGen/SelectionDAGNodes.h" 30#include "llvm/CodeGen/RuntimeLibcalls.h" 31#include "llvm/Support/DebugLoc.h" 32#include "llvm/Target/TargetCallingConv.h" 33#include "llvm/Target/TargetMachine.h" 34#include <climits> 35#include <map> 36#include <vector> 37 38namespace llvm { 39 class AllocaInst; 40 class APFloat; 41 class CallInst; 42 class CCState; 43 class Function; 44 class FastISel; 45 class FunctionLoweringInfo; 46 class ImmutableCallSite; 47 class MachineBasicBlock; 48 class MachineFunction; 49 class MachineFrameInfo; 50 class MachineInstr; 51 class MachineJumpTableInfo; 52 class MCContext; 53 class MCExpr; 54 class SDNode; 55 class SDValue; 56 class SelectionDAG; 57 template<typename T> class SmallVectorImpl; 58 class TargetData; 59 class TargetMachine; 60 class TargetRegisterClass; 61 class TargetLoweringObjectFile; 62 class Value; 63 64 // FIXME: should this be here? 65 namespace TLSModel { 66 enum Model { 67 GeneralDynamic, 68 LocalDynamic, 69 InitialExec, 70 LocalExec 71 }; 72 } 73 TLSModel::Model getTLSModel(const GlobalValue *GV, Reloc::Model reloc); 74 75 76//===----------------------------------------------------------------------===// 77/// TargetLowering - This class defines information used to lower LLVM code to 78/// legal SelectionDAG operators that the target instruction selector can accept 79/// natively. 80/// 81/// This class also defines callbacks that targets must implement to lower 82/// target-specific constructs to SelectionDAG operators. 83/// 84class TargetLowering { 85 TargetLowering(const TargetLowering&); // DO NOT IMPLEMENT 86 void operator=(const TargetLowering&); // DO NOT IMPLEMENT 87public: 88 /// LegalizeAction - This enum indicates whether operations are valid for a 89 /// target, and if not, what action should be used to make them valid. 90 enum LegalizeAction { 91 Legal, // The target natively supports this operation. 92 Promote, // This operation should be executed in a larger type. 93 Expand, // Try to expand this to other ops, otherwise use a libcall. 94 Custom // Use the LowerOperation hook to implement custom lowering. 95 }; 96 97 /// LegalizeAction - This enum indicates whether a types are legal for a 98 /// target, and if not, what action should be used to make them valid. 99 enum LegalizeTypeAction { 100 TypeLegal, // The target natively supports this type. 101 TypePromoteInteger, // Replace this integer with a larger one. 102 TypeExpandInteger, // Split this integer into two of half the size. 103 TypeSoftenFloat, // Convert this float to a same size integer type. 104 TypeExpandFloat, // Split this float into two of half the size. 105 TypeScalarizeVector, // Replace this one-element vector with its element. 106 TypeSplitVector, // Split this vector into two of half the size. 107 TypeWidenVector // This vector should be widened into a larger vector. 108 }; 109 110 enum BooleanContent { // How the target represents true/false values. 111 UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage. 112 ZeroOrOneBooleanContent, // All bits zero except for bit 0. 113 ZeroOrNegativeOneBooleanContent // All bits equal to bit 0. 114 }; 115 116 /// NOTE: The constructor takes ownership of TLOF. 117 explicit TargetLowering(const TargetMachine &TM, 118 const TargetLoweringObjectFile *TLOF); 119 virtual ~TargetLowering(); 120 121 const TargetMachine &getTargetMachine() const { return TM; } 122 const TargetData *getTargetData() const { return TD; } 123 const TargetLoweringObjectFile &getObjFileLowering() const { return TLOF; } 124 125 bool isBigEndian() const { return !IsLittleEndian; } 126 bool isLittleEndian() const { return IsLittleEndian; } 127 MVT getPointerTy() const { return PointerTy; } 128 virtual MVT getShiftAmountTy(EVT LHSTy) const; 129 130 /// isSelectExpensive - Return true if the select operation is expensive for 131 /// this target. 132 bool isSelectExpensive() const { return SelectIsExpensive; } 133 134 /// isIntDivCheap() - Return true if integer divide is usually cheaper than 135 /// a sequence of several shifts, adds, and multiplies for this target. 136 bool isIntDivCheap() const { return IntDivIsCheap; } 137 138 /// isPow2DivCheap() - Return true if pow2 div is cheaper than a chain of 139 /// srl/add/sra. 140 bool isPow2DivCheap() const { return Pow2DivIsCheap; } 141 142 /// isJumpExpensive() - Return true if Flow Control is an expensive operation 143 /// that should be avoided. 144 bool isJumpExpensive() const { return JumpIsExpensive; } 145 146 /// getSetCCResultType - Return the ValueType of the result of SETCC 147 /// operations. Also used to obtain the target's preferred type for 148 /// the condition operand of SELECT and BRCOND nodes. In the case of 149 /// BRCOND the argument passed is MVT::Other since there are no other 150 /// operands to get a type hint from. 151 virtual 152 MVT::SimpleValueType getSetCCResultType(EVT VT) const; 153 154 /// getCmpLibcallReturnType - Return the ValueType for comparison 155 /// libcalls. Comparions libcalls include floating point comparion calls, 156 /// and Ordered/Unordered check calls on floating point numbers. 157 virtual 158 MVT::SimpleValueType getCmpLibcallReturnType() const; 159 160 /// getBooleanContents - For targets without i1 registers, this gives the 161 /// nature of the high-bits of boolean values held in types wider than i1. 162 /// "Boolean values" are special true/false values produced by nodes like 163 /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND. 164 /// Not to be confused with general values promoted from i1. 165 BooleanContent getBooleanContents() const { return BooleanContents;} 166 167 /// getSchedulingPreference - Return target scheduling preference. 168 Sched::Preference getSchedulingPreference() const { 169 return SchedPreferenceInfo; 170 } 171 172 /// getSchedulingPreference - Some scheduler, e.g. hybrid, can switch to 173 /// different scheduling heuristics for different nodes. This function returns 174 /// the preference (or none) for the given node. 175 virtual Sched::Preference getSchedulingPreference(SDNode *N) const { 176 return Sched::None; 177 } 178 179 /// getRegClassFor - Return the register class that should be used for the 180 /// specified value type. 181 virtual TargetRegisterClass *getRegClassFor(EVT VT) const { 182 assert(VT.isSimple() && "getRegClassFor called on illegal type!"); 183 TargetRegisterClass *RC = RegClassForVT[VT.getSimpleVT().SimpleTy]; 184 assert(RC && "This value type is not natively supported!"); 185 return RC; 186 } 187 188 /// getRepRegClassFor - Return the 'representative' register class for the 189 /// specified value type. The 'representative' register class is the largest 190 /// legal super-reg register class for the register class of the value type. 191 /// For example, on i386 the rep register class for i8, i16, and i32 are GR32; 192 /// while the rep register class is GR64 on x86_64. 193 virtual const TargetRegisterClass *getRepRegClassFor(EVT VT) const { 194 assert(VT.isSimple() && "getRepRegClassFor called on illegal type!"); 195 const TargetRegisterClass *RC = RepRegClassForVT[VT.getSimpleVT().SimpleTy]; 196 return RC; 197 } 198 199 /// getRepRegClassCostFor - Return the cost of the 'representative' register 200 /// class for the specified value type. 201 virtual uint8_t getRepRegClassCostFor(EVT VT) const { 202 assert(VT.isSimple() && "getRepRegClassCostFor called on illegal type!"); 203 return RepRegClassCostForVT[VT.getSimpleVT().SimpleTy]; 204 } 205 206 /// isTypeLegal - Return true if the target has native support for the 207 /// specified value type. This means that it has a register that directly 208 /// holds it without promotions or expansions. 209 bool isTypeLegal(EVT VT) const { 210 assert(!VT.isSimple() || 211 (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)); 212 return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != 0; 213 } 214 215 class ValueTypeActionImpl { 216 /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum 217 /// that indicates how instruction selection should deal with the type. 218 uint8_t ValueTypeActions[MVT::LAST_VALUETYPE]; 219 220 public: 221 ValueTypeActionImpl() { 222 std::fill(ValueTypeActions, array_endof(ValueTypeActions), 0); 223 } 224 225 LegalizeTypeAction getTypeAction(MVT VT) const { 226 return (LegalizeTypeAction)ValueTypeActions[VT.SimpleTy]; 227 } 228 229 void setTypeAction(EVT VT, LegalizeTypeAction Action) { 230 unsigned I = VT.getSimpleVT().SimpleTy; 231 ValueTypeActions[I] = Action; 232 } 233 }; 234 235 const ValueTypeActionImpl &getValueTypeActions() const { 236 return ValueTypeActions; 237 } 238 239 /// getTypeAction - Return how we should legalize values of this type, either 240 /// it is already legal (return 'Legal') or we need to promote it to a larger 241 /// type (return 'Promote'), or we need to expand it into multiple registers 242 /// of smaller integer type (return 'Expand'). 'Custom' is not an option. 243 LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const { 244 return getTypeConversion(Context, VT).first; 245 } 246 LegalizeTypeAction getTypeAction(MVT VT) const { 247 return ValueTypeActions.getTypeAction(VT); 248 } 249 250 /// getTypeToTransformTo - For types supported by the target, this is an 251 /// identity function. For types that must be promoted to larger types, this 252 /// returns the larger type to promote to. For integer types that are larger 253 /// than the largest integer register, this contains one step in the expansion 254 /// to get to the smaller register. For illegal floating point types, this 255 /// returns the integer type to transform to. 256 EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const { 257 return getTypeConversion(Context, VT).second; 258 } 259 260 /// getTypeToExpandTo - For types supported by the target, this is an 261 /// identity function. For types that must be expanded (i.e. integer types 262 /// that are larger than the largest integer register or illegal floating 263 /// point types), this returns the largest legal type it will be expanded to. 264 EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const { 265 assert(!VT.isVector()); 266 while (true) { 267 switch (getTypeAction(Context, VT)) { 268 case Legal: 269 return VT; 270 case Expand: 271 VT = getTypeToTransformTo(Context, VT); 272 break; 273 default: 274 assert(false && "Type is not legal nor is it to be expanded!"); 275 return VT; 276 } 277 } 278 return VT; 279 } 280 281 /// getVectorTypeBreakdown - Vector types are broken down into some number of 282 /// legal first class types. For example, EVT::v8f32 maps to 2 EVT::v4f32 283 /// with Altivec or SSE1, or 8 promoted EVT::f64 values with the X86 FP stack. 284 /// Similarly, EVT::v2i64 turns into 4 EVT::i32 values with both PPC and X86. 285 /// 286 /// This method returns the number of registers needed, and the VT for each 287 /// register. It also returns the VT and quantity of the intermediate values 288 /// before they are promoted/expanded. 289 /// 290 unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT, 291 EVT &IntermediateVT, 292 unsigned &NumIntermediates, 293 EVT &RegisterVT) const; 294 295 /// getTgtMemIntrinsic: Given an intrinsic, checks if on the target the 296 /// intrinsic will need to map to a MemIntrinsicNode (touches memory). If 297 /// this is the case, it returns true and store the intrinsic 298 /// information into the IntrinsicInfo that was passed to the function. 299 struct IntrinsicInfo { 300 unsigned opc; // target opcode 301 EVT memVT; // memory VT 302 const Value* ptrVal; // value representing memory location 303 int offset; // offset off of ptrVal 304 unsigned align; // alignment 305 bool vol; // is volatile? 306 bool readMem; // reads memory? 307 bool writeMem; // writes memory? 308 }; 309 310 virtual bool getTgtMemIntrinsic(IntrinsicInfo &Info, 311 const CallInst &I, unsigned Intrinsic) const { 312 return false; 313 } 314 315 /// isFPImmLegal - Returns true if the target can instruction select the 316 /// specified FP immediate natively. If false, the legalizer will materialize 317 /// the FP immediate as a load from a constant pool. 318 virtual bool isFPImmLegal(const APFloat &Imm, EVT VT) const { 319 return false; 320 } 321 322 /// isShuffleMaskLegal - Targets can use this to indicate that they only 323 /// support *some* VECTOR_SHUFFLE operations, those with specific masks. 324 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values 325 /// are assumed to be legal. 326 virtual bool isShuffleMaskLegal(const SmallVectorImpl<int> &Mask, 327 EVT VT) const { 328 return true; 329 } 330 331 /// canOpTrap - Returns true if the operation can trap for the value type. 332 /// VT must be a legal type. By default, we optimistically assume most 333 /// operations don't trap except for divide and remainder. 334 virtual bool canOpTrap(unsigned Op, EVT VT) const; 335 336 /// isVectorClearMaskLegal - Similar to isShuffleMaskLegal. This is 337 /// used by Targets can use this to indicate if there is a suitable 338 /// VECTOR_SHUFFLE that can be used to replace a VAND with a constant 339 /// pool entry. 340 virtual bool isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask, 341 EVT VT) const { 342 return false; 343 } 344 345 /// getOperationAction - Return how this operation should be treated: either 346 /// it is legal, needs to be promoted to a larger size, needs to be 347 /// expanded to some other code sequence, or the target has a custom expander 348 /// for it. 349 LegalizeAction getOperationAction(unsigned Op, EVT VT) const { 350 if (VT.isExtended()) return Expand; 351 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!"); 352 unsigned I = (unsigned) VT.getSimpleVT().SimpleTy; 353 return (LegalizeAction)OpActions[I][Op]; 354 } 355 356 /// isOperationLegalOrCustom - Return true if the specified operation is 357 /// legal on this target or can be made legal with custom lowering. This 358 /// is used to help guide high-level lowering decisions. 359 bool isOperationLegalOrCustom(unsigned Op, EVT VT) const { 360 return (VT == MVT::Other || isTypeLegal(VT)) && 361 (getOperationAction(Op, VT) == Legal || 362 getOperationAction(Op, VT) == Custom); 363 } 364 365 /// isOperationLegal - Return true if the specified operation is legal on this 366 /// target. 367 bool isOperationLegal(unsigned Op, EVT VT) const { 368 return (VT == MVT::Other || isTypeLegal(VT)) && 369 getOperationAction(Op, VT) == Legal; 370 } 371 372 /// getLoadExtAction - Return how this load with extension should be treated: 373 /// either it is legal, needs to be promoted to a larger size, needs to be 374 /// expanded to some other code sequence, or the target has a custom expander 375 /// for it. 376 LegalizeAction getLoadExtAction(unsigned ExtType, EVT VT) const { 377 assert(ExtType < ISD::LAST_LOADEXT_TYPE && 378 VT.getSimpleVT() < MVT::LAST_VALUETYPE && 379 "Table isn't big enough!"); 380 return (LegalizeAction)LoadExtActions[VT.getSimpleVT().SimpleTy][ExtType]; 381 } 382 383 /// isLoadExtLegal - Return true if the specified load with extension is legal 384 /// on this target. 385 bool isLoadExtLegal(unsigned ExtType, EVT VT) const { 386 return VT.isSimple() && 387 (getLoadExtAction(ExtType, VT) == Legal || 388 getLoadExtAction(ExtType, VT) == Custom); 389 } 390 391 /// getTruncStoreAction - Return how this store with truncation should be 392 /// treated: either it is legal, needs to be promoted to a larger size, needs 393 /// to be expanded to some other code sequence, or the target has a custom 394 /// expander for it. 395 LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const { 396 assert(ValVT.getSimpleVT() < MVT::LAST_VALUETYPE && 397 MemVT.getSimpleVT() < MVT::LAST_VALUETYPE && 398 "Table isn't big enough!"); 399 return (LegalizeAction)TruncStoreActions[ValVT.getSimpleVT().SimpleTy] 400 [MemVT.getSimpleVT().SimpleTy]; 401 } 402 403 /// isTruncStoreLegal - Return true if the specified store with truncation is 404 /// legal on this target. 405 bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const { 406 return isTypeLegal(ValVT) && MemVT.isSimple() && 407 (getTruncStoreAction(ValVT, MemVT) == Legal || 408 getTruncStoreAction(ValVT, MemVT) == Custom); 409 } 410 411 /// getIndexedLoadAction - Return how the indexed load should be treated: 412 /// either it is legal, needs to be promoted to a larger size, needs to be 413 /// expanded to some other code sequence, or the target has a custom expander 414 /// for it. 415 LegalizeAction 416 getIndexedLoadAction(unsigned IdxMode, EVT VT) const { 417 assert(IdxMode < ISD::LAST_INDEXED_MODE && 418 VT.getSimpleVT() < MVT::LAST_VALUETYPE && 419 "Table isn't big enough!"); 420 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy; 421 return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] & 0xf0) >> 4); 422 } 423 424 /// isIndexedLoadLegal - Return true if the specified indexed load is legal 425 /// on this target. 426 bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const { 427 return VT.isSimple() && 428 (getIndexedLoadAction(IdxMode, VT) == Legal || 429 getIndexedLoadAction(IdxMode, VT) == Custom); 430 } 431 432 /// getIndexedStoreAction - Return how the indexed store should be treated: 433 /// either it is legal, needs to be promoted to a larger size, needs to be 434 /// expanded to some other code sequence, or the target has a custom expander 435 /// for it. 436 LegalizeAction 437 getIndexedStoreAction(unsigned IdxMode, EVT VT) const { 438 assert(IdxMode < ISD::LAST_INDEXED_MODE && 439 VT.getSimpleVT() < MVT::LAST_VALUETYPE && 440 "Table isn't big enough!"); 441 unsigned Ty = (unsigned)VT.getSimpleVT().SimpleTy; 442 return (LegalizeAction)(IndexedModeActions[Ty][IdxMode] & 0x0f); 443 } 444 445 /// isIndexedStoreLegal - Return true if the specified indexed load is legal 446 /// on this target. 447 bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const { 448 return VT.isSimple() && 449 (getIndexedStoreAction(IdxMode, VT) == Legal || 450 getIndexedStoreAction(IdxMode, VT) == Custom); 451 } 452 453 /// getCondCodeAction - Return how the condition code should be treated: 454 /// either it is legal, needs to be expanded to some other code sequence, 455 /// or the target has a custom expander for it. 456 LegalizeAction 457 getCondCodeAction(ISD::CondCode CC, EVT VT) const { 458 assert((unsigned)CC < array_lengthof(CondCodeActions) && 459 (unsigned)VT.getSimpleVT().SimpleTy < sizeof(CondCodeActions[0])*4 && 460 "Table isn't big enough!"); 461 LegalizeAction Action = (LegalizeAction) 462 ((CondCodeActions[CC] >> (2*VT.getSimpleVT().SimpleTy)) & 3); 463 assert(Action != Promote && "Can't promote condition code!"); 464 return Action; 465 } 466 467 /// isCondCodeLegal - Return true if the specified condition code is legal 468 /// on this target. 469 bool isCondCodeLegal(ISD::CondCode CC, EVT VT) const { 470 return getCondCodeAction(CC, VT) == Legal || 471 getCondCodeAction(CC, VT) == Custom; 472 } 473 474 475 /// getTypeToPromoteTo - If the action for this operation is to promote, this 476 /// method returns the ValueType to promote to. 477 EVT getTypeToPromoteTo(unsigned Op, EVT VT) const { 478 assert(getOperationAction(Op, VT) == Promote && 479 "This operation isn't promoted!"); 480 481 // See if this has an explicit type specified. 482 std::map<std::pair<unsigned, MVT::SimpleValueType>, 483 MVT::SimpleValueType>::const_iterator PTTI = 484 PromoteToType.find(std::make_pair(Op, VT.getSimpleVT().SimpleTy)); 485 if (PTTI != PromoteToType.end()) return PTTI->second; 486 487 assert((VT.isInteger() || VT.isFloatingPoint()) && 488 "Cannot autopromote this type, add it with AddPromotedToType."); 489 490 EVT NVT = VT; 491 do { 492 NVT = (MVT::SimpleValueType)(NVT.getSimpleVT().SimpleTy+1); 493 assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid && 494 "Didn't find type to promote to!"); 495 } while (!isTypeLegal(NVT) || 496 getOperationAction(Op, NVT) == Promote); 497 return NVT; 498 } 499 500 /// getValueType - Return the EVT corresponding to this LLVM type. 501 /// This is fixed by the LLVM operations except for the pointer size. If 502 /// AllowUnknown is true, this will return MVT::Other for types with no EVT 503 /// counterpart (e.g. structs), otherwise it will assert. 504 EVT getValueType(const Type *Ty, bool AllowUnknown = false) const { 505 EVT VT = EVT::getEVT(Ty, AllowUnknown); 506 return VT == MVT::iPTR ? PointerTy : VT; 507 } 508 509 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate 510 /// function arguments in the caller parameter area. This is the actual 511 /// alignment, not its logarithm. 512 virtual unsigned getByValTypeAlignment(const Type *Ty) const; 513 514 /// getRegisterType - Return the type of registers that this ValueType will 515 /// eventually require. 516 EVT getRegisterType(MVT VT) const { 517 assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT)); 518 return RegisterTypeForVT[VT.SimpleTy]; 519 } 520 521 /// getRegisterType - Return the type of registers that this ValueType will 522 /// eventually require. 523 EVT getRegisterType(LLVMContext &Context, EVT VT) const { 524 if (VT.isSimple()) { 525 assert((unsigned)VT.getSimpleVT().SimpleTy < 526 array_lengthof(RegisterTypeForVT)); 527 return RegisterTypeForVT[VT.getSimpleVT().SimpleTy]; 528 } 529 if (VT.isVector()) { 530 EVT VT1, RegisterVT; 531 unsigned NumIntermediates; 532 (void)getVectorTypeBreakdown(Context, VT, VT1, 533 NumIntermediates, RegisterVT); 534 return RegisterVT; 535 } 536 if (VT.isInteger()) { 537 return getRegisterType(Context, getTypeToTransformTo(Context, VT)); 538 } 539 assert(0 && "Unsupported extended type!"); 540 return EVT(MVT::Other); // Not reached 541 } 542 543 /// getNumRegisters - Return the number of registers that this ValueType will 544 /// eventually require. This is one for any types promoted to live in larger 545 /// registers, but may be more than one for types (like i64) that are split 546 /// into pieces. For types like i140, which are first promoted then expanded, 547 /// it is the number of registers needed to hold all the bits of the original 548 /// type. For an i140 on a 32 bit machine this means 5 registers. 549 unsigned getNumRegisters(LLVMContext &Context, EVT VT) const { 550 if (VT.isSimple()) { 551 assert((unsigned)VT.getSimpleVT().SimpleTy < 552 array_lengthof(NumRegistersForVT)); 553 return NumRegistersForVT[VT.getSimpleVT().SimpleTy]; 554 } 555 if (VT.isVector()) { 556 EVT VT1, VT2; 557 unsigned NumIntermediates; 558 return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2); 559 } 560 if (VT.isInteger()) { 561 unsigned BitWidth = VT.getSizeInBits(); 562 unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits(); 563 return (BitWidth + RegWidth - 1) / RegWidth; 564 } 565 assert(0 && "Unsupported extended type!"); 566 return 0; // Not reached 567 } 568 569 /// ShouldShrinkFPConstant - If true, then instruction selection should 570 /// seek to shrink the FP constant of the specified type to a smaller type 571 /// in order to save space and / or reduce runtime. 572 virtual bool ShouldShrinkFPConstant(EVT VT) const { return true; } 573 574 /// hasTargetDAGCombine - If true, the target has custom DAG combine 575 /// transformations that it can perform for the specified node. 576 bool hasTargetDAGCombine(ISD::NodeType NT) const { 577 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)); 578 return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7)); 579 } 580 581 /// This function returns the maximum number of store operations permitted 582 /// to replace a call to llvm.memset. The value is set by the target at the 583 /// performance threshold for such a replacement. If OptSize is true, 584 /// return the limit for functions that have OptSize attribute. 585 /// @brief Get maximum # of store operations permitted for llvm.memset 586 unsigned getMaxStoresPerMemset(bool OptSize) const { 587 return OptSize ? maxStoresPerMemsetOptSize : maxStoresPerMemset; 588 } 589 590 /// This function returns the maximum number of store operations permitted 591 /// to replace a call to llvm.memcpy. The value is set by the target at the 592 /// performance threshold for such a replacement. If OptSize is true, 593 /// return the limit for functions that have OptSize attribute. 594 /// @brief Get maximum # of store operations permitted for llvm.memcpy 595 unsigned getMaxStoresPerMemcpy(bool OptSize) const { 596 return OptSize ? maxStoresPerMemcpyOptSize : maxStoresPerMemcpy; 597 } 598 599 /// This function returns the maximum number of store operations permitted 600 /// to replace a call to llvm.memmove. The value is set by the target at the 601 /// performance threshold for such a replacement. If OptSize is true, 602 /// return the limit for functions that have OptSize attribute. 603 /// @brief Get maximum # of store operations permitted for llvm.memmove 604 unsigned getMaxStoresPerMemmove(bool OptSize) const { 605 return OptSize ? maxStoresPerMemmoveOptSize : maxStoresPerMemmove; 606 } 607 608 /// This function returns true if the target allows unaligned memory accesses. 609 /// of the specified type. This is used, for example, in situations where an 610 /// array copy/move/set is converted to a sequence of store operations. It's 611 /// use helps to ensure that such replacements don't generate code that causes 612 /// an alignment error (trap) on the target machine. 613 /// @brief Determine if the target supports unaligned memory accesses. 614 virtual bool allowsUnalignedMemoryAccesses(EVT VT) const { 615 return false; 616 } 617 618 /// This function returns true if the target would benefit from code placement 619 /// optimization. 620 /// @brief Determine if the target should perform code placement optimization. 621 bool shouldOptimizeCodePlacement() const { 622 return benefitFromCodePlacementOpt; 623 } 624 625 /// getOptimalMemOpType - Returns the target specific optimal type for load 626 /// and store operations as a result of memset, memcpy, and memmove 627 /// lowering. If DstAlign is zero that means it's safe to destination 628 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it 629 /// means there isn't a need to check it against alignment requirement, 630 /// probably because the source does not need to be loaded. If 631 /// 'NonScalarIntSafe' is true, that means it's safe to return a 632 /// non-scalar-integer type, e.g. empty string source, constant, or loaded 633 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is 634 /// constant so it does not need to be loaded. 635 /// It returns EVT::Other if the type should be determined using generic 636 /// target-independent logic. 637 virtual EVT getOptimalMemOpType(uint64_t Size, 638 unsigned DstAlign, unsigned SrcAlign, 639 bool NonScalarIntSafe, bool MemcpyStrSrc, 640 MachineFunction &MF) const { 641 return MVT::Other; 642 } 643 644 /// usesUnderscoreSetJmp - Determine if we should use _setjmp or setjmp 645 /// to implement llvm.setjmp. 646 bool usesUnderscoreSetJmp() const { 647 return UseUnderscoreSetJmp; 648 } 649 650 /// usesUnderscoreLongJmp - Determine if we should use _longjmp or longjmp 651 /// to implement llvm.longjmp. 652 bool usesUnderscoreLongJmp() const { 653 return UseUnderscoreLongJmp; 654 } 655 656 /// getStackPointerRegisterToSaveRestore - If a physical register, this 657 /// specifies the register that llvm.savestack/llvm.restorestack should save 658 /// and restore. 659 unsigned getStackPointerRegisterToSaveRestore() const { 660 return StackPointerRegisterToSaveRestore; 661 } 662 663 /// getExceptionAddressRegister - If a physical register, this returns 664 /// the register that receives the exception address on entry to a landing 665 /// pad. 666 unsigned getExceptionAddressRegister() const { 667 return ExceptionPointerRegister; 668 } 669 670 /// getExceptionSelectorRegister - If a physical register, this returns 671 /// the register that receives the exception typeid on entry to a landing 672 /// pad. 673 unsigned getExceptionSelectorRegister() const { 674 return ExceptionSelectorRegister; 675 } 676 677 /// getJumpBufSize - returns the target's jmp_buf size in bytes (if never 678 /// set, the default is 200) 679 unsigned getJumpBufSize() const { 680 return JumpBufSize; 681 } 682 683 /// getJumpBufAlignment - returns the target's jmp_buf alignment in bytes 684 /// (if never set, the default is 0) 685 unsigned getJumpBufAlignment() const { 686 return JumpBufAlignment; 687 } 688 689 /// getMinStackArgumentAlignment - return the minimum stack alignment of an 690 /// argument. 691 unsigned getMinStackArgumentAlignment() const { 692 return MinStackArgumentAlignment; 693 } 694 695 /// getMinFunctionAlignment - return the minimum function alignment. 696 /// 697 unsigned getMinFunctionAlignment() const { 698 return MinFunctionAlignment; 699 } 700 701 /// getPrefFunctionAlignment - return the preferred function alignment. 702 /// 703 unsigned getPrefFunctionAlignment() const { 704 return PrefFunctionAlignment; 705 } 706 707 /// getPrefLoopAlignment - return the preferred loop alignment. 708 /// 709 unsigned getPrefLoopAlignment() const { 710 return PrefLoopAlignment; 711 } 712 713 /// getShouldFoldAtomicFences - return whether the combiner should fold 714 /// fence MEMBARRIER instructions into the atomic intrinsic instructions. 715 /// 716 bool getShouldFoldAtomicFences() const { 717 return ShouldFoldAtomicFences; 718 } 719 720 /// getPreIndexedAddressParts - returns true by value, base pointer and 721 /// offset pointer and addressing mode by reference if the node's address 722 /// can be legally represented as pre-indexed load / store address. 723 virtual bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, 724 SDValue &Offset, 725 ISD::MemIndexedMode &AM, 726 SelectionDAG &DAG) const { 727 return false; 728 } 729 730 /// getPostIndexedAddressParts - returns true by value, base pointer and 731 /// offset pointer and addressing mode by reference if this node can be 732 /// combined with a load / store to form a post-indexed load / store. 733 virtual bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, 734 SDValue &Base, SDValue &Offset, 735 ISD::MemIndexedMode &AM, 736 SelectionDAG &DAG) const { 737 return false; 738 } 739 740 /// getJumpTableEncoding - Return the entry encoding for a jump table in the 741 /// current function. The returned value is a member of the 742 /// MachineJumpTableInfo::JTEntryKind enum. 743 virtual unsigned getJumpTableEncoding() const; 744 745 virtual const MCExpr * 746 LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI, 747 const MachineBasicBlock *MBB, unsigned uid, 748 MCContext &Ctx) const { 749 assert(0 && "Need to implement this hook if target has custom JTIs"); 750 return 0; 751 } 752 753 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC 754 /// jumptable. 755 virtual SDValue getPICJumpTableRelocBase(SDValue Table, 756 SelectionDAG &DAG) const; 757 758 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 759 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 760 /// MCExpr. 761 virtual const MCExpr * 762 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 763 unsigned JTI, MCContext &Ctx) const; 764 765 /// isOffsetFoldingLegal - Return true if folding a constant offset 766 /// with the given GlobalAddress is legal. It is frequently not legal in 767 /// PIC relocation models. 768 virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const; 769 770 /// getStackCookieLocation - Return true if the target stores stack 771 /// protector cookies at a fixed offset in some non-standard address 772 /// space, and populates the address space and offset as 773 /// appropriate. 774 virtual bool getStackCookieLocation(unsigned &AddressSpace, unsigned &Offset) const { 775 return false; 776 } 777 778 /// getMaximalGlobalOffset - Returns the maximal possible offset which can be 779 /// used for loads / stores from the global. 780 virtual unsigned getMaximalGlobalOffset() const { 781 return 0; 782 } 783 784 //===--------------------------------------------------------------------===// 785 // TargetLowering Optimization Methods 786 // 787 788 /// TargetLoweringOpt - A convenience struct that encapsulates a DAG, and two 789 /// SDValues for returning information from TargetLowering to its clients 790 /// that want to combine 791 struct TargetLoweringOpt { 792 SelectionDAG &DAG; 793 bool LegalTys; 794 bool LegalOps; 795 SDValue Old; 796 SDValue New; 797 798 explicit TargetLoweringOpt(SelectionDAG &InDAG, 799 bool LT, bool LO) : 800 DAG(InDAG), LegalTys(LT), LegalOps(LO) {} 801 802 bool LegalTypes() const { return LegalTys; } 803 bool LegalOperations() const { return LegalOps; } 804 805 bool CombineTo(SDValue O, SDValue N) { 806 Old = O; 807 New = N; 808 return true; 809 } 810 811 /// ShrinkDemandedConstant - Check to see if the specified operand of the 812 /// specified instruction is a constant integer. If so, check to see if 813 /// there are any bits set in the constant that are not demanded. If so, 814 /// shrink the constant and return true. 815 bool ShrinkDemandedConstant(SDValue Op, const APInt &Demanded); 816 817 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the 818 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening 819 /// cast, but it could be generalized for targets with other types of 820 /// implicit widening casts. 821 bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded, 822 DebugLoc dl); 823 }; 824 825 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the 826 /// DemandedMask bits of the result of Op are ever used downstream. If we can 827 /// use this information to simplify Op, create a new simplified DAG node and 828 /// return true, returning the original and new nodes in Old and New. 829 /// Otherwise, analyze the expression and return a mask of KnownOne and 830 /// KnownZero bits for the expression (used to simplify the caller). 831 /// The KnownZero/One bits may only be accurate for those bits in the 832 /// DemandedMask. 833 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedMask, 834 APInt &KnownZero, APInt &KnownOne, 835 TargetLoweringOpt &TLO, unsigned Depth = 0) const; 836 837 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in 838 /// Mask are known to be either zero or one and return them in the 839 /// KnownZero/KnownOne bitsets. 840 virtual void computeMaskedBitsForTargetNode(const SDValue Op, 841 const APInt &Mask, 842 APInt &KnownZero, 843 APInt &KnownOne, 844 const SelectionDAG &DAG, 845 unsigned Depth = 0) const; 846 847 /// ComputeNumSignBitsForTargetNode - This method can be implemented by 848 /// targets that want to expose additional information about sign bits to the 849 /// DAG Combiner. 850 virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op, 851 unsigned Depth = 0) const; 852 853 struct DAGCombinerInfo { 854 void *DC; // The DAG Combiner object. 855 bool BeforeLegalize; 856 bool BeforeLegalizeOps; 857 bool CalledByLegalizer; 858 public: 859 SelectionDAG &DAG; 860 861 DAGCombinerInfo(SelectionDAG &dag, bool bl, bool blo, bool cl, void *dc) 862 : DC(dc), BeforeLegalize(bl), BeforeLegalizeOps(blo), 863 CalledByLegalizer(cl), DAG(dag) {} 864 865 bool isBeforeLegalize() const { return BeforeLegalize; } 866 bool isBeforeLegalizeOps() const { return BeforeLegalizeOps; } 867 bool isCalledByLegalizer() const { return CalledByLegalizer; } 868 869 void AddToWorklist(SDNode *N); 870 void RemoveFromWorklist(SDNode *N); 871 SDValue CombineTo(SDNode *N, const std::vector<SDValue> &To, 872 bool AddTo = true); 873 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true); 874 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true); 875 876 void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO); 877 }; 878 879 /// SimplifySetCC - Try to simplify a setcc built with the specified operands 880 /// and cc. If it is unable to simplify it, return a null SDValue. 881 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 882 ISD::CondCode Cond, bool foldBooleans, 883 DAGCombinerInfo &DCI, DebugLoc dl) const; 884 885 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 886 /// node is a GlobalAddress + offset. 887 virtual bool 888 isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const; 889 890 /// PerformDAGCombine - This method will be invoked for all target nodes and 891 /// for any target-independent nodes that the target has registered with 892 /// invoke it for. 893 /// 894 /// The semantics are as follows: 895 /// Return Value: 896 /// SDValue.Val == 0 - No change was made 897 /// SDValue.Val == N - N was replaced, is dead, and is already handled. 898 /// otherwise - N should be replaced by the returned Operand. 899 /// 900 /// In addition, methods provided by DAGCombinerInfo may be used to perform 901 /// more complex transformations. 902 /// 903 virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const; 904 905 /// isTypeDesirableForOp - Return true if the target has native support for 906 /// the specified value type and it is 'desirable' to use the type for the 907 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16 908 /// instruction encodings are longer and some i16 instructions are slow. 909 virtual bool isTypeDesirableForOp(unsigned Opc, EVT VT) const { 910 // By default, assume all legal types are desirable. 911 return isTypeLegal(VT); 912 } 913 914 /// isDesirableToPromoteOp - Return true if it is profitable for dag combiner 915 /// to transform a floating point op of specified opcode to a equivalent op of 916 /// an integer type. e.g. f32 load -> i32 load can be profitable on ARM. 917 virtual bool isDesirableToTransformToIntegerOp(unsigned Opc, EVT VT) const { 918 return false; 919 } 920 921 /// IsDesirableToPromoteOp - This method query the target whether it is 922 /// beneficial for dag combiner to promote the specified node. If true, it 923 /// should return the desired promotion type by reference. 924 virtual bool IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const { 925 return false; 926 } 927 928 //===--------------------------------------------------------------------===// 929 // TargetLowering Configuration Methods - These methods should be invoked by 930 // the derived class constructor to configure this object for the target. 931 // 932 933protected: 934 /// setBooleanContents - Specify how the target extends the result of a 935 /// boolean value from i1 to a wider type. See getBooleanContents. 936 void setBooleanContents(BooleanContent Ty) { BooleanContents = Ty; } 937 938 /// setSchedulingPreference - Specify the target scheduling preference. 939 void setSchedulingPreference(Sched::Preference Pref) { 940 SchedPreferenceInfo = Pref; 941 } 942 943 /// setUseUnderscoreSetJmp - Indicate whether this target prefers to 944 /// use _setjmp to implement llvm.setjmp or the non _ version. 945 /// Defaults to false. 946 void setUseUnderscoreSetJmp(bool Val) { 947 UseUnderscoreSetJmp = Val; 948 } 949 950 /// setUseUnderscoreLongJmp - Indicate whether this target prefers to 951 /// use _longjmp to implement llvm.longjmp or the non _ version. 952 /// Defaults to false. 953 void setUseUnderscoreLongJmp(bool Val) { 954 UseUnderscoreLongJmp = Val; 955 } 956 957 /// setStackPointerRegisterToSaveRestore - If set to a physical register, this 958 /// specifies the register that llvm.savestack/llvm.restorestack should save 959 /// and restore. 960 void setStackPointerRegisterToSaveRestore(unsigned R) { 961 StackPointerRegisterToSaveRestore = R; 962 } 963 964 /// setExceptionPointerRegister - If set to a physical register, this sets 965 /// the register that receives the exception address on entry to a landing 966 /// pad. 967 void setExceptionPointerRegister(unsigned R) { 968 ExceptionPointerRegister = R; 969 } 970 971 /// setExceptionSelectorRegister - If set to a physical register, this sets 972 /// the register that receives the exception typeid on entry to a landing 973 /// pad. 974 void setExceptionSelectorRegister(unsigned R) { 975 ExceptionSelectorRegister = R; 976 } 977 978 /// SelectIsExpensive - Tells the code generator not to expand operations 979 /// into sequences that use the select operations if possible. 980 void setSelectIsExpensive(bool isExpensive = true) { 981 SelectIsExpensive = isExpensive; 982 } 983 984 /// JumpIsExpensive - Tells the code generator not to expand sequence of 985 /// operations into a separate sequences that increases the amount of 986 /// flow control. 987 void setJumpIsExpensive(bool isExpensive = true) { 988 JumpIsExpensive = isExpensive; 989 } 990 991 /// setIntDivIsCheap - Tells the code generator that integer divide is 992 /// expensive, and if possible, should be replaced by an alternate sequence 993 /// of instructions not containing an integer divide. 994 void setIntDivIsCheap(bool isCheap = true) { IntDivIsCheap = isCheap; } 995 996 /// setPow2DivIsCheap - Tells the code generator that it shouldn't generate 997 /// srl/add/sra for a signed divide by power of two, and let the target handle 998 /// it. 999 void setPow2DivIsCheap(bool isCheap = true) { Pow2DivIsCheap = isCheap; } 1000 1001 /// addRegisterClass - Add the specified register class as an available 1002 /// regclass for the specified value type. This indicates the selector can 1003 /// handle values of that class natively. 1004 void addRegisterClass(EVT VT, TargetRegisterClass *RC) { 1005 assert((unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT)); 1006 AvailableRegClasses.push_back(std::make_pair(VT, RC)); 1007 RegClassForVT[VT.getSimpleVT().SimpleTy] = RC; 1008 } 1009 1010 /// findRepresentativeClass - Return the largest legal super-reg register class 1011 /// of the register class for the specified type and its associated "cost". 1012 virtual std::pair<const TargetRegisterClass*, uint8_t> 1013 findRepresentativeClass(EVT VT) const; 1014 1015 /// computeRegisterProperties - Once all of the register classes are added, 1016 /// this allows us to compute derived properties we expose. 1017 void computeRegisterProperties(); 1018 1019 /// setOperationAction - Indicate that the specified operation does not work 1020 /// with the specified type and indicate what to do about it. 1021 void setOperationAction(unsigned Op, MVT VT, 1022 LegalizeAction Action) { 1023 assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!"); 1024 OpActions[(unsigned)VT.SimpleTy][Op] = (uint8_t)Action; 1025 } 1026 1027 /// setLoadExtAction - Indicate that the specified load with extension does 1028 /// not work with the specified type and indicate what to do about it. 1029 void setLoadExtAction(unsigned ExtType, MVT VT, 1030 LegalizeAction Action) { 1031 assert(ExtType < ISD::LAST_LOADEXT_TYPE && VT < MVT::LAST_VALUETYPE && 1032 "Table isn't big enough!"); 1033 LoadExtActions[VT.SimpleTy][ExtType] = (uint8_t)Action; 1034 } 1035 1036 /// setTruncStoreAction - Indicate that the specified truncating store does 1037 /// not work with the specified type and indicate what to do about it. 1038 void setTruncStoreAction(MVT ValVT, MVT MemVT, 1039 LegalizeAction Action) { 1040 assert(ValVT < MVT::LAST_VALUETYPE && MemVT < MVT::LAST_VALUETYPE && 1041 "Table isn't big enough!"); 1042 TruncStoreActions[ValVT.SimpleTy][MemVT.SimpleTy] = (uint8_t)Action; 1043 } 1044 1045 /// setIndexedLoadAction - Indicate that the specified indexed load does or 1046 /// does not work with the specified type and indicate what to do abort 1047 /// it. NOTE: All indexed mode loads are initialized to Expand in 1048 /// TargetLowering.cpp 1049 void setIndexedLoadAction(unsigned IdxMode, MVT VT, 1050 LegalizeAction Action) { 1051 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE && 1052 (unsigned)Action < 0xf && "Table isn't big enough!"); 1053 // Load action are kept in the upper half. 1054 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0xf0; 1055 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action) <<4; 1056 } 1057 1058 /// setIndexedStoreAction - Indicate that the specified indexed store does or 1059 /// does not work with the specified type and indicate what to do about 1060 /// it. NOTE: All indexed mode stores are initialized to Expand in 1061 /// TargetLowering.cpp 1062 void setIndexedStoreAction(unsigned IdxMode, MVT VT, 1063 LegalizeAction Action) { 1064 assert(VT < MVT::LAST_VALUETYPE && IdxMode < ISD::LAST_INDEXED_MODE && 1065 (unsigned)Action < 0xf && "Table isn't big enough!"); 1066 // Store action are kept in the lower half. 1067 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] &= ~0x0f; 1068 IndexedModeActions[(unsigned)VT.SimpleTy][IdxMode] |= ((uint8_t)Action); 1069 } 1070 1071 /// setCondCodeAction - Indicate that the specified condition code is or isn't 1072 /// supported on the target and indicate what to do about it. 1073 void setCondCodeAction(ISD::CondCode CC, MVT VT, 1074 LegalizeAction Action) { 1075 assert(VT < MVT::LAST_VALUETYPE && 1076 (unsigned)CC < array_lengthof(CondCodeActions) && 1077 "Table isn't big enough!"); 1078 CondCodeActions[(unsigned)CC] &= ~(uint64_t(3UL) << VT.SimpleTy*2); 1079 CondCodeActions[(unsigned)CC] |= (uint64_t)Action << VT.SimpleTy*2; 1080 } 1081 1082 /// AddPromotedToType - If Opc/OrigVT is specified as being promoted, the 1083 /// promotion code defaults to trying a larger integer/fp until it can find 1084 /// one that works. If that default is insufficient, this method can be used 1085 /// by the target to override the default. 1086 void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) { 1087 PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy; 1088 } 1089 1090 /// setTargetDAGCombine - Targets should invoke this method for each target 1091 /// independent node that they want to provide a custom DAG combiner for by 1092 /// implementing the PerformDAGCombine virtual method. 1093 void setTargetDAGCombine(ISD::NodeType NT) { 1094 assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray)); 1095 TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7); 1096 } 1097 1098 /// setJumpBufSize - Set the target's required jmp_buf buffer size (in 1099 /// bytes); default is 200 1100 void setJumpBufSize(unsigned Size) { 1101 JumpBufSize = Size; 1102 } 1103 1104 /// setJumpBufAlignment - Set the target's required jmp_buf buffer 1105 /// alignment (in bytes); default is 0 1106 void setJumpBufAlignment(unsigned Align) { 1107 JumpBufAlignment = Align; 1108 } 1109 1110 /// setMinFunctionAlignment - Set the target's minimum function alignment. 1111 void setMinFunctionAlignment(unsigned Align) { 1112 MinFunctionAlignment = Align; 1113 } 1114 1115 /// setPrefFunctionAlignment - Set the target's preferred function alignment. 1116 /// This should be set if there is a performance benefit to 1117 /// higher-than-minimum alignment 1118 void setPrefFunctionAlignment(unsigned Align) { 1119 PrefFunctionAlignment = Align; 1120 } 1121 1122 /// setPrefLoopAlignment - Set the target's preferred loop alignment. Default 1123 /// alignment is zero, it means the target does not care about loop alignment. 1124 void setPrefLoopAlignment(unsigned Align) { 1125 PrefLoopAlignment = Align; 1126 } 1127 1128 /// setMinStackArgumentAlignment - Set the minimum stack alignment of an 1129 /// argument. 1130 void setMinStackArgumentAlignment(unsigned Align) { 1131 MinStackArgumentAlignment = Align; 1132 } 1133 1134 /// setShouldFoldAtomicFences - Set if the target's implementation of the 1135 /// atomic operation intrinsics includes locking. Default is false. 1136 void setShouldFoldAtomicFences(bool fold) { 1137 ShouldFoldAtomicFences = fold; 1138 } 1139 1140public: 1141 //===--------------------------------------------------------------------===// 1142 // Lowering methods - These methods must be implemented by targets so that 1143 // the SelectionDAGLowering code knows how to lower these. 1144 // 1145 1146 /// LowerFormalArguments - This hook must be implemented to lower the 1147 /// incoming (formal) arguments, described by the Ins array, into the 1148 /// specified DAG. The implementation should fill in the InVals array 1149 /// with legal-type argument values, and return the resulting token 1150 /// chain value. 1151 /// 1152 virtual SDValue 1153 LowerFormalArguments(SDValue Chain, 1154 CallingConv::ID CallConv, bool isVarArg, 1155 const SmallVectorImpl<ISD::InputArg> &Ins, 1156 DebugLoc dl, SelectionDAG &DAG, 1157 SmallVectorImpl<SDValue> &InVals) const { 1158 assert(0 && "Not Implemented"); 1159 return SDValue(); // this is here to silence compiler errors 1160 } 1161 1162 /// LowerCallTo - This function lowers an abstract call to a function into an 1163 /// actual call. This returns a pair of operands. The first element is the 1164 /// return value for the function (if RetTy is not VoidTy). The second 1165 /// element is the outgoing token chain. It calls LowerCall to do the actual 1166 /// lowering. 1167 struct ArgListEntry { 1168 SDValue Node; 1169 const Type* Ty; 1170 bool isSExt : 1; 1171 bool isZExt : 1; 1172 bool isInReg : 1; 1173 bool isSRet : 1; 1174 bool isNest : 1; 1175 bool isByVal : 1; 1176 uint16_t Alignment; 1177 1178 ArgListEntry() : isSExt(false), isZExt(false), isInReg(false), 1179 isSRet(false), isNest(false), isByVal(false), Alignment(0) { } 1180 }; 1181 typedef std::vector<ArgListEntry> ArgListTy; 1182 std::pair<SDValue, SDValue> 1183 LowerCallTo(SDValue Chain, const Type *RetTy, bool RetSExt, bool RetZExt, 1184 bool isVarArg, bool isInreg, unsigned NumFixedArgs, 1185 CallingConv::ID CallConv, bool isTailCall, 1186 bool isReturnValueUsed, SDValue Callee, ArgListTy &Args, 1187 SelectionDAG &DAG, DebugLoc dl) const; 1188 1189 /// LowerCall - This hook must be implemented to lower calls into the 1190 /// the specified DAG. The outgoing arguments to the call are described 1191 /// by the Outs array, and the values to be returned by the call are 1192 /// described by the Ins array. The implementation should fill in the 1193 /// InVals array with legal-type return values from the call, and return 1194 /// the resulting token chain value. 1195 virtual SDValue 1196 LowerCall(SDValue Chain, SDValue Callee, 1197 CallingConv::ID CallConv, bool isVarArg, bool &isTailCall, 1198 const SmallVectorImpl<ISD::OutputArg> &Outs, 1199 const SmallVectorImpl<SDValue> &OutVals, 1200 const SmallVectorImpl<ISD::InputArg> &Ins, 1201 DebugLoc dl, SelectionDAG &DAG, 1202 SmallVectorImpl<SDValue> &InVals) const { 1203 assert(0 && "Not Implemented"); 1204 return SDValue(); // this is here to silence compiler errors 1205 } 1206 1207 /// HandleByVal - Target-specific cleanup for formal ByVal parameters. 1208 virtual void HandleByVal(CCState *, unsigned &) const {} 1209 1210 /// CanLowerReturn - This hook should be implemented to check whether the 1211 /// return values described by the Outs array can fit into the return 1212 /// registers. If false is returned, an sret-demotion is performed. 1213 /// 1214 virtual bool CanLowerReturn(CallingConv::ID CallConv, bool isVarArg, 1215 const SmallVectorImpl<ISD::OutputArg> &Outs, 1216 LLVMContext &Context) const 1217 { 1218 // Return true by default to get preexisting behavior. 1219 return true; 1220 } 1221 1222 /// LowerReturn - This hook must be implemented to lower outgoing 1223 /// return values, described by the Outs array, into the specified 1224 /// DAG. The implementation should return the resulting token chain 1225 /// value. 1226 /// 1227 virtual SDValue 1228 LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1229 const SmallVectorImpl<ISD::OutputArg> &Outs, 1230 const SmallVectorImpl<SDValue> &OutVals, 1231 DebugLoc dl, SelectionDAG &DAG) const { 1232 assert(0 && "Not Implemented"); 1233 return SDValue(); // this is here to silence compiler errors 1234 } 1235 1236 /// isUsedByReturnOnly - Return true if result of the specified node is used 1237 /// by a return node only. This is used to determine whether it is possible 1238 /// to codegen a libcall as tail call at legalization time. 1239 virtual bool isUsedByReturnOnly(SDNode *N) const { 1240 return false; 1241 } 1242 1243 /// mayBeEmittedAsTailCall - Return true if the target may be able emit the 1244 /// call instruction as a tail call. This is used by optimization passes to 1245 /// determine if it's profitable to duplicate return instructions to enable 1246 /// tailcall optimization. 1247 virtual bool mayBeEmittedAsTailCall(CallInst *CI) const { 1248 return false; 1249 } 1250 1251 /// getTypeForExtArgOrReturn - Return the type that should be used to zero or 1252 /// sign extend a zeroext/signext integer argument or return value. 1253 /// FIXME: Most C calling convention requires the return type to be promoted, 1254 /// but this is not true all the time, e.g. i1 on x86-64. It is also not 1255 /// necessary for non-C calling conventions. The frontend should handle this 1256 /// and include all of the necessary information. 1257 virtual EVT getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT, 1258 ISD::NodeType ExtendKind) const { 1259 EVT MinVT = getRegisterType(Context, MVT::i32); 1260 return VT.bitsLT(MinVT) ? MinVT : VT; 1261 } 1262 1263 /// LowerOperationWrapper - This callback is invoked by the type legalizer 1264 /// to legalize nodes with an illegal operand type but legal result types. 1265 /// It replaces the LowerOperation callback in the type Legalizer. 1266 /// The reason we can not do away with LowerOperation entirely is that 1267 /// LegalizeDAG isn't yet ready to use this callback. 1268 /// TODO: Consider merging with ReplaceNodeResults. 1269 1270 /// The target places new result values for the node in Results (their number 1271 /// and types must exactly match those of the original return values of 1272 /// the node), or leaves Results empty, which indicates that the node is not 1273 /// to be custom lowered after all. 1274 /// The default implementation calls LowerOperation. 1275 virtual void LowerOperationWrapper(SDNode *N, 1276 SmallVectorImpl<SDValue> &Results, 1277 SelectionDAG &DAG) const; 1278 1279 /// LowerOperation - This callback is invoked for operations that are 1280 /// unsupported by the target, which are registered to use 'custom' lowering, 1281 /// and whose defined values are all legal. 1282 /// If the target has no operations that require custom lowering, it need not 1283 /// implement this. The default implementation of this aborts. 1284 virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const; 1285 1286 /// ReplaceNodeResults - This callback is invoked when a node result type is 1287 /// illegal for the target, and the operation was registered to use 'custom' 1288 /// lowering for that result type. The target places new result values for 1289 /// the node in Results (their number and types must exactly match those of 1290 /// the original return values of the node), or leaves Results empty, which 1291 /// indicates that the node is not to be custom lowered after all. 1292 /// 1293 /// If the target has no operations that require custom lowering, it need not 1294 /// implement this. The default implementation aborts. 1295 virtual void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 1296 SelectionDAG &DAG) const { 1297 assert(0 && "ReplaceNodeResults not implemented for this target!"); 1298 } 1299 1300 /// getTargetNodeName() - This method returns the name of a target specific 1301 /// DAG node. 1302 virtual const char *getTargetNodeName(unsigned Opcode) const; 1303 1304 /// createFastISel - This method returns a target specific FastISel object, 1305 /// or null if the target does not support "fast" ISel. 1306 virtual FastISel *createFastISel(FunctionLoweringInfo &funcInfo) const { 1307 return 0; 1308 } 1309 1310 //===--------------------------------------------------------------------===// 1311 // Inline Asm Support hooks 1312 // 1313 1314 /// ExpandInlineAsm - This hook allows the target to expand an inline asm 1315 /// call to be explicit llvm code if it wants to. This is useful for 1316 /// turning simple inline asms into LLVM intrinsics, which gives the 1317 /// compiler more information about the behavior of the code. 1318 virtual bool ExpandInlineAsm(CallInst *CI) const { 1319 return false; 1320 } 1321 1322 enum ConstraintType { 1323 C_Register, // Constraint represents specific register(s). 1324 C_RegisterClass, // Constraint represents any of register(s) in class. 1325 C_Memory, // Memory constraint. 1326 C_Other, // Something else. 1327 C_Unknown // Unsupported constraint. 1328 }; 1329 1330 enum ConstraintWeight { 1331 // Generic weights. 1332 CW_Invalid = -1, // No match. 1333 CW_Okay = 0, // Acceptable. 1334 CW_Good = 1, // Good weight. 1335 CW_Better = 2, // Better weight. 1336 CW_Best = 3, // Best weight. 1337 1338 // Well-known weights. 1339 CW_SpecificReg = CW_Okay, // Specific register operands. 1340 CW_Register = CW_Good, // Register operands. 1341 CW_Memory = CW_Better, // Memory operands. 1342 CW_Constant = CW_Best, // Constant operand. 1343 CW_Default = CW_Okay // Default or don't know type. 1344 }; 1345 1346 /// AsmOperandInfo - This contains information for each constraint that we are 1347 /// lowering. 1348 struct AsmOperandInfo : public InlineAsm::ConstraintInfo { 1349 /// ConstraintCode - This contains the actual string for the code, like "m". 1350 /// TargetLowering picks the 'best' code from ConstraintInfo::Codes that 1351 /// most closely matches the operand. 1352 std::string ConstraintCode; 1353 1354 /// ConstraintType - Information about the constraint code, e.g. Register, 1355 /// RegisterClass, Memory, Other, Unknown. 1356 TargetLowering::ConstraintType ConstraintType; 1357 1358 /// CallOperandval - If this is the result output operand or a 1359 /// clobber, this is null, otherwise it is the incoming operand to the 1360 /// CallInst. This gets modified as the asm is processed. 1361 Value *CallOperandVal; 1362 1363 /// ConstraintVT - The ValueType for the operand value. 1364 EVT ConstraintVT; 1365 1366 /// isMatchingInputConstraint - Return true of this is an input operand that 1367 /// is a matching constraint like "4". 1368 bool isMatchingInputConstraint() const; 1369 1370 /// getMatchedOperand - If this is an input matching constraint, this method 1371 /// returns the output operand it matches. 1372 unsigned getMatchedOperand() const; 1373 1374 /// Copy constructor for copying from an AsmOperandInfo. 1375 AsmOperandInfo(const AsmOperandInfo &info) 1376 : InlineAsm::ConstraintInfo(info), 1377 ConstraintCode(info.ConstraintCode), 1378 ConstraintType(info.ConstraintType), 1379 CallOperandVal(info.CallOperandVal), 1380 ConstraintVT(info.ConstraintVT) { 1381 } 1382 1383 /// Copy constructor for copying from a ConstraintInfo. 1384 AsmOperandInfo(const InlineAsm::ConstraintInfo &info) 1385 : InlineAsm::ConstraintInfo(info), 1386 ConstraintType(TargetLowering::C_Unknown), 1387 CallOperandVal(0), ConstraintVT(MVT::Other) { 1388 } 1389 }; 1390 1391 typedef std::vector<AsmOperandInfo> AsmOperandInfoVector; 1392 1393 /// ParseConstraints - Split up the constraint string from the inline 1394 /// assembly value into the specific constraints and their prefixes, 1395 /// and also tie in the associated operand values. 1396 /// If this returns an empty vector, and if the constraint string itself 1397 /// isn't empty, there was an error parsing. 1398 virtual AsmOperandInfoVector ParseConstraints(ImmutableCallSite CS) const; 1399 1400 /// Examine constraint type and operand type and determine a weight value. 1401 /// The operand object must already have been set up with the operand type. 1402 virtual ConstraintWeight getMultipleConstraintMatchWeight( 1403 AsmOperandInfo &info, int maIndex) const; 1404 1405 /// Examine constraint string and operand type and determine a weight value. 1406 /// The operand object must already have been set up with the operand type. 1407 virtual ConstraintWeight getSingleConstraintMatchWeight( 1408 AsmOperandInfo &info, const char *constraint) const; 1409 1410 /// ComputeConstraintToUse - Determines the constraint code and constraint 1411 /// type to use for the specific AsmOperandInfo, setting 1412 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. If the actual operand 1413 /// being passed in is available, it can be passed in as Op, otherwise an 1414 /// empty SDValue can be passed. 1415 virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, 1416 SDValue Op, 1417 SelectionDAG *DAG = 0) const; 1418 1419 /// getConstraintType - Given a constraint, return the type of constraint it 1420 /// is for this target. 1421 virtual ConstraintType getConstraintType(const std::string &Constraint) const; 1422 1423 /// getRegClassForInlineAsmConstraint - Given a constraint letter (e.g. "r"), 1424 /// return a list of registers that can be used to satisfy the constraint. 1425 /// This should only be used for C_RegisterClass constraints. 1426 virtual std::vector<unsigned> 1427 getRegClassForInlineAsmConstraint(const std::string &Constraint, 1428 EVT VT) const; 1429 1430 /// getRegForInlineAsmConstraint - Given a physical register constraint (e.g. 1431 /// {edx}), return the register number and the register class for the 1432 /// register. 1433 /// 1434 /// Given a register class constraint, like 'r', if this corresponds directly 1435 /// to an LLVM register class, return a register of 0 and the register class 1436 /// pointer. 1437 /// 1438 /// This should only be used for C_Register constraints. On error, 1439 /// this returns a register number of 0 and a null register class pointer.. 1440 virtual std::pair<unsigned, const TargetRegisterClass*> 1441 getRegForInlineAsmConstraint(const std::string &Constraint, 1442 EVT VT) const; 1443 1444 /// LowerXConstraint - try to replace an X constraint, which matches anything, 1445 /// with another that has more specific requirements based on the type of the 1446 /// corresponding operand. This returns null if there is no replacement to 1447 /// make. 1448 virtual const char *LowerXConstraint(EVT ConstraintVT) const; 1449 1450 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 1451 /// vector. If it is invalid, don't add anything to Ops. 1452 virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint, 1453 std::vector<SDValue> &Ops, 1454 SelectionDAG &DAG) const; 1455 1456 //===--------------------------------------------------------------------===// 1457 // Instruction Emitting Hooks 1458 // 1459 1460 // EmitInstrWithCustomInserter - This method should be implemented by targets 1461 // that mark instructions with the 'usesCustomInserter' flag. These 1462 // instructions are special in various ways, which require special support to 1463 // insert. The specified MachineInstr is created but not inserted into any 1464 // basic blocks, and this method is called to expand it into a sequence of 1465 // instructions, potentially also creating new basic blocks and control flow. 1466 virtual MachineBasicBlock * 1467 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const; 1468 1469 //===--------------------------------------------------------------------===// 1470 // Addressing mode description hooks (used by LSR etc). 1471 // 1472 1473 /// AddrMode - This represents an addressing mode of: 1474 /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg 1475 /// If BaseGV is null, there is no BaseGV. 1476 /// If BaseOffs is zero, there is no base offset. 1477 /// If HasBaseReg is false, there is no base register. 1478 /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with 1479 /// no scale. 1480 /// 1481 struct AddrMode { 1482 GlobalValue *BaseGV; 1483 int64_t BaseOffs; 1484 bool HasBaseReg; 1485 int64_t Scale; 1486 AddrMode() : BaseGV(0), BaseOffs(0), HasBaseReg(false), Scale(0) {} 1487 }; 1488 1489 /// isLegalAddressingMode - Return true if the addressing mode represented by 1490 /// AM is legal for this target, for a load/store of the specified type. 1491 /// The type may be VoidTy, in which case only return true if the addressing 1492 /// mode is legal for a load/store of any legal type. 1493 /// TODO: Handle pre/postinc as well. 1494 virtual bool isLegalAddressingMode(const AddrMode &AM, const Type *Ty) const; 1495 1496 /// isTruncateFree - Return true if it's free to truncate a value of 1497 /// type Ty1 to type Ty2. e.g. On x86 it's free to truncate a i32 value in 1498 /// register EAX to i16 by referencing its sub-register AX. 1499 virtual bool isTruncateFree(const Type *Ty1, const Type *Ty2) const { 1500 return false; 1501 } 1502 1503 virtual bool isTruncateFree(EVT VT1, EVT VT2) const { 1504 return false; 1505 } 1506 1507 /// isZExtFree - Return true if any actual instruction that defines a 1508 /// value of type Ty1 implicitly zero-extends the value to Ty2 in the result 1509 /// register. This does not necessarily include registers defined in 1510 /// unknown ways, such as incoming arguments, or copies from unknown 1511 /// virtual registers. Also, if isTruncateFree(Ty2, Ty1) is true, this 1512 /// does not necessarily apply to truncate instructions. e.g. on x86-64, 1513 /// all instructions that define 32-bit values implicit zero-extend the 1514 /// result out to 64 bits. 1515 virtual bool isZExtFree(const Type *Ty1, const Type *Ty2) const { 1516 return false; 1517 } 1518 1519 virtual bool isZExtFree(EVT VT1, EVT VT2) const { 1520 return false; 1521 } 1522 1523 /// isNarrowingProfitable - Return true if it's profitable to narrow 1524 /// operations of type VT1 to VT2. e.g. on x86, it's profitable to narrow 1525 /// from i32 to i8 but not from i32 to i16. 1526 virtual bool isNarrowingProfitable(EVT VT1, EVT VT2) const { 1527 return false; 1528 } 1529 1530 /// isLegalICmpImmediate - Return true if the specified immediate is legal 1531 /// icmp immediate, that is the target has icmp instructions which can compare 1532 /// a register against the immediate without having to materialize the 1533 /// immediate into a register. 1534 virtual bool isLegalICmpImmediate(int64_t Imm) const { 1535 return true; 1536 } 1537 1538 /// isLegalAddImmediate - Return true if the specified immediate is legal 1539 /// add immediate, that is the target has add instructions which can add 1540 /// a register with the immediate without having to materialize the 1541 /// immediate into a register. 1542 virtual bool isLegalAddImmediate(int64_t Imm) const { 1543 return true; 1544 } 1545 1546 //===--------------------------------------------------------------------===// 1547 // Div utility functions 1548 // 1549 SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, 1550 std::vector<SDNode*>* Created) const; 1551 SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, 1552 std::vector<SDNode*>* Created) const; 1553 1554 1555 //===--------------------------------------------------------------------===// 1556 // Runtime Library hooks 1557 // 1558 1559 /// setLibcallName - Rename the default libcall routine name for the specified 1560 /// libcall. 1561 void setLibcallName(RTLIB::Libcall Call, const char *Name) { 1562 LibcallRoutineNames[Call] = Name; 1563 } 1564 1565 /// getLibcallName - Get the libcall routine name for the specified libcall. 1566 /// 1567 const char *getLibcallName(RTLIB::Libcall Call) const { 1568 return LibcallRoutineNames[Call]; 1569 } 1570 1571 /// setCmpLibcallCC - Override the default CondCode to be used to test the 1572 /// result of the comparison libcall against zero. 1573 void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) { 1574 CmpLibcallCCs[Call] = CC; 1575 } 1576 1577 /// getCmpLibcallCC - Get the CondCode that's to be used to test the result of 1578 /// the comparison libcall against zero. 1579 ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const { 1580 return CmpLibcallCCs[Call]; 1581 } 1582 1583 /// setLibcallCallingConv - Set the CallingConv that should be used for the 1584 /// specified libcall. 1585 void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) { 1586 LibcallCallingConvs[Call] = CC; 1587 } 1588 1589 /// getLibcallCallingConv - Get the CallingConv that should be used for the 1590 /// specified libcall. 1591 CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const { 1592 return LibcallCallingConvs[Call]; 1593 } 1594 1595private: 1596 const TargetMachine &TM; 1597 const TargetData *TD; 1598 const TargetLoweringObjectFile &TLOF; 1599 1600 /// We are in the process of implementing a new TypeLegalization action 1601 /// which is the promotion of vector elements. This feature is under 1602 /// development. Until this feature is complete, it is only enabled using a 1603 /// flag. We pass this flag using a member because of circular dep issues. 1604 /// This member will be removed with the flag once we complete the transition. 1605 bool mayPromoteElements; 1606 1607 /// PointerTy - The type to use for pointers, usually i32 or i64. 1608 /// 1609 MVT PointerTy; 1610 1611 /// IsLittleEndian - True if this is a little endian target. 1612 /// 1613 bool IsLittleEndian; 1614 1615 /// SelectIsExpensive - Tells the code generator not to expand operations 1616 /// into sequences that use the select operations if possible. 1617 bool SelectIsExpensive; 1618 1619 /// IntDivIsCheap - Tells the code generator not to expand integer divides by 1620 /// constants into a sequence of muls, adds, and shifts. This is a hack until 1621 /// a real cost model is in place. If we ever optimize for size, this will be 1622 /// set to true unconditionally. 1623 bool IntDivIsCheap; 1624 1625 /// Pow2DivIsCheap - Tells the code generator that it shouldn't generate 1626 /// srl/add/sra for a signed divide by power of two, and let the target handle 1627 /// it. 1628 bool Pow2DivIsCheap; 1629 1630 /// JumpIsExpensive - Tells the code generator that it shouldn't generate 1631 /// extra flow control instructions and should attempt to combine flow 1632 /// control instructions via predication. 1633 bool JumpIsExpensive; 1634 1635 /// UseUnderscoreSetJmp - This target prefers to use _setjmp to implement 1636 /// llvm.setjmp. Defaults to false. 1637 bool UseUnderscoreSetJmp; 1638 1639 /// UseUnderscoreLongJmp - This target prefers to use _longjmp to implement 1640 /// llvm.longjmp. Defaults to false. 1641 bool UseUnderscoreLongJmp; 1642 1643 /// BooleanContents - Information about the contents of the high-bits in 1644 /// boolean values held in a type wider than i1. See getBooleanContents. 1645 BooleanContent BooleanContents; 1646 1647 /// SchedPreferenceInfo - The target scheduling preference: shortest possible 1648 /// total cycles or lowest register usage. 1649 Sched::Preference SchedPreferenceInfo; 1650 1651 /// JumpBufSize - The size, in bytes, of the target's jmp_buf buffers 1652 unsigned JumpBufSize; 1653 1654 /// JumpBufAlignment - The alignment, in bytes, of the target's jmp_buf 1655 /// buffers 1656 unsigned JumpBufAlignment; 1657 1658 /// MinStackArgumentAlignment - The minimum alignment that any argument 1659 /// on the stack needs to have. 1660 /// 1661 unsigned MinStackArgumentAlignment; 1662 1663 /// MinFunctionAlignment - The minimum function alignment (used when 1664 /// optimizing for size, and to prevent explicitly provided alignment 1665 /// from leading to incorrect code). 1666 /// 1667 unsigned MinFunctionAlignment; 1668 1669 /// PrefFunctionAlignment - The preferred function alignment (used when 1670 /// alignment unspecified and optimizing for speed). 1671 /// 1672 unsigned PrefFunctionAlignment; 1673 1674 /// PrefLoopAlignment - The preferred loop alignment. 1675 /// 1676 unsigned PrefLoopAlignment; 1677 1678 /// ShouldFoldAtomicFences - Whether fencing MEMBARRIER instructions should 1679 /// be folded into the enclosed atomic intrinsic instruction by the 1680 /// combiner. 1681 bool ShouldFoldAtomicFences; 1682 1683 /// StackPointerRegisterToSaveRestore - If set to a physical register, this 1684 /// specifies the register that llvm.savestack/llvm.restorestack should save 1685 /// and restore. 1686 unsigned StackPointerRegisterToSaveRestore; 1687 1688 /// ExceptionPointerRegister - If set to a physical register, this specifies 1689 /// the register that receives the exception address on entry to a landing 1690 /// pad. 1691 unsigned ExceptionPointerRegister; 1692 1693 /// ExceptionSelectorRegister - If set to a physical register, this specifies 1694 /// the register that receives the exception typeid on entry to a landing 1695 /// pad. 1696 unsigned ExceptionSelectorRegister; 1697 1698 /// RegClassForVT - This indicates the default register class to use for 1699 /// each ValueType the target supports natively. 1700 TargetRegisterClass *RegClassForVT[MVT::LAST_VALUETYPE]; 1701 unsigned char NumRegistersForVT[MVT::LAST_VALUETYPE]; 1702 EVT RegisterTypeForVT[MVT::LAST_VALUETYPE]; 1703 1704 /// RepRegClassForVT - This indicates the "representative" register class to 1705 /// use for each ValueType the target supports natively. This information is 1706 /// used by the scheduler to track register pressure. By default, the 1707 /// representative register class is the largest legal super-reg register 1708 /// class of the register class of the specified type. e.g. On x86, i8, i16, 1709 /// and i32's representative class would be GR32. 1710 const TargetRegisterClass *RepRegClassForVT[MVT::LAST_VALUETYPE]; 1711 1712 /// RepRegClassCostForVT - This indicates the "cost" of the "representative" 1713 /// register class for each ValueType. The cost is used by the scheduler to 1714 /// approximate register pressure. 1715 uint8_t RepRegClassCostForVT[MVT::LAST_VALUETYPE]; 1716 1717 /// TransformToType - For any value types we are promoting or expanding, this 1718 /// contains the value type that we are changing to. For Expanded types, this 1719 /// contains one step of the expand (e.g. i64 -> i32), even if there are 1720 /// multiple steps required (e.g. i64 -> i16). For types natively supported 1721 /// by the system, this holds the same type (e.g. i32 -> i32). 1722 EVT TransformToType[MVT::LAST_VALUETYPE]; 1723 1724 /// OpActions - For each operation and each value type, keep a LegalizeAction 1725 /// that indicates how instruction selection should deal with the operation. 1726 /// Most operations are Legal (aka, supported natively by the target), but 1727 /// operations that are not should be described. Note that operations on 1728 /// non-legal value types are not described here. 1729 uint8_t OpActions[MVT::LAST_VALUETYPE][ISD::BUILTIN_OP_END]; 1730 1731 /// LoadExtActions - For each load extension type and each value type, 1732 /// keep a LegalizeAction that indicates how instruction selection should deal 1733 /// with a load of a specific value type and extension type. 1734 uint8_t LoadExtActions[MVT::LAST_VALUETYPE][ISD::LAST_LOADEXT_TYPE]; 1735 1736 /// TruncStoreActions - For each value type pair keep a LegalizeAction that 1737 /// indicates whether a truncating store of a specific value type and 1738 /// truncating type is legal. 1739 uint8_t TruncStoreActions[MVT::LAST_VALUETYPE][MVT::LAST_VALUETYPE]; 1740 1741 /// IndexedModeActions - For each indexed mode and each value type, 1742 /// keep a pair of LegalizeAction that indicates how instruction 1743 /// selection should deal with the load / store. The first dimension is the 1744 /// value_type for the reference. The second dimension represents the various 1745 /// modes for load store. 1746 uint8_t IndexedModeActions[MVT::LAST_VALUETYPE][ISD::LAST_INDEXED_MODE]; 1747 1748 /// CondCodeActions - For each condition code (ISD::CondCode) keep a 1749 /// LegalizeAction that indicates how instruction selection should 1750 /// deal with the condition code. 1751 uint64_t CondCodeActions[ISD::SETCC_INVALID]; 1752 1753 ValueTypeActionImpl ValueTypeActions; 1754 1755 typedef std::pair<LegalizeTypeAction, EVT> LegalizeKind; 1756 1757 LegalizeKind 1758 getTypeConversion(LLVMContext &Context, EVT VT) const { 1759 // If this is a simple type, use the ComputeRegisterProp mechanism. 1760 if (VT.isSimple()) { 1761 assert((unsigned)VT.getSimpleVT().SimpleTy < 1762 array_lengthof(TransformToType)); 1763 EVT NVT = TransformToType[VT.getSimpleVT().SimpleTy]; 1764 LegalizeTypeAction LA = ValueTypeActions.getTypeAction(VT.getSimpleVT()); 1765 1766 assert( 1767 (!(NVT.isSimple() && LA != TypeLegal) || 1768 ValueTypeActions.getTypeAction(NVT.getSimpleVT()) != TypePromoteInteger) 1769 && "Promote may not follow Expand or Promote"); 1770 1771 return LegalizeKind(LA, NVT); 1772 } 1773 1774 // Handle Extended Scalar Types. 1775 if (!VT.isVector()) { 1776 assert(VT.isInteger() && "Float types must be simple"); 1777 unsigned BitSize = VT.getSizeInBits(); 1778 // First promote to a power-of-two size, then expand if necessary. 1779 if (BitSize < 8 || !isPowerOf2_32(BitSize)) { 1780 EVT NVT = VT.getRoundIntegerType(Context); 1781 assert(NVT != VT && "Unable to round integer VT"); 1782 LegalizeKind NextStep = getTypeConversion(Context, NVT); 1783 // Avoid multi-step promotion. 1784 if (NextStep.first == TypePromoteInteger) return NextStep; 1785 // Return rounded integer type. 1786 return LegalizeKind(TypePromoteInteger, NVT); 1787 } 1788 1789 return LegalizeKind(TypeExpandInteger, 1790 EVT::getIntegerVT(Context, VT.getSizeInBits()/2)); 1791 } 1792 1793 // Handle vector types. 1794 unsigned NumElts = VT.getVectorNumElements(); 1795 EVT EltVT = VT.getVectorElementType(); 1796 1797 // Vectors with only one element are always scalarized. 1798 if (NumElts == 1) 1799 return LegalizeKind(TypeScalarizeVector, EltVT); 1800 1801 // If we allow the promotion of vector elements using a flag, 1802 // then try to widen vector elements until a legal type is found. 1803 if (mayPromoteElements && EltVT.isInteger()) { 1804 // Vectors with a number of elements that is not a power of two are always 1805 // widened, for example <3 x float> -> <4 x float>. 1806 if (!VT.isPow2VectorType()) { 1807 NumElts = (unsigned)NextPowerOf2(NumElts); 1808 EVT NVT = EVT::getVectorVT(Context, EltVT, NumElts); 1809 return LegalizeKind(TypeWidenVector, NVT); 1810 } 1811 1812 // Examine the element type. 1813 LegalizeKind LK = getTypeConversion(Context, EltVT); 1814 1815 // If type is to be expanded, split the vector. 1816 // <4 x i140> -> <2 x i140> 1817 if (LK.first == TypeExpandInteger) 1818 return LegalizeKind(TypeSplitVector, 1819 EVT::getVectorVT(Context, EltVT, NumElts / 2)); 1820 1821 // Promote the integer element types until a legal vector type is found 1822 // or until the element integer type is too big. If a legal type was not 1823 // found, fallback to the usual mechanism of widening/splitting the 1824 // vector. 1825 while (1) { 1826 // Increase the bitwidth of the element to the next pow-of-two 1827 // (which is greater than 8 bits). 1828 EltVT = EVT::getIntegerVT(Context, 1 + EltVT.getSizeInBits() 1829 ).getRoundIntegerType(Context); 1830 1831 // Stop trying when getting a non-simple element type. 1832 // Note that vector elements may be greater than legal vector element 1833 // types. Example: X86 XMM registers hold 64bit element on 32bit systems. 1834 if (!EltVT.isSimple()) break; 1835 1836 // Build a new vector type and check if it is legal. 1837 MVT NVT = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1838 1839 // Found a legal promoted vector type. 1840 if (ValueTypeActions.getTypeAction(NVT) == TypeLegal) 1841 return LegalizeKind(TypePromoteInteger, 1842 EVT::getVectorVT(Context, EltVT, NumElts)); 1843 } 1844 } 1845 1846 // Try to widen the vector until a legal type is found. 1847 // If there is no wider legal type, split the vector. 1848 while (1) { 1849 // Round up to the next power of 2. 1850 NumElts = (unsigned)NextPowerOf2(NumElts); 1851 1852 // If there is no simple vector type with this many elements then there 1853 // cannot be a larger legal vector type. Note that this assumes that 1854 // there are no skipped intermediate vector types in the simple types. 1855 MVT LargerVector = MVT::getVectorVT(EltVT.getSimpleVT(), NumElts); 1856 if (LargerVector == MVT()) break; 1857 1858 // If this type is legal then widen the vector. 1859 if (ValueTypeActions.getTypeAction(LargerVector) == TypeLegal) 1860 return LegalizeKind(TypeWidenVector, LargerVector); 1861 } 1862 1863 // Widen odd vectors to next power of two. 1864 if (!VT.isPow2VectorType()) { 1865 EVT NVT = VT.getPow2VectorType(Context); 1866 return LegalizeKind(TypeWidenVector, NVT); 1867 } 1868 1869 // Vectors with illegal element types are expanded. 1870 EVT NVT = EVT::getVectorVT(Context, EltVT, VT.getVectorNumElements() / 2); 1871 return LegalizeKind(TypeSplitVector, NVT); 1872 1873 assert(false && "Unable to handle this kind of vector type"); 1874 return LegalizeKind(TypeLegal, VT); 1875 } 1876 1877 std::vector<std::pair<EVT, TargetRegisterClass*> > AvailableRegClasses; 1878 1879 /// TargetDAGCombineArray - Targets can specify ISD nodes that they would 1880 /// like PerformDAGCombine callbacks for by calling setTargetDAGCombine(), 1881 /// which sets a bit in this array. 1882 unsigned char 1883 TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT]; 1884 1885 /// PromoteToType - For operations that must be promoted to a specific type, 1886 /// this holds the destination type. This map should be sparse, so don't hold 1887 /// it as an array. 1888 /// 1889 /// Targets add entries to this map with AddPromotedToType(..), clients access 1890 /// this with getTypeToPromoteTo(..). 1891 std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType> 1892 PromoteToType; 1893 1894 /// LibcallRoutineNames - Stores the name each libcall. 1895 /// 1896 const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL]; 1897 1898 /// CmpLibcallCCs - The ISD::CondCode that should be used to test the result 1899 /// of each of the comparison libcall against zero. 1900 ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL]; 1901 1902 /// LibcallCallingConvs - Stores the CallingConv that should be used for each 1903 /// libcall. 1904 CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL]; 1905 1906protected: 1907 /// When lowering \@llvm.memset this field specifies the maximum number of 1908 /// store operations that may be substituted for the call to memset. Targets 1909 /// must set this value based on the cost threshold for that target. Targets 1910 /// should assume that the memset will be done using as many of the largest 1911 /// store operations first, followed by smaller ones, if necessary, per 1912 /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine 1913 /// with 16-bit alignment would result in four 2-byte stores and one 1-byte 1914 /// store. This only applies to setting a constant array of a constant size. 1915 /// @brief Specify maximum number of store instructions per memset call. 1916 unsigned maxStoresPerMemset; 1917 1918 /// Maximum number of stores operations that may be substituted for the call 1919 /// to memset, used for functions with OptSize attribute. 1920 unsigned maxStoresPerMemsetOptSize; 1921 1922 /// When lowering \@llvm.memcpy this field specifies the maximum number of 1923 /// store operations that may be substituted for a call to memcpy. Targets 1924 /// must set this value based on the cost threshold for that target. Targets 1925 /// should assume that the memcpy will be done using as many of the largest 1926 /// store operations first, followed by smaller ones, if necessary, per 1927 /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine 1928 /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store 1929 /// and one 1-byte store. This only applies to copying a constant array of 1930 /// constant size. 1931 /// @brief Specify maximum bytes of store instructions per memcpy call. 1932 unsigned maxStoresPerMemcpy; 1933 1934 /// Maximum number of store operations that may be substituted for a call 1935 /// to memcpy, used for functions with OptSize attribute. 1936 unsigned maxStoresPerMemcpyOptSize; 1937 1938 /// When lowering \@llvm.memmove this field specifies the maximum number of 1939 /// store instructions that may be substituted for a call to memmove. Targets 1940 /// must set this value based on the cost threshold for that target. Targets 1941 /// should assume that the memmove will be done using as many of the largest 1942 /// store operations first, followed by smaller ones, if necessary, per 1943 /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine 1944 /// with 8-bit alignment would result in nine 1-byte stores. This only 1945 /// applies to copying a constant array of constant size. 1946 /// @brief Specify maximum bytes of store instructions per memmove call. 1947 unsigned maxStoresPerMemmove; 1948 1949 /// Maximum number of store instructions that may be substituted for a call 1950 /// to memmove, used for functions with OpSize attribute. 1951 unsigned maxStoresPerMemmoveOptSize; 1952 1953 /// This field specifies whether the target can benefit from code placement 1954 /// optimization. 1955 bool benefitFromCodePlacementOpt; 1956 1957private: 1958 /// isLegalRC - Return true if the value types that can be represented by the 1959 /// specified register class are all legal. 1960 bool isLegalRC(const TargetRegisterClass *RC) const; 1961 1962 /// hasLegalSuperRegRegClasses - Return true if the specified register class 1963 /// has one or more super-reg register classes that are legal. 1964 bool hasLegalSuperRegRegClasses(const TargetRegisterClass *RC) const; 1965}; 1966 1967/// GetReturnInfo - Given an LLVM IR type and return type attributes, 1968/// compute the return value EVTs and flags, and optionally also 1969/// the offsets, if the return value is being lowered to memory. 1970void GetReturnInfo(const Type* ReturnType, Attributes attr, 1971 SmallVectorImpl<ISD::OutputArg> &Outs, 1972 const TargetLowering &TLI, 1973 SmallVectorImpl<uint64_t> *Offsets = 0); 1974 1975} // end llvm namespace 1976 1977#endif 1978