1//===-- llvm/CallingConvLower.h - Calling Conventions -----------*- 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 declares the CCState and CCValAssign classes, used for lowering 11// and implementing calling conventions. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_CODEGEN_CALLINGCONVLOWER_H 16#define LLVM_CODEGEN_CALLINGCONVLOWER_H 17 18#include "llvm/ADT/SmallVector.h" 19#include "llvm/CodeGen/MachineFrameInfo.h" 20#include "llvm/CodeGen/MachineFunction.h" 21#include "llvm/IR/CallingConv.h" 22#include "llvm/MC/MCRegisterInfo.h" 23#include "llvm/Target/TargetCallingConv.h" 24 25namespace llvm { 26class CCState; 27class MVT; 28class TargetMachine; 29class TargetRegisterInfo; 30 31/// CCValAssign - Represent assignment of one arg/retval to a location. 32class CCValAssign { 33public: 34 enum LocInfo { 35 Full, // The value fills the full location. 36 SExt, // The value is sign extended in the location. 37 ZExt, // The value is zero extended in the location. 38 AExt, // The value is extended with undefined upper bits. 39 SExtUpper, // The value is in the upper bits of the location and should be 40 // sign extended when retrieved. 41 ZExtUpper, // The value is in the upper bits of the location and should be 42 // zero extended when retrieved. 43 AExtUpper, // The value is in the upper bits of the location and should be 44 // extended with undefined upper bits when retrieved. 45 BCvt, // The value is bit-converted in the location. 46 VExt, // The value is vector-widened in the location. 47 // FIXME: Not implemented yet. Code that uses AExt to mean 48 // vector-widen should be fixed to use VExt instead. 49 FPExt, // The floating-point value is fp-extended in the location. 50 Indirect // The location contains pointer to the value. 51 // TODO: a subset of the value is in the location. 52 }; 53 54private: 55 /// ValNo - This is the value number begin assigned (e.g. an argument number). 56 unsigned ValNo; 57 58 /// Loc is either a stack offset or a register number. 59 unsigned Loc; 60 61 /// isMem - True if this is a memory loc, false if it is a register loc. 62 unsigned isMem : 1; 63 64 /// isCustom - True if this arg/retval requires special handling. 65 unsigned isCustom : 1; 66 67 /// Information about how the value is assigned. 68 LocInfo HTP : 6; 69 70 /// ValVT - The type of the value being assigned. 71 MVT ValVT; 72 73 /// LocVT - The type of the location being assigned to. 74 MVT LocVT; 75public: 76 77 static CCValAssign getReg(unsigned ValNo, MVT ValVT, 78 unsigned RegNo, MVT LocVT, 79 LocInfo HTP) { 80 CCValAssign Ret; 81 Ret.ValNo = ValNo; 82 Ret.Loc = RegNo; 83 Ret.isMem = false; 84 Ret.isCustom = false; 85 Ret.HTP = HTP; 86 Ret.ValVT = ValVT; 87 Ret.LocVT = LocVT; 88 return Ret; 89 } 90 91 static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT, 92 unsigned RegNo, MVT LocVT, 93 LocInfo HTP) { 94 CCValAssign Ret; 95 Ret = getReg(ValNo, ValVT, RegNo, LocVT, HTP); 96 Ret.isCustom = true; 97 return Ret; 98 } 99 100 static CCValAssign getMem(unsigned ValNo, MVT ValVT, 101 unsigned Offset, MVT LocVT, 102 LocInfo HTP) { 103 CCValAssign Ret; 104 Ret.ValNo = ValNo; 105 Ret.Loc = Offset; 106 Ret.isMem = true; 107 Ret.isCustom = false; 108 Ret.HTP = HTP; 109 Ret.ValVT = ValVT; 110 Ret.LocVT = LocVT; 111 return Ret; 112 } 113 114 static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT, 115 unsigned Offset, MVT LocVT, 116 LocInfo HTP) { 117 CCValAssign Ret; 118 Ret = getMem(ValNo, ValVT, Offset, LocVT, HTP); 119 Ret.isCustom = true; 120 return Ret; 121 } 122 123 // There is no need to differentiate between a pending CCValAssign and other 124 // kinds, as they are stored in a different list. 125 static CCValAssign getPending(unsigned ValNo, MVT ValVT, MVT LocVT, 126 LocInfo HTP, unsigned ExtraInfo = 0) { 127 return getReg(ValNo, ValVT, ExtraInfo, LocVT, HTP); 128 } 129 130 void convertToReg(unsigned RegNo) { 131 Loc = RegNo; 132 isMem = false; 133 } 134 135 void convertToMem(unsigned Offset) { 136 Loc = Offset; 137 isMem = true; 138 } 139 140 unsigned getValNo() const { return ValNo; } 141 MVT getValVT() const { return ValVT; } 142 143 bool isRegLoc() const { return !isMem; } 144 bool isMemLoc() const { return isMem; } 145 146 bool needsCustom() const { return isCustom; } 147 148 unsigned getLocReg() const { assert(isRegLoc()); return Loc; } 149 unsigned getLocMemOffset() const { assert(isMemLoc()); return Loc; } 150 unsigned getExtraInfo() const { return Loc; } 151 MVT getLocVT() const { return LocVT; } 152 153 LocInfo getLocInfo() const { return HTP; } 154 bool isExtInLoc() const { 155 return (HTP == AExt || HTP == SExt || HTP == ZExt); 156 } 157 158 bool isUpperBitsInLoc() const { 159 return HTP == AExtUpper || HTP == SExtUpper || HTP == ZExtUpper; 160 } 161}; 162 163/// Describes a register that needs to be forwarded from the prologue to a 164/// musttail call. 165struct ForwardedRegister { 166 ForwardedRegister(unsigned VReg, MCPhysReg PReg, MVT VT) 167 : VReg(VReg), PReg(PReg), VT(VT) {} 168 unsigned VReg; 169 MCPhysReg PReg; 170 MVT VT; 171}; 172 173/// CCAssignFn - This function assigns a location for Val, updating State to 174/// reflect the change. It returns 'true' if it failed to handle Val. 175typedef bool CCAssignFn(unsigned ValNo, MVT ValVT, 176 MVT LocVT, CCValAssign::LocInfo LocInfo, 177 ISD::ArgFlagsTy ArgFlags, CCState &State); 178 179/// CCCustomFn - This function assigns a location for Val, possibly updating 180/// all args to reflect changes and indicates if it handled it. It must set 181/// isCustom if it handles the arg and returns true. 182typedef bool CCCustomFn(unsigned &ValNo, MVT &ValVT, 183 MVT &LocVT, CCValAssign::LocInfo &LocInfo, 184 ISD::ArgFlagsTy &ArgFlags, CCState &State); 185 186/// CCState - This class holds information needed while lowering arguments and 187/// return values. It captures which registers are already assigned and which 188/// stack slots are used. It provides accessors to allocate these values. 189class CCState { 190private: 191 CallingConv::ID CallingConv; 192 bool IsVarArg; 193 bool AnalyzingMustTailForwardedRegs = false; 194 MachineFunction &MF; 195 const TargetRegisterInfo &TRI; 196 SmallVectorImpl<CCValAssign> &Locs; 197 LLVMContext &Context; 198 199 unsigned StackOffset; 200 unsigned MaxStackArgAlign; 201 SmallVector<uint32_t, 16> UsedRegs; 202 SmallVector<CCValAssign, 4> PendingLocs; 203 204 // ByValInfo and SmallVector<ByValInfo, 4> ByValRegs: 205 // 206 // Vector of ByValInfo instances (ByValRegs) is introduced for byval registers 207 // tracking. 208 // Or, in another words it tracks byval parameters that are stored in 209 // general purpose registers. 210 // 211 // For 4 byte stack alignment, 212 // instance index means byval parameter number in formal 213 // arguments set. Assume, we have some "struct_type" with size = 4 bytes, 214 // then, for function "foo": 215 // 216 // i32 foo(i32 %p, %struct_type* %r, i32 %s, %struct_type* %t) 217 // 218 // ByValRegs[0] describes how "%r" is stored (Begin == r1, End == r2) 219 // ByValRegs[1] describes how "%t" is stored (Begin == r3, End == r4). 220 // 221 // In case of 8 bytes stack alignment, 222 // ByValRegs may also contain information about wasted registers. 223 // In function shown above, r3 would be wasted according to AAPCS rules. 224 // And in that case ByValRegs[1].Waste would be "true". 225 // ByValRegs vector size still would be 2, 226 // while "%t" goes to the stack: it wouldn't be described in ByValRegs. 227 // 228 // Supposed use-case for this collection: 229 // 1. Initially ByValRegs is empty, InRegsParamsProcessed is 0. 230 // 2. HandleByVal fillups ByValRegs. 231 // 3. Argument analysis (LowerFormatArguments, for example). After 232 // some byval argument was analyzed, InRegsParamsProcessed is increased. 233 struct ByValInfo { 234 ByValInfo(unsigned B, unsigned E, bool IsWaste = false) : 235 Begin(B), End(E), Waste(IsWaste) {} 236 // First register allocated for current parameter. 237 unsigned Begin; 238 239 // First after last register allocated for current parameter. 240 unsigned End; 241 242 // Means that current range of registers doesn't belong to any 243 // parameters. It was wasted due to stack alignment rules. 244 // For more information see: 245 // AAPCS, 5.5 Parameter Passing, Stage C, C.3. 246 bool Waste; 247 }; 248 SmallVector<ByValInfo, 4 > ByValRegs; 249 250 // InRegsParamsProcessed - shows how many instances of ByValRegs was proceed 251 // during argument analysis. 252 unsigned InRegsParamsProcessed; 253 254public: 255 CCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF, 256 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C); 257 258 void addLoc(const CCValAssign &V) { 259 Locs.push_back(V); 260 } 261 262 LLVMContext &getContext() const { return Context; } 263 MachineFunction &getMachineFunction() const { return MF; } 264 CallingConv::ID getCallingConv() const { return CallingConv; } 265 bool isVarArg() const { return IsVarArg; } 266 267 /// getNextStackOffset - Return the next stack offset such that all stack 268 /// slots satisfy their alignment requirements. 269 unsigned getNextStackOffset() const { 270 return StackOffset; 271 } 272 273 /// getAlignedCallFrameSize - Return the size of the call frame needed to 274 /// be able to store all arguments and such that the alignment requirement 275 /// of each of the arguments is satisfied. 276 unsigned getAlignedCallFrameSize() const { 277 return alignTo(StackOffset, MaxStackArgAlign); 278 } 279 280 /// isAllocated - Return true if the specified register (or an alias) is 281 /// allocated. 282 bool isAllocated(unsigned Reg) const { 283 return UsedRegs[Reg/32] & (1 << (Reg&31)); 284 } 285 286 /// AnalyzeFormalArguments - Analyze an array of argument values, 287 /// incorporating info about the formals into this state. 288 void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins, 289 CCAssignFn Fn); 290 291 /// The function will invoke AnalyzeFormalArguments. 292 void AnalyzeArguments(const SmallVectorImpl<ISD::InputArg> &Ins, 293 CCAssignFn Fn) { 294 AnalyzeFormalArguments(Ins, Fn); 295 } 296 297 /// AnalyzeReturn - Analyze the returned values of a return, 298 /// incorporating info about the result values into this state. 299 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, 300 CCAssignFn Fn); 301 302 /// CheckReturn - Analyze the return values of a function, returning 303 /// true if the return can be performed without sret-demotion, and 304 /// false otherwise. 305 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags, 306 CCAssignFn Fn); 307 308 /// AnalyzeCallOperands - Analyze the outgoing arguments to a call, 309 /// incorporating info about the passed values into this state. 310 void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs, 311 CCAssignFn Fn); 312 313 /// AnalyzeCallOperands - Same as above except it takes vectors of types 314 /// and argument flags. 315 void AnalyzeCallOperands(SmallVectorImpl<MVT> &ArgVTs, 316 SmallVectorImpl<ISD::ArgFlagsTy> &Flags, 317 CCAssignFn Fn); 318 319 /// The function will invoke AnalyzeCallOperands. 320 void AnalyzeArguments(const SmallVectorImpl<ISD::OutputArg> &Outs, 321 CCAssignFn Fn) { 322 AnalyzeCallOperands(Outs, Fn); 323 } 324 325 /// AnalyzeCallResult - Analyze the return values of a call, 326 /// incorporating info about the passed values into this state. 327 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, 328 CCAssignFn Fn); 329 330 /// A shadow allocated register is a register that was allocated 331 /// but wasn't added to the location list (Locs). 332 /// \returns true if the register was allocated as shadow or false otherwise. 333 bool IsShadowAllocatedReg(unsigned Reg) const; 334 335 /// AnalyzeCallResult - Same as above except it's specialized for calls which 336 /// produce a single value. 337 void AnalyzeCallResult(MVT VT, CCAssignFn Fn); 338 339 /// getFirstUnallocated - Return the index of the first unallocated register 340 /// in the set, or Regs.size() if they are all allocated. 341 unsigned getFirstUnallocated(ArrayRef<MCPhysReg> Regs) const { 342 for (unsigned i = 0; i < Regs.size(); ++i) 343 if (!isAllocated(Regs[i])) 344 return i; 345 return Regs.size(); 346 } 347 348 /// AllocateReg - Attempt to allocate one register. If it is not available, 349 /// return zero. Otherwise, return the register, marking it and any aliases 350 /// as allocated. 351 unsigned AllocateReg(unsigned Reg) { 352 if (isAllocated(Reg)) return 0; 353 MarkAllocated(Reg); 354 return Reg; 355 } 356 357 /// Version of AllocateReg with extra register to be shadowed. 358 unsigned AllocateReg(unsigned Reg, unsigned ShadowReg) { 359 if (isAllocated(Reg)) return 0; 360 MarkAllocated(Reg); 361 MarkAllocated(ShadowReg); 362 return Reg; 363 } 364 365 /// AllocateReg - Attempt to allocate one of the specified registers. If none 366 /// are available, return zero. Otherwise, return the first one available, 367 /// marking it and any aliases as allocated. 368 unsigned AllocateReg(ArrayRef<MCPhysReg> Regs) { 369 unsigned FirstUnalloc = getFirstUnallocated(Regs); 370 if (FirstUnalloc == Regs.size()) 371 return 0; // Didn't find the reg. 372 373 // Mark the register and any aliases as allocated. 374 unsigned Reg = Regs[FirstUnalloc]; 375 MarkAllocated(Reg); 376 return Reg; 377 } 378 379 /// AllocateRegBlock - Attempt to allocate a block of RegsRequired consecutive 380 /// registers. If this is not possible, return zero. Otherwise, return the first 381 /// register of the block that were allocated, marking the entire block as allocated. 382 unsigned AllocateRegBlock(ArrayRef<MCPhysReg> Regs, unsigned RegsRequired) { 383 if (RegsRequired > Regs.size()) 384 return 0; 385 386 for (unsigned StartIdx = 0; StartIdx <= Regs.size() - RegsRequired; 387 ++StartIdx) { 388 bool BlockAvailable = true; 389 // Check for already-allocated regs in this block 390 for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) { 391 if (isAllocated(Regs[StartIdx + BlockIdx])) { 392 BlockAvailable = false; 393 break; 394 } 395 } 396 if (BlockAvailable) { 397 // Mark the entire block as allocated 398 for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) { 399 MarkAllocated(Regs[StartIdx + BlockIdx]); 400 } 401 return Regs[StartIdx]; 402 } 403 } 404 // No block was available 405 return 0; 406 } 407 408 /// Version of AllocateReg with list of registers to be shadowed. 409 unsigned AllocateReg(ArrayRef<MCPhysReg> Regs, const MCPhysReg *ShadowRegs) { 410 unsigned FirstUnalloc = getFirstUnallocated(Regs); 411 if (FirstUnalloc == Regs.size()) 412 return 0; // Didn't find the reg. 413 414 // Mark the register and any aliases as allocated. 415 unsigned Reg = Regs[FirstUnalloc], ShadowReg = ShadowRegs[FirstUnalloc]; 416 MarkAllocated(Reg); 417 MarkAllocated(ShadowReg); 418 return Reg; 419 } 420 421 /// AllocateStack - Allocate a chunk of stack space with the specified size 422 /// and alignment. 423 unsigned AllocateStack(unsigned Size, unsigned Align) { 424 assert(Align && ((Align - 1) & Align) == 0); // Align is power of 2. 425 StackOffset = alignTo(StackOffset, Align); 426 unsigned Result = StackOffset; 427 StackOffset += Size; 428 MaxStackArgAlign = std::max(Align, MaxStackArgAlign); 429 ensureMaxAlignment(Align); 430 return Result; 431 } 432 433 void ensureMaxAlignment(unsigned Align) { 434 if (!AnalyzingMustTailForwardedRegs) 435 MF.getFrameInfo().ensureMaxAlignment(Align); 436 } 437 438 /// Version of AllocateStack with extra register to be shadowed. 439 unsigned AllocateStack(unsigned Size, unsigned Align, unsigned ShadowReg) { 440 MarkAllocated(ShadowReg); 441 return AllocateStack(Size, Align); 442 } 443 444 /// Version of AllocateStack with list of extra registers to be shadowed. 445 /// Note that, unlike AllocateReg, this shadows ALL of the shadow registers. 446 unsigned AllocateStack(unsigned Size, unsigned Align, 447 ArrayRef<MCPhysReg> ShadowRegs) { 448 for (unsigned i = 0; i < ShadowRegs.size(); ++i) 449 MarkAllocated(ShadowRegs[i]); 450 return AllocateStack(Size, Align); 451 } 452 453 // HandleByVal - Allocate a stack slot large enough to pass an argument by 454 // value. The size and alignment information of the argument is encoded in its 455 // parameter attribute. 456 void HandleByVal(unsigned ValNo, MVT ValVT, 457 MVT LocVT, CCValAssign::LocInfo LocInfo, 458 int MinSize, int MinAlign, ISD::ArgFlagsTy ArgFlags); 459 460 // Returns count of byval arguments that are to be stored (even partly) 461 // in registers. 462 unsigned getInRegsParamsCount() const { return ByValRegs.size(); } 463 464 // Returns count of byval in-regs arguments proceed. 465 unsigned getInRegsParamsProcessed() const { return InRegsParamsProcessed; } 466 467 // Get information about N-th byval parameter that is stored in registers. 468 // Here "ByValParamIndex" is N. 469 void getInRegsParamInfo(unsigned InRegsParamRecordIndex, 470 unsigned& BeginReg, unsigned& EndReg) const { 471 assert(InRegsParamRecordIndex < ByValRegs.size() && 472 "Wrong ByVal parameter index"); 473 474 const ByValInfo& info = ByValRegs[InRegsParamRecordIndex]; 475 BeginReg = info.Begin; 476 EndReg = info.End; 477 } 478 479 // Add information about parameter that is kept in registers. 480 void addInRegsParamInfo(unsigned RegBegin, unsigned RegEnd) { 481 ByValRegs.push_back(ByValInfo(RegBegin, RegEnd)); 482 } 483 484 // Goes either to next byval parameter (excluding "waste" record), or 485 // to the end of collection. 486 // Returns false, if end is reached. 487 bool nextInRegsParam() { 488 unsigned e = ByValRegs.size(); 489 if (InRegsParamsProcessed < e) 490 ++InRegsParamsProcessed; 491 return InRegsParamsProcessed < e; 492 } 493 494 // Clear byval registers tracking info. 495 void clearByValRegsInfo() { 496 InRegsParamsProcessed = 0; 497 ByValRegs.clear(); 498 } 499 500 // Rewind byval registers tracking info. 501 void rewindByValRegsInfo() { 502 InRegsParamsProcessed = 0; 503 } 504 505 // Get list of pending assignments 506 SmallVectorImpl<llvm::CCValAssign> &getPendingLocs() { 507 return PendingLocs; 508 } 509 510 /// Compute the remaining unused register parameters that would be used for 511 /// the given value type. This is useful when varargs are passed in the 512 /// registers that normal prototyped parameters would be passed in, or for 513 /// implementing perfect forwarding. 514 void getRemainingRegParmsForType(SmallVectorImpl<MCPhysReg> &Regs, MVT VT, 515 CCAssignFn Fn); 516 517 /// Compute the set of registers that need to be preserved and forwarded to 518 /// any musttail calls. 519 void analyzeMustTailForwardedRegisters( 520 SmallVectorImpl<ForwardedRegister> &Forwards, ArrayRef<MVT> RegParmTypes, 521 CCAssignFn Fn); 522 523 /// Returns true if the results of the two calling conventions are compatible. 524 /// This is usually part of the check for tailcall eligibility. 525 static bool resultsCompatible(CallingConv::ID CalleeCC, 526 CallingConv::ID CallerCC, MachineFunction &MF, 527 LLVMContext &C, 528 const SmallVectorImpl<ISD::InputArg> &Ins, 529 CCAssignFn CalleeFn, CCAssignFn CallerFn); 530 531 /// The function runs an additional analysis pass over function arguments. 532 /// It will mark each argument with the attribute flag SecArgPass. 533 /// After running, it will sort the locs list. 534 template <class T> 535 void AnalyzeArgumentsSecondPass(const SmallVectorImpl<T> &Args, 536 CCAssignFn Fn) { 537 unsigned NumFirstPassLocs = Locs.size(); 538 539 /// Creates similar argument list to \p Args in which each argument is 540 /// marked using SecArgPass flag. 541 SmallVector<T, 16> SecPassArg; 542 // SmallVector<ISD::InputArg, 16> SecPassArg; 543 for (auto Arg : Args) { 544 Arg.Flags.setSecArgPass(); 545 SecPassArg.push_back(Arg); 546 } 547 548 // Run the second argument pass 549 AnalyzeArguments(SecPassArg, Fn); 550 551 // Sort the locations of the arguments according to their original position. 552 SmallVector<CCValAssign, 16> TmpArgLocs; 553 std::swap(TmpArgLocs, Locs); 554 auto B = TmpArgLocs.begin(), E = TmpArgLocs.end(); 555 std::merge(B, B + NumFirstPassLocs, B + NumFirstPassLocs, E, 556 std::back_inserter(Locs), 557 [](const CCValAssign &A, const CCValAssign &B) -> bool { 558 return A.getValNo() < B.getValNo(); 559 }); 560 } 561 562private: 563 /// MarkAllocated - Mark a register and all of its aliases as allocated. 564 void MarkAllocated(unsigned Reg); 565}; 566 567 568 569} // end namespace llvm 570 571#endif 572