File: | clang/lib/CodeGen/TargetInfo.cpp |
Warning: | line 10397, column 24 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // These classes wrap the information about a call or function |
10 | // definition used to handle ABI compliancy. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #include "TargetInfo.h" |
15 | #include "ABIInfo.h" |
16 | #include "CGBlocks.h" |
17 | #include "CGCXXABI.h" |
18 | #include "CGValue.h" |
19 | #include "CodeGenFunction.h" |
20 | #include "clang/AST/Attr.h" |
21 | #include "clang/AST/RecordLayout.h" |
22 | #include "clang/Basic/CodeGenOptions.h" |
23 | #include "clang/Basic/DiagnosticFrontend.h" |
24 | #include "clang/CodeGen/CGFunctionInfo.h" |
25 | #include "clang/CodeGen/SwiftCallingConv.h" |
26 | #include "llvm/ADT/SmallBitVector.h" |
27 | #include "llvm/ADT/StringExtras.h" |
28 | #include "llvm/ADT/StringSwitch.h" |
29 | #include "llvm/ADT/Triple.h" |
30 | #include "llvm/ADT/Twine.h" |
31 | #include "llvm/IR/DataLayout.h" |
32 | #include "llvm/IR/IntrinsicsNVPTX.h" |
33 | #include "llvm/IR/Type.h" |
34 | #include "llvm/Support/raw_ostream.h" |
35 | #include <algorithm> // std::sort |
36 | |
37 | using namespace clang; |
38 | using namespace CodeGen; |
39 | |
40 | // Helper for coercing an aggregate argument or return value into an integer |
41 | // array of the same size (including padding) and alignment. This alternate |
42 | // coercion happens only for the RenderScript ABI and can be removed after |
43 | // runtimes that rely on it are no longer supported. |
44 | // |
45 | // RenderScript assumes that the size of the argument / return value in the IR |
46 | // is the same as the size of the corresponding qualified type. This helper |
47 | // coerces the aggregate type into an array of the same size (including |
48 | // padding). This coercion is used in lieu of expansion of struct members or |
49 | // other canonical coercions that return a coerced-type of larger size. |
50 | // |
51 | // Ty - The argument / return value type |
52 | // Context - The associated ASTContext |
53 | // LLVMContext - The associated LLVMContext |
54 | static ABIArgInfo coerceToIntArray(QualType Ty, |
55 | ASTContext &Context, |
56 | llvm::LLVMContext &LLVMContext) { |
57 | // Alignment and Size are measured in bits. |
58 | const uint64_t Size = Context.getTypeSize(Ty); |
59 | const uint64_t Alignment = Context.getTypeAlign(Ty); |
60 | llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); |
61 | const uint64_t NumElements = (Size + Alignment - 1) / Alignment; |
62 | return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); |
63 | } |
64 | |
65 | static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, |
66 | llvm::Value *Array, |
67 | llvm::Value *Value, |
68 | unsigned FirstIndex, |
69 | unsigned LastIndex) { |
70 | // Alternatively, we could emit this as a loop in the source. |
71 | for (unsigned I = FirstIndex; I <= LastIndex; ++I) { |
72 | llvm::Value *Cell = |
73 | Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); |
74 | Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); |
75 | } |
76 | } |
77 | |
78 | static bool isAggregateTypeForABI(QualType T) { |
79 | return !CodeGenFunction::hasScalarEvaluationKind(T) || |
80 | T->isMemberFunctionPointerType(); |
81 | } |
82 | |
83 | ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal, |
84 | bool Realign, |
85 | llvm::Type *Padding) const { |
86 | return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal, |
87 | Realign, Padding); |
88 | } |
89 | |
90 | ABIArgInfo |
91 | ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { |
92 | return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), |
93 | /*ByVal*/ false, Realign); |
94 | } |
95 | |
96 | Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, |
97 | QualType Ty) const { |
98 | return Address::invalid(); |
99 | } |
100 | |
101 | bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { |
102 | if (Ty->isPromotableIntegerType()) |
103 | return true; |
104 | |
105 | if (const auto *EIT = Ty->getAs<ExtIntType>()) |
106 | if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) |
107 | return true; |
108 | |
109 | return false; |
110 | } |
111 | |
112 | ABIInfo::~ABIInfo() {} |
113 | |
114 | /// Does the given lowering require more than the given number of |
115 | /// registers when expanded? |
116 | /// |
117 | /// This is intended to be the basis of a reasonable basic implementation |
118 | /// of should{Pass,Return}IndirectlyForSwift. |
119 | /// |
120 | /// For most targets, a limit of four total registers is reasonable; this |
121 | /// limits the amount of code required in order to move around the value |
122 | /// in case it wasn't produced immediately prior to the call by the caller |
123 | /// (or wasn't produced in exactly the right registers) or isn't used |
124 | /// immediately within the callee. But some targets may need to further |
125 | /// limit the register count due to an inability to support that many |
126 | /// return registers. |
127 | static bool occupiesMoreThan(CodeGenTypes &cgt, |
128 | ArrayRef<llvm::Type*> scalarTypes, |
129 | unsigned maxAllRegisters) { |
130 | unsigned intCount = 0, fpCount = 0; |
131 | for (llvm::Type *type : scalarTypes) { |
132 | if (type->isPointerTy()) { |
133 | intCount++; |
134 | } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { |
135 | auto ptrWidth = cgt.getTarget().getPointerWidth(0); |
136 | intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; |
137 | } else { |
138 | assert(type->isVectorTy() || type->isFloatingPointTy())((type->isVectorTy() || type->isFloatingPointTy()) ? static_cast <void> (0) : __assert_fail ("type->isVectorTy() || type->isFloatingPointTy()" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 138, __PRETTY_FUNCTION__)); |
139 | fpCount++; |
140 | } |
141 | } |
142 | |
143 | return (intCount + fpCount > maxAllRegisters); |
144 | } |
145 | |
146 | bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, |
147 | llvm::Type *eltTy, |
148 | unsigned numElts) const { |
149 | // The default implementation of this assumes that the target guarantees |
150 | // 128-bit SIMD support but nothing more. |
151 | return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); |
152 | } |
153 | |
154 | static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, |
155 | CGCXXABI &CXXABI) { |
156 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); |
157 | if (!RD) { |
158 | if (!RT->getDecl()->canPassInRegisters()) |
159 | return CGCXXABI::RAA_Indirect; |
160 | return CGCXXABI::RAA_Default; |
161 | } |
162 | return CXXABI.getRecordArgABI(RD); |
163 | } |
164 | |
165 | static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, |
166 | CGCXXABI &CXXABI) { |
167 | const RecordType *RT = T->getAs<RecordType>(); |
168 | if (!RT) |
169 | return CGCXXABI::RAA_Default; |
170 | return getRecordArgABI(RT, CXXABI); |
171 | } |
172 | |
173 | static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, |
174 | const ABIInfo &Info) { |
175 | QualType Ty = FI.getReturnType(); |
176 | |
177 | if (const auto *RT = Ty->getAs<RecordType>()) |
178 | if (!isa<CXXRecordDecl>(RT->getDecl()) && |
179 | !RT->getDecl()->canPassInRegisters()) { |
180 | FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); |
181 | return true; |
182 | } |
183 | |
184 | return CXXABI.classifyReturnType(FI); |
185 | } |
186 | |
187 | /// Pass transparent unions as if they were the type of the first element. Sema |
188 | /// should ensure that all elements of the union have the same "machine type". |
189 | static QualType useFirstFieldIfTransparentUnion(QualType Ty) { |
190 | if (const RecordType *UT = Ty->getAsUnionType()) { |
191 | const RecordDecl *UD = UT->getDecl(); |
192 | if (UD->hasAttr<TransparentUnionAttr>()) { |
193 | assert(!UD->field_empty() && "sema created an empty transparent union")((!UD->field_empty() && "sema created an empty transparent union" ) ? static_cast<void> (0) : __assert_fail ("!UD->field_empty() && \"sema created an empty transparent union\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 193, __PRETTY_FUNCTION__)); |
194 | return UD->field_begin()->getType(); |
195 | } |
196 | } |
197 | return Ty; |
198 | } |
199 | |
200 | CGCXXABI &ABIInfo::getCXXABI() const { |
201 | return CGT.getCXXABI(); |
202 | } |
203 | |
204 | ASTContext &ABIInfo::getContext() const { |
205 | return CGT.getContext(); |
206 | } |
207 | |
208 | llvm::LLVMContext &ABIInfo::getVMContext() const { |
209 | return CGT.getLLVMContext(); |
210 | } |
211 | |
212 | const llvm::DataLayout &ABIInfo::getDataLayout() const { |
213 | return CGT.getDataLayout(); |
214 | } |
215 | |
216 | const TargetInfo &ABIInfo::getTarget() const { |
217 | return CGT.getTarget(); |
218 | } |
219 | |
220 | const CodeGenOptions &ABIInfo::getCodeGenOpts() const { |
221 | return CGT.getCodeGenOpts(); |
222 | } |
223 | |
224 | bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } |
225 | |
226 | bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { |
227 | return false; |
228 | } |
229 | |
230 | bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, |
231 | uint64_t Members) const { |
232 | return false; |
233 | } |
234 | |
235 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ABIArgInfo::dump() const { |
236 | raw_ostream &OS = llvm::errs(); |
237 | OS << "(ABIArgInfo Kind="; |
238 | switch (TheKind) { |
239 | case Direct: |
240 | OS << "Direct Type="; |
241 | if (llvm::Type *Ty = getCoerceToType()) |
242 | Ty->print(OS); |
243 | else |
244 | OS << "null"; |
245 | break; |
246 | case Extend: |
247 | OS << "Extend"; |
248 | break; |
249 | case Ignore: |
250 | OS << "Ignore"; |
251 | break; |
252 | case InAlloca: |
253 | OS << "InAlloca Offset=" << getInAllocaFieldIndex(); |
254 | break; |
255 | case Indirect: |
256 | OS << "Indirect Align=" << getIndirectAlign().getQuantity() |
257 | << " ByVal=" << getIndirectByVal() |
258 | << " Realign=" << getIndirectRealign(); |
259 | break; |
260 | case IndirectAliased: |
261 | OS << "Indirect Align=" << getIndirectAlign().getQuantity() |
262 | << " AadrSpace=" << getIndirectAddrSpace() |
263 | << " Realign=" << getIndirectRealign(); |
264 | break; |
265 | case Expand: |
266 | OS << "Expand"; |
267 | break; |
268 | case CoerceAndExpand: |
269 | OS << "CoerceAndExpand Type="; |
270 | getCoerceAndExpandType()->print(OS); |
271 | break; |
272 | } |
273 | OS << ")\n"; |
274 | } |
275 | |
276 | // Dynamically round a pointer up to a multiple of the given alignment. |
277 | static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, |
278 | llvm::Value *Ptr, |
279 | CharUnits Align) { |
280 | llvm::Value *PtrAsInt = Ptr; |
281 | // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; |
282 | PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); |
283 | PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, |
284 | llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); |
285 | PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, |
286 | llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); |
287 | PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, |
288 | Ptr->getType(), |
289 | Ptr->getName() + ".aligned"); |
290 | return PtrAsInt; |
291 | } |
292 | |
293 | /// Emit va_arg for a platform using the common void* representation, |
294 | /// where arguments are simply emitted in an array of slots on the stack. |
295 | /// |
296 | /// This version implements the core direct-value passing rules. |
297 | /// |
298 | /// \param SlotSize - The size and alignment of a stack slot. |
299 | /// Each argument will be allocated to a multiple of this number of |
300 | /// slots, and all the slots will be aligned to this value. |
301 | /// \param AllowHigherAlign - The slot alignment is not a cap; |
302 | /// an argument type with an alignment greater than the slot size |
303 | /// will be emitted on a higher-alignment address, potentially |
304 | /// leaving one or more empty slots behind as padding. If this |
305 | /// is false, the returned address might be less-aligned than |
306 | /// DirectAlign. |
307 | static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, |
308 | Address VAListAddr, |
309 | llvm::Type *DirectTy, |
310 | CharUnits DirectSize, |
311 | CharUnits DirectAlign, |
312 | CharUnits SlotSize, |
313 | bool AllowHigherAlign) { |
314 | // Cast the element type to i8* if necessary. Some platforms define |
315 | // va_list as a struct containing an i8* instead of just an i8*. |
316 | if (VAListAddr.getElementType() != CGF.Int8PtrTy) |
317 | VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); |
318 | |
319 | llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); |
320 | |
321 | // If the CC aligns values higher than the slot size, do so if needed. |
322 | Address Addr = Address::invalid(); |
323 | if (AllowHigherAlign && DirectAlign > SlotSize) { |
324 | Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), |
325 | DirectAlign); |
326 | } else { |
327 | Addr = Address(Ptr, SlotSize); |
328 | } |
329 | |
330 | // Advance the pointer past the argument, then store that back. |
331 | CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); |
332 | Address NextPtr = |
333 | CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); |
334 | CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); |
335 | |
336 | // If the argument is smaller than a slot, and this is a big-endian |
337 | // target, the argument will be right-adjusted in its slot. |
338 | if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && |
339 | !DirectTy->isStructTy()) { |
340 | Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); |
341 | } |
342 | |
343 | Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); |
344 | return Addr; |
345 | } |
346 | |
347 | /// Emit va_arg for a platform using the common void* representation, |
348 | /// where arguments are simply emitted in an array of slots on the stack. |
349 | /// |
350 | /// \param IsIndirect - Values of this type are passed indirectly. |
351 | /// \param ValueInfo - The size and alignment of this type, generally |
352 | /// computed with getContext().getTypeInfoInChars(ValueTy). |
353 | /// \param SlotSizeAndAlign - The size and alignment of a stack slot. |
354 | /// Each argument will be allocated to a multiple of this number of |
355 | /// slots, and all the slots will be aligned to this value. |
356 | /// \param AllowHigherAlign - The slot alignment is not a cap; |
357 | /// an argument type with an alignment greater than the slot size |
358 | /// will be emitted on a higher-alignment address, potentially |
359 | /// leaving one or more empty slots behind as padding. |
360 | static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, |
361 | QualType ValueTy, bool IsIndirect, |
362 | TypeInfoChars ValueInfo, |
363 | CharUnits SlotSizeAndAlign, |
364 | bool AllowHigherAlign) { |
365 | // The size and alignment of the value that was passed directly. |
366 | CharUnits DirectSize, DirectAlign; |
367 | if (IsIndirect) { |
368 | DirectSize = CGF.getPointerSize(); |
369 | DirectAlign = CGF.getPointerAlign(); |
370 | } else { |
371 | DirectSize = ValueInfo.Width; |
372 | DirectAlign = ValueInfo.Align; |
373 | } |
374 | |
375 | // Cast the address we've calculated to the right type. |
376 | llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); |
377 | if (IsIndirect) |
378 | DirectTy = DirectTy->getPointerTo(0); |
379 | |
380 | Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, |
381 | DirectSize, DirectAlign, |
382 | SlotSizeAndAlign, |
383 | AllowHigherAlign); |
384 | |
385 | if (IsIndirect) { |
386 | Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align); |
387 | } |
388 | |
389 | return Addr; |
390 | |
391 | } |
392 | |
393 | static Address emitMergePHI(CodeGenFunction &CGF, |
394 | Address Addr1, llvm::BasicBlock *Block1, |
395 | Address Addr2, llvm::BasicBlock *Block2, |
396 | const llvm::Twine &Name = "") { |
397 | assert(Addr1.getType() == Addr2.getType())((Addr1.getType() == Addr2.getType()) ? static_cast<void> (0) : __assert_fail ("Addr1.getType() == Addr2.getType()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 397, __PRETTY_FUNCTION__)); |
398 | llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); |
399 | PHI->addIncoming(Addr1.getPointer(), Block1); |
400 | PHI->addIncoming(Addr2.getPointer(), Block2); |
401 | CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); |
402 | return Address(PHI, Align); |
403 | } |
404 | |
405 | TargetCodeGenInfo::~TargetCodeGenInfo() = default; |
406 | |
407 | // If someone can figure out a general rule for this, that would be great. |
408 | // It's probably just doomed to be platform-dependent, though. |
409 | unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { |
410 | // Verified for: |
411 | // x86-64 FreeBSD, Linux, Darwin |
412 | // x86-32 FreeBSD, Linux, Darwin |
413 | // PowerPC Linux, Darwin |
414 | // ARM Darwin (*not* EABI) |
415 | // AArch64 Linux |
416 | return 32; |
417 | } |
418 | |
419 | bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, |
420 | const FunctionNoProtoType *fnType) const { |
421 | // The following conventions are known to require this to be false: |
422 | // x86_stdcall |
423 | // MIPS |
424 | // For everything else, we just prefer false unless we opt out. |
425 | return false; |
426 | } |
427 | |
428 | void |
429 | TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, |
430 | llvm::SmallString<24> &Opt) const { |
431 | // This assumes the user is passing a library name like "rt" instead of a |
432 | // filename like "librt.a/so", and that they don't care whether it's static or |
433 | // dynamic. |
434 | Opt = "-l"; |
435 | Opt += Lib; |
436 | } |
437 | |
438 | unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { |
439 | // OpenCL kernels are called via an explicit runtime API with arguments |
440 | // set with clSetKernelArg(), not as normal sub-functions. |
441 | // Return SPIR_KERNEL by default as the kernel calling convention to |
442 | // ensure the fingerprint is fixed such way that each OpenCL argument |
443 | // gets one matching argument in the produced kernel function argument |
444 | // list to enable feasible implementation of clSetKernelArg() with |
445 | // aggregates etc. In case we would use the default C calling conv here, |
446 | // clSetKernelArg() might break depending on the target-specific |
447 | // conventions; different targets might split structs passed as values |
448 | // to multiple function arguments etc. |
449 | return llvm::CallingConv::SPIR_KERNEL; |
450 | } |
451 | |
452 | llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, |
453 | llvm::PointerType *T, QualType QT) const { |
454 | return llvm::ConstantPointerNull::get(T); |
455 | } |
456 | |
457 | LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, |
458 | const VarDecl *D) const { |
459 | assert(!CGM.getLangOpts().OpenCL &&((!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && "Address space agnostic languages only" ) ? static_cast<void> (0) : __assert_fail ("!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && \"Address space agnostic languages only\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 461, __PRETTY_FUNCTION__)) |
460 | !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&((!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && "Address space agnostic languages only" ) ? static_cast<void> (0) : __assert_fail ("!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && \"Address space agnostic languages only\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 461, __PRETTY_FUNCTION__)) |
461 | "Address space agnostic languages only")((!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && "Address space agnostic languages only" ) ? static_cast<void> (0) : __assert_fail ("!CGM.getLangOpts().OpenCL && !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && \"Address space agnostic languages only\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 461, __PRETTY_FUNCTION__)); |
462 | return D ? D->getType().getAddressSpace() : LangAS::Default; |
463 | } |
464 | |
465 | llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( |
466 | CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, |
467 | LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { |
468 | // Since target may map different address spaces in AST to the same address |
469 | // space, an address space conversion may end up as a bitcast. |
470 | if (auto *C = dyn_cast<llvm::Constant>(Src)) |
471 | return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); |
472 | // Try to preserve the source's name to make IR more readable. |
473 | return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( |
474 | Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); |
475 | } |
476 | |
477 | llvm::Constant * |
478 | TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, |
479 | LangAS SrcAddr, LangAS DestAddr, |
480 | llvm::Type *DestTy) const { |
481 | // Since target may map different address spaces in AST to the same address |
482 | // space, an address space conversion may end up as a bitcast. |
483 | return llvm::ConstantExpr::getPointerCast(Src, DestTy); |
484 | } |
485 | |
486 | llvm::SyncScope::ID |
487 | TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, |
488 | SyncScope Scope, |
489 | llvm::AtomicOrdering Ordering, |
490 | llvm::LLVMContext &Ctx) const { |
491 | return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ |
492 | } |
493 | |
494 | static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); |
495 | |
496 | /// isEmptyField - Return true iff a the field is "empty", that is it |
497 | /// is an unnamed bit-field or an (array of) empty record(s). |
498 | static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, |
499 | bool AllowArrays) { |
500 | if (FD->isUnnamedBitfield()) |
501 | return true; |
502 | |
503 | QualType FT = FD->getType(); |
504 | |
505 | // Constant arrays of empty records count as empty, strip them off. |
506 | // Constant arrays of zero length always count as empty. |
507 | bool WasArray = false; |
508 | if (AllowArrays) |
509 | while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { |
510 | if (AT->getSize() == 0) |
511 | return true; |
512 | FT = AT->getElementType(); |
513 | // The [[no_unique_address]] special case below does not apply to |
514 | // arrays of C++ empty records, so we need to remember this fact. |
515 | WasArray = true; |
516 | } |
517 | |
518 | const RecordType *RT = FT->getAs<RecordType>(); |
519 | if (!RT) |
520 | return false; |
521 | |
522 | // C++ record fields are never empty, at least in the Itanium ABI. |
523 | // |
524 | // FIXME: We should use a predicate for whether this behavior is true in the |
525 | // current ABI. |
526 | // |
527 | // The exception to the above rule are fields marked with the |
528 | // [[no_unique_address]] attribute (since C++20). Those do count as empty |
529 | // according to the Itanium ABI. The exception applies only to records, |
530 | // not arrays of records, so we must also check whether we stripped off an |
531 | // array type above. |
532 | if (isa<CXXRecordDecl>(RT->getDecl()) && |
533 | (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) |
534 | return false; |
535 | |
536 | return isEmptyRecord(Context, FT, AllowArrays); |
537 | } |
538 | |
539 | /// isEmptyRecord - Return true iff a structure contains only empty |
540 | /// fields. Note that a structure with a flexible array member is not |
541 | /// considered empty. |
542 | static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { |
543 | const RecordType *RT = T->getAs<RecordType>(); |
544 | if (!RT) |
545 | return false; |
546 | const RecordDecl *RD = RT->getDecl(); |
547 | if (RD->hasFlexibleArrayMember()) |
548 | return false; |
549 | |
550 | // If this is a C++ record, check the bases first. |
551 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) |
552 | for (const auto &I : CXXRD->bases()) |
553 | if (!isEmptyRecord(Context, I.getType(), true)) |
554 | return false; |
555 | |
556 | for (const auto *I : RD->fields()) |
557 | if (!isEmptyField(Context, I, AllowArrays)) |
558 | return false; |
559 | return true; |
560 | } |
561 | |
562 | /// isSingleElementStruct - Determine if a structure is a "single |
563 | /// element struct", i.e. it has exactly one non-empty field or |
564 | /// exactly one field which is itself a single element |
565 | /// struct. Structures with flexible array members are never |
566 | /// considered single element structs. |
567 | /// |
568 | /// \return The field declaration for the single non-empty field, if |
569 | /// it exists. |
570 | static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { |
571 | const RecordType *RT = T->getAs<RecordType>(); |
572 | if (!RT) |
573 | return nullptr; |
574 | |
575 | const RecordDecl *RD = RT->getDecl(); |
576 | if (RD->hasFlexibleArrayMember()) |
577 | return nullptr; |
578 | |
579 | const Type *Found = nullptr; |
580 | |
581 | // If this is a C++ record, check the bases first. |
582 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
583 | for (const auto &I : CXXRD->bases()) { |
584 | // Ignore empty records. |
585 | if (isEmptyRecord(Context, I.getType(), true)) |
586 | continue; |
587 | |
588 | // If we already found an element then this isn't a single-element struct. |
589 | if (Found) |
590 | return nullptr; |
591 | |
592 | // If this is non-empty and not a single element struct, the composite |
593 | // cannot be a single element struct. |
594 | Found = isSingleElementStruct(I.getType(), Context); |
595 | if (!Found) |
596 | return nullptr; |
597 | } |
598 | } |
599 | |
600 | // Check for single element. |
601 | for (const auto *FD : RD->fields()) { |
602 | QualType FT = FD->getType(); |
603 | |
604 | // Ignore empty fields. |
605 | if (isEmptyField(Context, FD, true)) |
606 | continue; |
607 | |
608 | // If we already found an element then this isn't a single-element |
609 | // struct. |
610 | if (Found) |
611 | return nullptr; |
612 | |
613 | // Treat single element arrays as the element. |
614 | while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { |
615 | if (AT->getSize().getZExtValue() != 1) |
616 | break; |
617 | FT = AT->getElementType(); |
618 | } |
619 | |
620 | if (!isAggregateTypeForABI(FT)) { |
621 | Found = FT.getTypePtr(); |
622 | } else { |
623 | Found = isSingleElementStruct(FT, Context); |
624 | if (!Found) |
625 | return nullptr; |
626 | } |
627 | } |
628 | |
629 | // We don't consider a struct a single-element struct if it has |
630 | // padding beyond the element type. |
631 | if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) |
632 | return nullptr; |
633 | |
634 | return Found; |
635 | } |
636 | |
637 | namespace { |
638 | Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, |
639 | const ABIArgInfo &AI) { |
640 | // This default implementation defers to the llvm backend's va_arg |
641 | // instruction. It can handle only passing arguments directly |
642 | // (typically only handled in the backend for primitive types), or |
643 | // aggregates passed indirectly by pointer (NOTE: if the "byval" |
644 | // flag has ABI impact in the callee, this implementation cannot |
645 | // work.) |
646 | |
647 | // Only a few cases are covered here at the moment -- those needed |
648 | // by the default abi. |
649 | llvm::Value *Val; |
650 | |
651 | if (AI.isIndirect()) { |
652 | assert(!AI.getPaddingType() &&((!AI.getPaddingType() && "Unexpected PaddingType seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getPaddingType() && \"Unexpected PaddingType seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 653, __PRETTY_FUNCTION__)) |
653 | "Unexpected PaddingType seen in arginfo in generic VAArg emitter!")((!AI.getPaddingType() && "Unexpected PaddingType seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getPaddingType() && \"Unexpected PaddingType seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 653, __PRETTY_FUNCTION__)); |
654 | assert(((!AI.getIndirectRealign() && "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getIndirectRealign() && \"Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 656, __PRETTY_FUNCTION__)) |
655 | !AI.getIndirectRealign() &&((!AI.getIndirectRealign() && "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getIndirectRealign() && \"Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 656, __PRETTY_FUNCTION__)) |
656 | "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!")((!AI.getIndirectRealign() && "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getIndirectRealign() && \"Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 656, __PRETTY_FUNCTION__)); |
657 | |
658 | auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); |
659 | CharUnits TyAlignForABI = TyInfo.Align; |
660 | |
661 | llvm::Type *BaseTy = |
662 | llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); |
663 | llvm::Value *Addr = |
664 | CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); |
665 | return Address(Addr, TyAlignForABI); |
666 | } else { |
667 | assert((AI.isDirect() || AI.isExtend()) &&(((AI.isDirect() || AI.isExtend()) && "Unexpected ArgInfo Kind in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("(AI.isDirect() || AI.isExtend()) && \"Unexpected ArgInfo Kind in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 668, __PRETTY_FUNCTION__)) |
668 | "Unexpected ArgInfo Kind in generic VAArg emitter!")(((AI.isDirect() || AI.isExtend()) && "Unexpected ArgInfo Kind in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("(AI.isDirect() || AI.isExtend()) && \"Unexpected ArgInfo Kind in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 668, __PRETTY_FUNCTION__)); |
669 | |
670 | assert(!AI.getInReg() &&((!AI.getInReg() && "Unexpected InReg seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getInReg() && \"Unexpected InReg seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 671, __PRETTY_FUNCTION__)) |
671 | "Unexpected InReg seen in arginfo in generic VAArg emitter!")((!AI.getInReg() && "Unexpected InReg seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getInReg() && \"Unexpected InReg seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 671, __PRETTY_FUNCTION__)); |
672 | assert(!AI.getPaddingType() &&((!AI.getPaddingType() && "Unexpected PaddingType seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getPaddingType() && \"Unexpected PaddingType seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 673, __PRETTY_FUNCTION__)) |
673 | "Unexpected PaddingType seen in arginfo in generic VAArg emitter!")((!AI.getPaddingType() && "Unexpected PaddingType seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getPaddingType() && \"Unexpected PaddingType seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 673, __PRETTY_FUNCTION__)); |
674 | assert(!AI.getDirectOffset() &&((!AI.getDirectOffset() && "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getDirectOffset() && \"Unexpected DirectOffset seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 675, __PRETTY_FUNCTION__)) |
675 | "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!")((!AI.getDirectOffset() && "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getDirectOffset() && \"Unexpected DirectOffset seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 675, __PRETTY_FUNCTION__)); |
676 | assert(!AI.getCoerceToType() &&((!AI.getCoerceToType() && "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getCoerceToType() && \"Unexpected CoerceToType seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 677, __PRETTY_FUNCTION__)) |
677 | "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!")((!AI.getCoerceToType() && "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!" ) ? static_cast<void> (0) : __assert_fail ("!AI.getCoerceToType() && \"Unexpected CoerceToType seen in arginfo in generic VAArg emitter!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 677, __PRETTY_FUNCTION__)); |
678 | |
679 | Address Temp = CGF.CreateMemTemp(Ty, "varet"); |
680 | Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); |
681 | CGF.Builder.CreateStore(Val, Temp); |
682 | return Temp; |
683 | } |
684 | } |
685 | |
686 | /// DefaultABIInfo - The default implementation for ABI specific |
687 | /// details. This implementation provides information which results in |
688 | /// self-consistent and sensible LLVM IR generation, but does not |
689 | /// conform to any particular ABI. |
690 | class DefaultABIInfo : public ABIInfo { |
691 | public: |
692 | DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} |
693 | |
694 | ABIArgInfo classifyReturnType(QualType RetTy) const; |
695 | ABIArgInfo classifyArgumentType(QualType RetTy) const; |
696 | |
697 | void computeInfo(CGFunctionInfo &FI) const override { |
698 | if (!getCXXABI().classifyReturnType(FI)) |
699 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); |
700 | for (auto &I : FI.arguments()) |
701 | I.info = classifyArgumentType(I.type); |
702 | } |
703 | |
704 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
705 | QualType Ty) const override { |
706 | return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); |
707 | } |
708 | }; |
709 | |
710 | class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { |
711 | public: |
712 | DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) |
713 | : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} |
714 | }; |
715 | |
716 | ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { |
717 | Ty = useFirstFieldIfTransparentUnion(Ty); |
718 | |
719 | if (isAggregateTypeForABI(Ty)) { |
720 | // Records with non-trivial destructors/copy-constructors should not be |
721 | // passed by value. |
722 | if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) |
723 | return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); |
724 | |
725 | return getNaturalAlignIndirect(Ty); |
726 | } |
727 | |
728 | // Treat an enum type as its underlying type. |
729 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
730 | Ty = EnumTy->getDecl()->getIntegerType(); |
731 | |
732 | ASTContext &Context = getContext(); |
733 | if (const auto *EIT = Ty->getAs<ExtIntType>()) |
734 | if (EIT->getNumBits() > |
735 | Context.getTypeSize(Context.getTargetInfo().hasInt128Type() |
736 | ? Context.Int128Ty |
737 | : Context.LongLongTy)) |
738 | return getNaturalAlignIndirect(Ty); |
739 | |
740 | return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) |
741 | : ABIArgInfo::getDirect()); |
742 | } |
743 | |
744 | ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { |
745 | if (RetTy->isVoidType()) |
746 | return ABIArgInfo::getIgnore(); |
747 | |
748 | if (isAggregateTypeForABI(RetTy)) |
749 | return getNaturalAlignIndirect(RetTy); |
750 | |
751 | // Treat an enum type as its underlying type. |
752 | if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) |
753 | RetTy = EnumTy->getDecl()->getIntegerType(); |
754 | |
755 | if (const auto *EIT = RetTy->getAs<ExtIntType>()) |
756 | if (EIT->getNumBits() > |
757 | getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() |
758 | ? getContext().Int128Ty |
759 | : getContext().LongLongTy)) |
760 | return getNaturalAlignIndirect(RetTy); |
761 | |
762 | return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) |
763 | : ABIArgInfo::getDirect()); |
764 | } |
765 | |
766 | //===----------------------------------------------------------------------===// |
767 | // WebAssembly ABI Implementation |
768 | // |
769 | // This is a very simple ABI that relies a lot on DefaultABIInfo. |
770 | //===----------------------------------------------------------------------===// |
771 | |
772 | class WebAssemblyABIInfo final : public SwiftABIInfo { |
773 | public: |
774 | enum ABIKind { |
775 | MVP = 0, |
776 | ExperimentalMV = 1, |
777 | }; |
778 | |
779 | private: |
780 | DefaultABIInfo defaultInfo; |
781 | ABIKind Kind; |
782 | |
783 | public: |
784 | explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) |
785 | : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} |
786 | |
787 | private: |
788 | ABIArgInfo classifyReturnType(QualType RetTy) const; |
789 | ABIArgInfo classifyArgumentType(QualType Ty) const; |
790 | |
791 | // DefaultABIInfo's classifyReturnType and classifyArgumentType are |
792 | // non-virtual, but computeInfo and EmitVAArg are virtual, so we |
793 | // overload them. |
794 | void computeInfo(CGFunctionInfo &FI) const override { |
795 | if (!getCXXABI().classifyReturnType(FI)) |
796 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); |
797 | for (auto &Arg : FI.arguments()) |
798 | Arg.info = classifyArgumentType(Arg.type); |
799 | } |
800 | |
801 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
802 | QualType Ty) const override; |
803 | |
804 | bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, |
805 | bool asReturnValue) const override { |
806 | return occupiesMoreThan(CGT, scalars, /*total*/ 4); |
807 | } |
808 | |
809 | bool isSwiftErrorInRegister() const override { |
810 | return false; |
811 | } |
812 | }; |
813 | |
814 | class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { |
815 | public: |
816 | explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, |
817 | WebAssemblyABIInfo::ABIKind K) |
818 | : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} |
819 | |
820 | void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
821 | CodeGen::CodeGenModule &CGM) const override { |
822 | TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); |
823 | if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { |
824 | if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { |
825 | llvm::Function *Fn = cast<llvm::Function>(GV); |
826 | llvm::AttrBuilder B; |
827 | B.addAttribute("wasm-import-module", Attr->getImportModule()); |
828 | Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); |
829 | } |
830 | if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { |
831 | llvm::Function *Fn = cast<llvm::Function>(GV); |
832 | llvm::AttrBuilder B; |
833 | B.addAttribute("wasm-import-name", Attr->getImportName()); |
834 | Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); |
835 | } |
836 | if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { |
837 | llvm::Function *Fn = cast<llvm::Function>(GV); |
838 | llvm::AttrBuilder B; |
839 | B.addAttribute("wasm-export-name", Attr->getExportName()); |
840 | Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); |
841 | } |
842 | } |
843 | |
844 | if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { |
845 | llvm::Function *Fn = cast<llvm::Function>(GV); |
846 | if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) |
847 | Fn->addFnAttr("no-prototype"); |
848 | } |
849 | } |
850 | }; |
851 | |
852 | /// Classify argument of given type \p Ty. |
853 | ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { |
854 | Ty = useFirstFieldIfTransparentUnion(Ty); |
855 | |
856 | if (isAggregateTypeForABI(Ty)) { |
857 | // Records with non-trivial destructors/copy-constructors should not be |
858 | // passed by value. |
859 | if (auto RAA = getRecordArgABI(Ty, getCXXABI())) |
860 | return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); |
861 | // Ignore empty structs/unions. |
862 | if (isEmptyRecord(getContext(), Ty, true)) |
863 | return ABIArgInfo::getIgnore(); |
864 | // Lower single-element structs to just pass a regular value. TODO: We |
865 | // could do reasonable-size multiple-element structs too, using getExpand(), |
866 | // though watch out for things like bitfields. |
867 | if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) |
868 | return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); |
869 | // For the experimental multivalue ABI, fully expand all other aggregates |
870 | if (Kind == ABIKind::ExperimentalMV) { |
871 | const RecordType *RT = Ty->getAs<RecordType>(); |
872 | assert(RT)((RT) ? static_cast<void> (0) : __assert_fail ("RT", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 872, __PRETTY_FUNCTION__)); |
873 | bool HasBitField = false; |
874 | for (auto *Field : RT->getDecl()->fields()) { |
875 | if (Field->isBitField()) { |
876 | HasBitField = true; |
877 | break; |
878 | } |
879 | } |
880 | if (!HasBitField) |
881 | return ABIArgInfo::getExpand(); |
882 | } |
883 | } |
884 | |
885 | // Otherwise just do the default thing. |
886 | return defaultInfo.classifyArgumentType(Ty); |
887 | } |
888 | |
889 | ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { |
890 | if (isAggregateTypeForABI(RetTy)) { |
891 | // Records with non-trivial destructors/copy-constructors should not be |
892 | // returned by value. |
893 | if (!getRecordArgABI(RetTy, getCXXABI())) { |
894 | // Ignore empty structs/unions. |
895 | if (isEmptyRecord(getContext(), RetTy, true)) |
896 | return ABIArgInfo::getIgnore(); |
897 | // Lower single-element structs to just return a regular value. TODO: We |
898 | // could do reasonable-size multiple-element structs too, using |
899 | // ABIArgInfo::getDirect(). |
900 | if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) |
901 | return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); |
902 | // For the experimental multivalue ABI, return all other aggregates |
903 | if (Kind == ABIKind::ExperimentalMV) |
904 | return ABIArgInfo::getDirect(); |
905 | } |
906 | } |
907 | |
908 | // Otherwise just do the default thing. |
909 | return defaultInfo.classifyReturnType(RetTy); |
910 | } |
911 | |
912 | Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
913 | QualType Ty) const { |
914 | bool IsIndirect = isAggregateTypeForABI(Ty) && |
915 | !isEmptyRecord(getContext(), Ty, true) && |
916 | !isSingleElementStruct(Ty, getContext()); |
917 | return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, |
918 | getContext().getTypeInfoInChars(Ty), |
919 | CharUnits::fromQuantity(4), |
920 | /*AllowHigherAlign=*/true); |
921 | } |
922 | |
923 | //===----------------------------------------------------------------------===// |
924 | // le32/PNaCl bitcode ABI Implementation |
925 | // |
926 | // This is a simplified version of the x86_32 ABI. Arguments and return values |
927 | // are always passed on the stack. |
928 | //===----------------------------------------------------------------------===// |
929 | |
930 | class PNaClABIInfo : public ABIInfo { |
931 | public: |
932 | PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} |
933 | |
934 | ABIArgInfo classifyReturnType(QualType RetTy) const; |
935 | ABIArgInfo classifyArgumentType(QualType RetTy) const; |
936 | |
937 | void computeInfo(CGFunctionInfo &FI) const override; |
938 | Address EmitVAArg(CodeGenFunction &CGF, |
939 | Address VAListAddr, QualType Ty) const override; |
940 | }; |
941 | |
942 | class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { |
943 | public: |
944 | PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) |
945 | : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} |
946 | }; |
947 | |
948 | void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { |
949 | if (!getCXXABI().classifyReturnType(FI)) |
950 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); |
951 | |
952 | for (auto &I : FI.arguments()) |
953 | I.info = classifyArgumentType(I.type); |
954 | } |
955 | |
956 | Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
957 | QualType Ty) const { |
958 | // The PNaCL ABI is a bit odd, in that varargs don't use normal |
959 | // function classification. Structs get passed directly for varargs |
960 | // functions, through a rewriting transform in |
961 | // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows |
962 | // this target to actually support a va_arg instructions with an |
963 | // aggregate type, unlike other targets. |
964 | return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); |
965 | } |
966 | |
967 | /// Classify argument of given type \p Ty. |
968 | ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { |
969 | if (isAggregateTypeForABI(Ty)) { |
970 | if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) |
971 | return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); |
972 | return getNaturalAlignIndirect(Ty); |
973 | } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { |
974 | // Treat an enum type as its underlying type. |
975 | Ty = EnumTy->getDecl()->getIntegerType(); |
976 | } else if (Ty->isFloatingType()) { |
977 | // Floating-point types don't go inreg. |
978 | return ABIArgInfo::getDirect(); |
979 | } else if (const auto *EIT = Ty->getAs<ExtIntType>()) { |
980 | // Treat extended integers as integers if <=64, otherwise pass indirectly. |
981 | if (EIT->getNumBits() > 64) |
982 | return getNaturalAlignIndirect(Ty); |
983 | return ABIArgInfo::getDirect(); |
984 | } |
985 | |
986 | return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) |
987 | : ABIArgInfo::getDirect()); |
988 | } |
989 | |
990 | ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { |
991 | if (RetTy->isVoidType()) |
992 | return ABIArgInfo::getIgnore(); |
993 | |
994 | // In the PNaCl ABI we always return records/structures on the stack. |
995 | if (isAggregateTypeForABI(RetTy)) |
996 | return getNaturalAlignIndirect(RetTy); |
997 | |
998 | // Treat extended integers as integers if <=64, otherwise pass indirectly. |
999 | if (const auto *EIT = RetTy->getAs<ExtIntType>()) { |
1000 | if (EIT->getNumBits() > 64) |
1001 | return getNaturalAlignIndirect(RetTy); |
1002 | return ABIArgInfo::getDirect(); |
1003 | } |
1004 | |
1005 | // Treat an enum type as its underlying type. |
1006 | if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) |
1007 | RetTy = EnumTy->getDecl()->getIntegerType(); |
1008 | |
1009 | return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) |
1010 | : ABIArgInfo::getDirect()); |
1011 | } |
1012 | |
1013 | /// IsX86_MMXType - Return true if this is an MMX type. |
1014 | bool IsX86_MMXType(llvm::Type *IRType) { |
1015 | // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. |
1016 | return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && |
1017 | cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && |
1018 | IRType->getScalarSizeInBits() != 64; |
1019 | } |
1020 | |
1021 | static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, |
1022 | StringRef Constraint, |
1023 | llvm::Type* Ty) { |
1024 | bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) |
1025 | .Cases("y", "&y", "^Ym", true) |
1026 | .Default(false); |
1027 | if (IsMMXCons && Ty->isVectorTy()) { |
1028 | if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != |
1029 | 64) { |
1030 | // Invalid MMX constraint |
1031 | return nullptr; |
1032 | } |
1033 | |
1034 | return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); |
1035 | } |
1036 | |
1037 | // No operation needed |
1038 | return Ty; |
1039 | } |
1040 | |
1041 | /// Returns true if this type can be passed in SSE registers with the |
1042 | /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. |
1043 | static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { |
1044 | if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { |
1045 | if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { |
1046 | if (BT->getKind() == BuiltinType::LongDouble) { |
1047 | if (&Context.getTargetInfo().getLongDoubleFormat() == |
1048 | &llvm::APFloat::x87DoubleExtended()) |
1049 | return false; |
1050 | } |
1051 | return true; |
1052 | } |
1053 | } else if (const VectorType *VT = Ty->getAs<VectorType>()) { |
1054 | // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX |
1055 | // registers specially. |
1056 | unsigned VecSize = Context.getTypeSize(VT); |
1057 | if (VecSize == 128 || VecSize == 256 || VecSize == 512) |
1058 | return true; |
1059 | } |
1060 | return false; |
1061 | } |
1062 | |
1063 | /// Returns true if this aggregate is small enough to be passed in SSE registers |
1064 | /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. |
1065 | static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { |
1066 | return NumMembers <= 4; |
1067 | } |
1068 | |
1069 | /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. |
1070 | static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { |
1071 | auto AI = ABIArgInfo::getDirect(T); |
1072 | AI.setInReg(true); |
1073 | AI.setCanBeFlattened(false); |
1074 | return AI; |
1075 | } |
1076 | |
1077 | //===----------------------------------------------------------------------===// |
1078 | // X86-32 ABI Implementation |
1079 | //===----------------------------------------------------------------------===// |
1080 | |
1081 | /// Similar to llvm::CCState, but for Clang. |
1082 | struct CCState { |
1083 | CCState(CGFunctionInfo &FI) |
1084 | : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} |
1085 | |
1086 | llvm::SmallBitVector IsPreassigned; |
1087 | unsigned CC = CallingConv::CC_C; |
1088 | unsigned FreeRegs = 0; |
1089 | unsigned FreeSSERegs = 0; |
1090 | }; |
1091 | |
1092 | enum { |
1093 | // Vectorcall only allows the first 6 parameters to be passed in registers. |
1094 | VectorcallMaxParamNumAsReg = 6 |
1095 | }; |
1096 | |
1097 | /// X86_32ABIInfo - The X86-32 ABI information. |
1098 | class X86_32ABIInfo : public SwiftABIInfo { |
1099 | enum Class { |
1100 | Integer, |
1101 | Float |
1102 | }; |
1103 | |
1104 | static const unsigned MinABIStackAlignInBytes = 4; |
1105 | |
1106 | bool IsDarwinVectorABI; |
1107 | bool IsRetSmallStructInRegABI; |
1108 | bool IsWin32StructABI; |
1109 | bool IsSoftFloatABI; |
1110 | bool IsMCUABI; |
1111 | unsigned DefaultNumRegisterParameters; |
1112 | |
1113 | static bool isRegisterSize(unsigned Size) { |
1114 | return (Size == 8 || Size == 16 || Size == 32 || Size == 64); |
1115 | } |
1116 | |
1117 | bool isHomogeneousAggregateBaseType(QualType Ty) const override { |
1118 | // FIXME: Assumes vectorcall is in use. |
1119 | return isX86VectorTypeForVectorCall(getContext(), Ty); |
1120 | } |
1121 | |
1122 | bool isHomogeneousAggregateSmallEnough(const Type *Ty, |
1123 | uint64_t NumMembers) const override { |
1124 | // FIXME: Assumes vectorcall is in use. |
1125 | return isX86VectorCallAggregateSmallEnough(NumMembers); |
1126 | } |
1127 | |
1128 | bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; |
1129 | |
1130 | /// getIndirectResult - Give a source type \arg Ty, return a suitable result |
1131 | /// such that the argument will be passed in memory. |
1132 | ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; |
1133 | |
1134 | ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; |
1135 | |
1136 | /// Return the alignment to use for the given type on the stack. |
1137 | unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; |
1138 | |
1139 | Class classify(QualType Ty) const; |
1140 | ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; |
1141 | ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; |
1142 | |
1143 | /// Updates the number of available free registers, returns |
1144 | /// true if any registers were allocated. |
1145 | bool updateFreeRegs(QualType Ty, CCState &State) const; |
1146 | |
1147 | bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, |
1148 | bool &NeedsPadding) const; |
1149 | bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; |
1150 | |
1151 | bool canExpandIndirectArgument(QualType Ty) const; |
1152 | |
1153 | /// Rewrite the function info so that all memory arguments use |
1154 | /// inalloca. |
1155 | void rewriteWithInAlloca(CGFunctionInfo &FI) const; |
1156 | |
1157 | void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, |
1158 | CharUnits &StackOffset, ABIArgInfo &Info, |
1159 | QualType Type) const; |
1160 | void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; |
1161 | |
1162 | public: |
1163 | |
1164 | void computeInfo(CGFunctionInfo &FI) const override; |
1165 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
1166 | QualType Ty) const override; |
1167 | |
1168 | X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, |
1169 | bool RetSmallStructInRegABI, bool Win32StructABI, |
1170 | unsigned NumRegisterParameters, bool SoftFloatABI) |
1171 | : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), |
1172 | IsRetSmallStructInRegABI(RetSmallStructInRegABI), |
1173 | IsWin32StructABI(Win32StructABI), |
1174 | IsSoftFloatABI(SoftFloatABI), |
1175 | IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), |
1176 | DefaultNumRegisterParameters(NumRegisterParameters) {} |
1177 | |
1178 | bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, |
1179 | bool asReturnValue) const override { |
1180 | // LLVM's x86-32 lowering currently only assigns up to three |
1181 | // integer registers and three fp registers. Oddly, it'll use up to |
1182 | // four vector registers for vectors, but those can overlap with the |
1183 | // scalar registers. |
1184 | return occupiesMoreThan(CGT, scalars, /*total*/ 3); |
1185 | } |
1186 | |
1187 | bool isSwiftErrorInRegister() const override { |
1188 | // x86-32 lowering does not support passing swifterror in a register. |
1189 | return false; |
1190 | } |
1191 | }; |
1192 | |
1193 | class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { |
1194 | public: |
1195 | X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, |
1196 | bool RetSmallStructInRegABI, bool Win32StructABI, |
1197 | unsigned NumRegisterParameters, bool SoftFloatABI) |
1198 | : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( |
1199 | CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, |
1200 | NumRegisterParameters, SoftFloatABI)) {} |
1201 | |
1202 | static bool isStructReturnInRegABI( |
1203 | const llvm::Triple &Triple, const CodeGenOptions &Opts); |
1204 | |
1205 | void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
1206 | CodeGen::CodeGenModule &CGM) const override; |
1207 | |
1208 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { |
1209 | // Darwin uses different dwarf register numbers for EH. |
1210 | if (CGM.getTarget().getTriple().isOSDarwin()) return 5; |
1211 | return 4; |
1212 | } |
1213 | |
1214 | bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
1215 | llvm::Value *Address) const override; |
1216 | |
1217 | llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, |
1218 | StringRef Constraint, |
1219 | llvm::Type* Ty) const override { |
1220 | return X86AdjustInlineAsmType(CGF, Constraint, Ty); |
1221 | } |
1222 | |
1223 | void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, |
1224 | std::string &Constraints, |
1225 | std::vector<llvm::Type *> &ResultRegTypes, |
1226 | std::vector<llvm::Type *> &ResultTruncRegTypes, |
1227 | std::vector<LValue> &ResultRegDests, |
1228 | std::string &AsmString, |
1229 | unsigned NumOutputs) const override; |
1230 | |
1231 | llvm::Constant * |
1232 | getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { |
1233 | unsigned Sig = (0xeb << 0) | // jmp rel8 |
1234 | (0x06 << 8) | // .+0x08 |
1235 | ('v' << 16) | |
1236 | ('2' << 24); |
1237 | return llvm::ConstantInt::get(CGM.Int32Ty, Sig); |
1238 | } |
1239 | |
1240 | StringRef getARCRetainAutoreleasedReturnValueMarker() const override { |
1241 | return "movl\t%ebp, %ebp" |
1242 | "\t\t// marker for objc_retainAutoreleaseReturnValue"; |
1243 | } |
1244 | }; |
1245 | |
1246 | } |
1247 | |
1248 | /// Rewrite input constraint references after adding some output constraints. |
1249 | /// In the case where there is one output and one input and we add one output, |
1250 | /// we need to replace all operand references greater than or equal to 1: |
1251 | /// mov $0, $1 |
1252 | /// mov eax, $1 |
1253 | /// The result will be: |
1254 | /// mov $0, $2 |
1255 | /// mov eax, $2 |
1256 | static void rewriteInputConstraintReferences(unsigned FirstIn, |
1257 | unsigned NumNewOuts, |
1258 | std::string &AsmString) { |
1259 | std::string Buf; |
1260 | llvm::raw_string_ostream OS(Buf); |
1261 | size_t Pos = 0; |
1262 | while (Pos < AsmString.size()) { |
1263 | size_t DollarStart = AsmString.find('$', Pos); |
1264 | if (DollarStart == std::string::npos) |
1265 | DollarStart = AsmString.size(); |
1266 | size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); |
1267 | if (DollarEnd == std::string::npos) |
1268 | DollarEnd = AsmString.size(); |
1269 | OS << StringRef(&AsmString[Pos], DollarEnd - Pos); |
1270 | Pos = DollarEnd; |
1271 | size_t NumDollars = DollarEnd - DollarStart; |
1272 | if (NumDollars % 2 != 0 && Pos < AsmString.size()) { |
1273 | // We have an operand reference. |
1274 | size_t DigitStart = Pos; |
1275 | if (AsmString[DigitStart] == '{') { |
1276 | OS << '{'; |
1277 | ++DigitStart; |
1278 | } |
1279 | size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); |
1280 | if (DigitEnd == std::string::npos) |
1281 | DigitEnd = AsmString.size(); |
1282 | StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); |
1283 | unsigned OperandIndex; |
1284 | if (!OperandStr.getAsInteger(10, OperandIndex)) { |
1285 | if (OperandIndex >= FirstIn) |
1286 | OperandIndex += NumNewOuts; |
1287 | OS << OperandIndex; |
1288 | } else { |
1289 | OS << OperandStr; |
1290 | } |
1291 | Pos = DigitEnd; |
1292 | } |
1293 | } |
1294 | AsmString = std::move(OS.str()); |
1295 | } |
1296 | |
1297 | /// Add output constraints for EAX:EDX because they are return registers. |
1298 | void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( |
1299 | CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, |
1300 | std::vector<llvm::Type *> &ResultRegTypes, |
1301 | std::vector<llvm::Type *> &ResultTruncRegTypes, |
1302 | std::vector<LValue> &ResultRegDests, std::string &AsmString, |
1303 | unsigned NumOutputs) const { |
1304 | uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); |
1305 | |
1306 | // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is |
1307 | // larger. |
1308 | if (!Constraints.empty()) |
1309 | Constraints += ','; |
1310 | if (RetWidth <= 32) { |
1311 | Constraints += "={eax}"; |
1312 | ResultRegTypes.push_back(CGF.Int32Ty); |
1313 | } else { |
1314 | // Use the 'A' constraint for EAX:EDX. |
1315 | Constraints += "=A"; |
1316 | ResultRegTypes.push_back(CGF.Int64Ty); |
1317 | } |
1318 | |
1319 | // Truncate EAX or EAX:EDX to an integer of the appropriate size. |
1320 | llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); |
1321 | ResultTruncRegTypes.push_back(CoerceTy); |
1322 | |
1323 | // Coerce the integer by bitcasting the return slot pointer. |
1324 | ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), |
1325 | CoerceTy->getPointerTo())); |
1326 | ResultRegDests.push_back(ReturnSlot); |
1327 | |
1328 | rewriteInputConstraintReferences(NumOutputs, 1, AsmString); |
1329 | } |
1330 | |
1331 | /// shouldReturnTypeInRegister - Determine if the given type should be |
1332 | /// returned in a register (for the Darwin and MCU ABI). |
1333 | bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, |
1334 | ASTContext &Context) const { |
1335 | uint64_t Size = Context.getTypeSize(Ty); |
1336 | |
1337 | // For i386, type must be register sized. |
1338 | // For the MCU ABI, it only needs to be <= 8-byte |
1339 | if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) |
1340 | return false; |
1341 | |
1342 | if (Ty->isVectorType()) { |
1343 | // 64- and 128- bit vectors inside structures are not returned in |
1344 | // registers. |
1345 | if (Size == 64 || Size == 128) |
1346 | return false; |
1347 | |
1348 | return true; |
1349 | } |
1350 | |
1351 | // If this is a builtin, pointer, enum, complex type, member pointer, or |
1352 | // member function pointer it is ok. |
1353 | if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || |
1354 | Ty->isAnyComplexType() || Ty->isEnumeralType() || |
1355 | Ty->isBlockPointerType() || Ty->isMemberPointerType()) |
1356 | return true; |
1357 | |
1358 | // Arrays are treated like records. |
1359 | if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) |
1360 | return shouldReturnTypeInRegister(AT->getElementType(), Context); |
1361 | |
1362 | // Otherwise, it must be a record type. |
1363 | const RecordType *RT = Ty->getAs<RecordType>(); |
1364 | if (!RT) return false; |
1365 | |
1366 | // FIXME: Traverse bases here too. |
1367 | |
1368 | // Structure types are passed in register if all fields would be |
1369 | // passed in a register. |
1370 | for (const auto *FD : RT->getDecl()->fields()) { |
1371 | // Empty fields are ignored. |
1372 | if (isEmptyField(Context, FD, true)) |
1373 | continue; |
1374 | |
1375 | // Check fields recursively. |
1376 | if (!shouldReturnTypeInRegister(FD->getType(), Context)) |
1377 | return false; |
1378 | } |
1379 | return true; |
1380 | } |
1381 | |
1382 | static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { |
1383 | // Treat complex types as the element type. |
1384 | if (const ComplexType *CTy = Ty->getAs<ComplexType>()) |
1385 | Ty = CTy->getElementType(); |
1386 | |
1387 | // Check for a type which we know has a simple scalar argument-passing |
1388 | // convention without any padding. (We're specifically looking for 32 |
1389 | // and 64-bit integer and integer-equivalents, float, and double.) |
1390 | if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && |
1391 | !Ty->isEnumeralType() && !Ty->isBlockPointerType()) |
1392 | return false; |
1393 | |
1394 | uint64_t Size = Context.getTypeSize(Ty); |
1395 | return Size == 32 || Size == 64; |
1396 | } |
1397 | |
1398 | static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, |
1399 | uint64_t &Size) { |
1400 | for (const auto *FD : RD->fields()) { |
1401 | // Scalar arguments on the stack get 4 byte alignment on x86. If the |
1402 | // argument is smaller than 32-bits, expanding the struct will create |
1403 | // alignment padding. |
1404 | if (!is32Or64BitBasicType(FD->getType(), Context)) |
1405 | return false; |
1406 | |
1407 | // FIXME: Reject bit-fields wholesale; there are two problems, we don't know |
1408 | // how to expand them yet, and the predicate for telling if a bitfield still |
1409 | // counts as "basic" is more complicated than what we were doing previously. |
1410 | if (FD->isBitField()) |
1411 | return false; |
1412 | |
1413 | Size += Context.getTypeSize(FD->getType()); |
1414 | } |
1415 | return true; |
1416 | } |
1417 | |
1418 | static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, |
1419 | uint64_t &Size) { |
1420 | // Don't do this if there are any non-empty bases. |
1421 | for (const CXXBaseSpecifier &Base : RD->bases()) { |
1422 | if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), |
1423 | Size)) |
1424 | return false; |
1425 | } |
1426 | if (!addFieldSizes(Context, RD, Size)) |
1427 | return false; |
1428 | return true; |
1429 | } |
1430 | |
1431 | /// Test whether an argument type which is to be passed indirectly (on the |
1432 | /// stack) would have the equivalent layout if it was expanded into separate |
1433 | /// arguments. If so, we prefer to do the latter to avoid inhibiting |
1434 | /// optimizations. |
1435 | bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { |
1436 | // We can only expand structure types. |
1437 | const RecordType *RT = Ty->getAs<RecordType>(); |
1438 | if (!RT) |
1439 | return false; |
1440 | const RecordDecl *RD = RT->getDecl(); |
1441 | uint64_t Size = 0; |
1442 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
1443 | if (!IsWin32StructABI) { |
1444 | // On non-Windows, we have to conservatively match our old bitcode |
1445 | // prototypes in order to be ABI-compatible at the bitcode level. |
1446 | if (!CXXRD->isCLike()) |
1447 | return false; |
1448 | } else { |
1449 | // Don't do this for dynamic classes. |
1450 | if (CXXRD->isDynamicClass()) |
1451 | return false; |
1452 | } |
1453 | if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) |
1454 | return false; |
1455 | } else { |
1456 | if (!addFieldSizes(getContext(), RD, Size)) |
1457 | return false; |
1458 | } |
1459 | |
1460 | // We can do this if there was no alignment padding. |
1461 | return Size == getContext().getTypeSize(Ty); |
1462 | } |
1463 | |
1464 | ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { |
1465 | // If the return value is indirect, then the hidden argument is consuming one |
1466 | // integer register. |
1467 | if (State.FreeRegs) { |
1468 | --State.FreeRegs; |
1469 | if (!IsMCUABI) |
1470 | return getNaturalAlignIndirectInReg(RetTy); |
1471 | } |
1472 | return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); |
1473 | } |
1474 | |
1475 | ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, |
1476 | CCState &State) const { |
1477 | if (RetTy->isVoidType()) |
1478 | return ABIArgInfo::getIgnore(); |
1479 | |
1480 | const Type *Base = nullptr; |
1481 | uint64_t NumElts = 0; |
1482 | if ((State.CC == llvm::CallingConv::X86_VectorCall || |
1483 | State.CC == llvm::CallingConv::X86_RegCall) && |
1484 | isHomogeneousAggregate(RetTy, Base, NumElts)) { |
1485 | // The LLVM struct type for such an aggregate should lower properly. |
1486 | return ABIArgInfo::getDirect(); |
1487 | } |
1488 | |
1489 | if (const VectorType *VT = RetTy->getAs<VectorType>()) { |
1490 | // On Darwin, some vectors are returned in registers. |
1491 | if (IsDarwinVectorABI) { |
1492 | uint64_t Size = getContext().getTypeSize(RetTy); |
1493 | |
1494 | // 128-bit vectors are a special case; they are returned in |
1495 | // registers and we need to make sure to pick a type the LLVM |
1496 | // backend will like. |
1497 | if (Size == 128) |
1498 | return ABIArgInfo::getDirect(llvm::FixedVectorType::get( |
1499 | llvm::Type::getInt64Ty(getVMContext()), 2)); |
1500 | |
1501 | // Always return in register if it fits in a general purpose |
1502 | // register, or if it is 64 bits and has a single element. |
1503 | if ((Size == 8 || Size == 16 || Size == 32) || |
1504 | (Size == 64 && VT->getNumElements() == 1)) |
1505 | return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), |
1506 | Size)); |
1507 | |
1508 | return getIndirectReturnResult(RetTy, State); |
1509 | } |
1510 | |
1511 | return ABIArgInfo::getDirect(); |
1512 | } |
1513 | |
1514 | if (isAggregateTypeForABI(RetTy)) { |
1515 | if (const RecordType *RT = RetTy->getAs<RecordType>()) { |
1516 | // Structures with flexible arrays are always indirect. |
1517 | if (RT->getDecl()->hasFlexibleArrayMember()) |
1518 | return getIndirectReturnResult(RetTy, State); |
1519 | } |
1520 | |
1521 | // If specified, structs and unions are always indirect. |
1522 | if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) |
1523 | return getIndirectReturnResult(RetTy, State); |
1524 | |
1525 | // Ignore empty structs/unions. |
1526 | if (isEmptyRecord(getContext(), RetTy, true)) |
1527 | return ABIArgInfo::getIgnore(); |
1528 | |
1529 | // Small structures which are register sized are generally returned |
1530 | // in a register. |
1531 | if (shouldReturnTypeInRegister(RetTy, getContext())) { |
1532 | uint64_t Size = getContext().getTypeSize(RetTy); |
1533 | |
1534 | // As a special-case, if the struct is a "single-element" struct, and |
1535 | // the field is of type "float" or "double", return it in a |
1536 | // floating-point register. (MSVC does not apply this special case.) |
1537 | // We apply a similar transformation for pointer types to improve the |
1538 | // quality of the generated IR. |
1539 | if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) |
1540 | if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) |
1541 | || SeltTy->hasPointerRepresentation()) |
1542 | return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); |
1543 | |
1544 | // FIXME: We should be able to narrow this integer in cases with dead |
1545 | // padding. |
1546 | return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); |
1547 | } |
1548 | |
1549 | return getIndirectReturnResult(RetTy, State); |
1550 | } |
1551 | |
1552 | // Treat an enum type as its underlying type. |
1553 | if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) |
1554 | RetTy = EnumTy->getDecl()->getIntegerType(); |
1555 | |
1556 | if (const auto *EIT = RetTy->getAs<ExtIntType>()) |
1557 | if (EIT->getNumBits() > 64) |
1558 | return getIndirectReturnResult(RetTy, State); |
1559 | |
1560 | return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) |
1561 | : ABIArgInfo::getDirect()); |
1562 | } |
1563 | |
1564 | static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { |
1565 | return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; |
1566 | } |
1567 | |
1568 | static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { |
1569 | const RecordType *RT = Ty->getAs<RecordType>(); |
1570 | if (!RT) |
1571 | return 0; |
1572 | const RecordDecl *RD = RT->getDecl(); |
1573 | |
1574 | // If this is a C++ record, check the bases first. |
1575 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) |
1576 | for (const auto &I : CXXRD->bases()) |
1577 | if (!isRecordWithSIMDVectorType(Context, I.getType())) |
1578 | return false; |
1579 | |
1580 | for (const auto *i : RD->fields()) { |
1581 | QualType FT = i->getType(); |
1582 | |
1583 | if (isSIMDVectorType(Context, FT)) |
1584 | return true; |
1585 | |
1586 | if (isRecordWithSIMDVectorType(Context, FT)) |
1587 | return true; |
1588 | } |
1589 | |
1590 | return false; |
1591 | } |
1592 | |
1593 | unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, |
1594 | unsigned Align) const { |
1595 | // Otherwise, if the alignment is less than or equal to the minimum ABI |
1596 | // alignment, just use the default; the backend will handle this. |
1597 | if (Align <= MinABIStackAlignInBytes) |
1598 | return 0; // Use default alignment. |
1599 | |
1600 | // On non-Darwin, the stack type alignment is always 4. |
1601 | if (!IsDarwinVectorABI) { |
1602 | // Set explicit alignment, since we may need to realign the top. |
1603 | return MinABIStackAlignInBytes; |
1604 | } |
1605 | |
1606 | // Otherwise, if the type contains an SSE vector type, the alignment is 16. |
1607 | if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || |
1608 | isRecordWithSIMDVectorType(getContext(), Ty))) |
1609 | return 16; |
1610 | |
1611 | return MinABIStackAlignInBytes; |
1612 | } |
1613 | |
1614 | ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, |
1615 | CCState &State) const { |
1616 | if (!ByVal) { |
1617 | if (State.FreeRegs) { |
1618 | --State.FreeRegs; // Non-byval indirects just use one pointer. |
1619 | if (!IsMCUABI) |
1620 | return getNaturalAlignIndirectInReg(Ty); |
1621 | } |
1622 | return getNaturalAlignIndirect(Ty, false); |
1623 | } |
1624 | |
1625 | // Compute the byval alignment. |
1626 | unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; |
1627 | unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); |
1628 | if (StackAlign == 0) |
1629 | return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); |
1630 | |
1631 | // If the stack alignment is less than the type alignment, realign the |
1632 | // argument. |
1633 | bool Realign = TypeAlign > StackAlign; |
1634 | return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), |
1635 | /*ByVal=*/true, Realign); |
1636 | } |
1637 | |
1638 | X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { |
1639 | const Type *T = isSingleElementStruct(Ty, getContext()); |
1640 | if (!T) |
1641 | T = Ty.getTypePtr(); |
1642 | |
1643 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) { |
1644 | BuiltinType::Kind K = BT->getKind(); |
1645 | if (K == BuiltinType::Float || K == BuiltinType::Double) |
1646 | return Float; |
1647 | } |
1648 | return Integer; |
1649 | } |
1650 | |
1651 | bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { |
1652 | if (!IsSoftFloatABI) { |
1653 | Class C = classify(Ty); |
1654 | if (C == Float) |
1655 | return false; |
1656 | } |
1657 | |
1658 | unsigned Size = getContext().getTypeSize(Ty); |
1659 | unsigned SizeInRegs = (Size + 31) / 32; |
1660 | |
1661 | if (SizeInRegs == 0) |
1662 | return false; |
1663 | |
1664 | if (!IsMCUABI) { |
1665 | if (SizeInRegs > State.FreeRegs) { |
1666 | State.FreeRegs = 0; |
1667 | return false; |
1668 | } |
1669 | } else { |
1670 | // The MCU psABI allows passing parameters in-reg even if there are |
1671 | // earlier parameters that are passed on the stack. Also, |
1672 | // it does not allow passing >8-byte structs in-register, |
1673 | // even if there are 3 free registers available. |
1674 | if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) |
1675 | return false; |
1676 | } |
1677 | |
1678 | State.FreeRegs -= SizeInRegs; |
1679 | return true; |
1680 | } |
1681 | |
1682 | bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, |
1683 | bool &InReg, |
1684 | bool &NeedsPadding) const { |
1685 | // On Windows, aggregates other than HFAs are never passed in registers, and |
1686 | // they do not consume register slots. Homogenous floating-point aggregates |
1687 | // (HFAs) have already been dealt with at this point. |
1688 | if (IsWin32StructABI && isAggregateTypeForABI(Ty)) |
1689 | return false; |
1690 | |
1691 | NeedsPadding = false; |
1692 | InReg = !IsMCUABI; |
1693 | |
1694 | if (!updateFreeRegs(Ty, State)) |
1695 | return false; |
1696 | |
1697 | if (IsMCUABI) |
1698 | return true; |
1699 | |
1700 | if (State.CC == llvm::CallingConv::X86_FastCall || |
1701 | State.CC == llvm::CallingConv::X86_VectorCall || |
1702 | State.CC == llvm::CallingConv::X86_RegCall) { |
1703 | if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) |
1704 | NeedsPadding = true; |
1705 | |
1706 | return false; |
1707 | } |
1708 | |
1709 | return true; |
1710 | } |
1711 | |
1712 | bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { |
1713 | if (!updateFreeRegs(Ty, State)) |
1714 | return false; |
1715 | |
1716 | if (IsMCUABI) |
1717 | return false; |
1718 | |
1719 | if (State.CC == llvm::CallingConv::X86_FastCall || |
1720 | State.CC == llvm::CallingConv::X86_VectorCall || |
1721 | State.CC == llvm::CallingConv::X86_RegCall) { |
1722 | if (getContext().getTypeSize(Ty) > 32) |
1723 | return false; |
1724 | |
1725 | return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || |
1726 | Ty->isReferenceType()); |
1727 | } |
1728 | |
1729 | return true; |
1730 | } |
1731 | |
1732 | void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { |
1733 | // Vectorcall x86 works subtly different than in x64, so the format is |
1734 | // a bit different than the x64 version. First, all vector types (not HVAs) |
1735 | // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. |
1736 | // This differs from the x64 implementation, where the first 6 by INDEX get |
1737 | // registers. |
1738 | // In the second pass over the arguments, HVAs are passed in the remaining |
1739 | // vector registers if possible, or indirectly by address. The address will be |
1740 | // passed in ECX/EDX if available. Any other arguments are passed according to |
1741 | // the usual fastcall rules. |
1742 | MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); |
1743 | for (int I = 0, E = Args.size(); I < E; ++I) { |
1744 | const Type *Base = nullptr; |
1745 | uint64_t NumElts = 0; |
1746 | const QualType &Ty = Args[I].type; |
1747 | if ((Ty->isVectorType() || Ty->isBuiltinType()) && |
1748 | isHomogeneousAggregate(Ty, Base, NumElts)) { |
1749 | if (State.FreeSSERegs >= NumElts) { |
1750 | State.FreeSSERegs -= NumElts; |
1751 | Args[I].info = ABIArgInfo::getDirectInReg(); |
1752 | State.IsPreassigned.set(I); |
1753 | } |
1754 | } |
1755 | } |
1756 | } |
1757 | |
1758 | ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, |
1759 | CCState &State) const { |
1760 | // FIXME: Set alignment on indirect arguments. |
1761 | bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; |
1762 | bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; |
1763 | bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; |
1764 | |
1765 | Ty = useFirstFieldIfTransparentUnion(Ty); |
1766 | TypeInfo TI = getContext().getTypeInfo(Ty); |
1767 | |
1768 | // Check with the C++ ABI first. |
1769 | const RecordType *RT = Ty->getAs<RecordType>(); |
1770 | if (RT) { |
1771 | CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); |
1772 | if (RAA == CGCXXABI::RAA_Indirect) { |
1773 | return getIndirectResult(Ty, false, State); |
1774 | } else if (RAA == CGCXXABI::RAA_DirectInMemory) { |
1775 | // The field index doesn't matter, we'll fix it up later. |
1776 | return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); |
1777 | } |
1778 | } |
1779 | |
1780 | // Regcall uses the concept of a homogenous vector aggregate, similar |
1781 | // to other targets. |
1782 | const Type *Base = nullptr; |
1783 | uint64_t NumElts = 0; |
1784 | if ((IsRegCall || IsVectorCall) && |
1785 | isHomogeneousAggregate(Ty, Base, NumElts)) { |
1786 | if (State.FreeSSERegs >= NumElts) { |
1787 | State.FreeSSERegs -= NumElts; |
1788 | |
1789 | // Vectorcall passes HVAs directly and does not flatten them, but regcall |
1790 | // does. |
1791 | if (IsVectorCall) |
1792 | return getDirectX86Hva(); |
1793 | |
1794 | if (Ty->isBuiltinType() || Ty->isVectorType()) |
1795 | return ABIArgInfo::getDirect(); |
1796 | return ABIArgInfo::getExpand(); |
1797 | } |
1798 | return getIndirectResult(Ty, /*ByVal=*/false, State); |
1799 | } |
1800 | |
1801 | if (isAggregateTypeForABI(Ty)) { |
1802 | // Structures with flexible arrays are always indirect. |
1803 | // FIXME: This should not be byval! |
1804 | if (RT && RT->getDecl()->hasFlexibleArrayMember()) |
1805 | return getIndirectResult(Ty, true, State); |
1806 | |
1807 | // Ignore empty structs/unions on non-Windows. |
1808 | if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) |
1809 | return ABIArgInfo::getIgnore(); |
1810 | |
1811 | llvm::LLVMContext &LLVMContext = getVMContext(); |
1812 | llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); |
1813 | bool NeedsPadding = false; |
1814 | bool InReg; |
1815 | if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { |
1816 | unsigned SizeInRegs = (TI.Width + 31) / 32; |
1817 | SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); |
1818 | llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); |
1819 | if (InReg) |
1820 | return ABIArgInfo::getDirectInReg(Result); |
1821 | else |
1822 | return ABIArgInfo::getDirect(Result); |
1823 | } |
1824 | llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; |
1825 | |
1826 | // Pass over-aligned aggregates on Windows indirectly. This behavior was |
1827 | // added in MSVC 2015. |
1828 | if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32) |
1829 | return getIndirectResult(Ty, /*ByVal=*/false, State); |
1830 | |
1831 | // Expand small (<= 128-bit) record types when we know that the stack layout |
1832 | // of those arguments will match the struct. This is important because the |
1833 | // LLVM backend isn't smart enough to remove byval, which inhibits many |
1834 | // optimizations. |
1835 | // Don't do this for the MCU if there are still free integer registers |
1836 | // (see X86_64 ABI for full explanation). |
1837 | if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && |
1838 | canExpandIndirectArgument(Ty)) |
1839 | return ABIArgInfo::getExpandWithPadding( |
1840 | IsFastCall || IsVectorCall || IsRegCall, PaddingType); |
1841 | |
1842 | return getIndirectResult(Ty, true, State); |
1843 | } |
1844 | |
1845 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
1846 | // On Windows, vectors are passed directly if registers are available, or |
1847 | // indirectly if not. This avoids the need to align argument memory. Pass |
1848 | // user-defined vector types larger than 512 bits indirectly for simplicity. |
1849 | if (IsWin32StructABI) { |
1850 | if (TI.Width <= 512 && State.FreeSSERegs > 0) { |
1851 | --State.FreeSSERegs; |
1852 | return ABIArgInfo::getDirectInReg(); |
1853 | } |
1854 | return getIndirectResult(Ty, /*ByVal=*/false, State); |
1855 | } |
1856 | |
1857 | // On Darwin, some vectors are passed in memory, we handle this by passing |
1858 | // it as an i8/i16/i32/i64. |
1859 | if (IsDarwinVectorABI) { |
1860 | if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || |
1861 | (TI.Width == 64 && VT->getNumElements() == 1)) |
1862 | return ABIArgInfo::getDirect( |
1863 | llvm::IntegerType::get(getVMContext(), TI.Width)); |
1864 | } |
1865 | |
1866 | if (IsX86_MMXType(CGT.ConvertType(Ty))) |
1867 | return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); |
1868 | |
1869 | return ABIArgInfo::getDirect(); |
1870 | } |
1871 | |
1872 | |
1873 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
1874 | Ty = EnumTy->getDecl()->getIntegerType(); |
1875 | |
1876 | bool InReg = shouldPrimitiveUseInReg(Ty, State); |
1877 | |
1878 | if (isPromotableIntegerTypeForABI(Ty)) { |
1879 | if (InReg) |
1880 | return ABIArgInfo::getExtendInReg(Ty); |
1881 | return ABIArgInfo::getExtend(Ty); |
1882 | } |
1883 | |
1884 | if (const auto * EIT = Ty->getAs<ExtIntType>()) { |
1885 | if (EIT->getNumBits() <= 64) { |
1886 | if (InReg) |
1887 | return ABIArgInfo::getDirectInReg(); |
1888 | return ABIArgInfo::getDirect(); |
1889 | } |
1890 | return getIndirectResult(Ty, /*ByVal=*/false, State); |
1891 | } |
1892 | |
1893 | if (InReg) |
1894 | return ABIArgInfo::getDirectInReg(); |
1895 | return ABIArgInfo::getDirect(); |
1896 | } |
1897 | |
1898 | void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { |
1899 | CCState State(FI); |
1900 | if (IsMCUABI) |
1901 | State.FreeRegs = 3; |
1902 | else if (State.CC == llvm::CallingConv::X86_FastCall) { |
1903 | State.FreeRegs = 2; |
1904 | State.FreeSSERegs = 3; |
1905 | } else if (State.CC == llvm::CallingConv::X86_VectorCall) { |
1906 | State.FreeRegs = 2; |
1907 | State.FreeSSERegs = 6; |
1908 | } else if (FI.getHasRegParm()) |
1909 | State.FreeRegs = FI.getRegParm(); |
1910 | else if (State.CC == llvm::CallingConv::X86_RegCall) { |
1911 | State.FreeRegs = 5; |
1912 | State.FreeSSERegs = 8; |
1913 | } else if (IsWin32StructABI) { |
1914 | // Since MSVC 2015, the first three SSE vectors have been passed in |
1915 | // registers. The rest are passed indirectly. |
1916 | State.FreeRegs = DefaultNumRegisterParameters; |
1917 | State.FreeSSERegs = 3; |
1918 | } else |
1919 | State.FreeRegs = DefaultNumRegisterParameters; |
1920 | |
1921 | if (!::classifyReturnType(getCXXABI(), FI, *this)) { |
1922 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); |
1923 | } else if (FI.getReturnInfo().isIndirect()) { |
1924 | // The C++ ABI is not aware of register usage, so we have to check if the |
1925 | // return value was sret and put it in a register ourselves if appropriate. |
1926 | if (State.FreeRegs) { |
1927 | --State.FreeRegs; // The sret parameter consumes a register. |
1928 | if (!IsMCUABI) |
1929 | FI.getReturnInfo().setInReg(true); |
1930 | } |
1931 | } |
1932 | |
1933 | // The chain argument effectively gives us another free register. |
1934 | if (FI.isChainCall()) |
1935 | ++State.FreeRegs; |
1936 | |
1937 | // For vectorcall, do a first pass over the arguments, assigning FP and vector |
1938 | // arguments to XMM registers as available. |
1939 | if (State.CC == llvm::CallingConv::X86_VectorCall) |
1940 | runVectorCallFirstPass(FI, State); |
1941 | |
1942 | bool UsedInAlloca = false; |
1943 | MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); |
1944 | for (int I = 0, E = Args.size(); I < E; ++I) { |
1945 | // Skip arguments that have already been assigned. |
1946 | if (State.IsPreassigned.test(I)) |
1947 | continue; |
1948 | |
1949 | Args[I].info = classifyArgumentType(Args[I].type, State); |
1950 | UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); |
1951 | } |
1952 | |
1953 | // If we needed to use inalloca for any argument, do a second pass and rewrite |
1954 | // all the memory arguments to use inalloca. |
1955 | if (UsedInAlloca) |
1956 | rewriteWithInAlloca(FI); |
1957 | } |
1958 | |
1959 | void |
1960 | X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, |
1961 | CharUnits &StackOffset, ABIArgInfo &Info, |
1962 | QualType Type) const { |
1963 | // Arguments are always 4-byte-aligned. |
1964 | CharUnits WordSize = CharUnits::fromQuantity(4); |
1965 | assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct")((StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct" ) ? static_cast<void> (0) : __assert_fail ("StackOffset.isMultipleOf(WordSize) && \"unaligned inalloca struct\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 1965, __PRETTY_FUNCTION__)); |
1966 | |
1967 | // sret pointers and indirect things will require an extra pointer |
1968 | // indirection, unless they are byval. Most things are byval, and will not |
1969 | // require this indirection. |
1970 | bool IsIndirect = false; |
1971 | if (Info.isIndirect() && !Info.getIndirectByVal()) |
1972 | IsIndirect = true; |
1973 | Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); |
1974 | llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); |
1975 | if (IsIndirect) |
1976 | LLTy = LLTy->getPointerTo(0); |
1977 | FrameFields.push_back(LLTy); |
1978 | StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); |
1979 | |
1980 | // Insert padding bytes to respect alignment. |
1981 | CharUnits FieldEnd = StackOffset; |
1982 | StackOffset = FieldEnd.alignTo(WordSize); |
1983 | if (StackOffset != FieldEnd) { |
1984 | CharUnits NumBytes = StackOffset - FieldEnd; |
1985 | llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); |
1986 | Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); |
1987 | FrameFields.push_back(Ty); |
1988 | } |
1989 | } |
1990 | |
1991 | static bool isArgInAlloca(const ABIArgInfo &Info) { |
1992 | // Leave ignored and inreg arguments alone. |
1993 | switch (Info.getKind()) { |
1994 | case ABIArgInfo::InAlloca: |
1995 | return true; |
1996 | case ABIArgInfo::Ignore: |
1997 | case ABIArgInfo::IndirectAliased: |
1998 | return false; |
1999 | case ABIArgInfo::Indirect: |
2000 | case ABIArgInfo::Direct: |
2001 | case ABIArgInfo::Extend: |
2002 | return !Info.getInReg(); |
2003 | case ABIArgInfo::Expand: |
2004 | case ABIArgInfo::CoerceAndExpand: |
2005 | // These are aggregate types which are never passed in registers when |
2006 | // inalloca is involved. |
2007 | return true; |
2008 | } |
2009 | llvm_unreachable("invalid enum")::llvm::llvm_unreachable_internal("invalid enum", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2009); |
2010 | } |
2011 | |
2012 | void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { |
2013 | assert(IsWin32StructABI && "inalloca only supported on win32")((IsWin32StructABI && "inalloca only supported on win32" ) ? static_cast<void> (0) : __assert_fail ("IsWin32StructABI && \"inalloca only supported on win32\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2013, __PRETTY_FUNCTION__)); |
2014 | |
2015 | // Build a packed struct type for all of the arguments in memory. |
2016 | SmallVector<llvm::Type *, 6> FrameFields; |
2017 | |
2018 | // The stack alignment is always 4. |
2019 | CharUnits StackAlign = CharUnits::fromQuantity(4); |
2020 | |
2021 | CharUnits StackOffset; |
2022 | CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); |
2023 | |
2024 | // Put 'this' into the struct before 'sret', if necessary. |
2025 | bool IsThisCall = |
2026 | FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; |
2027 | ABIArgInfo &Ret = FI.getReturnInfo(); |
2028 | if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && |
2029 | isArgInAlloca(I->info)) { |
2030 | addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); |
2031 | ++I; |
2032 | } |
2033 | |
2034 | // Put the sret parameter into the inalloca struct if it's in memory. |
2035 | if (Ret.isIndirect() && !Ret.getInReg()) { |
2036 | addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); |
2037 | // On Windows, the hidden sret parameter is always returned in eax. |
2038 | Ret.setInAllocaSRet(IsWin32StructABI); |
2039 | } |
2040 | |
2041 | // Skip the 'this' parameter in ecx. |
2042 | if (IsThisCall) |
2043 | ++I; |
2044 | |
2045 | // Put arguments passed in memory into the struct. |
2046 | for (; I != E; ++I) { |
2047 | if (isArgInAlloca(I->info)) |
2048 | addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); |
2049 | } |
2050 | |
2051 | FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, |
2052 | /*isPacked=*/true), |
2053 | StackAlign); |
2054 | } |
2055 | |
2056 | Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, |
2057 | Address VAListAddr, QualType Ty) const { |
2058 | |
2059 | auto TypeInfo = getContext().getTypeInfoInChars(Ty); |
2060 | |
2061 | // x86-32 changes the alignment of certain arguments on the stack. |
2062 | // |
2063 | // Just messing with TypeInfo like this works because we never pass |
2064 | // anything indirectly. |
2065 | TypeInfo.Align = CharUnits::fromQuantity( |
2066 | getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); |
2067 | |
2068 | return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, |
2069 | TypeInfo, CharUnits::fromQuantity(4), |
2070 | /*AllowHigherAlign*/ true); |
2071 | } |
2072 | |
2073 | bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( |
2074 | const llvm::Triple &Triple, const CodeGenOptions &Opts) { |
2075 | assert(Triple.getArch() == llvm::Triple::x86)((Triple.getArch() == llvm::Triple::x86) ? static_cast<void > (0) : __assert_fail ("Triple.getArch() == llvm::Triple::x86" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2075, __PRETTY_FUNCTION__)); |
2076 | |
2077 | switch (Opts.getStructReturnConvention()) { |
2078 | case CodeGenOptions::SRCK_Default: |
2079 | break; |
2080 | case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return |
2081 | return false; |
2082 | case CodeGenOptions::SRCK_InRegs: // -freg-struct-return |
2083 | return true; |
2084 | } |
2085 | |
2086 | if (Triple.isOSDarwin() || Triple.isOSIAMCU()) |
2087 | return true; |
2088 | |
2089 | switch (Triple.getOS()) { |
2090 | case llvm::Triple::DragonFly: |
2091 | case llvm::Triple::FreeBSD: |
2092 | case llvm::Triple::OpenBSD: |
2093 | case llvm::Triple::Win32: |
2094 | return true; |
2095 | default: |
2096 | return false; |
2097 | } |
2098 | } |
2099 | |
2100 | void X86_32TargetCodeGenInfo::setTargetAttributes( |
2101 | const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { |
2102 | if (GV->isDeclaration()) |
2103 | return; |
2104 | if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { |
2105 | if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { |
2106 | llvm::Function *Fn = cast<llvm::Function>(GV); |
2107 | Fn->addFnAttr("stackrealign"); |
2108 | } |
2109 | if (FD->hasAttr<AnyX86InterruptAttr>()) { |
2110 | llvm::Function *Fn = cast<llvm::Function>(GV); |
2111 | Fn->setCallingConv(llvm::CallingConv::X86_INTR); |
2112 | } |
2113 | } |
2114 | } |
2115 | |
2116 | bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( |
2117 | CodeGen::CodeGenFunction &CGF, |
2118 | llvm::Value *Address) const { |
2119 | CodeGen::CGBuilderTy &Builder = CGF.Builder; |
2120 | |
2121 | llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); |
2122 | |
2123 | // 0-7 are the eight integer registers; the order is different |
2124 | // on Darwin (for EH), but the range is the same. |
2125 | // 8 is %eip. |
2126 | AssignToArrayRange(Builder, Address, Four8, 0, 8); |
2127 | |
2128 | if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { |
2129 | // 12-16 are st(0..4). Not sure why we stop at 4. |
2130 | // These have size 16, which is sizeof(long double) on |
2131 | // platforms with 8-byte alignment for that type. |
2132 | llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); |
2133 | AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); |
2134 | |
2135 | } else { |
2136 | // 9 is %eflags, which doesn't get a size on Darwin for some |
2137 | // reason. |
2138 | Builder.CreateAlignedStore( |
2139 | Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), |
2140 | CharUnits::One()); |
2141 | |
2142 | // 11-16 are st(0..5). Not sure why we stop at 5. |
2143 | // These have size 12, which is sizeof(long double) on |
2144 | // platforms with 4-byte alignment for that type. |
2145 | llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); |
2146 | AssignToArrayRange(Builder, Address, Twelve8, 11, 16); |
2147 | } |
2148 | |
2149 | return false; |
2150 | } |
2151 | |
2152 | //===----------------------------------------------------------------------===// |
2153 | // X86-64 ABI Implementation |
2154 | //===----------------------------------------------------------------------===// |
2155 | |
2156 | |
2157 | namespace { |
2158 | /// The AVX ABI level for X86 targets. |
2159 | enum class X86AVXABILevel { |
2160 | None, |
2161 | AVX, |
2162 | AVX512 |
2163 | }; |
2164 | |
2165 | /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. |
2166 | static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { |
2167 | switch (AVXLevel) { |
2168 | case X86AVXABILevel::AVX512: |
2169 | return 512; |
2170 | case X86AVXABILevel::AVX: |
2171 | return 256; |
2172 | case X86AVXABILevel::None: |
2173 | return 128; |
2174 | } |
2175 | llvm_unreachable("Unknown AVXLevel")::llvm::llvm_unreachable_internal("Unknown AVXLevel", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2175); |
2176 | } |
2177 | |
2178 | /// X86_64ABIInfo - The X86_64 ABI information. |
2179 | class X86_64ABIInfo : public SwiftABIInfo { |
2180 | enum Class { |
2181 | Integer = 0, |
2182 | SSE, |
2183 | SSEUp, |
2184 | X87, |
2185 | X87Up, |
2186 | ComplexX87, |
2187 | NoClass, |
2188 | Memory |
2189 | }; |
2190 | |
2191 | /// merge - Implement the X86_64 ABI merging algorithm. |
2192 | /// |
2193 | /// Merge an accumulating classification \arg Accum with a field |
2194 | /// classification \arg Field. |
2195 | /// |
2196 | /// \param Accum - The accumulating classification. This should |
2197 | /// always be either NoClass or the result of a previous merge |
2198 | /// call. In addition, this should never be Memory (the caller |
2199 | /// should just return Memory for the aggregate). |
2200 | static Class merge(Class Accum, Class Field); |
2201 | |
2202 | /// postMerge - Implement the X86_64 ABI post merging algorithm. |
2203 | /// |
2204 | /// Post merger cleanup, reduces a malformed Hi and Lo pair to |
2205 | /// final MEMORY or SSE classes when necessary. |
2206 | /// |
2207 | /// \param AggregateSize - The size of the current aggregate in |
2208 | /// the classification process. |
2209 | /// |
2210 | /// \param Lo - The classification for the parts of the type |
2211 | /// residing in the low word of the containing object. |
2212 | /// |
2213 | /// \param Hi - The classification for the parts of the type |
2214 | /// residing in the higher words of the containing object. |
2215 | /// |
2216 | void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; |
2217 | |
2218 | /// classify - Determine the x86_64 register classes in which the |
2219 | /// given type T should be passed. |
2220 | /// |
2221 | /// \param Lo - The classification for the parts of the type |
2222 | /// residing in the low word of the containing object. |
2223 | /// |
2224 | /// \param Hi - The classification for the parts of the type |
2225 | /// residing in the high word of the containing object. |
2226 | /// |
2227 | /// \param OffsetBase - The bit offset of this type in the |
2228 | /// containing object. Some parameters are classified different |
2229 | /// depending on whether they straddle an eightbyte boundary. |
2230 | /// |
2231 | /// \param isNamedArg - Whether the argument in question is a "named" |
2232 | /// argument, as used in AMD64-ABI 3.5.7. |
2233 | /// |
2234 | /// If a word is unused its result will be NoClass; if a type should |
2235 | /// be passed in Memory then at least the classification of \arg Lo |
2236 | /// will be Memory. |
2237 | /// |
2238 | /// The \arg Lo class will be NoClass iff the argument is ignored. |
2239 | /// |
2240 | /// If the \arg Lo class is ComplexX87, then the \arg Hi class will |
2241 | /// also be ComplexX87. |
2242 | void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, |
2243 | bool isNamedArg) const; |
2244 | |
2245 | llvm::Type *GetByteVectorType(QualType Ty) const; |
2246 | llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, |
2247 | unsigned IROffset, QualType SourceTy, |
2248 | unsigned SourceOffset) const; |
2249 | llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, |
2250 | unsigned IROffset, QualType SourceTy, |
2251 | unsigned SourceOffset) const; |
2252 | |
2253 | /// getIndirectResult - Give a source type \arg Ty, return a suitable result |
2254 | /// such that the argument will be returned in memory. |
2255 | ABIArgInfo getIndirectReturnResult(QualType Ty) const; |
2256 | |
2257 | /// getIndirectResult - Give a source type \arg Ty, return a suitable result |
2258 | /// such that the argument will be passed in memory. |
2259 | /// |
2260 | /// \param freeIntRegs - The number of free integer registers remaining |
2261 | /// available. |
2262 | ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; |
2263 | |
2264 | ABIArgInfo classifyReturnType(QualType RetTy) const; |
2265 | |
2266 | ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, |
2267 | unsigned &neededInt, unsigned &neededSSE, |
2268 | bool isNamedArg) const; |
2269 | |
2270 | ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, |
2271 | unsigned &NeededSSE) const; |
2272 | |
2273 | ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, |
2274 | unsigned &NeededSSE) const; |
2275 | |
2276 | bool IsIllegalVectorType(QualType Ty) const; |
2277 | |
2278 | /// The 0.98 ABI revision clarified a lot of ambiguities, |
2279 | /// unfortunately in ways that were not always consistent with |
2280 | /// certain previous compilers. In particular, platforms which |
2281 | /// required strict binary compatibility with older versions of GCC |
2282 | /// may need to exempt themselves. |
2283 | bool honorsRevision0_98() const { |
2284 | return !getTarget().getTriple().isOSDarwin(); |
2285 | } |
2286 | |
2287 | /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to |
2288 | /// classify it as INTEGER (for compatibility with older clang compilers). |
2289 | bool classifyIntegerMMXAsSSE() const { |
2290 | // Clang <= 3.8 did not do this. |
2291 | if (getContext().getLangOpts().getClangABICompat() <= |
2292 | LangOptions::ClangABI::Ver3_8) |
2293 | return false; |
2294 | |
2295 | const llvm::Triple &Triple = getTarget().getTriple(); |
2296 | if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) |
2297 | return false; |
2298 | if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) |
2299 | return false; |
2300 | return true; |
2301 | } |
2302 | |
2303 | // GCC classifies vectors of __int128 as memory. |
2304 | bool passInt128VectorsInMem() const { |
2305 | // Clang <= 9.0 did not do this. |
2306 | if (getContext().getLangOpts().getClangABICompat() <= |
2307 | LangOptions::ClangABI::Ver9) |
2308 | return false; |
2309 | |
2310 | const llvm::Triple &T = getTarget().getTriple(); |
2311 | return T.isOSLinux() || T.isOSNetBSD(); |
2312 | } |
2313 | |
2314 | X86AVXABILevel AVXLevel; |
2315 | // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on |
2316 | // 64-bit hardware. |
2317 | bool Has64BitPointers; |
2318 | |
2319 | public: |
2320 | X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : |
2321 | SwiftABIInfo(CGT), AVXLevel(AVXLevel), |
2322 | Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { |
2323 | } |
2324 | |
2325 | bool isPassedUsingAVXType(QualType type) const { |
2326 | unsigned neededInt, neededSSE; |
2327 | // The freeIntRegs argument doesn't matter here. |
2328 | ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, |
2329 | /*isNamedArg*/true); |
2330 | if (info.isDirect()) { |
2331 | llvm::Type *ty = info.getCoerceToType(); |
2332 | if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) |
2333 | return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; |
2334 | } |
2335 | return false; |
2336 | } |
2337 | |
2338 | void computeInfo(CGFunctionInfo &FI) const override; |
2339 | |
2340 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
2341 | QualType Ty) const override; |
2342 | Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, |
2343 | QualType Ty) const override; |
2344 | |
2345 | bool has64BitPointers() const { |
2346 | return Has64BitPointers; |
2347 | } |
2348 | |
2349 | bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, |
2350 | bool asReturnValue) const override { |
2351 | return occupiesMoreThan(CGT, scalars, /*total*/ 4); |
2352 | } |
2353 | bool isSwiftErrorInRegister() const override { |
2354 | return true; |
2355 | } |
2356 | }; |
2357 | |
2358 | /// WinX86_64ABIInfo - The Windows X86_64 ABI information. |
2359 | class WinX86_64ABIInfo : public SwiftABIInfo { |
2360 | public: |
2361 | WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) |
2362 | : SwiftABIInfo(CGT), AVXLevel(AVXLevel), |
2363 | IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} |
2364 | |
2365 | void computeInfo(CGFunctionInfo &FI) const override; |
2366 | |
2367 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
2368 | QualType Ty) const override; |
2369 | |
2370 | bool isHomogeneousAggregateBaseType(QualType Ty) const override { |
2371 | // FIXME: Assumes vectorcall is in use. |
2372 | return isX86VectorTypeForVectorCall(getContext(), Ty); |
2373 | } |
2374 | |
2375 | bool isHomogeneousAggregateSmallEnough(const Type *Ty, |
2376 | uint64_t NumMembers) const override { |
2377 | // FIXME: Assumes vectorcall is in use. |
2378 | return isX86VectorCallAggregateSmallEnough(NumMembers); |
2379 | } |
2380 | |
2381 | bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, |
2382 | bool asReturnValue) const override { |
2383 | return occupiesMoreThan(CGT, scalars, /*total*/ 4); |
2384 | } |
2385 | |
2386 | bool isSwiftErrorInRegister() const override { |
2387 | return true; |
2388 | } |
2389 | |
2390 | private: |
2391 | ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, |
2392 | bool IsVectorCall, bool IsRegCall) const; |
2393 | ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, |
2394 | const ABIArgInfo ¤t) const; |
2395 | void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, |
2396 | bool IsVectorCall, bool IsRegCall) const; |
2397 | |
2398 | X86AVXABILevel AVXLevel; |
2399 | |
2400 | bool IsMingw64; |
2401 | }; |
2402 | |
2403 | class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { |
2404 | public: |
2405 | X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) |
2406 | : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} |
2407 | |
2408 | const X86_64ABIInfo &getABIInfo() const { |
2409 | return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); |
2410 | } |
2411 | |
2412 | /// Disable tail call on x86-64. The epilogue code before the tail jump blocks |
2413 | /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. |
2414 | bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } |
2415 | |
2416 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { |
2417 | return 7; |
2418 | } |
2419 | |
2420 | bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
2421 | llvm::Value *Address) const override { |
2422 | llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); |
2423 | |
2424 | // 0-15 are the 16 integer registers. |
2425 | // 16 is %rip. |
2426 | AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); |
2427 | return false; |
2428 | } |
2429 | |
2430 | llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, |
2431 | StringRef Constraint, |
2432 | llvm::Type* Ty) const override { |
2433 | return X86AdjustInlineAsmType(CGF, Constraint, Ty); |
2434 | } |
2435 | |
2436 | bool isNoProtoCallVariadic(const CallArgList &args, |
2437 | const FunctionNoProtoType *fnType) const override { |
2438 | // The default CC on x86-64 sets %al to the number of SSA |
2439 | // registers used, and GCC sets this when calling an unprototyped |
2440 | // function, so we override the default behavior. However, don't do |
2441 | // that when AVX types are involved: the ABI explicitly states it is |
2442 | // undefined, and it doesn't work in practice because of how the ABI |
2443 | // defines varargs anyway. |
2444 | if (fnType->getCallConv() == CC_C) { |
2445 | bool HasAVXType = false; |
2446 | for (CallArgList::const_iterator |
2447 | it = args.begin(), ie = args.end(); it != ie; ++it) { |
2448 | if (getABIInfo().isPassedUsingAVXType(it->Ty)) { |
2449 | HasAVXType = true; |
2450 | break; |
2451 | } |
2452 | } |
2453 | |
2454 | if (!HasAVXType) |
2455 | return true; |
2456 | } |
2457 | |
2458 | return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); |
2459 | } |
2460 | |
2461 | llvm::Constant * |
2462 | getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { |
2463 | unsigned Sig = (0xeb << 0) | // jmp rel8 |
2464 | (0x06 << 8) | // .+0x08 |
2465 | ('v' << 16) | |
2466 | ('2' << 24); |
2467 | return llvm::ConstantInt::get(CGM.Int32Ty, Sig); |
2468 | } |
2469 | |
2470 | void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
2471 | CodeGen::CodeGenModule &CGM) const override { |
2472 | if (GV->isDeclaration()) |
2473 | return; |
2474 | if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { |
2475 | if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { |
2476 | llvm::Function *Fn = cast<llvm::Function>(GV); |
2477 | Fn->addFnAttr("stackrealign"); |
2478 | } |
2479 | if (FD->hasAttr<AnyX86InterruptAttr>()) { |
2480 | llvm::Function *Fn = cast<llvm::Function>(GV); |
2481 | Fn->setCallingConv(llvm::CallingConv::X86_INTR); |
2482 | } |
2483 | } |
2484 | } |
2485 | |
2486 | void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, |
2487 | const FunctionDecl *Caller, |
2488 | const FunctionDecl *Callee, |
2489 | const CallArgList &Args) const override; |
2490 | }; |
2491 | |
2492 | static void initFeatureMaps(const ASTContext &Ctx, |
2493 | llvm::StringMap<bool> &CallerMap, |
2494 | const FunctionDecl *Caller, |
2495 | llvm::StringMap<bool> &CalleeMap, |
2496 | const FunctionDecl *Callee) { |
2497 | if (CalleeMap.empty() && CallerMap.empty()) { |
2498 | // The caller is potentially nullptr in the case where the call isn't in a |
2499 | // function. In this case, the getFunctionFeatureMap ensures we just get |
2500 | // the TU level setting (since it cannot be modified by 'target'.. |
2501 | Ctx.getFunctionFeatureMap(CallerMap, Caller); |
2502 | Ctx.getFunctionFeatureMap(CalleeMap, Callee); |
2503 | } |
2504 | } |
2505 | |
2506 | static bool checkAVXParamFeature(DiagnosticsEngine &Diag, |
2507 | SourceLocation CallLoc, |
2508 | const llvm::StringMap<bool> &CallerMap, |
2509 | const llvm::StringMap<bool> &CalleeMap, |
2510 | QualType Ty, StringRef Feature, |
2511 | bool IsArgument) { |
2512 | bool CallerHasFeat = CallerMap.lookup(Feature); |
2513 | bool CalleeHasFeat = CalleeMap.lookup(Feature); |
2514 | if (!CallerHasFeat && !CalleeHasFeat) |
2515 | return Diag.Report(CallLoc, diag::warn_avx_calling_convention) |
2516 | << IsArgument << Ty << Feature; |
2517 | |
2518 | // Mixing calling conventions here is very clearly an error. |
2519 | if (!CallerHasFeat || !CalleeHasFeat) |
2520 | return Diag.Report(CallLoc, diag::err_avx_calling_convention) |
2521 | << IsArgument << Ty << Feature; |
2522 | |
2523 | // Else, both caller and callee have the required feature, so there is no need |
2524 | // to diagnose. |
2525 | return false; |
2526 | } |
2527 | |
2528 | static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, |
2529 | SourceLocation CallLoc, |
2530 | const llvm::StringMap<bool> &CallerMap, |
2531 | const llvm::StringMap<bool> &CalleeMap, QualType Ty, |
2532 | bool IsArgument) { |
2533 | uint64_t Size = Ctx.getTypeSize(Ty); |
2534 | if (Size > 256) |
2535 | return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, |
2536 | "avx512f", IsArgument); |
2537 | |
2538 | if (Size > 128) |
2539 | return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", |
2540 | IsArgument); |
2541 | |
2542 | return false; |
2543 | } |
2544 | |
2545 | void X86_64TargetCodeGenInfo::checkFunctionCallABI( |
2546 | CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, |
2547 | const FunctionDecl *Callee, const CallArgList &Args) const { |
2548 | llvm::StringMap<bool> CallerMap; |
2549 | llvm::StringMap<bool> CalleeMap; |
2550 | unsigned ArgIndex = 0; |
2551 | |
2552 | // We need to loop through the actual call arguments rather than the the |
2553 | // function's parameters, in case this variadic. |
2554 | for (const CallArg &Arg : Args) { |
2555 | // The "avx" feature changes how vectors >128 in size are passed. "avx512f" |
2556 | // additionally changes how vectors >256 in size are passed. Like GCC, we |
2557 | // warn when a function is called with an argument where this will change. |
2558 | // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, |
2559 | // the caller and callee features are mismatched. |
2560 | // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can |
2561 | // change its ABI with attribute-target after this call. |
2562 | if (Arg.getType()->isVectorType() && |
2563 | CGM.getContext().getTypeSize(Arg.getType()) > 128) { |
2564 | initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); |
2565 | QualType Ty = Arg.getType(); |
2566 | // The CallArg seems to have desugared the type already, so for clearer |
2567 | // diagnostics, replace it with the type in the FunctionDecl if possible. |
2568 | if (ArgIndex < Callee->getNumParams()) |
2569 | Ty = Callee->getParamDecl(ArgIndex)->getType(); |
2570 | |
2571 | if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, |
2572 | CalleeMap, Ty, /*IsArgument*/ true)) |
2573 | return; |
2574 | } |
2575 | ++ArgIndex; |
2576 | } |
2577 | |
2578 | // Check return always, as we don't have a good way of knowing in codegen |
2579 | // whether this value is used, tail-called, etc. |
2580 | if (Callee->getReturnType()->isVectorType() && |
2581 | CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { |
2582 | initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); |
2583 | checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, |
2584 | CalleeMap, Callee->getReturnType(), |
2585 | /*IsArgument*/ false); |
2586 | } |
2587 | } |
2588 | |
2589 | static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { |
2590 | // If the argument does not end in .lib, automatically add the suffix. |
2591 | // If the argument contains a space, enclose it in quotes. |
2592 | // This matches the behavior of MSVC. |
2593 | bool Quote = (Lib.find(" ") != StringRef::npos); |
2594 | std::string ArgStr = Quote ? "\"" : ""; |
2595 | ArgStr += Lib; |
2596 | if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) |
2597 | ArgStr += ".lib"; |
2598 | ArgStr += Quote ? "\"" : ""; |
2599 | return ArgStr; |
2600 | } |
2601 | |
2602 | class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { |
2603 | public: |
2604 | WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, |
2605 | bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, |
2606 | unsigned NumRegisterParameters) |
2607 | : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, |
2608 | Win32StructABI, NumRegisterParameters, false) {} |
2609 | |
2610 | void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
2611 | CodeGen::CodeGenModule &CGM) const override; |
2612 | |
2613 | void getDependentLibraryOption(llvm::StringRef Lib, |
2614 | llvm::SmallString<24> &Opt) const override { |
2615 | Opt = "/DEFAULTLIB:"; |
2616 | Opt += qualifyWindowsLibrary(Lib); |
2617 | } |
2618 | |
2619 | void getDetectMismatchOption(llvm::StringRef Name, |
2620 | llvm::StringRef Value, |
2621 | llvm::SmallString<32> &Opt) const override { |
2622 | Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; |
2623 | } |
2624 | }; |
2625 | |
2626 | static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
2627 | CodeGen::CodeGenModule &CGM) { |
2628 | if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { |
2629 | |
2630 | if (CGM.getCodeGenOpts().StackProbeSize != 4096) |
2631 | Fn->addFnAttr("stack-probe-size", |
2632 | llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); |
2633 | if (CGM.getCodeGenOpts().NoStackArgProbe) |
2634 | Fn->addFnAttr("no-stack-arg-probe"); |
2635 | } |
2636 | } |
2637 | |
2638 | void WinX86_32TargetCodeGenInfo::setTargetAttributes( |
2639 | const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { |
2640 | X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); |
2641 | if (GV->isDeclaration()) |
2642 | return; |
2643 | addStackProbeTargetAttributes(D, GV, CGM); |
2644 | } |
2645 | |
2646 | class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { |
2647 | public: |
2648 | WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, |
2649 | X86AVXABILevel AVXLevel) |
2650 | : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} |
2651 | |
2652 | void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
2653 | CodeGen::CodeGenModule &CGM) const override; |
2654 | |
2655 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { |
2656 | return 7; |
2657 | } |
2658 | |
2659 | bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
2660 | llvm::Value *Address) const override { |
2661 | llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); |
2662 | |
2663 | // 0-15 are the 16 integer registers. |
2664 | // 16 is %rip. |
2665 | AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); |
2666 | return false; |
2667 | } |
2668 | |
2669 | void getDependentLibraryOption(llvm::StringRef Lib, |
2670 | llvm::SmallString<24> &Opt) const override { |
2671 | Opt = "/DEFAULTLIB:"; |
2672 | Opt += qualifyWindowsLibrary(Lib); |
2673 | } |
2674 | |
2675 | void getDetectMismatchOption(llvm::StringRef Name, |
2676 | llvm::StringRef Value, |
2677 | llvm::SmallString<32> &Opt) const override { |
2678 | Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; |
2679 | } |
2680 | }; |
2681 | |
2682 | void WinX86_64TargetCodeGenInfo::setTargetAttributes( |
2683 | const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { |
2684 | TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); |
2685 | if (GV->isDeclaration()) |
2686 | return; |
2687 | if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { |
2688 | if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { |
2689 | llvm::Function *Fn = cast<llvm::Function>(GV); |
2690 | Fn->addFnAttr("stackrealign"); |
2691 | } |
2692 | if (FD->hasAttr<AnyX86InterruptAttr>()) { |
2693 | llvm::Function *Fn = cast<llvm::Function>(GV); |
2694 | Fn->setCallingConv(llvm::CallingConv::X86_INTR); |
2695 | } |
2696 | } |
2697 | |
2698 | addStackProbeTargetAttributes(D, GV, CGM); |
2699 | } |
2700 | } |
2701 | |
2702 | void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, |
2703 | Class &Hi) const { |
2704 | // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: |
2705 | // |
2706 | // (a) If one of the classes is Memory, the whole argument is passed in |
2707 | // memory. |
2708 | // |
2709 | // (b) If X87UP is not preceded by X87, the whole argument is passed in |
2710 | // memory. |
2711 | // |
2712 | // (c) If the size of the aggregate exceeds two eightbytes and the first |
2713 | // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole |
2714 | // argument is passed in memory. NOTE: This is necessary to keep the |
2715 | // ABI working for processors that don't support the __m256 type. |
2716 | // |
2717 | // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. |
2718 | // |
2719 | // Some of these are enforced by the merging logic. Others can arise |
2720 | // only with unions; for example: |
2721 | // union { _Complex double; unsigned; } |
2722 | // |
2723 | // Note that clauses (b) and (c) were added in 0.98. |
2724 | // |
2725 | if (Hi == Memory) |
2726 | Lo = Memory; |
2727 | if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) |
2728 | Lo = Memory; |
2729 | if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) |
2730 | Lo = Memory; |
2731 | if (Hi == SSEUp && Lo != SSE) |
2732 | Hi = SSE; |
2733 | } |
2734 | |
2735 | X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { |
2736 | // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is |
2737 | // classified recursively so that always two fields are |
2738 | // considered. The resulting class is calculated according to |
2739 | // the classes of the fields in the eightbyte: |
2740 | // |
2741 | // (a) If both classes are equal, this is the resulting class. |
2742 | // |
2743 | // (b) If one of the classes is NO_CLASS, the resulting class is |
2744 | // the other class. |
2745 | // |
2746 | // (c) If one of the classes is MEMORY, the result is the MEMORY |
2747 | // class. |
2748 | // |
2749 | // (d) If one of the classes is INTEGER, the result is the |
2750 | // INTEGER. |
2751 | // |
2752 | // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, |
2753 | // MEMORY is used as class. |
2754 | // |
2755 | // (f) Otherwise class SSE is used. |
2756 | |
2757 | // Accum should never be memory (we should have returned) or |
2758 | // ComplexX87 (because this cannot be passed in a structure). |
2759 | assert((Accum != Memory && Accum != ComplexX87) &&(((Accum != Memory && Accum != ComplexX87) && "Invalid accumulated classification during merge.") ? static_cast <void> (0) : __assert_fail ("(Accum != Memory && Accum != ComplexX87) && \"Invalid accumulated classification during merge.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2760, __PRETTY_FUNCTION__)) |
2760 | "Invalid accumulated classification during merge.")(((Accum != Memory && Accum != ComplexX87) && "Invalid accumulated classification during merge.") ? static_cast <void> (0) : __assert_fail ("(Accum != Memory && Accum != ComplexX87) && \"Invalid accumulated classification during merge.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2760, __PRETTY_FUNCTION__)); |
2761 | if (Accum == Field || Field == NoClass) |
2762 | return Accum; |
2763 | if (Field == Memory) |
2764 | return Memory; |
2765 | if (Accum == NoClass) |
2766 | return Field; |
2767 | if (Accum == Integer || Field == Integer) |
2768 | return Integer; |
2769 | if (Field == X87 || Field == X87Up || Field == ComplexX87 || |
2770 | Accum == X87 || Accum == X87Up) |
2771 | return Memory; |
2772 | return SSE; |
2773 | } |
2774 | |
2775 | void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, |
2776 | Class &Lo, Class &Hi, bool isNamedArg) const { |
2777 | // FIXME: This code can be simplified by introducing a simple value class for |
2778 | // Class pairs with appropriate constructor methods for the various |
2779 | // situations. |
2780 | |
2781 | // FIXME: Some of the split computations are wrong; unaligned vectors |
2782 | // shouldn't be passed in registers for example, so there is no chance they |
2783 | // can straddle an eightbyte. Verify & simplify. |
2784 | |
2785 | Lo = Hi = NoClass; |
2786 | |
2787 | Class &Current = OffsetBase < 64 ? Lo : Hi; |
2788 | Current = Memory; |
2789 | |
2790 | if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { |
2791 | BuiltinType::Kind k = BT->getKind(); |
2792 | |
2793 | if (k == BuiltinType::Void) { |
2794 | Current = NoClass; |
2795 | } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { |
2796 | Lo = Integer; |
2797 | Hi = Integer; |
2798 | } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { |
2799 | Current = Integer; |
2800 | } else if (k == BuiltinType::Float || k == BuiltinType::Double) { |
2801 | Current = SSE; |
2802 | } else if (k == BuiltinType::LongDouble) { |
2803 | const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); |
2804 | if (LDF == &llvm::APFloat::IEEEquad()) { |
2805 | Lo = SSE; |
2806 | Hi = SSEUp; |
2807 | } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { |
2808 | Lo = X87; |
2809 | Hi = X87Up; |
2810 | } else if (LDF == &llvm::APFloat::IEEEdouble()) { |
2811 | Current = SSE; |
2812 | } else |
2813 | llvm_unreachable("unexpected long double representation!")::llvm::llvm_unreachable_internal("unexpected long double representation!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2813); |
2814 | } |
2815 | // FIXME: _Decimal32 and _Decimal64 are SSE. |
2816 | // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). |
2817 | return; |
2818 | } |
2819 | |
2820 | if (const EnumType *ET = Ty->getAs<EnumType>()) { |
2821 | // Classify the underlying integer type. |
2822 | classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); |
2823 | return; |
2824 | } |
2825 | |
2826 | if (Ty->hasPointerRepresentation()) { |
2827 | Current = Integer; |
2828 | return; |
2829 | } |
2830 | |
2831 | if (Ty->isMemberPointerType()) { |
2832 | if (Ty->isMemberFunctionPointerType()) { |
2833 | if (Has64BitPointers) { |
2834 | // If Has64BitPointers, this is an {i64, i64}, so classify both |
2835 | // Lo and Hi now. |
2836 | Lo = Hi = Integer; |
2837 | } else { |
2838 | // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that |
2839 | // straddles an eightbyte boundary, Hi should be classified as well. |
2840 | uint64_t EB_FuncPtr = (OffsetBase) / 64; |
2841 | uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; |
2842 | if (EB_FuncPtr != EB_ThisAdj) { |
2843 | Lo = Hi = Integer; |
2844 | } else { |
2845 | Current = Integer; |
2846 | } |
2847 | } |
2848 | } else { |
2849 | Current = Integer; |
2850 | } |
2851 | return; |
2852 | } |
2853 | |
2854 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
2855 | uint64_t Size = getContext().getTypeSize(VT); |
2856 | if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { |
2857 | // gcc passes the following as integer: |
2858 | // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> |
2859 | // 2 bytes - <2 x char>, <1 x short> |
2860 | // 1 byte - <1 x char> |
2861 | Current = Integer; |
2862 | |
2863 | // If this type crosses an eightbyte boundary, it should be |
2864 | // split. |
2865 | uint64_t EB_Lo = (OffsetBase) / 64; |
2866 | uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; |
2867 | if (EB_Lo != EB_Hi) |
2868 | Hi = Lo; |
2869 | } else if (Size == 64) { |
2870 | QualType ElementType = VT->getElementType(); |
2871 | |
2872 | // gcc passes <1 x double> in memory. :( |
2873 | if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) |
2874 | return; |
2875 | |
2876 | // gcc passes <1 x long long> as SSE but clang used to unconditionally |
2877 | // pass them as integer. For platforms where clang is the de facto |
2878 | // platform compiler, we must continue to use integer. |
2879 | if (!classifyIntegerMMXAsSSE() && |
2880 | (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || |
2881 | ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || |
2882 | ElementType->isSpecificBuiltinType(BuiltinType::Long) || |
2883 | ElementType->isSpecificBuiltinType(BuiltinType::ULong))) |
2884 | Current = Integer; |
2885 | else |
2886 | Current = SSE; |
2887 | |
2888 | // If this type crosses an eightbyte boundary, it should be |
2889 | // split. |
2890 | if (OffsetBase && OffsetBase != 64) |
2891 | Hi = Lo; |
2892 | } else if (Size == 128 || |
2893 | (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { |
2894 | QualType ElementType = VT->getElementType(); |
2895 | |
2896 | // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( |
2897 | if (passInt128VectorsInMem() && Size != 128 && |
2898 | (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || |
2899 | ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) |
2900 | return; |
2901 | |
2902 | // Arguments of 256-bits are split into four eightbyte chunks. The |
2903 | // least significant one belongs to class SSE and all the others to class |
2904 | // SSEUP. The original Lo and Hi design considers that types can't be |
2905 | // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. |
2906 | // This design isn't correct for 256-bits, but since there're no cases |
2907 | // where the upper parts would need to be inspected, avoid adding |
2908 | // complexity and just consider Hi to match the 64-256 part. |
2909 | // |
2910 | // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in |
2911 | // registers if they are "named", i.e. not part of the "..." of a |
2912 | // variadic function. |
2913 | // |
2914 | // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are |
2915 | // split into eight eightbyte chunks, one SSE and seven SSEUP. |
2916 | Lo = SSE; |
2917 | Hi = SSEUp; |
2918 | } |
2919 | return; |
2920 | } |
2921 | |
2922 | if (const ComplexType *CT = Ty->getAs<ComplexType>()) { |
2923 | QualType ET = getContext().getCanonicalType(CT->getElementType()); |
2924 | |
2925 | uint64_t Size = getContext().getTypeSize(Ty); |
2926 | if (ET->isIntegralOrEnumerationType()) { |
2927 | if (Size <= 64) |
2928 | Current = Integer; |
2929 | else if (Size <= 128) |
2930 | Lo = Hi = Integer; |
2931 | } else if (ET == getContext().FloatTy) { |
2932 | Current = SSE; |
2933 | } else if (ET == getContext().DoubleTy) { |
2934 | Lo = Hi = SSE; |
2935 | } else if (ET == getContext().LongDoubleTy) { |
2936 | const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); |
2937 | if (LDF == &llvm::APFloat::IEEEquad()) |
2938 | Current = Memory; |
2939 | else if (LDF == &llvm::APFloat::x87DoubleExtended()) |
2940 | Current = ComplexX87; |
2941 | else if (LDF == &llvm::APFloat::IEEEdouble()) |
2942 | Lo = Hi = SSE; |
2943 | else |
2944 | llvm_unreachable("unexpected long double representation!")::llvm::llvm_unreachable_internal("unexpected long double representation!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 2944); |
2945 | } |
2946 | |
2947 | // If this complex type crosses an eightbyte boundary then it |
2948 | // should be split. |
2949 | uint64_t EB_Real = (OffsetBase) / 64; |
2950 | uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; |
2951 | if (Hi == NoClass && EB_Real != EB_Imag) |
2952 | Hi = Lo; |
2953 | |
2954 | return; |
2955 | } |
2956 | |
2957 | if (const auto *EITy = Ty->getAs<ExtIntType>()) { |
2958 | if (EITy->getNumBits() <= 64) |
2959 | Current = Integer; |
2960 | else if (EITy->getNumBits() <= 128) |
2961 | Lo = Hi = Integer; |
2962 | // Larger values need to get passed in memory. |
2963 | return; |
2964 | } |
2965 | |
2966 | if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { |
2967 | // Arrays are treated like structures. |
2968 | |
2969 | uint64_t Size = getContext().getTypeSize(Ty); |
2970 | |
2971 | // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger |
2972 | // than eight eightbytes, ..., it has class MEMORY. |
2973 | if (Size > 512) |
2974 | return; |
2975 | |
2976 | // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned |
2977 | // fields, it has class MEMORY. |
2978 | // |
2979 | // Only need to check alignment of array base. |
2980 | if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) |
2981 | return; |
2982 | |
2983 | // Otherwise implement simplified merge. We could be smarter about |
2984 | // this, but it isn't worth it and would be harder to verify. |
2985 | Current = NoClass; |
2986 | uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); |
2987 | uint64_t ArraySize = AT->getSize().getZExtValue(); |
2988 | |
2989 | // The only case a 256-bit wide vector could be used is when the array |
2990 | // contains a single 256-bit element. Since Lo and Hi logic isn't extended |
2991 | // to work for sizes wider than 128, early check and fallback to memory. |
2992 | // |
2993 | if (Size > 128 && |
2994 | (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) |
2995 | return; |
2996 | |
2997 | for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { |
2998 | Class FieldLo, FieldHi; |
2999 | classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); |
3000 | Lo = merge(Lo, FieldLo); |
3001 | Hi = merge(Hi, FieldHi); |
3002 | if (Lo == Memory || Hi == Memory) |
3003 | break; |
3004 | } |
3005 | |
3006 | postMerge(Size, Lo, Hi); |
3007 | assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.")(((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification." ) ? static_cast<void> (0) : __assert_fail ("(Hi != SSEUp || Lo == SSE) && \"Invalid SSEUp array classification.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3007, __PRETTY_FUNCTION__)); |
3008 | return; |
3009 | } |
3010 | |
3011 | if (const RecordType *RT = Ty->getAs<RecordType>()) { |
3012 | uint64_t Size = getContext().getTypeSize(Ty); |
3013 | |
3014 | // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger |
3015 | // than eight eightbytes, ..., it has class MEMORY. |
3016 | if (Size > 512) |
3017 | return; |
3018 | |
3019 | // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial |
3020 | // copy constructor or a non-trivial destructor, it is passed by invisible |
3021 | // reference. |
3022 | if (getRecordArgABI(RT, getCXXABI())) |
3023 | return; |
3024 | |
3025 | const RecordDecl *RD = RT->getDecl(); |
3026 | |
3027 | // Assume variable sized types are passed in memory. |
3028 | if (RD->hasFlexibleArrayMember()) |
3029 | return; |
3030 | |
3031 | const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); |
3032 | |
3033 | // Reset Lo class, this will be recomputed. |
3034 | Current = NoClass; |
3035 | |
3036 | // If this is a C++ record, classify the bases first. |
3037 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
3038 | for (const auto &I : CXXRD->bases()) { |
3039 | assert(!I.isVirtual() && !I.getType()->isDependentType() &&((!I.isVirtual() && !I.getType()->isDependentType( ) && "Unexpected base class!") ? static_cast<void> (0) : __assert_fail ("!I.isVirtual() && !I.getType()->isDependentType() && \"Unexpected base class!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3040, __PRETTY_FUNCTION__)) |
3040 | "Unexpected base class!")((!I.isVirtual() && !I.getType()->isDependentType( ) && "Unexpected base class!") ? static_cast<void> (0) : __assert_fail ("!I.isVirtual() && !I.getType()->isDependentType() && \"Unexpected base class!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3040, __PRETTY_FUNCTION__)); |
3041 | const auto *Base = |
3042 | cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); |
3043 | |
3044 | // Classify this field. |
3045 | // |
3046 | // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a |
3047 | // single eightbyte, each is classified separately. Each eightbyte gets |
3048 | // initialized to class NO_CLASS. |
3049 | Class FieldLo, FieldHi; |
3050 | uint64_t Offset = |
3051 | OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); |
3052 | classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); |
3053 | Lo = merge(Lo, FieldLo); |
3054 | Hi = merge(Hi, FieldHi); |
3055 | if (Lo == Memory || Hi == Memory) { |
3056 | postMerge(Size, Lo, Hi); |
3057 | return; |
3058 | } |
3059 | } |
3060 | } |
3061 | |
3062 | // Classify the fields one at a time, merging the results. |
3063 | unsigned idx = 0; |
3064 | bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= |
3065 | LangOptions::ClangABI::Ver11 || |
3066 | getContext().getTargetInfo().getTriple().isPS4(); |
3067 | bool IsUnion = RT->isUnionType() && !UseClang11Compat; |
3068 | |
3069 | for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); |
3070 | i != e; ++i, ++idx) { |
3071 | uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); |
3072 | bool BitField = i->isBitField(); |
3073 | |
3074 | // Ignore padding bit-fields. |
3075 | if (BitField && i->isUnnamedBitfield()) |
3076 | continue; |
3077 | |
3078 | // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than |
3079 | // eight eightbytes, or it contains unaligned fields, it has class MEMORY. |
3080 | // |
3081 | // The only case a 256-bit or a 512-bit wide vector could be used is when |
3082 | // the struct contains a single 256-bit or 512-bit element. Early check |
3083 | // and fallback to memory. |
3084 | // |
3085 | // FIXME: Extended the Lo and Hi logic properly to work for size wider |
3086 | // than 128. |
3087 | if (Size > 128 && |
3088 | ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || |
3089 | Size > getNativeVectorSizeForAVXABI(AVXLevel))) { |
3090 | Lo = Memory; |
3091 | postMerge(Size, Lo, Hi); |
3092 | return; |
3093 | } |
3094 | // Note, skip this test for bit-fields, see below. |
3095 | if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { |
3096 | Lo = Memory; |
3097 | postMerge(Size, Lo, Hi); |
3098 | return; |
3099 | } |
3100 | |
3101 | // Classify this field. |
3102 | // |
3103 | // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate |
3104 | // exceeds a single eightbyte, each is classified |
3105 | // separately. Each eightbyte gets initialized to class |
3106 | // NO_CLASS. |
3107 | Class FieldLo, FieldHi; |
3108 | |
3109 | // Bit-fields require special handling, they do not force the |
3110 | // structure to be passed in memory even if unaligned, and |
3111 | // therefore they can straddle an eightbyte. |
3112 | if (BitField) { |
3113 | assert(!i->isUnnamedBitfield())((!i->isUnnamedBitfield()) ? static_cast<void> (0) : __assert_fail ("!i->isUnnamedBitfield()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3113, __PRETTY_FUNCTION__)); |
3114 | uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); |
3115 | uint64_t Size = i->getBitWidthValue(getContext()); |
3116 | |
3117 | uint64_t EB_Lo = Offset / 64; |
3118 | uint64_t EB_Hi = (Offset + Size - 1) / 64; |
3119 | |
3120 | if (EB_Lo) { |
3121 | assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.")((EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes." ) ? static_cast<void> (0) : __assert_fail ("EB_Hi == EB_Lo && \"Invalid classification, type > 16 bytes.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3121, __PRETTY_FUNCTION__)); |
3122 | FieldLo = NoClass; |
3123 | FieldHi = Integer; |
3124 | } else { |
3125 | FieldLo = Integer; |
3126 | FieldHi = EB_Hi ? Integer : NoClass; |
3127 | } |
3128 | } else |
3129 | classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); |
3130 | Lo = merge(Lo, FieldLo); |
3131 | Hi = merge(Hi, FieldHi); |
3132 | if (Lo == Memory || Hi == Memory) |
3133 | break; |
3134 | } |
3135 | |
3136 | postMerge(Size, Lo, Hi); |
3137 | } |
3138 | } |
3139 | |
3140 | ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { |
3141 | // If this is a scalar LLVM value then assume LLVM will pass it in the right |
3142 | // place naturally. |
3143 | if (!isAggregateTypeForABI(Ty)) { |
3144 | // Treat an enum type as its underlying type. |
3145 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
3146 | Ty = EnumTy->getDecl()->getIntegerType(); |
3147 | |
3148 | if (Ty->isExtIntType()) |
3149 | return getNaturalAlignIndirect(Ty); |
3150 | |
3151 | return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) |
3152 | : ABIArgInfo::getDirect()); |
3153 | } |
3154 | |
3155 | return getNaturalAlignIndirect(Ty); |
3156 | } |
3157 | |
3158 | bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { |
3159 | if (const VectorType *VecTy = Ty->getAs<VectorType>()) { |
3160 | uint64_t Size = getContext().getTypeSize(VecTy); |
3161 | unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); |
3162 | if (Size <= 64 || Size > LargestVector) |
3163 | return true; |
3164 | QualType EltTy = VecTy->getElementType(); |
3165 | if (passInt128VectorsInMem() && |
3166 | (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || |
3167 | EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) |
3168 | return true; |
3169 | } |
3170 | |
3171 | return false; |
3172 | } |
3173 | |
3174 | ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, |
3175 | unsigned freeIntRegs) const { |
3176 | // If this is a scalar LLVM value then assume LLVM will pass it in the right |
3177 | // place naturally. |
3178 | // |
3179 | // This assumption is optimistic, as there could be free registers available |
3180 | // when we need to pass this argument in memory, and LLVM could try to pass |
3181 | // the argument in the free register. This does not seem to happen currently, |
3182 | // but this code would be much safer if we could mark the argument with |
3183 | // 'onstack'. See PR12193. |
3184 | if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && |
3185 | !Ty->isExtIntType()) { |
3186 | // Treat an enum type as its underlying type. |
3187 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
3188 | Ty = EnumTy->getDecl()->getIntegerType(); |
3189 | |
3190 | return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) |
3191 | : ABIArgInfo::getDirect()); |
3192 | } |
3193 | |
3194 | if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) |
3195 | return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); |
3196 | |
3197 | // Compute the byval alignment. We specify the alignment of the byval in all |
3198 | // cases so that the mid-level optimizer knows the alignment of the byval. |
3199 | unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); |
3200 | |
3201 | // Attempt to avoid passing indirect results using byval when possible. This |
3202 | // is important for good codegen. |
3203 | // |
3204 | // We do this by coercing the value into a scalar type which the backend can |
3205 | // handle naturally (i.e., without using byval). |
3206 | // |
3207 | // For simplicity, we currently only do this when we have exhausted all of the |
3208 | // free integer registers. Doing this when there are free integer registers |
3209 | // would require more care, as we would have to ensure that the coerced value |
3210 | // did not claim the unused register. That would require either reording the |
3211 | // arguments to the function (so that any subsequent inreg values came first), |
3212 | // or only doing this optimization when there were no following arguments that |
3213 | // might be inreg. |
3214 | // |
3215 | // We currently expect it to be rare (particularly in well written code) for |
3216 | // arguments to be passed on the stack when there are still free integer |
3217 | // registers available (this would typically imply large structs being passed |
3218 | // by value), so this seems like a fair tradeoff for now. |
3219 | // |
3220 | // We can revisit this if the backend grows support for 'onstack' parameter |
3221 | // attributes. See PR12193. |
3222 | if (freeIntRegs == 0) { |
3223 | uint64_t Size = getContext().getTypeSize(Ty); |
3224 | |
3225 | // If this type fits in an eightbyte, coerce it into the matching integral |
3226 | // type, which will end up on the stack (with alignment 8). |
3227 | if (Align == 8 && Size <= 64) |
3228 | return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), |
3229 | Size)); |
3230 | } |
3231 | |
3232 | return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); |
3233 | } |
3234 | |
3235 | /// The ABI specifies that a value should be passed in a full vector XMM/YMM |
3236 | /// register. Pick an LLVM IR type that will be passed as a vector register. |
3237 | llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { |
3238 | // Wrapper structs/arrays that only contain vectors are passed just like |
3239 | // vectors; strip them off if present. |
3240 | if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) |
3241 | Ty = QualType(InnerTy, 0); |
3242 | |
3243 | llvm::Type *IRType = CGT.ConvertType(Ty); |
3244 | if (isa<llvm::VectorType>(IRType)) { |
3245 | // Don't pass vXi128 vectors in their native type, the backend can't |
3246 | // legalize them. |
3247 | if (passInt128VectorsInMem() && |
3248 | cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { |
3249 | // Use a vXi64 vector. |
3250 | uint64_t Size = getContext().getTypeSize(Ty); |
3251 | return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), |
3252 | Size / 64); |
3253 | } |
3254 | |
3255 | return IRType; |
3256 | } |
3257 | |
3258 | if (IRType->getTypeID() == llvm::Type::FP128TyID) |
3259 | return IRType; |
3260 | |
3261 | // We couldn't find the preferred IR vector type for 'Ty'. |
3262 | uint64_t Size = getContext().getTypeSize(Ty); |
3263 | assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!")(((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!" ) ? static_cast<void> (0) : __assert_fail ("(Size == 128 || Size == 256 || Size == 512) && \"Invalid type found!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3263, __PRETTY_FUNCTION__)); |
3264 | |
3265 | |
3266 | // Return a LLVM IR vector type based on the size of 'Ty'. |
3267 | return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), |
3268 | Size / 64); |
3269 | } |
3270 | |
3271 | /// BitsContainNoUserData - Return true if the specified [start,end) bit range |
3272 | /// is known to either be off the end of the specified type or being in |
3273 | /// alignment padding. The user type specified is known to be at most 128 bits |
3274 | /// in size, and have passed through X86_64ABIInfo::classify with a successful |
3275 | /// classification that put one of the two halves in the INTEGER class. |
3276 | /// |
3277 | /// It is conservatively correct to return false. |
3278 | static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, |
3279 | unsigned EndBit, ASTContext &Context) { |
3280 | // If the bytes being queried are off the end of the type, there is no user |
3281 | // data hiding here. This handles analysis of builtins, vectors and other |
3282 | // types that don't contain interesting padding. |
3283 | unsigned TySize = (unsigned)Context.getTypeSize(Ty); |
3284 | if (TySize <= StartBit) |
3285 | return true; |
3286 | |
3287 | if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { |
3288 | unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); |
3289 | unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); |
3290 | |
3291 | // Check each element to see if the element overlaps with the queried range. |
3292 | for (unsigned i = 0; i != NumElts; ++i) { |
3293 | // If the element is after the span we care about, then we're done.. |
3294 | unsigned EltOffset = i*EltSize; |
3295 | if (EltOffset >= EndBit) break; |
3296 | |
3297 | unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; |
3298 | if (!BitsContainNoUserData(AT->getElementType(), EltStart, |
3299 | EndBit-EltOffset, Context)) |
3300 | return false; |
3301 | } |
3302 | // If it overlaps no elements, then it is safe to process as padding. |
3303 | return true; |
3304 | } |
3305 | |
3306 | if (const RecordType *RT = Ty->getAs<RecordType>()) { |
3307 | const RecordDecl *RD = RT->getDecl(); |
3308 | const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); |
3309 | |
3310 | // If this is a C++ record, check the bases first. |
3311 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
3312 | for (const auto &I : CXXRD->bases()) { |
3313 | assert(!I.isVirtual() && !I.getType()->isDependentType() &&((!I.isVirtual() && !I.getType()->isDependentType( ) && "Unexpected base class!") ? static_cast<void> (0) : __assert_fail ("!I.isVirtual() && !I.getType()->isDependentType() && \"Unexpected base class!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3314, __PRETTY_FUNCTION__)) |
3314 | "Unexpected base class!")((!I.isVirtual() && !I.getType()->isDependentType( ) && "Unexpected base class!") ? static_cast<void> (0) : __assert_fail ("!I.isVirtual() && !I.getType()->isDependentType() && \"Unexpected base class!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3314, __PRETTY_FUNCTION__)); |
3315 | const auto *Base = |
3316 | cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); |
3317 | |
3318 | // If the base is after the span we care about, ignore it. |
3319 | unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); |
3320 | if (BaseOffset >= EndBit) continue; |
3321 | |
3322 | unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; |
3323 | if (!BitsContainNoUserData(I.getType(), BaseStart, |
3324 | EndBit-BaseOffset, Context)) |
3325 | return false; |
3326 | } |
3327 | } |
3328 | |
3329 | // Verify that no field has data that overlaps the region of interest. Yes |
3330 | // this could be sped up a lot by being smarter about queried fields, |
3331 | // however we're only looking at structs up to 16 bytes, so we don't care |
3332 | // much. |
3333 | unsigned idx = 0; |
3334 | for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); |
3335 | i != e; ++i, ++idx) { |
3336 | unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); |
3337 | |
3338 | // If we found a field after the region we care about, then we're done. |
3339 | if (FieldOffset >= EndBit) break; |
3340 | |
3341 | unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; |
3342 | if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, |
3343 | Context)) |
3344 | return false; |
3345 | } |
3346 | |
3347 | // If nothing in this record overlapped the area of interest, then we're |
3348 | // clean. |
3349 | return true; |
3350 | } |
3351 | |
3352 | return false; |
3353 | } |
3354 | |
3355 | /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a |
3356 | /// float member at the specified offset. For example, {int,{float}} has a |
3357 | /// float at offset 4. It is conservatively correct for this routine to return |
3358 | /// false. |
3359 | static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, |
3360 | const llvm::DataLayout &TD) { |
3361 | // Base case if we find a float. |
3362 | if (IROffset == 0 && IRType->isFloatTy()) |
3363 | return true; |
3364 | |
3365 | // If this is a struct, recurse into the field at the specified offset. |
3366 | if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { |
3367 | const llvm::StructLayout *SL = TD.getStructLayout(STy); |
3368 | unsigned Elt = SL->getElementContainingOffset(IROffset); |
3369 | IROffset -= SL->getElementOffset(Elt); |
3370 | return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); |
3371 | } |
3372 | |
3373 | // If this is an array, recurse into the field at the specified offset. |
3374 | if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { |
3375 | llvm::Type *EltTy = ATy->getElementType(); |
3376 | unsigned EltSize = TD.getTypeAllocSize(EltTy); |
3377 | IROffset -= IROffset/EltSize*EltSize; |
3378 | return ContainsFloatAtOffset(EltTy, IROffset, TD); |
3379 | } |
3380 | |
3381 | return false; |
3382 | } |
3383 | |
3384 | |
3385 | /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the |
3386 | /// low 8 bytes of an XMM register, corresponding to the SSE class. |
3387 | llvm::Type *X86_64ABIInfo:: |
3388 | GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, |
3389 | QualType SourceTy, unsigned SourceOffset) const { |
3390 | // The only three choices we have are either double, <2 x float>, or float. We |
3391 | // pass as float if the last 4 bytes is just padding. This happens for |
3392 | // structs that contain 3 floats. |
3393 | if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, |
3394 | SourceOffset*8+64, getContext())) |
3395 | return llvm::Type::getFloatTy(getVMContext()); |
3396 | |
3397 | // We want to pass as <2 x float> if the LLVM IR type contains a float at |
3398 | // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the |
3399 | // case. |
3400 | if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && |
3401 | ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) |
3402 | return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()), |
3403 | 2); |
3404 | |
3405 | return llvm::Type::getDoubleTy(getVMContext()); |
3406 | } |
3407 | |
3408 | |
3409 | /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in |
3410 | /// an 8-byte GPR. This means that we either have a scalar or we are talking |
3411 | /// about the high or low part of an up-to-16-byte struct. This routine picks |
3412 | /// the best LLVM IR type to represent this, which may be i64 or may be anything |
3413 | /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, |
3414 | /// etc). |
3415 | /// |
3416 | /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for |
3417 | /// the source type. IROffset is an offset in bytes into the LLVM IR type that |
3418 | /// the 8-byte value references. PrefType may be null. |
3419 | /// |
3420 | /// SourceTy is the source-level type for the entire argument. SourceOffset is |
3421 | /// an offset into this that we're processing (which is always either 0 or 8). |
3422 | /// |
3423 | llvm::Type *X86_64ABIInfo:: |
3424 | GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, |
3425 | QualType SourceTy, unsigned SourceOffset) const { |
3426 | // If we're dealing with an un-offset LLVM IR type, then it means that we're |
3427 | // returning an 8-byte unit starting with it. See if we can safely use it. |
3428 | if (IROffset == 0) { |
3429 | // Pointers and int64's always fill the 8-byte unit. |
3430 | if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || |
3431 | IRType->isIntegerTy(64)) |
3432 | return IRType; |
3433 | |
3434 | // If we have a 1/2/4-byte integer, we can use it only if the rest of the |
3435 | // goodness in the source type is just tail padding. This is allowed to |
3436 | // kick in for struct {double,int} on the int, but not on |
3437 | // struct{double,int,int} because we wouldn't return the second int. We |
3438 | // have to do this analysis on the source type because we can't depend on |
3439 | // unions being lowered a specific way etc. |
3440 | if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || |
3441 | IRType->isIntegerTy(32) || |
3442 | (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { |
3443 | unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : |
3444 | cast<llvm::IntegerType>(IRType)->getBitWidth(); |
3445 | |
3446 | if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, |
3447 | SourceOffset*8+64, getContext())) |
3448 | return IRType; |
3449 | } |
3450 | } |
3451 | |
3452 | if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { |
3453 | // If this is a struct, recurse into the field at the specified offset. |
3454 | const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); |
3455 | if (IROffset < SL->getSizeInBytes()) { |
3456 | unsigned FieldIdx = SL->getElementContainingOffset(IROffset); |
3457 | IROffset -= SL->getElementOffset(FieldIdx); |
3458 | |
3459 | return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, |
3460 | SourceTy, SourceOffset); |
3461 | } |
3462 | } |
3463 | |
3464 | if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { |
3465 | llvm::Type *EltTy = ATy->getElementType(); |
3466 | unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); |
3467 | unsigned EltOffset = IROffset/EltSize*EltSize; |
3468 | return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, |
3469 | SourceOffset); |
3470 | } |
3471 | |
3472 | // Okay, we don't have any better idea of what to pass, so we pass this in an |
3473 | // integer register that isn't too big to fit the rest of the struct. |
3474 | unsigned TySizeInBytes = |
3475 | (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); |
3476 | |
3477 | assert(TySizeInBytes != SourceOffset && "Empty field?")((TySizeInBytes != SourceOffset && "Empty field?") ? static_cast <void> (0) : __assert_fail ("TySizeInBytes != SourceOffset && \"Empty field?\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3477, __PRETTY_FUNCTION__)); |
3478 | |
3479 | // It is always safe to classify this as an integer type up to i64 that |
3480 | // isn't larger than the structure. |
3481 | return llvm::IntegerType::get(getVMContext(), |
3482 | std::min(TySizeInBytes-SourceOffset, 8U)*8); |
3483 | } |
3484 | |
3485 | |
3486 | /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally |
3487 | /// be used as elements of a two register pair to pass or return, return a |
3488 | /// first class aggregate to represent them. For example, if the low part of |
3489 | /// a by-value argument should be passed as i32* and the high part as float, |
3490 | /// return {i32*, float}. |
3491 | static llvm::Type * |
3492 | GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, |
3493 | const llvm::DataLayout &TD) { |
3494 | // In order to correctly satisfy the ABI, we need to the high part to start |
3495 | // at offset 8. If the high and low parts we inferred are both 4-byte types |
3496 | // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have |
3497 | // the second element at offset 8. Check for this: |
3498 | unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); |
3499 | unsigned HiAlign = TD.getABITypeAlignment(Hi); |
3500 | unsigned HiStart = llvm::alignTo(LoSize, HiAlign); |
3501 | assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!")((HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!" ) ? static_cast<void> (0) : __assert_fail ("HiStart != 0 && HiStart <= 8 && \"Invalid x86-64 argument pair!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3501, __PRETTY_FUNCTION__)); |
3502 | |
3503 | // To handle this, we have to increase the size of the low part so that the |
3504 | // second element will start at an 8 byte offset. We can't increase the size |
3505 | // of the second element because it might make us access off the end of the |
3506 | // struct. |
3507 | if (HiStart != 8) { |
3508 | // There are usually two sorts of types the ABI generation code can produce |
3509 | // for the low part of a pair that aren't 8 bytes in size: float or |
3510 | // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and |
3511 | // NaCl). |
3512 | // Promote these to a larger type. |
3513 | if (Lo->isFloatTy()) |
3514 | Lo = llvm::Type::getDoubleTy(Lo->getContext()); |
3515 | else { |
3516 | assert((Lo->isIntegerTy() || Lo->isPointerTy())(((Lo->isIntegerTy() || Lo->isPointerTy()) && "Invalid/unknown lo type" ) ? static_cast<void> (0) : __assert_fail ("(Lo->isIntegerTy() || Lo->isPointerTy()) && \"Invalid/unknown lo type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3517, __PRETTY_FUNCTION__)) |
3517 | && "Invalid/unknown lo type")(((Lo->isIntegerTy() || Lo->isPointerTy()) && "Invalid/unknown lo type" ) ? static_cast<void> (0) : __assert_fail ("(Lo->isIntegerTy() || Lo->isPointerTy()) && \"Invalid/unknown lo type\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3517, __PRETTY_FUNCTION__)); |
3518 | Lo = llvm::Type::getInt64Ty(Lo->getContext()); |
3519 | } |
3520 | } |
3521 | |
3522 | llvm::StructType *Result = llvm::StructType::get(Lo, Hi); |
3523 | |
3524 | // Verify that the second element is at an 8-byte offset. |
3525 | assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&((TD.getStructLayout(Result)->getElementOffset(1) == 8 && "Invalid x86-64 argument pair!") ? static_cast<void> ( 0) : __assert_fail ("TD.getStructLayout(Result)->getElementOffset(1) == 8 && \"Invalid x86-64 argument pair!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3526, __PRETTY_FUNCTION__)) |
3526 | "Invalid x86-64 argument pair!")((TD.getStructLayout(Result)->getElementOffset(1) == 8 && "Invalid x86-64 argument pair!") ? static_cast<void> ( 0) : __assert_fail ("TD.getStructLayout(Result)->getElementOffset(1) == 8 && \"Invalid x86-64 argument pair!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3526, __PRETTY_FUNCTION__)); |
3527 | return Result; |
3528 | } |
3529 | |
3530 | ABIArgInfo X86_64ABIInfo:: |
3531 | classifyReturnType(QualType RetTy) const { |
3532 | // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the |
3533 | // classification algorithm. |
3534 | X86_64ABIInfo::Class Lo, Hi; |
3535 | classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); |
3536 | |
3537 | // Check some invariants. |
3538 | assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.")(((Hi != Memory || Lo == Memory) && "Invalid memory classification." ) ? static_cast<void> (0) : __assert_fail ("(Hi != Memory || Lo == Memory) && \"Invalid memory classification.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3538, __PRETTY_FUNCTION__)); |
3539 | assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.")(((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification." ) ? static_cast<void> (0) : __assert_fail ("(Hi != SSEUp || Lo == SSE) && \"Invalid SSEUp classification.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3539, __PRETTY_FUNCTION__)); |
3540 | |
3541 | llvm::Type *ResType = nullptr; |
3542 | switch (Lo) { |
3543 | case NoClass: |
3544 | if (Hi == NoClass) |
3545 | return ABIArgInfo::getIgnore(); |
3546 | // If the low part is just padding, it takes no register, leave ResType |
3547 | // null. |
3548 | assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&(((Hi == SSE || Hi == Integer || Hi == X87Up) && "Unknown missing lo part" ) ? static_cast<void> (0) : __assert_fail ("(Hi == SSE || Hi == Integer || Hi == X87Up) && \"Unknown missing lo part\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3549, __PRETTY_FUNCTION__)) |
3549 | "Unknown missing lo part")(((Hi == SSE || Hi == Integer || Hi == X87Up) && "Unknown missing lo part" ) ? static_cast<void> (0) : __assert_fail ("(Hi == SSE || Hi == Integer || Hi == X87Up) && \"Unknown missing lo part\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3549, __PRETTY_FUNCTION__)); |
3550 | break; |
3551 | |
3552 | case SSEUp: |
3553 | case X87Up: |
3554 | llvm_unreachable("Invalid classification for lo word.")::llvm::llvm_unreachable_internal("Invalid classification for lo word." , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3554); |
3555 | |
3556 | // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via |
3557 | // hidden argument. |
3558 | case Memory: |
3559 | return getIndirectReturnResult(RetTy); |
3560 | |
3561 | // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next |
3562 | // available register of the sequence %rax, %rdx is used. |
3563 | case Integer: |
3564 | ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); |
3565 | |
3566 | // If we have a sign or zero extended integer, make sure to return Extend |
3567 | // so that the parameter gets the right LLVM IR attributes. |
3568 | if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { |
3569 | // Treat an enum type as its underlying type. |
3570 | if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) |
3571 | RetTy = EnumTy->getDecl()->getIntegerType(); |
3572 | |
3573 | if (RetTy->isIntegralOrEnumerationType() && |
3574 | isPromotableIntegerTypeForABI(RetTy)) |
3575 | return ABIArgInfo::getExtend(RetTy); |
3576 | } |
3577 | break; |
3578 | |
3579 | // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next |
3580 | // available SSE register of the sequence %xmm0, %xmm1 is used. |
3581 | case SSE: |
3582 | ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); |
3583 | break; |
3584 | |
3585 | // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is |
3586 | // returned on the X87 stack in %st0 as 80-bit x87 number. |
3587 | case X87: |
3588 | ResType = llvm::Type::getX86_FP80Ty(getVMContext()); |
3589 | break; |
3590 | |
3591 | // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real |
3592 | // part of the value is returned in %st0 and the imaginary part in |
3593 | // %st1. |
3594 | case ComplexX87: |
3595 | assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.")((Hi == ComplexX87 && "Unexpected ComplexX87 classification." ) ? static_cast<void> (0) : __assert_fail ("Hi == ComplexX87 && \"Unexpected ComplexX87 classification.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3595, __PRETTY_FUNCTION__)); |
3596 | ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), |
3597 | llvm::Type::getX86_FP80Ty(getVMContext())); |
3598 | break; |
3599 | } |
3600 | |
3601 | llvm::Type *HighPart = nullptr; |
3602 | switch (Hi) { |
3603 | // Memory was handled previously and X87 should |
3604 | // never occur as a hi class. |
3605 | case Memory: |
3606 | case X87: |
3607 | llvm_unreachable("Invalid classification for hi word.")::llvm::llvm_unreachable_internal("Invalid classification for hi word." , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3607); |
3608 | |
3609 | case ComplexX87: // Previously handled. |
3610 | case NoClass: |
3611 | break; |
3612 | |
3613 | case Integer: |
3614 | HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); |
3615 | if (Lo == NoClass) // Return HighPart at offset 8 in memory. |
3616 | return ABIArgInfo::getDirect(HighPart, 8); |
3617 | break; |
3618 | case SSE: |
3619 | HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); |
3620 | if (Lo == NoClass) // Return HighPart at offset 8 in memory. |
3621 | return ABIArgInfo::getDirect(HighPart, 8); |
3622 | break; |
3623 | |
3624 | // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte |
3625 | // is passed in the next available eightbyte chunk if the last used |
3626 | // vector register. |
3627 | // |
3628 | // SSEUP should always be preceded by SSE, just widen. |
3629 | case SSEUp: |
3630 | assert(Lo == SSE && "Unexpected SSEUp classification.")((Lo == SSE && "Unexpected SSEUp classification.") ? static_cast <void> (0) : __assert_fail ("Lo == SSE && \"Unexpected SSEUp classification.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3630, __PRETTY_FUNCTION__)); |
3631 | ResType = GetByteVectorType(RetTy); |
3632 | break; |
3633 | |
3634 | // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is |
3635 | // returned together with the previous X87 value in %st0. |
3636 | case X87Up: |
3637 | // If X87Up is preceded by X87, we don't need to do |
3638 | // anything. However, in some cases with unions it may not be |
3639 | // preceded by X87. In such situations we follow gcc and pass the |
3640 | // extra bits in an SSE reg. |
3641 | if (Lo != X87) { |
3642 | HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); |
3643 | if (Lo == NoClass) // Return HighPart at offset 8 in memory. |
3644 | return ABIArgInfo::getDirect(HighPart, 8); |
3645 | } |
3646 | break; |
3647 | } |
3648 | |
3649 | // If a high part was specified, merge it together with the low part. It is |
3650 | // known to pass in the high eightbyte of the result. We do this by forming a |
3651 | // first class struct aggregate with the high and low part: {low, high} |
3652 | if (HighPart) |
3653 | ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); |
3654 | |
3655 | return ABIArgInfo::getDirect(ResType); |
3656 | } |
3657 | |
3658 | ABIArgInfo X86_64ABIInfo::classifyArgumentType( |
3659 | QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, |
3660 | bool isNamedArg) |
3661 | const |
3662 | { |
3663 | Ty = useFirstFieldIfTransparentUnion(Ty); |
3664 | |
3665 | X86_64ABIInfo::Class Lo, Hi; |
3666 | classify(Ty, 0, Lo, Hi, isNamedArg); |
3667 | |
3668 | // Check some invariants. |
3669 | // FIXME: Enforce these by construction. |
3670 | assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.")(((Hi != Memory || Lo == Memory) && "Invalid memory classification." ) ? static_cast<void> (0) : __assert_fail ("(Hi != Memory || Lo == Memory) && \"Invalid memory classification.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3670, __PRETTY_FUNCTION__)); |
3671 | assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.")(((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification." ) ? static_cast<void> (0) : __assert_fail ("(Hi != SSEUp || Lo == SSE) && \"Invalid SSEUp classification.\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3671, __PRETTY_FUNCTION__)); |
3672 | |
3673 | neededInt = 0; |
3674 | neededSSE = 0; |
3675 | llvm::Type *ResType = nullptr; |
3676 | switch (Lo) { |
3677 | case NoClass: |
3678 | if (Hi == NoClass) |
3679 | return ABIArgInfo::getIgnore(); |
3680 | // If the low part is just padding, it takes no register, leave ResType |
3681 | // null. |
3682 | assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&(((Hi == SSE || Hi == Integer || Hi == X87Up) && "Unknown missing lo part" ) ? static_cast<void> (0) : __assert_fail ("(Hi == SSE || Hi == Integer || Hi == X87Up) && \"Unknown missing lo part\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3683, __PRETTY_FUNCTION__)) |
3683 | "Unknown missing lo part")(((Hi == SSE || Hi == Integer || Hi == X87Up) && "Unknown missing lo part" ) ? static_cast<void> (0) : __assert_fail ("(Hi == SSE || Hi == Integer || Hi == X87Up) && \"Unknown missing lo part\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3683, __PRETTY_FUNCTION__)); |
3684 | break; |
3685 | |
3686 | // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument |
3687 | // on the stack. |
3688 | case Memory: |
3689 | |
3690 | // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or |
3691 | // COMPLEX_X87, it is passed in memory. |
3692 | case X87: |
3693 | case ComplexX87: |
3694 | if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) |
3695 | ++neededInt; |
3696 | return getIndirectResult(Ty, freeIntRegs); |
3697 | |
3698 | case SSEUp: |
3699 | case X87Up: |
3700 | llvm_unreachable("Invalid classification for lo word.")::llvm::llvm_unreachable_internal("Invalid classification for lo word." , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3700); |
3701 | |
3702 | // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next |
3703 | // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 |
3704 | // and %r9 is used. |
3705 | case Integer: |
3706 | ++neededInt; |
3707 | |
3708 | // Pick an 8-byte type based on the preferred type. |
3709 | ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); |
3710 | |
3711 | // If we have a sign or zero extended integer, make sure to return Extend |
3712 | // so that the parameter gets the right LLVM IR attributes. |
3713 | if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { |
3714 | // Treat an enum type as its underlying type. |
3715 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
3716 | Ty = EnumTy->getDecl()->getIntegerType(); |
3717 | |
3718 | if (Ty->isIntegralOrEnumerationType() && |
3719 | isPromotableIntegerTypeForABI(Ty)) |
3720 | return ABIArgInfo::getExtend(Ty); |
3721 | } |
3722 | |
3723 | break; |
3724 | |
3725 | // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next |
3726 | // available SSE register is used, the registers are taken in the |
3727 | // order from %xmm0 to %xmm7. |
3728 | case SSE: { |
3729 | llvm::Type *IRType = CGT.ConvertType(Ty); |
3730 | ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); |
3731 | ++neededSSE; |
3732 | break; |
3733 | } |
3734 | } |
3735 | |
3736 | llvm::Type *HighPart = nullptr; |
3737 | switch (Hi) { |
3738 | // Memory was handled previously, ComplexX87 and X87 should |
3739 | // never occur as hi classes, and X87Up must be preceded by X87, |
3740 | // which is passed in memory. |
3741 | case Memory: |
3742 | case X87: |
3743 | case ComplexX87: |
3744 | llvm_unreachable("Invalid classification for hi word.")::llvm::llvm_unreachable_internal("Invalid classification for hi word." , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3744); |
3745 | |
3746 | case NoClass: break; |
3747 | |
3748 | case Integer: |
3749 | ++neededInt; |
3750 | // Pick an 8-byte type based on the preferred type. |
3751 | HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); |
3752 | |
3753 | if (Lo == NoClass) // Pass HighPart at offset 8 in memory. |
3754 | return ABIArgInfo::getDirect(HighPart, 8); |
3755 | break; |
3756 | |
3757 | // X87Up generally doesn't occur here (long double is passed in |
3758 | // memory), except in situations involving unions. |
3759 | case X87Up: |
3760 | case SSE: |
3761 | HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); |
3762 | |
3763 | if (Lo == NoClass) // Pass HighPart at offset 8 in memory. |
3764 | return ABIArgInfo::getDirect(HighPart, 8); |
3765 | |
3766 | ++neededSSE; |
3767 | break; |
3768 | |
3769 | // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the |
3770 | // eightbyte is passed in the upper half of the last used SSE |
3771 | // register. This only happens when 128-bit vectors are passed. |
3772 | case SSEUp: |
3773 | assert(Lo == SSE && "Unexpected SSEUp classification")((Lo == SSE && "Unexpected SSEUp classification") ? static_cast <void> (0) : __assert_fail ("Lo == SSE && \"Unexpected SSEUp classification\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3773, __PRETTY_FUNCTION__)); |
3774 | ResType = GetByteVectorType(Ty); |
3775 | break; |
3776 | } |
3777 | |
3778 | // If a high part was specified, merge it together with the low part. It is |
3779 | // known to pass in the high eightbyte of the result. We do this by forming a |
3780 | // first class struct aggregate with the high and low part: {low, high} |
3781 | if (HighPart) |
3782 | ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); |
3783 | |
3784 | return ABIArgInfo::getDirect(ResType); |
3785 | } |
3786 | |
3787 | ABIArgInfo |
3788 | X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, |
3789 | unsigned &NeededSSE) const { |
3790 | auto RT = Ty->getAs<RecordType>(); |
3791 | assert(RT && "classifyRegCallStructType only valid with struct types")((RT && "classifyRegCallStructType only valid with struct types" ) ? static_cast<void> (0) : __assert_fail ("RT && \"classifyRegCallStructType only valid with struct types\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 3791, __PRETTY_FUNCTION__)); |
3792 | |
3793 | if (RT->getDecl()->hasFlexibleArrayMember()) |
3794 | return getIndirectReturnResult(Ty); |
3795 | |
3796 | // Sum up bases |
3797 | if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { |
3798 | if (CXXRD->isDynamicClass()) { |
3799 | NeededInt = NeededSSE = 0; |
3800 | return getIndirectReturnResult(Ty); |
3801 | } |
3802 | |
3803 | for (const auto &I : CXXRD->bases()) |
3804 | if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) |
3805 | .isIndirect()) { |
3806 | NeededInt = NeededSSE = 0; |
3807 | return getIndirectReturnResult(Ty); |
3808 | } |
3809 | } |
3810 | |
3811 | // Sum up members |
3812 | for (const auto *FD : RT->getDecl()->fields()) { |
3813 | if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { |
3814 | if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) |
3815 | .isIndirect()) { |
3816 | NeededInt = NeededSSE = 0; |
3817 | return getIndirectReturnResult(Ty); |
3818 | } |
3819 | } else { |
3820 | unsigned LocalNeededInt, LocalNeededSSE; |
3821 | if (classifyArgumentType(FD->getType(), UINT_MAX(2147483647 *2U +1U), LocalNeededInt, |
3822 | LocalNeededSSE, true) |
3823 | .isIndirect()) { |
3824 | NeededInt = NeededSSE = 0; |
3825 | return getIndirectReturnResult(Ty); |
3826 | } |
3827 | NeededInt += LocalNeededInt; |
3828 | NeededSSE += LocalNeededSSE; |
3829 | } |
3830 | } |
3831 | |
3832 | return ABIArgInfo::getDirect(); |
3833 | } |
3834 | |
3835 | ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, |
3836 | unsigned &NeededInt, |
3837 | unsigned &NeededSSE) const { |
3838 | |
3839 | NeededInt = 0; |
3840 | NeededSSE = 0; |
3841 | |
3842 | return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); |
3843 | } |
3844 | |
3845 | void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { |
3846 | |
3847 | const unsigned CallingConv = FI.getCallingConvention(); |
3848 | // It is possible to force Win64 calling convention on any x86_64 target by |
3849 | // using __attribute__((ms_abi)). In such case to correctly emit Win64 |
3850 | // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. |
3851 | if (CallingConv == llvm::CallingConv::Win64) { |
3852 | WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); |
3853 | Win64ABIInfo.computeInfo(FI); |
3854 | return; |
3855 | } |
3856 | |
3857 | bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; |
3858 | |
3859 | // Keep track of the number of assigned registers. |
3860 | unsigned FreeIntRegs = IsRegCall ? 11 : 6; |
3861 | unsigned FreeSSERegs = IsRegCall ? 16 : 8; |
3862 | unsigned NeededInt, NeededSSE; |
3863 | |
3864 | if (!::classifyReturnType(getCXXABI(), FI, *this)) { |
3865 | if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && |
3866 | !FI.getReturnType()->getTypePtr()->isUnionType()) { |
3867 | FI.getReturnInfo() = |
3868 | classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); |
3869 | if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { |
3870 | FreeIntRegs -= NeededInt; |
3871 | FreeSSERegs -= NeededSSE; |
3872 | } else { |
3873 | FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); |
3874 | } |
3875 | } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && |
3876 | getContext().getCanonicalType(FI.getReturnType() |
3877 | ->getAs<ComplexType>() |
3878 | ->getElementType()) == |
3879 | getContext().LongDoubleTy) |
3880 | // Complex Long Double Type is passed in Memory when Regcall |
3881 | // calling convention is used. |
3882 | FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); |
3883 | else |
3884 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); |
3885 | } |
3886 | |
3887 | // If the return value is indirect, then the hidden argument is consuming one |
3888 | // integer register. |
3889 | if (FI.getReturnInfo().isIndirect()) |
3890 | --FreeIntRegs; |
3891 | |
3892 | // The chain argument effectively gives us another free register. |
3893 | if (FI.isChainCall()) |
3894 | ++FreeIntRegs; |
3895 | |
3896 | unsigned NumRequiredArgs = FI.getNumRequiredArgs(); |
3897 | // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers |
3898 | // get assigned (in left-to-right order) for passing as follows... |
3899 | unsigned ArgNo = 0; |
3900 | for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); |
3901 | it != ie; ++it, ++ArgNo) { |
3902 | bool IsNamedArg = ArgNo < NumRequiredArgs; |
3903 | |
3904 | if (IsRegCall && it->type->isStructureOrClassType()) |
3905 | it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); |
3906 | else |
3907 | it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, |
3908 | NeededSSE, IsNamedArg); |
3909 | |
3910 | // AMD64-ABI 3.2.3p3: If there are no registers available for any |
3911 | // eightbyte of an argument, the whole argument is passed on the |
3912 | // stack. If registers have already been assigned for some |
3913 | // eightbytes of such an argument, the assignments get reverted. |
3914 | if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { |
3915 | FreeIntRegs -= NeededInt; |
3916 | FreeSSERegs -= NeededSSE; |
3917 | } else { |
3918 | it->info = getIndirectResult(it->type, FreeIntRegs); |
3919 | } |
3920 | } |
3921 | } |
3922 | |
3923 | static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, |
3924 | Address VAListAddr, QualType Ty) { |
3925 | Address overflow_arg_area_p = |
3926 | CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); |
3927 | llvm::Value *overflow_arg_area = |
3928 | CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); |
3929 | |
3930 | // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 |
3931 | // byte boundary if alignment needed by type exceeds 8 byte boundary. |
3932 | // It isn't stated explicitly in the standard, but in practice we use |
3933 | // alignment greater than 16 where necessary. |
3934 | CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); |
3935 | if (Align > CharUnits::fromQuantity(8)) { |
3936 | overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, |
3937 | Align); |
3938 | } |
3939 | |
3940 | // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. |
3941 | llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); |
3942 | llvm::Value *Res = |
3943 | CGF.Builder.CreateBitCast(overflow_arg_area, |
3944 | llvm::PointerType::getUnqual(LTy)); |
3945 | |
3946 | // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: |
3947 | // l->overflow_arg_area + sizeof(type). |
3948 | // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to |
3949 | // an 8 byte boundary. |
3950 | |
3951 | uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; |
3952 | llvm::Value *Offset = |
3953 | llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); |
3954 | overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, |
3955 | "overflow_arg_area.next"); |
3956 | CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); |
3957 | |
3958 | // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. |
3959 | return Address(Res, Align); |
3960 | } |
3961 | |
3962 | Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
3963 | QualType Ty) const { |
3964 | // Assume that va_list type is correct; should be pointer to LLVM type: |
3965 | // struct { |
3966 | // i32 gp_offset; |
3967 | // i32 fp_offset; |
3968 | // i8* overflow_arg_area; |
3969 | // i8* reg_save_area; |
3970 | // }; |
3971 | unsigned neededInt, neededSSE; |
3972 | |
3973 | Ty = getContext().getCanonicalType(Ty); |
3974 | ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, |
3975 | /*isNamedArg*/false); |
3976 | |
3977 | // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed |
3978 | // in the registers. If not go to step 7. |
3979 | if (!neededInt && !neededSSE) |
3980 | return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); |
3981 | |
3982 | // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of |
3983 | // general purpose registers needed to pass type and num_fp to hold |
3984 | // the number of floating point registers needed. |
3985 | |
3986 | // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into |
3987 | // registers. In the case: l->gp_offset > 48 - num_gp * 8 or |
3988 | // l->fp_offset > 304 - num_fp * 16 go to step 7. |
3989 | // |
3990 | // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of |
3991 | // register save space). |
3992 | |
3993 | llvm::Value *InRegs = nullptr; |
3994 | Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); |
3995 | llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; |
3996 | if (neededInt) { |
3997 | gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); |
3998 | gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); |
3999 | InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); |
4000 | InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); |
4001 | } |
4002 | |
4003 | if (neededSSE) { |
4004 | fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); |
4005 | fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); |
4006 | llvm::Value *FitsInFP = |
4007 | llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); |
4008 | FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); |
4009 | InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; |
4010 | } |
4011 | |
4012 | llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); |
4013 | llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); |
4014 | llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); |
4015 | CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); |
4016 | |
4017 | // Emit code to load the value if it was passed in registers. |
4018 | |
4019 | CGF.EmitBlock(InRegBlock); |
4020 | |
4021 | // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with |
4022 | // an offset of l->gp_offset and/or l->fp_offset. This may require |
4023 | // copying to a temporary location in case the parameter is passed |
4024 | // in different register classes or requires an alignment greater |
4025 | // than 8 for general purpose registers and 16 for XMM registers. |
4026 | // |
4027 | // FIXME: This really results in shameful code when we end up needing to |
4028 | // collect arguments from different places; often what should result in a |
4029 | // simple assembling of a structure from scattered addresses has many more |
4030 | // loads than necessary. Can we clean this up? |
4031 | llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); |
4032 | llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( |
4033 | CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); |
4034 | |
4035 | Address RegAddr = Address::invalid(); |
4036 | if (neededInt && neededSSE) { |
4037 | // FIXME: Cleanup. |
4038 | assert(AI.isDirect() && "Unexpected ABI info for mixed regs")((AI.isDirect() && "Unexpected ABI info for mixed regs" ) ? static_cast<void> (0) : __assert_fail ("AI.isDirect() && \"Unexpected ABI info for mixed regs\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 4038, __PRETTY_FUNCTION__)); |
4039 | llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); |
4040 | Address Tmp = CGF.CreateMemTemp(Ty); |
4041 | Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); |
4042 | assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs")((ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs" ) ? static_cast<void> (0) : __assert_fail ("ST->getNumElements() == 2 && \"Unexpected ABI info for mixed regs\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 4042, __PRETTY_FUNCTION__)); |
4043 | llvm::Type *TyLo = ST->getElementType(0); |
4044 | llvm::Type *TyHi = ST->getElementType(1); |
4045 | assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&(((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && "Unexpected ABI info for mixed regs") ? static_cast <void> (0) : __assert_fail ("(TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && \"Unexpected ABI info for mixed regs\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 4046, __PRETTY_FUNCTION__)) |
4046 | "Unexpected ABI info for mixed regs")(((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && "Unexpected ABI info for mixed regs") ? static_cast <void> (0) : __assert_fail ("(TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && \"Unexpected ABI info for mixed regs\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 4046, __PRETTY_FUNCTION__)); |
4047 | llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); |
4048 | llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); |
4049 | llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); |
4050 | llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); |
4051 | llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; |
4052 | llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; |
4053 | |
4054 | // Copy the first element. |
4055 | // FIXME: Our choice of alignment here and below is probably pessimistic. |
4056 | llvm::Value *V = CGF.Builder.CreateAlignedLoad( |
4057 | TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), |
4058 | CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); |
4059 | CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); |
4060 | |
4061 | // Copy the second element. |
4062 | V = CGF.Builder.CreateAlignedLoad( |
4063 | TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), |
4064 | CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); |
4065 | CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); |
4066 | |
4067 | RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); |
4068 | } else if (neededInt) { |
4069 | RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), |
4070 | CharUnits::fromQuantity(8)); |
4071 | RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); |
4072 | |
4073 | // Copy to a temporary if necessary to ensure the appropriate alignment. |
4074 | auto TInfo = getContext().getTypeInfoInChars(Ty); |
4075 | uint64_t TySize = TInfo.Width.getQuantity(); |
4076 | CharUnits TyAlign = TInfo.Align; |
4077 | |
4078 | // Copy into a temporary if the type is more aligned than the |
4079 | // register save area. |
4080 | if (TyAlign.getQuantity() > 8) { |
4081 | Address Tmp = CGF.CreateMemTemp(Ty); |
4082 | CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); |
4083 | RegAddr = Tmp; |
4084 | } |
4085 | |
4086 | } else if (neededSSE == 1) { |
4087 | RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), |
4088 | CharUnits::fromQuantity(16)); |
4089 | RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); |
4090 | } else { |
4091 | assert(neededSSE == 2 && "Invalid number of needed registers!")((neededSSE == 2 && "Invalid number of needed registers!" ) ? static_cast<void> (0) : __assert_fail ("neededSSE == 2 && \"Invalid number of needed registers!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 4091, __PRETTY_FUNCTION__)); |
4092 | // SSE registers are spaced 16 bytes apart in the register save |
4093 | // area, we need to collect the two eightbytes together. |
4094 | // The ABI isn't explicit about this, but it seems reasonable |
4095 | // to assume that the slots are 16-byte aligned, since the stack is |
4096 | // naturally 16-byte aligned and the prologue is expected to store |
4097 | // all the SSE registers to the RSA. |
4098 | Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), |
4099 | CharUnits::fromQuantity(16)); |
4100 | Address RegAddrHi = |
4101 | CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, |
4102 | CharUnits::fromQuantity(16)); |
4103 | llvm::Type *ST = AI.canHaveCoerceToType() |
4104 | ? AI.getCoerceToType() |
4105 | : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); |
4106 | llvm::Value *V; |
4107 | Address Tmp = CGF.CreateMemTemp(Ty); |
4108 | Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); |
4109 | V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( |
4110 | RegAddrLo, ST->getStructElementType(0))); |
4111 | CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); |
4112 | V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( |
4113 | RegAddrHi, ST->getStructElementType(1))); |
4114 | CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); |
4115 | |
4116 | RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); |
4117 | } |
4118 | |
4119 | // AMD64-ABI 3.5.7p5: Step 5. Set: |
4120 | // l->gp_offset = l->gp_offset + num_gp * 8 |
4121 | // l->fp_offset = l->fp_offset + num_fp * 16. |
4122 | if (neededInt) { |
4123 | llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); |
4124 | CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), |
4125 | gp_offset_p); |
4126 | } |
4127 | if (neededSSE) { |
4128 | llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); |
4129 | CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), |
4130 | fp_offset_p); |
4131 | } |
4132 | CGF.EmitBranch(ContBlock); |
4133 | |
4134 | // Emit code to load the value if it was passed in memory. |
4135 | |
4136 | CGF.EmitBlock(InMemBlock); |
4137 | Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); |
4138 | |
4139 | // Return the appropriate result. |
4140 | |
4141 | CGF.EmitBlock(ContBlock); |
4142 | Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, |
4143 | "vaarg.addr"); |
4144 | return ResAddr; |
4145 | } |
4146 | |
4147 | Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, |
4148 | QualType Ty) const { |
4149 | return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, |
4150 | CGF.getContext().getTypeInfoInChars(Ty), |
4151 | CharUnits::fromQuantity(8), |
4152 | /*allowHigherAlign*/ false); |
4153 | } |
4154 | |
4155 | ABIArgInfo |
4156 | WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, |
4157 | const ABIArgInfo ¤t) const { |
4158 | // Assumes vectorCall calling convention. |
4159 | const Type *Base = nullptr; |
4160 | uint64_t NumElts = 0; |
4161 | |
4162 | if (!Ty->isBuiltinType() && !Ty->isVectorType() && |
4163 | isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { |
4164 | FreeSSERegs -= NumElts; |
4165 | return getDirectX86Hva(); |
4166 | } |
4167 | return current; |
4168 | } |
4169 | |
4170 | ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, |
4171 | bool IsReturnType, bool IsVectorCall, |
4172 | bool IsRegCall) const { |
4173 | |
4174 | if (Ty->isVoidType()) |
4175 | return ABIArgInfo::getIgnore(); |
4176 | |
4177 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
4178 | Ty = EnumTy->getDecl()->getIntegerType(); |
4179 | |
4180 | TypeInfo Info = getContext().getTypeInfo(Ty); |
4181 | uint64_t Width = Info.Width; |
4182 | CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); |
4183 | |
4184 | const RecordType *RT = Ty->getAs<RecordType>(); |
4185 | if (RT) { |
4186 | if (!IsReturnType) { |
4187 | if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) |
4188 | return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); |
4189 | } |
4190 | |
4191 | if (RT->getDecl()->hasFlexibleArrayMember()) |
4192 | return getNaturalAlignIndirect(Ty, /*ByVal=*/false); |
4193 | |
4194 | } |
4195 | |
4196 | const Type *Base = nullptr; |
4197 | uint64_t NumElts = 0; |
4198 | // vectorcall adds the concept of a homogenous vector aggregate, similar to |
4199 | // other targets. |
4200 | if ((IsVectorCall || IsRegCall) && |
4201 | isHomogeneousAggregate(Ty, Base, NumElts)) { |
4202 | if (IsRegCall) { |
4203 | if (FreeSSERegs >= NumElts) { |
4204 | FreeSSERegs -= NumElts; |
4205 | if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) |
4206 | return ABIArgInfo::getDirect(); |
4207 | return ABIArgInfo::getExpand(); |
4208 | } |
4209 | return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); |
4210 | } else if (IsVectorCall) { |
4211 | if (FreeSSERegs >= NumElts && |
4212 | (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { |
4213 | FreeSSERegs -= NumElts; |
4214 | return ABIArgInfo::getDirect(); |
4215 | } else if (IsReturnType) { |
4216 | return ABIArgInfo::getExpand(); |
4217 | } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { |
4218 | // HVAs are delayed and reclassified in the 2nd step. |
4219 | return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); |
4220 | } |
4221 | } |
4222 | } |
4223 | |
4224 | if (Ty->isMemberPointerType()) { |
4225 | // If the member pointer is represented by an LLVM int or ptr, pass it |
4226 | // directly. |
4227 | llvm::Type *LLTy = CGT.ConvertType(Ty); |
4228 | if (LLTy->isPointerTy() || LLTy->isIntegerTy()) |
4229 | return ABIArgInfo::getDirect(); |
4230 | } |
4231 | |
4232 | if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { |
4233 | // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is |
4234 | // not 1, 2, 4, or 8 bytes, must be passed by reference." |
4235 | if (Width > 64 || !llvm::isPowerOf2_64(Width)) |
4236 | return getNaturalAlignIndirect(Ty, /*ByVal=*/false); |
4237 | |
4238 | // Otherwise, coerce it to a small integer. |
4239 | return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); |
4240 | } |
4241 | |
4242 | if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { |
4243 | switch (BT->getKind()) { |
4244 | case BuiltinType::Bool: |
4245 | // Bool type is always extended to the ABI, other builtin types are not |
4246 | // extended. |
4247 | return ABIArgInfo::getExtend(Ty); |
4248 | |
4249 | case BuiltinType::LongDouble: |
4250 | // Mingw64 GCC uses the old 80 bit extended precision floating point |
4251 | // unit. It passes them indirectly through memory. |
4252 | if (IsMingw64) { |
4253 | const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); |
4254 | if (LDF == &llvm::APFloat::x87DoubleExtended()) |
4255 | return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); |
4256 | } |
4257 | break; |
4258 | |
4259 | case BuiltinType::Int128: |
4260 | case BuiltinType::UInt128: |
4261 | // If it's a parameter type, the normal ABI rule is that arguments larger |
4262 | // than 8 bytes are passed indirectly. GCC follows it. We follow it too, |
4263 | // even though it isn't particularly efficient. |
4264 | if (!IsReturnType) |
4265 | return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); |
4266 | |
4267 | // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. |
4268 | // Clang matches them for compatibility. |
4269 | return ABIArgInfo::getDirect(llvm::FixedVectorType::get( |
4270 | llvm::Type::getInt64Ty(getVMContext()), 2)); |
4271 | |
4272 | default: |
4273 | break; |
4274 | } |
4275 | } |
4276 | |
4277 | if (Ty->isExtIntType()) { |
4278 | // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is |
4279 | // not 1, 2, 4, or 8 bytes, must be passed by reference." |
4280 | // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes |
4281 | // anyway as long is it fits in them, so we don't have to check the power of |
4282 | // 2. |
4283 | if (Width <= 64) |
4284 | return ABIArgInfo::getDirect(); |
4285 | return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); |
4286 | } |
4287 | |
4288 | return ABIArgInfo::getDirect(); |
4289 | } |
4290 | |
4291 | void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, |
4292 | unsigned FreeSSERegs, |
4293 | bool IsVectorCall, |
4294 | bool IsRegCall) const { |
4295 | unsigned Count = 0; |
4296 | for (auto &I : FI.arguments()) { |
4297 | // Vectorcall in x64 only permits the first 6 arguments to be passed |
4298 | // as XMM/YMM registers. |
4299 | if (Count < VectorcallMaxParamNumAsReg) |
4300 | I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); |
4301 | else { |
4302 | // Since these cannot be passed in registers, pretend no registers |
4303 | // are left. |
4304 | unsigned ZeroSSERegsAvail = 0; |
4305 | I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, |
4306 | IsVectorCall, IsRegCall); |
4307 | } |
4308 | ++Count; |
4309 | } |
4310 | |
4311 | for (auto &I : FI.arguments()) { |
4312 | I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); |
4313 | } |
4314 | } |
4315 | |
4316 | void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { |
4317 | const unsigned CC = FI.getCallingConvention(); |
4318 | bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; |
4319 | bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; |
4320 | |
4321 | // If __attribute__((sysv_abi)) is in use, use the SysV argument |
4322 | // classification rules. |
4323 | if (CC == llvm::CallingConv::X86_64_SysV) { |
4324 | X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); |
4325 | SysVABIInfo.computeInfo(FI); |
4326 | return; |
4327 | } |
4328 | |
4329 | unsigned FreeSSERegs = 0; |
4330 | if (IsVectorCall) { |
4331 | // We can use up to 4 SSE return registers with vectorcall. |
4332 | FreeSSERegs = 4; |
4333 | } else if (IsRegCall) { |
4334 | // RegCall gives us 16 SSE registers. |
4335 | FreeSSERegs = 16; |
4336 | } |
4337 | |
4338 | if (!getCXXABI().classifyReturnType(FI)) |
4339 | FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, |
4340 | IsVectorCall, IsRegCall); |
4341 | |
4342 | if (IsVectorCall) { |
4343 | // We can use up to 6 SSE register parameters with vectorcall. |
4344 | FreeSSERegs = 6; |
4345 | } else if (IsRegCall) { |
4346 | // RegCall gives us 16 SSE registers, we can reuse the return registers. |
4347 | FreeSSERegs = 16; |
4348 | } |
4349 | |
4350 | if (IsVectorCall) { |
4351 | computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); |
4352 | } else { |
4353 | for (auto &I : FI.arguments()) |
4354 | I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); |
4355 | } |
4356 | |
4357 | } |
4358 | |
4359 | Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
4360 | QualType Ty) const { |
4361 | |
4362 | bool IsIndirect = false; |
4363 | |
4364 | // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is |
4365 | // not 1, 2, 4, or 8 bytes, must be passed by reference." |
4366 | if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { |
4367 | uint64_t Width = getContext().getTypeSize(Ty); |
4368 | IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); |
4369 | } |
4370 | |
4371 | return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, |
4372 | CGF.getContext().getTypeInfoInChars(Ty), |
4373 | CharUnits::fromQuantity(8), |
4374 | /*allowHigherAlign*/ false); |
4375 | } |
4376 | |
4377 | static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
4378 | llvm::Value *Address, bool Is64Bit, |
4379 | bool IsAIX) { |
4380 | // This is calculated from the LLVM and GCC tables and verified |
4381 | // against gcc output. AFAIK all PPC ABIs use the same encoding. |
4382 | |
4383 | CodeGen::CGBuilderTy &Builder = CGF.Builder; |
4384 | |
4385 | llvm::IntegerType *i8 = CGF.Int8Ty; |
4386 | llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); |
4387 | llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); |
4388 | llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); |
4389 | |
4390 | // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers |
4391 | AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); |
4392 | |
4393 | // 32-63: fp0-31, the 8-byte floating-point registers |
4394 | AssignToArrayRange(Builder, Address, Eight8, 32, 63); |
4395 | |
4396 | // 64-67 are various 4-byte or 8-byte special-purpose registers: |
4397 | // 64: mq |
4398 | // 65: lr |
4399 | // 66: ctr |
4400 | // 67: ap |
4401 | AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); |
4402 | |
4403 | // 68-76 are various 4-byte special-purpose registers: |
4404 | // 68-75 cr0-7 |
4405 | // 76: xer |
4406 | AssignToArrayRange(Builder, Address, Four8, 68, 76); |
4407 | |
4408 | // 77-108: v0-31, the 16-byte vector registers |
4409 | AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); |
4410 | |
4411 | // 109: vrsave |
4412 | // 110: vscr |
4413 | AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); |
4414 | |
4415 | // AIX does not utilize the rest of the registers. |
4416 | if (IsAIX) |
4417 | return false; |
4418 | |
4419 | // 111: spe_acc |
4420 | // 112: spefscr |
4421 | // 113: sfp |
4422 | AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); |
4423 | |
4424 | if (!Is64Bit) |
4425 | return false; |
4426 | |
4427 | // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 |
4428 | // or above CPU. |
4429 | // 64-bit only registers: |
4430 | // 114: tfhar |
4431 | // 115: tfiar |
4432 | // 116: texasr |
4433 | AssignToArrayRange(Builder, Address, Eight8, 114, 116); |
4434 | |
4435 | return false; |
4436 | } |
4437 | |
4438 | // AIX |
4439 | namespace { |
4440 | /// AIXABIInfo - The AIX XCOFF ABI information. |
4441 | class AIXABIInfo : public ABIInfo { |
4442 | const bool Is64Bit; |
4443 | const unsigned PtrByteSize; |
4444 | CharUnits getParamTypeAlignment(QualType Ty) const; |
4445 | |
4446 | public: |
4447 | AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) |
4448 | : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} |
4449 | |
4450 | bool isPromotableTypeForABI(QualType Ty) const; |
4451 | |
4452 | ABIArgInfo classifyReturnType(QualType RetTy) const; |
4453 | ABIArgInfo classifyArgumentType(QualType Ty) const; |
4454 | |
4455 | void computeInfo(CGFunctionInfo &FI) const override { |
4456 | if (!getCXXABI().classifyReturnType(FI)) |
4457 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); |
4458 | |
4459 | for (auto &I : FI.arguments()) |
4460 | I.info = classifyArgumentType(I.type); |
4461 | } |
4462 | |
4463 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
4464 | QualType Ty) const override; |
4465 | }; |
4466 | |
4467 | class AIXTargetCodeGenInfo : public TargetCodeGenInfo { |
4468 | const bool Is64Bit; |
4469 | |
4470 | public: |
4471 | AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) |
4472 | : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), |
4473 | Is64Bit(Is64Bit) {} |
4474 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { |
4475 | return 1; // r1 is the dedicated stack pointer |
4476 | } |
4477 | |
4478 | bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
4479 | llvm::Value *Address) const override; |
4480 | }; |
4481 | } // namespace |
4482 | |
4483 | // Return true if the ABI requires Ty to be passed sign- or zero- |
4484 | // extended to 32/64 bits. |
4485 | bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { |
4486 | // Treat an enum type as its underlying type. |
4487 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
4488 | Ty = EnumTy->getDecl()->getIntegerType(); |
4489 | |
4490 | // Promotable integer types are required to be promoted by the ABI. |
4491 | if (Ty->isPromotableIntegerType()) |
4492 | return true; |
4493 | |
4494 | if (!Is64Bit) |
4495 | return false; |
4496 | |
4497 | // For 64 bit mode, in addition to the usual promotable integer types, we also |
4498 | // need to extend all 32-bit types, since the ABI requires promotion to 64 |
4499 | // bits. |
4500 | if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) |
4501 | switch (BT->getKind()) { |
4502 | case BuiltinType::Int: |
4503 | case BuiltinType::UInt: |
4504 | return true; |
4505 | default: |
4506 | break; |
4507 | } |
4508 | |
4509 | return false; |
4510 | } |
4511 | |
4512 | ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { |
4513 | if (RetTy->isAnyComplexType()) |
4514 | return ABIArgInfo::getDirect(); |
4515 | |
4516 | if (RetTy->isVectorType()) |
4517 | llvm::report_fatal_error("vector type is not supported on AIX yet"); |
4518 | |
4519 | if (RetTy->isVoidType()) |
4520 | return ABIArgInfo::getIgnore(); |
4521 | |
4522 | if (isAggregateTypeForABI(RetTy)) |
4523 | return getNaturalAlignIndirect(RetTy); |
4524 | |
4525 | return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) |
4526 | : ABIArgInfo::getDirect()); |
4527 | } |
4528 | |
4529 | ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { |
4530 | Ty = useFirstFieldIfTransparentUnion(Ty); |
4531 | |
4532 | if (Ty->isAnyComplexType()) |
4533 | return ABIArgInfo::getDirect(); |
4534 | |
4535 | if (Ty->isVectorType()) |
4536 | llvm::report_fatal_error("vector type is not supported on AIX yet"); |
4537 | |
4538 | if (isAggregateTypeForABI(Ty)) { |
4539 | // Records with non-trivial destructors/copy-constructors should not be |
4540 | // passed by value. |
4541 | if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) |
4542 | return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); |
4543 | |
4544 | CharUnits CCAlign = getParamTypeAlignment(Ty); |
4545 | CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); |
4546 | |
4547 | return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, |
4548 | /*Realign*/ TyAlign > CCAlign); |
4549 | } |
4550 | |
4551 | return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) |
4552 | : ABIArgInfo::getDirect()); |
4553 | } |
4554 | |
4555 | CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { |
4556 | // Complex types are passed just like their elements. |
4557 | if (const ComplexType *CTy = Ty->getAs<ComplexType>()) |
4558 | Ty = CTy->getElementType(); |
4559 | |
4560 | if (Ty->isVectorType()) |
4561 | llvm::report_fatal_error("vector type is not supported on AIX yet"); |
4562 | |
4563 | // If the structure contains a vector type, the alignment is 16. |
4564 | if (isRecordWithSIMDVectorType(getContext(), Ty)) |
4565 | return CharUnits::fromQuantity(16); |
4566 | |
4567 | return CharUnits::fromQuantity(PtrByteSize); |
4568 | } |
4569 | |
4570 | Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
4571 | QualType Ty) const { |
4572 | if (Ty->isAnyComplexType()) |
4573 | llvm::report_fatal_error("complex type is not supported on AIX yet"); |
4574 | |
4575 | if (Ty->isVectorType()) |
4576 | llvm::report_fatal_error("vector type is not supported on AIX yet"); |
4577 | |
4578 | auto TypeInfo = getContext().getTypeInfoInChars(Ty); |
4579 | TypeInfo.Align = getParamTypeAlignment(Ty); |
4580 | |
4581 | CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); |
4582 | |
4583 | return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, |
4584 | SlotSize, /*AllowHigher*/ true); |
4585 | } |
4586 | |
4587 | bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( |
4588 | CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { |
4589 | return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); |
4590 | } |
4591 | |
4592 | // PowerPC-32 |
4593 | namespace { |
4594 | /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. |
4595 | class PPC32_SVR4_ABIInfo : public DefaultABIInfo { |
4596 | bool IsSoftFloatABI; |
4597 | bool IsRetSmallStructInRegABI; |
4598 | |
4599 | CharUnits getParamTypeAlignment(QualType Ty) const; |
4600 | |
4601 | public: |
4602 | PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, |
4603 | bool RetSmallStructInRegABI) |
4604 | : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), |
4605 | IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} |
4606 | |
4607 | ABIArgInfo classifyReturnType(QualType RetTy) const; |
4608 | |
4609 | void computeInfo(CGFunctionInfo &FI) const override { |
4610 | if (!getCXXABI().classifyReturnType(FI)) |
4611 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); |
4612 | for (auto &I : FI.arguments()) |
4613 | I.info = classifyArgumentType(I.type); |
4614 | } |
4615 | |
4616 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
4617 | QualType Ty) const override; |
4618 | }; |
4619 | |
4620 | class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { |
4621 | public: |
4622 | PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, |
4623 | bool RetSmallStructInRegABI) |
4624 | : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( |
4625 | CGT, SoftFloatABI, RetSmallStructInRegABI)) {} |
4626 | |
4627 | static bool isStructReturnInRegABI(const llvm::Triple &Triple, |
4628 | const CodeGenOptions &Opts); |
4629 | |
4630 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { |
4631 | // This is recovered from gcc output. |
4632 | return 1; // r1 is the dedicated stack pointer |
4633 | } |
4634 | |
4635 | bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
4636 | llvm::Value *Address) const override; |
4637 | }; |
4638 | } |
4639 | |
4640 | CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { |
4641 | // Complex types are passed just like their elements. |
4642 | if (const ComplexType *CTy = Ty->getAs<ComplexType>()) |
4643 | Ty = CTy->getElementType(); |
4644 | |
4645 | if (Ty->isVectorType()) |
4646 | return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 |
4647 | : 4); |
4648 | |
4649 | // For single-element float/vector structs, we consider the whole type |
4650 | // to have the same alignment requirements as its single element. |
4651 | const Type *AlignTy = nullptr; |
4652 | if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { |
4653 | const BuiltinType *BT = EltType->getAs<BuiltinType>(); |
4654 | if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || |
4655 | (BT && BT->isFloatingPoint())) |
4656 | AlignTy = EltType; |
4657 | } |
4658 | |
4659 | if (AlignTy) |
4660 | return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); |
4661 | return CharUnits::fromQuantity(4); |
4662 | } |
4663 | |
4664 | ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { |
4665 | uint64_t Size; |
4666 | |
4667 | // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. |
4668 | if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && |
4669 | (Size = getContext().getTypeSize(RetTy)) <= 64) { |
4670 | // System V ABI (1995), page 3-22, specified: |
4671 | // > A structure or union whose size is less than or equal to 8 bytes |
4672 | // > shall be returned in r3 and r4, as if it were first stored in the |
4673 | // > 8-byte aligned memory area and then the low addressed word were |
4674 | // > loaded into r3 and the high-addressed word into r4. Bits beyond |
4675 | // > the last member of the structure or union are not defined. |
4676 | // |
4677 | // GCC for big-endian PPC32 inserts the pad before the first member, |
4678 | // not "beyond the last member" of the struct. To stay compatible |
4679 | // with GCC, we coerce the struct to an integer of the same size. |
4680 | // LLVM will extend it and return i32 in r3, or i64 in r3:r4. |
4681 | if (Size == 0) |
4682 | return ABIArgInfo::getIgnore(); |
4683 | else { |
4684 | llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); |
4685 | return ABIArgInfo::getDirect(CoerceTy); |
4686 | } |
4687 | } |
4688 | |
4689 | return DefaultABIInfo::classifyReturnType(RetTy); |
4690 | } |
4691 | |
4692 | // TODO: this implementation is now likely redundant with |
4693 | // DefaultABIInfo::EmitVAArg. |
4694 | Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, |
4695 | QualType Ty) const { |
4696 | if (getTarget().getTriple().isOSDarwin()) { |
4697 | auto TI = getContext().getTypeInfoInChars(Ty); |
4698 | TI.Align = getParamTypeAlignment(Ty); |
4699 | |
4700 | CharUnits SlotSize = CharUnits::fromQuantity(4); |
4701 | return emitVoidPtrVAArg(CGF, VAList, Ty, |
4702 | classifyArgumentType(Ty).isIndirect(), TI, SlotSize, |
4703 | /*AllowHigherAlign=*/true); |
4704 | } |
4705 | |
4706 | const unsigned OverflowLimit = 8; |
4707 | if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { |
4708 | // TODO: Implement this. For now ignore. |
4709 | (void)CTy; |
4710 | return Address::invalid(); // FIXME? |
4711 | } |
4712 | |
4713 | // struct __va_list_tag { |
4714 | // unsigned char gpr; |
4715 | // unsigned char fpr; |
4716 | // unsigned short reserved; |
4717 | // void *overflow_arg_area; |
4718 | // void *reg_save_area; |
4719 | // }; |
4720 | |
4721 | bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; |
4722 | bool isInt = |
4723 | Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType(); |
4724 | bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; |
4725 | |
4726 | // All aggregates are passed indirectly? That doesn't seem consistent |
4727 | // with the argument-lowering code. |
4728 | bool isIndirect = Ty->isAggregateType(); |
4729 | |
4730 | CGBuilderTy &Builder = CGF.Builder; |
4731 | |
4732 | // The calling convention either uses 1-2 GPRs or 1 FPR. |
4733 | Address NumRegsAddr = Address::invalid(); |
4734 | if (isInt || IsSoftFloatABI) { |
4735 | NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); |
4736 | } else { |
4737 | NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); |
4738 | } |
4739 | |
4740 | llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); |
4741 | |
4742 | // "Align" the register count when TY is i64. |
4743 | if (isI64 || (isF64 && IsSoftFloatABI)) { |
4744 | NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); |
4745 | NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); |
4746 | } |
4747 | |
4748 | llvm::Value *CC = |
4749 | Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); |
4750 | |
4751 | llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); |
4752 | llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); |
4753 | llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); |
4754 | |
4755 | Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); |
4756 | |
4757 | llvm::Type *DirectTy = CGF.ConvertType(Ty); |
4758 | if (isIndirect) DirectTy = DirectTy->getPointerTo(0); |
4759 | |
4760 | // Case 1: consume registers. |
4761 | Address RegAddr = Address::invalid(); |
4762 | { |
4763 | CGF.EmitBlock(UsingRegs); |
4764 | |
4765 | Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); |
4766 | RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), |
4767 | CharUnits::fromQuantity(8)); |
4768 | assert(RegAddr.getElementType() == CGF.Int8Ty)((RegAddr.getElementType() == CGF.Int8Ty) ? static_cast<void > (0) : __assert_fail ("RegAddr.getElementType() == CGF.Int8Ty" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 4768, __PRETTY_FUNCTION__)); |
4769 | |
4770 | // Floating-point registers start after the general-purpose registers. |
4771 | if (!(isInt || IsSoftFloatABI)) { |
4772 | RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, |
4773 | CharUnits::fromQuantity(32)); |
4774 | } |
4775 | |
4776 | // Get the address of the saved value by scaling the number of |
4777 | // registers we've used by the number of |
4778 | CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); |
4779 | llvm::Value *RegOffset = |
4780 | Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); |
4781 | RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, |
4782 | RegAddr.getPointer(), RegOffset), |
4783 | RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); |
4784 | RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); |
4785 | |
4786 | // Increase the used-register count. |
4787 | NumRegs = |
4788 | Builder.CreateAdd(NumRegs, |
4789 | Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); |
4790 | Builder.CreateStore(NumRegs, NumRegsAddr); |
4791 | |
4792 | CGF.EmitBranch(Cont); |
4793 | } |
4794 | |
4795 | // Case 2: consume space in the overflow area. |
4796 | Address MemAddr = Address::invalid(); |
4797 | { |
4798 | CGF.EmitBlock(UsingOverflow); |
4799 | |
4800 | Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); |
4801 | |
4802 | // Everything in the overflow area is rounded up to a size of at least 4. |
4803 | CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); |
4804 | |
4805 | CharUnits Size; |
4806 | if (!isIndirect) { |
4807 | auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); |
4808 | Size = TypeInfo.Width.alignTo(OverflowAreaAlign); |
4809 | } else { |
4810 | Size = CGF.getPointerSize(); |
4811 | } |
4812 | |
4813 | Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); |
4814 | Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), |
4815 | OverflowAreaAlign); |
4816 | // Round up address of argument to alignment |
4817 | CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); |
4818 | if (Align > OverflowAreaAlign) { |
4819 | llvm::Value *Ptr = OverflowArea.getPointer(); |
4820 | OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), |
4821 | Align); |
4822 | } |
4823 | |
4824 | MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); |
4825 | |
4826 | // Increase the overflow area. |
4827 | OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); |
4828 | Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); |
4829 | CGF.EmitBranch(Cont); |
4830 | } |
4831 | |
4832 | CGF.EmitBlock(Cont); |
4833 | |
4834 | // Merge the cases with a phi. |
4835 | Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, |
4836 | "vaarg.addr"); |
4837 | |
4838 | // Load the pointer if the argument was passed indirectly. |
4839 | if (isIndirect) { |
4840 | Result = Address(Builder.CreateLoad(Result, "aggr"), |
4841 | getContext().getTypeAlignInChars(Ty)); |
4842 | } |
4843 | |
4844 | return Result; |
4845 | } |
4846 | |
4847 | bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( |
4848 | const llvm::Triple &Triple, const CodeGenOptions &Opts) { |
4849 | assert(Triple.getArch() == llvm::Triple::ppc)((Triple.getArch() == llvm::Triple::ppc) ? static_cast<void > (0) : __assert_fail ("Triple.getArch() == llvm::Triple::ppc" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 4849, __PRETTY_FUNCTION__)); |
4850 | |
4851 | switch (Opts.getStructReturnConvention()) { |
4852 | case CodeGenOptions::SRCK_Default: |
4853 | break; |
4854 | case CodeGenOptions::SRCK_OnStack: // -maix-struct-return |
4855 | return false; |
4856 | case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return |
4857 | return true; |
4858 | } |
4859 | |
4860 | if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) |
4861 | return true; |
4862 | |
4863 | return false; |
4864 | } |
4865 | |
4866 | bool |
4867 | PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
4868 | llvm::Value *Address) const { |
4869 | return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, |
4870 | /*IsAIX*/ false); |
4871 | } |
4872 | |
4873 | // PowerPC-64 |
4874 | |
4875 | namespace { |
4876 | /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. |
4877 | class PPC64_SVR4_ABIInfo : public SwiftABIInfo { |
4878 | public: |
4879 | enum ABIKind { |
4880 | ELFv1 = 0, |
4881 | ELFv2 |
4882 | }; |
4883 | |
4884 | private: |
4885 | static const unsigned GPRBits = 64; |
4886 | ABIKind Kind; |
4887 | bool HasQPX; |
4888 | bool IsSoftFloatABI; |
4889 | |
4890 | // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and |
4891 | // will be passed in a QPX register. |
4892 | bool IsQPXVectorTy(const Type *Ty) const { |
4893 | if (!HasQPX) |
4894 | return false; |
4895 | |
4896 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
4897 | unsigned NumElements = VT->getNumElements(); |
4898 | if (NumElements == 1) |
4899 | return false; |
4900 | |
4901 | if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { |
4902 | if (getContext().getTypeSize(Ty) <= 256) |
4903 | return true; |
4904 | } else if (VT->getElementType()-> |
4905 | isSpecificBuiltinType(BuiltinType::Float)) { |
4906 | if (getContext().getTypeSize(Ty) <= 128) |
4907 | return true; |
4908 | } |
4909 | } |
4910 | |
4911 | return false; |
4912 | } |
4913 | |
4914 | bool IsQPXVectorTy(QualType Ty) const { |
4915 | return IsQPXVectorTy(Ty.getTypePtr()); |
4916 | } |
4917 | |
4918 | public: |
4919 | PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, |
4920 | bool SoftFloatABI) |
4921 | : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), |
4922 | IsSoftFloatABI(SoftFloatABI) {} |
4923 | |
4924 | bool isPromotableTypeForABI(QualType Ty) const; |
4925 | CharUnits getParamTypeAlignment(QualType Ty) const; |
4926 | |
4927 | ABIArgInfo classifyReturnType(QualType RetTy) const; |
4928 | ABIArgInfo classifyArgumentType(QualType Ty) const; |
4929 | |
4930 | bool isHomogeneousAggregateBaseType(QualType Ty) const override; |
4931 | bool isHomogeneousAggregateSmallEnough(const Type *Ty, |
4932 | uint64_t Members) const override; |
4933 | |
4934 | // TODO: We can add more logic to computeInfo to improve performance. |
4935 | // Example: For aggregate arguments that fit in a register, we could |
4936 | // use getDirectInReg (as is done below for structs containing a single |
4937 | // floating-point value) to avoid pushing them to memory on function |
4938 | // entry. This would require changing the logic in PPCISelLowering |
4939 | // when lowering the parameters in the caller and args in the callee. |
4940 | void computeInfo(CGFunctionInfo &FI) const override { |
4941 | if (!getCXXABI().classifyReturnType(FI)) |
4942 | FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); |
4943 | for (auto &I : FI.arguments()) { |
4944 | // We rely on the default argument classification for the most part. |
4945 | // One exception: An aggregate containing a single floating-point |
4946 | // or vector item must be passed in a register if one is available. |
4947 | const Type *T = isSingleElementStruct(I.type, getContext()); |
4948 | if (T) { |
4949 | const BuiltinType *BT = T->getAs<BuiltinType>(); |
4950 | if (IsQPXVectorTy(T) || |
4951 | (T->isVectorType() && getContext().getTypeSize(T) == 128) || |
4952 | (BT && BT->isFloatingPoint())) { |
4953 | QualType QT(T, 0); |
4954 | I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); |
4955 | continue; |
4956 | } |
4957 | } |
4958 | I.info = classifyArgumentType(I.type); |
4959 | } |
4960 | } |
4961 | |
4962 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
4963 | QualType Ty) const override; |
4964 | |
4965 | bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, |
4966 | bool asReturnValue) const override { |
4967 | return occupiesMoreThan(CGT, scalars, /*total*/ 4); |
4968 | } |
4969 | |
4970 | bool isSwiftErrorInRegister() const override { |
4971 | return false; |
4972 | } |
4973 | }; |
4974 | |
4975 | class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { |
4976 | |
4977 | public: |
4978 | PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, |
4979 | PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, |
4980 | bool SoftFloatABI) |
4981 | : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>( |
4982 | CGT, Kind, HasQPX, SoftFloatABI)) {} |
4983 | |
4984 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { |
4985 | // This is recovered from gcc output. |
4986 | return 1; // r1 is the dedicated stack pointer |
4987 | } |
4988 | |
4989 | bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
4990 | llvm::Value *Address) const override; |
4991 | }; |
4992 | |
4993 | class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { |
4994 | public: |
4995 | PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} |
4996 | |
4997 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { |
4998 | // This is recovered from gcc output. |
4999 | return 1; // r1 is the dedicated stack pointer |
5000 | } |
5001 | |
5002 | bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
5003 | llvm::Value *Address) const override; |
5004 | }; |
5005 | |
5006 | } |
5007 | |
5008 | // Return true if the ABI requires Ty to be passed sign- or zero- |
5009 | // extended to 64 bits. |
5010 | bool |
5011 | PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { |
5012 | // Treat an enum type as its underlying type. |
5013 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
5014 | Ty = EnumTy->getDecl()->getIntegerType(); |
5015 | |
5016 | // Promotable integer types are required to be promoted by the ABI. |
5017 | if (isPromotableIntegerTypeForABI(Ty)) |
5018 | return true; |
5019 | |
5020 | // In addition to the usual promotable integer types, we also need to |
5021 | // extend all 32-bit types, since the ABI requires promotion to 64 bits. |
5022 | if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) |
5023 | switch (BT->getKind()) { |
5024 | case BuiltinType::Int: |
5025 | case BuiltinType::UInt: |
5026 | return true; |
5027 | default: |
5028 | break; |
5029 | } |
5030 | |
5031 | if (const auto *EIT = Ty->getAs<ExtIntType>()) |
5032 | if (EIT->getNumBits() < 64) |
5033 | return true; |
5034 | |
5035 | return false; |
5036 | } |
5037 | |
5038 | /// isAlignedParamType - Determine whether a type requires 16-byte or |
5039 | /// higher alignment in the parameter area. Always returns at least 8. |
5040 | CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { |
5041 | // Complex types are passed just like their elements. |
5042 | if (const ComplexType *CTy = Ty->getAs<ComplexType>()) |
5043 | Ty = CTy->getElementType(); |
5044 | |
5045 | // Only vector types of size 16 bytes need alignment (larger types are |
5046 | // passed via reference, smaller types are not aligned). |
5047 | if (IsQPXVectorTy(Ty)) { |
5048 | if (getContext().getTypeSize(Ty) > 128) |
5049 | return CharUnits::fromQuantity(32); |
5050 | |
5051 | return CharUnits::fromQuantity(16); |
5052 | } else if (Ty->isVectorType()) { |
5053 | return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); |
5054 | } else if (Ty->isRealFloatingType() && getContext().getTypeSize(Ty) == 128) { |
5055 | // IEEE 128-bit floating numbers are also stored in vector registers. |
5056 | // And both IEEE quad-precision and IBM extended double (ppc_fp128) should |
5057 | // be quad-word aligned. |
5058 | return CharUnits::fromQuantity(16); |
5059 | } |
5060 | |
5061 | // For single-element float/vector structs, we consider the whole type |
5062 | // to have the same alignment requirements as its single element. |
5063 | const Type *AlignAsType = nullptr; |
5064 | const Type *EltType = isSingleElementStruct(Ty, getContext()); |
5065 | if (EltType) { |
5066 | const BuiltinType *BT = EltType->getAs<BuiltinType>(); |
5067 | if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && |
5068 | getContext().getTypeSize(EltType) == 128) || |
5069 | (BT && BT->isFloatingPoint())) |
5070 | AlignAsType = EltType; |
5071 | } |
5072 | |
5073 | // Likewise for ELFv2 homogeneous aggregates. |
5074 | const Type *Base = nullptr; |
5075 | uint64_t Members = 0; |
5076 | if (!AlignAsType && Kind == ELFv2 && |
5077 | isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) |
5078 | AlignAsType = Base; |
5079 | |
5080 | // With special case aggregates, only vector base types need alignment. |
5081 | if (AlignAsType && IsQPXVectorTy(AlignAsType)) { |
5082 | if (getContext().getTypeSize(AlignAsType) > 128) |
5083 | return CharUnits::fromQuantity(32); |
5084 | |
5085 | return CharUnits::fromQuantity(16); |
5086 | } else if (AlignAsType) { |
5087 | return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); |
5088 | } |
5089 | |
5090 | // Otherwise, we only need alignment for any aggregate type that |
5091 | // has an alignment requirement of >= 16 bytes. |
5092 | if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { |
5093 | if (HasQPX && getContext().getTypeAlign(Ty) >= 256) |
5094 | return CharUnits::fromQuantity(32); |
5095 | return CharUnits::fromQuantity(16); |
5096 | } |
5097 | |
5098 | return CharUnits::fromQuantity(8); |
5099 | } |
5100 | |
5101 | /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous |
5102 | /// aggregate. Base is set to the base element type, and Members is set |
5103 | /// to the number of base elements. |
5104 | bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, |
5105 | uint64_t &Members) const { |
5106 | if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { |
5107 | uint64_t NElements = AT->getSize().getZExtValue(); |
5108 | if (NElements == 0) |
5109 | return false; |
5110 | if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) |
5111 | return false; |
5112 | Members *= NElements; |
5113 | } else if (const RecordType *RT = Ty->getAs<RecordType>()) { |
5114 | const RecordDecl *RD = RT->getDecl(); |
5115 | if (RD->hasFlexibleArrayMember()) |
5116 | return false; |
5117 | |
5118 | Members = 0; |
5119 | |
5120 | // If this is a C++ record, check the bases first. |
5121 | if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { |
5122 | for (const auto &I : CXXRD->bases()) { |
5123 | // Ignore empty records. |
5124 | if (isEmptyRecord(getContext(), I.getType(), true)) |
5125 | continue; |
5126 | |
5127 | uint64_t FldMembers; |
5128 | if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) |
5129 | return false; |
5130 | |
5131 | Members += FldMembers; |
5132 | } |
5133 | } |
5134 | |
5135 | for (const auto *FD : RD->fields()) { |
5136 | // Ignore (non-zero arrays of) empty records. |
5137 | QualType FT = FD->getType(); |
5138 | while (const ConstantArrayType *AT = |
5139 | getContext().getAsConstantArrayType(FT)) { |
5140 | if (AT->getSize().getZExtValue() == 0) |
5141 | return false; |
5142 | FT = AT->getElementType(); |
5143 | } |
5144 | if (isEmptyRecord(getContext(), FT, true)) |
5145 | continue; |
5146 | |
5147 | // For compatibility with GCC, ignore empty bitfields in C++ mode. |
5148 | if (getContext().getLangOpts().CPlusPlus && |
5149 | FD->isZeroLengthBitField(getContext())) |
5150 | continue; |
5151 | |
5152 | uint64_t FldMembers; |
5153 | if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) |
5154 | return false; |
5155 | |
5156 | Members = (RD->isUnion() ? |
5157 | std::max(Members, FldMembers) : Members + FldMembers); |
5158 | } |
5159 | |
5160 | if (!Base) |
5161 | return false; |
5162 | |
5163 | // Ensure there is no padding. |
5164 | if (getContext().getTypeSize(Base) * Members != |
5165 | getContext().getTypeSize(Ty)) |
5166 | return false; |
5167 | } else { |
5168 | Members = 1; |
5169 | if (const ComplexType *CT = Ty->getAs<ComplexType>()) { |
5170 | Members = 2; |
5171 | Ty = CT->getElementType(); |
5172 | } |
5173 | |
5174 | // Most ABIs only support float, double, and some vector type widths. |
5175 | if (!isHomogeneousAggregateBaseType(Ty)) |
5176 | return false; |
5177 | |
5178 | // The base type must be the same for all members. Types that |
5179 | // agree in both total size and mode (float vs. vector) are |
5180 | // treated as being equivalent here. |
5181 | const Type *TyPtr = Ty.getTypePtr(); |
5182 | if (!Base) { |
5183 | Base = TyPtr; |
5184 | // If it's a non-power-of-2 vector, its size is already a power-of-2, |
5185 | // so make sure to widen it explicitly. |
5186 | if (const VectorType *VT = Base->getAs<VectorType>()) { |
5187 | QualType EltTy = VT->getElementType(); |
5188 | unsigned NumElements = |
5189 | getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); |
5190 | Base = getContext() |
5191 | .getVectorType(EltTy, NumElements, VT->getVectorKind()) |
5192 | .getTypePtr(); |
5193 | } |
5194 | } |
5195 | |
5196 | if (Base->isVectorType() != TyPtr->isVectorType() || |
5197 | getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) |
5198 | return false; |
5199 | } |
5200 | return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); |
5201 | } |
5202 | |
5203 | bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { |
5204 | // Homogeneous aggregates for ELFv2 must have base types of float, |
5205 | // double, long double, or 128-bit vectors. |
5206 | if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { |
5207 | if (BT->getKind() == BuiltinType::Float || |
5208 | BT->getKind() == BuiltinType::Double || |
5209 | BT->getKind() == BuiltinType::LongDouble || |
5210 | (getContext().getTargetInfo().hasFloat128Type() && |
5211 | (BT->getKind() == BuiltinType::Float128))) { |
5212 | if (IsSoftFloatABI) |
5213 | return false; |
5214 | return true; |
5215 | } |
5216 | } |
5217 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
5218 | if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) |
5219 | return true; |
5220 | } |
5221 | return false; |
5222 | } |
5223 | |
5224 | bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( |
5225 | const Type *Base, uint64_t Members) const { |
5226 | // Vector and fp128 types require one register, other floating point types |
5227 | // require one or two registers depending on their size. |
5228 | uint32_t NumRegs = |
5229 | ((getContext().getTargetInfo().hasFloat128Type() && |
5230 | Base->isFloat128Type()) || |
5231 | Base->isVectorType()) ? 1 |
5232 | : (getContext().getTypeSize(Base) + 63) / 64; |
5233 | |
5234 | // Homogeneous Aggregates may occupy at most 8 registers. |
5235 | return Members * NumRegs <= 8; |
5236 | } |
5237 | |
5238 | ABIArgInfo |
5239 | PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { |
5240 | Ty = useFirstFieldIfTransparentUnion(Ty); |
5241 | |
5242 | if (Ty->isAnyComplexType()) |
5243 | return ABIArgInfo::getDirect(); |
5244 | |
5245 | // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) |
5246 | // or via reference (larger than 16 bytes). |
5247 | if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { |
5248 | uint64_t Size = getContext().getTypeSize(Ty); |
5249 | if (Size > 128) |
5250 | return getNaturalAlignIndirect(Ty, /*ByVal=*/false); |
5251 | else if (Size < 128) { |
5252 | llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); |
5253 | return ABIArgInfo::getDirect(CoerceTy); |
5254 | } |
5255 | } |
5256 | |
5257 | if (const auto *EIT = Ty->getAs<ExtIntType>()) |
5258 | if (EIT->getNumBits() > 128) |
5259 | return getNaturalAlignIndirect(Ty, /*ByVal=*/true); |
5260 | |
5261 | if (isAggregateTypeForABI(Ty)) { |
5262 | if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) |
5263 | return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); |
5264 | |
5265 | uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); |
5266 | uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); |
5267 | |
5268 | // ELFv2 homogeneous aggregates are passed as array types. |
5269 | const Type *Base = nullptr; |
5270 | uint64_t Members = 0; |
5271 | if (Kind == ELFv2 && |
5272 | isHomogeneousAggregate(Ty, Base, Members)) { |
5273 | llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); |
5274 | llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); |
5275 | return ABIArgInfo::getDirect(CoerceTy); |
5276 | } |
5277 | |
5278 | // If an aggregate may end up fully in registers, we do not |
5279 | // use the ByVal method, but pass the aggregate as array. |
5280 | // This is usually beneficial since we avoid forcing the |
5281 | // back-end to store the argument to memory. |
5282 | uint64_t Bits = getContext().getTypeSize(Ty); |
5283 | if (Bits > 0 && Bits <= 8 * GPRBits) { |
5284 | llvm::Type *CoerceTy; |
5285 | |
5286 | // Types up to 8 bytes are passed as integer type (which will be |
5287 | // properly aligned in the argument save area doubleword). |
5288 | if (Bits <= GPRBits) |
5289 | CoerceTy = |
5290 | llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); |
5291 | // Larger types are passed as arrays, with the base type selected |
5292 | // according to the required alignment in the save area. |
5293 | else { |
5294 | uint64_t RegBits = ABIAlign * 8; |
5295 | uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; |
5296 | llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); |
5297 | CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); |
5298 | } |
5299 | |
5300 | return ABIArgInfo::getDirect(CoerceTy); |
5301 | } |
5302 | |
5303 | // All other aggregates are passed ByVal. |
5304 | return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), |
5305 | /*ByVal=*/true, |
5306 | /*Realign=*/TyAlign > ABIAlign); |
5307 | } |
5308 | |
5309 | return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) |
5310 | : ABIArgInfo::getDirect()); |
5311 | } |
5312 | |
5313 | ABIArgInfo |
5314 | PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { |
5315 | if (RetTy->isVoidType()) |
5316 | return ABIArgInfo::getIgnore(); |
5317 | |
5318 | if (RetTy->isAnyComplexType()) |
5319 | return ABIArgInfo::getDirect(); |
5320 | |
5321 | // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) |
5322 | // or via reference (larger than 16 bytes). |
5323 | if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { |
5324 | uint64_t Size = getContext().getTypeSize(RetTy); |
5325 | if (Size > 128) |
5326 | return getNaturalAlignIndirect(RetTy); |
5327 | else if (Size < 128) { |
5328 | llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); |
5329 | return ABIArgInfo::getDirect(CoerceTy); |
5330 | } |
5331 | } |
5332 | |
5333 | if (const auto *EIT = RetTy->getAs<ExtIntType>()) |
5334 | if (EIT->getNumBits() > 128) |
5335 | return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); |
5336 | |
5337 | if (isAggregateTypeForABI(RetTy)) { |
5338 | // ELFv2 homogeneous aggregates are returned as array types. |
5339 | const Type *Base = nullptr; |
5340 | uint64_t Members = 0; |
5341 | if (Kind == ELFv2 && |
5342 | isHomogeneousAggregate(RetTy, Base, Members)) { |
5343 | llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); |
5344 | llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); |
5345 | return ABIArgInfo::getDirect(CoerceTy); |
5346 | } |
5347 | |
5348 | // ELFv2 small aggregates are returned in up to two registers. |
5349 | uint64_t Bits = getContext().getTypeSize(RetTy); |
5350 | if (Kind == ELFv2 && Bits <= 2 * GPRBits) { |
5351 | if (Bits == 0) |
5352 | return ABIArgInfo::getIgnore(); |
5353 | |
5354 | llvm::Type *CoerceTy; |
5355 | if (Bits > GPRBits) { |
5356 | CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); |
5357 | CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); |
5358 | } else |
5359 | CoerceTy = |
5360 | llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); |
5361 | return ABIArgInfo::getDirect(CoerceTy); |
5362 | } |
5363 | |
5364 | // All other aggregates are returned indirectly. |
5365 | return getNaturalAlignIndirect(RetTy); |
5366 | } |
5367 | |
5368 | return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) |
5369 | : ABIArgInfo::getDirect()); |
5370 | } |
5371 | |
5372 | // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. |
5373 | Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
5374 | QualType Ty) const { |
5375 | auto TypeInfo = getContext().getTypeInfoInChars(Ty); |
5376 | TypeInfo.Align = getParamTypeAlignment(Ty); |
5377 | |
5378 | CharUnits SlotSize = CharUnits::fromQuantity(8); |
5379 | |
5380 | // If we have a complex type and the base type is smaller than 8 bytes, |
5381 | // the ABI calls for the real and imaginary parts to be right-adjusted |
5382 | // in separate doublewords. However, Clang expects us to produce a |
5383 | // pointer to a structure with the two parts packed tightly. So generate |
5384 | // loads of the real and imaginary parts relative to the va_list pointer, |
5385 | // and store them to a temporary structure. |
5386 | if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { |
5387 | CharUnits EltSize = TypeInfo.Width / 2; |
5388 | if (EltSize < SlotSize) { |
5389 | Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, |
5390 | SlotSize * 2, SlotSize, |
5391 | SlotSize, /*AllowHigher*/ true); |
5392 | |
5393 | Address RealAddr = Addr; |
5394 | Address ImagAddr = RealAddr; |
5395 | if (CGF.CGM.getDataLayout().isBigEndian()) { |
5396 | RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, |
5397 | SlotSize - EltSize); |
5398 | ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, |
5399 | 2 * SlotSize - EltSize); |
5400 | } else { |
5401 | ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); |
5402 | } |
5403 | |
5404 | llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); |
5405 | RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); |
5406 | ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); |
5407 | llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); |
5408 | llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); |
5409 | |
5410 | Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); |
5411 | CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), |
5412 | /*init*/ true); |
5413 | return Temp; |
5414 | } |
5415 | } |
5416 | |
5417 | // Otherwise, just use the general rule. |
5418 | return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, |
5419 | TypeInfo, SlotSize, /*AllowHigher*/ true); |
5420 | } |
5421 | |
5422 | bool |
5423 | PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( |
5424 | CodeGen::CodeGenFunction &CGF, |
5425 | llvm::Value *Address) const { |
5426 | return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, |
5427 | /*IsAIX*/ false); |
5428 | } |
5429 | |
5430 | bool |
5431 | PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, |
5432 | llvm::Value *Address) const { |
5433 | return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, |
5434 | /*IsAIX*/ false); |
5435 | } |
5436 | |
5437 | //===----------------------------------------------------------------------===// |
5438 | // AArch64 ABI Implementation |
5439 | //===----------------------------------------------------------------------===// |
5440 | |
5441 | namespace { |
5442 | |
5443 | class AArch64ABIInfo : public SwiftABIInfo { |
5444 | public: |
5445 | enum ABIKind { |
5446 | AAPCS = 0, |
5447 | DarwinPCS, |
5448 | Win64 |
5449 | }; |
5450 | |
5451 | private: |
5452 | ABIKind Kind; |
5453 | |
5454 | public: |
5455 | AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) |
5456 | : SwiftABIInfo(CGT), Kind(Kind) {} |
5457 | |
5458 | private: |
5459 | ABIKind getABIKind() const { return Kind; } |
5460 | bool isDarwinPCS() const { return Kind == DarwinPCS; } |
5461 | |
5462 | ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; |
5463 | ABIArgInfo classifyArgumentType(QualType RetTy) const; |
5464 | ABIArgInfo coerceIllegalVector(QualType Ty) const; |
5465 | bool isHomogeneousAggregateBaseType(QualType Ty) const override; |
5466 | bool isHomogeneousAggregateSmallEnough(const Type *Ty, |
5467 | uint64_t Members) const override; |
5468 | |
5469 | bool isIllegalVectorType(QualType Ty) const; |
5470 | |
5471 | void computeInfo(CGFunctionInfo &FI) const override { |
5472 | if (!::classifyReturnType(getCXXABI(), FI, *this)) |
5473 | FI.getReturnInfo() = |
5474 | classifyReturnType(FI.getReturnType(), FI.isVariadic()); |
5475 | |
5476 | for (auto &it : FI.arguments()) |
5477 | it.info = classifyArgumentType(it.type); |
5478 | } |
5479 | |
5480 | Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, |
5481 | CodeGenFunction &CGF) const; |
5482 | |
5483 | Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, |
5484 | CodeGenFunction &CGF) const; |
5485 | |
5486 | Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, |
5487 | QualType Ty) const override { |
5488 | llvm::Type *BaseTy = CGF.ConvertType(Ty); |
5489 | if (isa<llvm::ScalableVectorType>(BaseTy)) |
5490 | llvm::report_fatal_error("Passing SVE types to variadic functions is " |
5491 | "currently not supported"); |
5492 | |
5493 | return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) |
5494 | : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) |
5495 | : EmitAAPCSVAArg(VAListAddr, Ty, CGF); |
5496 | } |
5497 | |
5498 | Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, |
5499 | QualType Ty) const override; |
5500 | |
5501 | bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, |
5502 | bool asReturnValue) const override { |
5503 | return occupiesMoreThan(CGT, scalars, /*total*/ 4); |
5504 | } |
5505 | bool isSwiftErrorInRegister() const override { |
5506 | return true; |
5507 | } |
5508 | |
5509 | bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, |
5510 | unsigned elts) const override; |
5511 | |
5512 | bool allowBFloatArgsAndRet() const override { |
5513 | return getTarget().hasBFloat16Type(); |
5514 | } |
5515 | }; |
5516 | |
5517 | class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { |
5518 | public: |
5519 | AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) |
5520 | : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} |
5521 | |
5522 | StringRef getARCRetainAutoreleasedReturnValueMarker() const override { |
5523 | return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; |
5524 | } |
5525 | |
5526 | int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { |
5527 | return 31; |
5528 | } |
5529 | |
5530 | bool doesReturnSlotInterfereWithArgs() const override { return false; } |
5531 | |
5532 | void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
5533 | CodeGen::CodeGenModule &CGM) const override { |
5534 | const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); |
5535 | if (!FD) |
5536 | return; |
5537 | |
5538 | const auto *TA = FD->getAttr<TargetAttr>(); |
5539 | if (TA == nullptr) |
5540 | return; |
5541 | |
5542 | ParsedTargetAttr Attr = TA->parse(); |
5543 | if (Attr.BranchProtection.empty()) |
5544 | return; |
5545 | |
5546 | TargetInfo::BranchProtectionInfo BPI; |
5547 | StringRef Error; |
5548 | (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, |
5549 | BPI, Error); |
5550 | assert(Error.empty())((Error.empty()) ? static_cast<void> (0) : __assert_fail ("Error.empty()", "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5550, __PRETTY_FUNCTION__)); |
5551 | |
5552 | auto *Fn = cast<llvm::Function>(GV); |
5553 | static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; |
5554 | Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); |
5555 | |
5556 | if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { |
5557 | Fn->addFnAttr("sign-return-address-key", |
5558 | BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey |
5559 | ? "a_key" |
5560 | : "b_key"); |
5561 | } |
5562 | |
5563 | Fn->addFnAttr("branch-target-enforcement", |
5564 | BPI.BranchTargetEnforcement ? "true" : "false"); |
5565 | } |
5566 | }; |
5567 | |
5568 | class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { |
5569 | public: |
5570 | WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) |
5571 | : AArch64TargetCodeGenInfo(CGT, K) {} |
5572 | |
5573 | void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, |
5574 | CodeGen::CodeGenModule &CGM) const override; |
5575 | |
5576 | void getDependentLibraryOption(llvm::StringRef Lib, |
5577 | llvm::SmallString<24> &Opt) const override { |
5578 | Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); |
5579 | } |
5580 | |
5581 | void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, |
5582 | llvm::SmallString<32> &Opt) const override { |
5583 | Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; |
5584 | } |
5585 | }; |
5586 | |
5587 | void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( |
5588 | const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { |
5589 | AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); |
5590 | if (GV->isDeclaration()) |
5591 | return; |
5592 | addStackProbeTargetAttributes(D, GV, CGM); |
5593 | } |
5594 | } |
5595 | |
5596 | ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { |
5597 | assert(Ty->isVectorType() && "expected vector type!")((Ty->isVectorType() && "expected vector type!") ? static_cast<void> (0) : __assert_fail ("Ty->isVectorType() && \"expected vector type!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5597, __PRETTY_FUNCTION__)); |
5598 | |
5599 | const auto *VT = Ty->castAs<VectorType>(); |
5600 | if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { |
5601 | assert(VT->getElementType()->isBuiltinType() && "expected builtin type!")((VT->getElementType()->isBuiltinType() && "expected builtin type!" ) ? static_cast<void> (0) : __assert_fail ("VT->getElementType()->isBuiltinType() && \"expected builtin type!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5601, __PRETTY_FUNCTION__)); |
5602 | assert(VT->getElementType()->castAs<BuiltinType>()->getKind() ==((VT->getElementType()->castAs<BuiltinType>()-> getKind() == BuiltinType::UChar && "unexpected builtin type for SVE predicate!" ) ? static_cast<void> (0) : __assert_fail ("VT->getElementType()->castAs<BuiltinType>()->getKind() == BuiltinType::UChar && \"unexpected builtin type for SVE predicate!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5604, __PRETTY_FUNCTION__)) |
5603 | BuiltinType::UChar &&((VT->getElementType()->castAs<BuiltinType>()-> getKind() == BuiltinType::UChar && "unexpected builtin type for SVE predicate!" ) ? static_cast<void> (0) : __assert_fail ("VT->getElementType()->castAs<BuiltinType>()->getKind() == BuiltinType::UChar && \"unexpected builtin type for SVE predicate!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5604, __PRETTY_FUNCTION__)) |
5604 | "unexpected builtin type for SVE predicate!")((VT->getElementType()->castAs<BuiltinType>()-> getKind() == BuiltinType::UChar && "unexpected builtin type for SVE predicate!" ) ? static_cast<void> (0) : __assert_fail ("VT->getElementType()->castAs<BuiltinType>()->getKind() == BuiltinType::UChar && \"unexpected builtin type for SVE predicate!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5604, __PRETTY_FUNCTION__)); |
5605 | return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( |
5606 | llvm::Type::getInt1Ty(getVMContext()), 16)); |
5607 | } |
5608 | |
5609 | if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { |
5610 | assert(VT->getElementType()->isBuiltinType() && "expected builtin type!")((VT->getElementType()->isBuiltinType() && "expected builtin type!" ) ? static_cast<void> (0) : __assert_fail ("VT->getElementType()->isBuiltinType() && \"expected builtin type!\"" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5610, __PRETTY_FUNCTION__)); |
5611 | |
5612 | const auto *BT = VT->getElementType()->castAs<BuiltinType>(); |
5613 | llvm::ScalableVectorType *ResType = nullptr; |
5614 | switch (BT->getKind()) { |
5615 | default: |
5616 | llvm_unreachable("unexpected builtin type for SVE vector!")::llvm::llvm_unreachable_internal("unexpected builtin type for SVE vector!" , "/build/llvm-toolchain-snapshot-12~++20201124111112+7b5254223ac/clang/lib/CodeGen/TargetInfo.cpp" , 5616); |
5617 | case BuiltinType::SChar: |
5618 | case BuiltinType::UChar: |
5619 | ResType = llvm::ScalableVectorType::get( |
5620 | llvm::Type::getInt8Ty(getVMContext()), 16); |
5621 | break; |
5622 | case BuiltinType::Short: |
5623 | case BuiltinType::UShort: |
5624 | ResType = llvm::ScalableVectorType::get( |
5625 | llvm::Type::getInt16Ty(getVMContext()), 8); |
5626 | break; |
5627 | case BuiltinType::Int: |
5628 | case BuiltinType::UInt: |
5629 | ResType = llvm::ScalableVectorType::get( |
5630 | llvm::Type::getInt32Ty(getVMContext()), 4); |
5631 | break; |
5632 | case BuiltinType::Long: |
5633 | case BuiltinType::ULong: |
5634 | ResType = llvm::ScalableVectorType::get( |
5635 | llvm::Type::getInt64Ty(getVMContext()), 2); |
5636 | break; |
5637 | case BuiltinType::Half: |
5638 | ResType = llvm::ScalableVectorType::get( |
5639 | llvm::Type::getHalfTy(getVMContext()), 8); |
5640 | break; |
5641 | case BuiltinType::Float: |
5642 | ResType = llvm::ScalableVectorType::get( |
5643 | llvm::Type::getFloatTy(getVMContext()), 4); |
5644 | break; |
5645 | case BuiltinType::Double: |
5646 | ResType = llvm::ScalableVectorType::get( |
5647 | llvm::Type::getDoubleTy(getVMContext()), 2); |
5648 | break; |
5649 | case BuiltinType::BFloat16: |
5650 | ResType = llvm::ScalableVectorType::get( |
5651 | llvm::Type::getBFloatTy(getVMContext()), 8); |
5652 | break; |
5653 | } |
5654 | return ABIArgInfo::getDirect(ResType); |
5655 | } |
5656 | |
5657 | uint64_t Size = getContext().getTypeSize(Ty); |
5658 | // Android promotes <2 x i8> to i16, not i32 |
5659 | if (isAndroid() && (Size <= 16)) { |
5660 | llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); |
5661 | return ABIArgInfo::getDirect(ResType); |
5662 | } |
5663 | if (Size <= 32) { |
5664 | llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); |
5665 | return ABIArgInfo::getDirect(ResType); |
5666 | } |
5667 | if (Size == 64) { |
5668 | auto *ResType = |
5669 | llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); |
5670 | return ABIArgInfo::getDirect(ResType); |
5671 | } |
5672 | if (Size == 128) { |
5673 | auto *ResType = |
5674 | llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); |
5675 | return ABIArgInfo::getDirect(ResType); |
5676 | } |
5677 | return getNaturalAlignIndirect(Ty, /*ByVal=*/false); |
5678 | } |
5679 | |
5680 | ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { |
5681 | Ty = useFirstFieldIfTransparentUnion(Ty); |
5682 | |
5683 | // Handle illegal vector types here. |
5684 | if (isIllegalVectorType(Ty)) |
5685 | return coerceIllegalVector(Ty); |
5686 | |
5687 | if (!isAggregateTypeForABI(Ty)) { |
5688 | // Treat an enum type as its underlying type. |
5689 | if (const EnumType *EnumTy = Ty->getAs<EnumType>()) |
5690 | Ty = EnumTy->getDecl()->getIntegerType(); |
5691 | |
5692 | if (const auto *EIT = Ty->getAs<ExtIntType>()) |
5693 | if (EIT->getNumBits() > 128) |
5694 | return getNaturalAlignIndirect(Ty); |
5695 | |
5696 | return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() |
5697 | ? ABIArgInfo::getExtend(Ty) |
5698 | : ABIArgInfo::getDirect()); |
5699 | } |
5700 | |
5701 | // Structures with either a non-trivial destructor or a non-trivial |
5702 | // copy constructor are always indirect. |
5703 | if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { |
5704 | return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == |
5705 | CGCXXABI::RAA_DirectInMemory); |
5706 | } |
5707 | |
5708 | // Empty records are always ignored on Darwin, but actually passed in C++ mode |
5709 | // elsewhere for GNU compatibility. |
5710 | uint64_t Size = getContext().getTypeSize(Ty); |
5711 | bool IsEmpty = isEmptyRecord(getContext(), Ty, true); |
5712 | if (IsEmpty || Size == 0) { |
5713 | if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) |
5714 | return ABIArgInfo::getIgnore(); |
5715 | |
5716 | // GNU C mode. The only argument that gets ignored is an empty one with size |
5717 | // 0. |
5718 | if (IsEmpty && Size == 0) |
5719 | return ABIArgInfo::getIgnore(); |
5720 | return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); |
5721 | } |
5722 | |
5723 | // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. |
5724 | const Type *Base = nullptr; |
5725 | uint64_t Members = 0; |
5726 | if (isHomogeneousAggregate(Ty, Base, Members)) { |
5727 | return ABIArgInfo::getDirect( |
5728 | llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); |
5729 | } |
5730 | |
5731 | // Aggregates <= 16 bytes are passed directly in registers or on the stack. |
5732 | if (Size <= 128) { |
5733 | // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of |
5734 | // same size and alignment. |
5735 | if (getTarget().isRenderScriptTarget()) { |
5736 | return coerceToIntArray(Ty, getContext(), getVMContext()); |
5737 | } |
5738 | unsigned Alignment; |
5739 | if (Kind == AArch64ABIInfo::AAPCS) { |
5740 | Alignment = getContext().getTypeUnadjustedAlign(Ty); |
5741 | Alignment = Alignment < 128 ? 64 : 128; |
5742 | } else { |
5743 | Alignment = std::max(getContext().getTypeAlign(Ty), |
5744 | (unsigned)getTarget().getPointerWidth(0)); |
5745 | } |
5746 | Size = llvm::alignTo(Size, Alignment); |
5747 | |
5748 | // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. |
5749 | // For aggregates with 16-byte alignment, we use i128. |
5750 | llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); |
5751 | return ABIArgInfo::getDirect( |
5752 | Size == Alignment ? BaseTy |
5753 | : llvm::ArrayType::get(BaseTy, Size / Alignment)); |
5754 | } |
5755 | |
5756 | return getNaturalAlignIndirect(Ty, /*ByVal=*/false); |
5757 | } |
5758 | |
5759 | ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, |
5760 | bool IsVariadic) const { |
5761 | if (RetTy->isVoidType()) |
5762 | return ABIArgInfo::getIgnore(); |
5763 | |
5764 | if (const auto *VT = RetTy->getAs<VectorType>()) { |
5765 | if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || |
5766 | VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) |
5767 | return coerceIllegalVector(RetTy); |
5768 | } |
5769 | |
5770 | // Large vector types should be returned via memory. |
5771 | if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) |
5772 | return getNaturalAlignIndirect(RetTy); |
5773 | |
5774 | if (!isAggregateTypeForABI(RetTy)) { |
5775 | // Treat an enum type as its underlying type. |
5776 | if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) |
5777 | RetTy = EnumTy->getDecl()->getIntegerType(); |
5778 | |
5779 | if (const auto *EIT = RetTy->getAs<ExtIntType>()) |
5780 | if (EIT->getNumBits() > 128) |
5781 | return getNaturalAlignIndirect(RetTy); |
5782 | |
5783 | return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() |
5784 | ? ABIArgInfo::getExtend(RetTy) |
5785 | : ABIArgInfo::getDirect()); |
5786 | } |
5787 | |
5788 | uint64_t Size = getContext().getTypeSize(RetTy); |
5789 | if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) |
5790 | return ABIArgInfo::getIgnore(); |
5791 | |
5792 | const Type *Base = nullptr; |
5793 | uint64_t Members = 0; |
5794 | if (isHomogeneousAggregate(RetTy, Base, Members) && |
5795 | !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && |
5796 | IsVariadic)) |
5797 | // Homogeneous Floating-point Aggregates (HFAs) are returned directly. |
5798 | return ABIArgInfo::getDirect(); |
5799 | |
5800 | // Aggregates <= 16 bytes are returned directly in registers or on the stack. |
5801 | if (Size <= 128) { |
5802 | // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of |
5803 | // same size and alignment. |
5804 | if (getTarget().isRenderScriptTarget()) { |
5805 | return coerceToIntArray(RetTy, getContext(), getVMContext()); |
5806 | } |
5807 | unsigned Alignment = getContext().getTypeAlign(RetTy); |
5808 | Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes |
5809 | |
5810 | // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. |
5811 | // For aggregates with 16-byte alignment, we use i128. |
5812 | if (Alignment < 128 && Size == 128) { |
5813 | llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); |
5814 | return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); |
5815 | } |
5816 | return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); |
5817 | } |
5818 | |
5819 | return getNaturalAlignIndirect(RetTy); |
5820 | } |
5821 | |
5822 | /// isIllegalVectorType - check whether the vector type is legal for AArch64. |
5823 | bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { |
5824 | if (const VectorType *VT = Ty->getAs<VectorType>()) { |
5825 | // Check whether VT is a fixed-length SVE vector. These types are |
5826 | // represented as scalable vectors in function args/return and must be |
5827 | // coerced from fixed vectors. |
5828 | if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || |
5829 | VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) |
5830 | return true; |
5831 | |
5832 | // Check whether VT is legal. |
5833 | unsigned NumElements = VT->getNumElements(); |
5834 | uint64_t Size = getContext().getTypeSize(VT); |
5835 | // NumElements should be power of 2. |
5836 | if (!llvm::isPowerOf2_32(NumElements)) |
5837 | return true; |
5838 | |
5839 | // arm64_32 has to be compatible with the ARM logic here, which allows huge |
5840 | // vectors for some reason. |
5841 | llvm::Triple Triple = getTarget().getTriple(); |
5842 | if (Triple.getArch() == llvm::Triple::aarch64_32 && |
5843 | Triple.isOSBinFormatMachO()) |
5844 | return Size <= 32; |
5845 | |
5846 | return Size != 64 && (Size != 128 || NumElements == 1); |
5847 | } |
5848 | return false; |
5849 | } |
5850 | |
5851 | bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, |
5852 | llvm::Type *eltTy, |
5853 | unsigned elts) const { |
5854 | if (!llvm::isPowerOf2_32(elts)) |
5855 | return false; |
5856 | if (totalSize.getQuantity() != 8 && |
5857 | (totalSize.getQuantity() != 16 || elts == 1)) |
5858 | return false; |
5859 | return true; |
5860 | } |
5861 | |
5862 | bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { |
5863 | // Homogeneous aggregates for AAPCS64 must have base types of a floating |
5864 | // point type or a short-vector type. This is the same as the 32-bit ABI, |
5865 | // but with the difference that any floating-point type is allowed, |
5866 | // including __fp16. |
5867 | if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { |
5868 | if (BT->isFloatingPoint()) |
5869 | return true; |
5870 | } else if (const VectorType *VT = Ty->getAs<VectorType>()) { |
5871 | unsigned VecSize = getContext().getTypeSize(VT); |
5872 | if (VecSize == 64 || VecSize == 128) |
5873 | return true; |
5874 | } |
5875 | return false; |
5876 | } |
5877 | |
5878 | bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, |
5879 | uint64_t Members) const { |
5880 | return Members <= 4; |
5881 | } |
5882 | |
5883 | Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, |
5884 | QualType Ty, |
5885 | CodeGenFunction &CGF) const { |
5886 | ABIArgInfo AI = classifyArgumentType(Ty); |
5887 | bool IsIndirect = AI.isIndirect(); |
5888 | |
5889 | llvm::Type *BaseTy = CGF.ConvertType(Ty); |
5890 | if (IsIndirect) |
5891 | BaseTy = llvm::PointerType::getUnqual(BaseTy); |
5892 | else if (AI.getCoerceToType()) |
5893 | BaseTy = AI.getCoerceToType(); |
5894 | |
5895 | unsigned NumRegs = 1; |
5896 | if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { |
5897 | BaseTy = ArrTy->getElementType(); |
5898 | NumRegs = ArrTy->getNumElements(); |
5899 | } |
5900 | bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); |
5901 | |
5902 | // The AArch64 va_list type and handling is specified in the Procedure Call |
5903 | // Standard, section B.4: |
5904 | // |
5905 | // struct { |
5906 | // void *__stack; |
5907 | // void *__gr_top; |
5908 | // void *__vr_top; |
5909 | // int __gr_offs; |
5910 | // int __vr_offs; |
5911 | // }; |
5912 | |
5913 | llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); |
5914 | llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); |
5915 | llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); |
5916 | llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); |
5917 | |
5918 | CharUnits TySize = getContext().getTypeSizeInChars(Ty); |
5919 | CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); |
5920 | |
5921 | Address reg_offs_p = Address::invalid(); |
5922 | llvm::Value *reg_offs = nullptr; |
5923 | int reg_top_index; |
5924 | int RegSize = IsIndirect ? 8 : TySize.getQuantity(); |
5925 | if (!IsFPR) { |
5926 | // 3 is the field number of __gr_offs |
5927 | reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); |
5928 | reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); |
5929 | reg_top_index = 1; // field number for __gr_top |
5930 | RegSize = llvm::alignTo(RegSize, 8); |
5931 | } else { |
5932 | // 4 is the field number of __vr_offs. |
5933 | reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); |
5934 | reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); |
5935 | reg_top_index = 2; // field number for __vr_top |
5936 | RegSize = 16 * NumRegs; |
5937 | } |
5938 | |
5939 | //======================================= |
5940 | // Find out where argument was passed |
5941 | //======================================= |
5942 | |
5943 | // If reg_offs >= 0 we're already using the stack for this type of |
5944 | // argument. We don't want to keep updating reg_offs (in case it overflows, |
5945 | // though anyone passing 2GB of arguments, each at most 16 bytes, deserves |
5946 | // whatever they get). |
5947 | llvm::Value *UsingStack = nullptr; |
5948 | UsingStack = CGF.Builder.CreateICmpSGE( |
5949 | reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); |
5950 | |
5951 | CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); |
5952 | |
5953 | // Otherwise, at least some kind of argument could go in these registers, the |
5954 | // question is whether this particular type is too big. |
5955 | CGF.EmitBlock(MaybeRegBlock); |
5956 | |
5957 | // Integer arguments may need to correct register alignment (for example a |
5958 | // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we |
5959 | // align __gr_offs to calculate the potential address. |
5960 | if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { |
5961 | int Align = TyAlign.getQuantity(); |
5962 | |
5963 | reg_offs = CGF.Builder.CreateAdd( |
5964 | reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), |
5965 | "align_regoffs"); |
5966 | reg_offs = CGF.Builder.CreateAnd( |
5967 | reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), |
5968 | "aligned_regoffs"); |
5969 | } |
5970 | |
5971 | // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. |
5972 | // The fact that this is done unconditionally reflects the fact that |
5973 | // allocating an argument to the stack also uses up all the remaining |
5974 | // registers of the appropriate kind. |
5975 | llvm::Value *NewOffset = nullptr; |
5976 | NewOffset = CGF.Builder.CreateAdd( |
5977 | reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); |
5978 | CGF.Builder.CreateStore(NewOffset, reg_offs_p); |
5979 | |
5980 | // Now we're in a position to decide whether this argument really was in |
5981 | // registers or not. |
5982 | llvm::Value *InRegs = nullptr; |
5983 | InRegs = CGF.Builder.CreateICmpSLE( |
5984 | NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); |
5985 | |
5986 | CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); |
5987 | |
5988 | //======================================= |
5989 | // Argument was in registers |
5990 | //======================================= |
5991 | |
5992 | // Now we emit the code for if the argument was originally passed in |
5993 | // registers. First start the appropriate block: |
5994 | CGF.EmitBlock(InRegBlock); |
5995 | |
5996 | llvm::Value *reg_top = nullptr; |
5997 | Address reg_top_p = |
5998 | CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); |
5999 | reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); |
6000 | Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), |
6001 | CharUnits::fromQuantity(IsFPR ? 16 : 8)); |
6002 | Address RegAddr = Address::invalid(); |
6003 | llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); |
6004 | |
6005 | if (IsIndirect) { |
6006 | // If it's b |