1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
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 "CGCall.h"
15 #include "ABIInfo.h"
16 #include "CGBlocks.h"
17 #include "CGCXXABI.h"
18 #include "CGCleanup.h"
19 #include "CGRecordLayout.h"
20 #include "CodeGenFunction.h"
21 #include "CodeGenModule.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/Basic/CodeGenOptions.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/CodeGen/CGFunctionInfo.h"
31 #include "clang/CodeGen/SwiftCallingConv.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/Assumptions.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/InlineAsm.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Type.h"
42 #include "llvm/Transforms/Utils/Local.h"
43 using namespace clang;
44 using namespace CodeGen;
45
46 /***/
47
ClangCallConvToLLVMCallConv(CallingConv CC)48 unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
49 switch (CC) {
50 default: return llvm::CallingConv::C;
51 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
52 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
53 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
54 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
55 case CC_Win64: return llvm::CallingConv::Win64;
56 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
57 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
58 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
59 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
60 // TODO: Add support for __pascal to LLVM.
61 case CC_X86Pascal: return llvm::CallingConv::C;
62 // TODO: Add support for __vectorcall to LLVM.
63 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
64 case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
65 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
66 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
67 case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
68 case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
69 case CC_Swift: return llvm::CallingConv::Swift;
70 case CC_SwiftAsync: return llvm::CallingConv::SwiftTail;
71 }
72 }
73
74 /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
75 /// qualification. Either or both of RD and MD may be null. A null RD indicates
76 /// that there is no meaningful 'this' type, and a null MD can occur when
77 /// calling a method pointer.
DeriveThisType(const CXXRecordDecl * RD,const CXXMethodDecl * MD)78 CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
79 const CXXMethodDecl *MD) {
80 QualType RecTy;
81 if (RD)
82 RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
83 else
84 RecTy = Context.VoidTy;
85
86 if (MD)
87 RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
88 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
89 }
90
91 /// Returns the canonical formal type of the given C++ method.
GetFormalType(const CXXMethodDecl * MD)92 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
93 return MD->getType()->getCanonicalTypeUnqualified()
94 .getAs<FunctionProtoType>();
95 }
96
97 /// Returns the "extra-canonicalized" return type, which discards
98 /// qualifiers on the return type. Codegen doesn't care about them,
99 /// and it makes ABI code a little easier to be able to assume that
100 /// all parameter and return types are top-level unqualified.
GetReturnType(QualType RetTy)101 static CanQualType GetReturnType(QualType RetTy) {
102 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
103 }
104
105 /// Arrange the argument and result information for a value of the given
106 /// unprototyped freestanding function type.
107 const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP)108 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
109 // When translating an unprototyped function type, always use a
110 // variadic type.
111 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
112 /*instanceMethod=*/false,
113 /*chainCall=*/false, None,
114 FTNP->getExtInfo(), {}, RequiredArgs(0));
115 }
116
addExtParameterInfosForCall(llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)117 static void addExtParameterInfosForCall(
118 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos,
119 const FunctionProtoType *proto,
120 unsigned prefixArgs,
121 unsigned totalArgs) {
122 assert(proto->hasExtParameterInfos());
123 assert(paramInfos.size() <= prefixArgs);
124 assert(proto->getNumParams() + prefixArgs <= totalArgs);
125
126 paramInfos.reserve(totalArgs);
127
128 // Add default infos for any prefix args that don't already have infos.
129 paramInfos.resize(prefixArgs);
130
131 // Add infos for the prototype.
132 for (const auto &ParamInfo : proto->getExtParameterInfos()) {
133 paramInfos.push_back(ParamInfo);
134 // pass_object_size params have no parameter info.
135 if (ParamInfo.hasPassObjectSize())
136 paramInfos.emplace_back();
137 }
138
139 assert(paramInfos.size() <= totalArgs &&
140 "Did we forget to insert pass_object_size args?");
141 // Add default infos for the variadic and/or suffix arguments.
142 paramInfos.resize(totalArgs);
143 }
144
145 /// Adds the formal parameters in FPT to the given prefix. If any parameter in
146 /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
appendParameterTypes(const CodeGenTypes & CGT,SmallVectorImpl<CanQualType> & prefix,SmallVectorImpl<FunctionProtoType::ExtParameterInfo> & paramInfos,CanQual<FunctionProtoType> FPT)147 static void appendParameterTypes(const CodeGenTypes &CGT,
148 SmallVectorImpl<CanQualType> &prefix,
149 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos,
150 CanQual<FunctionProtoType> FPT) {
151 // Fast path: don't touch param info if we don't need to.
152 if (!FPT->hasExtParameterInfos()) {
153 assert(paramInfos.empty() &&
154 "We have paramInfos, but the prototype doesn't?");
155 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
156 return;
157 }
158
159 unsigned PrefixSize = prefix.size();
160 // In the vast majority of cases, we'll have precisely FPT->getNumParams()
161 // parameters; the only thing that can change this is the presence of
162 // pass_object_size. So, we preallocate for the common case.
163 prefix.reserve(prefix.size() + FPT->getNumParams());
164
165 auto ExtInfos = FPT->getExtParameterInfos();
166 assert(ExtInfos.size() == FPT->getNumParams());
167 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
168 prefix.push_back(FPT->getParamType(I));
169 if (ExtInfos[I].hasPassObjectSize())
170 prefix.push_back(CGT.getContext().getSizeType());
171 }
172
173 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
174 prefix.size());
175 }
176
177 /// Arrange the LLVM function layout for a value of the given function
178 /// type, on top of any implicit parameters already stored.
179 static const CGFunctionInfo &
arrangeLLVMFunctionInfo(CodeGenTypes & CGT,bool instanceMethod,SmallVectorImpl<CanQualType> & prefix,CanQual<FunctionProtoType> FTP)180 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
181 SmallVectorImpl<CanQualType> &prefix,
182 CanQual<FunctionProtoType> FTP) {
183 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
184 RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
185 // FIXME: Kill copy.
186 appendParameterTypes(CGT, prefix, paramInfos, FTP);
187 CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
188
189 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
190 /*chainCall=*/false, prefix,
191 FTP->getExtInfo(), paramInfos,
192 Required);
193 }
194
195 /// Arrange the argument and result information for a value of the
196 /// given freestanding function type.
197 const CGFunctionInfo &
arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP)198 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
199 SmallVector<CanQualType, 16> argTypes;
200 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
201 FTP);
202 }
203
getCallingConventionForDecl(const ObjCMethodDecl * D,bool IsWindows)204 static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
205 bool IsWindows) {
206 // Set the appropriate calling convention for the Function.
207 if (D->hasAttr<StdCallAttr>())
208 return CC_X86StdCall;
209
210 if (D->hasAttr<FastCallAttr>())
211 return CC_X86FastCall;
212
213 if (D->hasAttr<RegCallAttr>())
214 return CC_X86RegCall;
215
216 if (D->hasAttr<ThisCallAttr>())
217 return CC_X86ThisCall;
218
219 if (D->hasAttr<VectorCallAttr>())
220 return CC_X86VectorCall;
221
222 if (D->hasAttr<PascalAttr>())
223 return CC_X86Pascal;
224
225 if (PcsAttr *PCS = D->getAttr<PcsAttr>())
226 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
227
228 if (D->hasAttr<AArch64VectorPcsAttr>())
229 return CC_AArch64VectorCall;
230
231 if (D->hasAttr<IntelOclBiccAttr>())
232 return CC_IntelOclBicc;
233
234 if (D->hasAttr<MSABIAttr>())
235 return IsWindows ? CC_C : CC_Win64;
236
237 if (D->hasAttr<SysVABIAttr>())
238 return IsWindows ? CC_X86_64SysV : CC_C;
239
240 if (D->hasAttr<PreserveMostAttr>())
241 return CC_PreserveMost;
242
243 if (D->hasAttr<PreserveAllAttr>())
244 return CC_PreserveAll;
245
246 return CC_C;
247 }
248
249 /// Arrange the argument and result information for a call to an
250 /// unknown C++ non-static member function of the given abstract type.
251 /// (A null RD means we don't have any meaningful "this" argument type,
252 /// so fall back to a generic pointer type).
253 /// The member function must be an ordinary function, i.e. not a
254 /// constructor or destructor.
255 const CGFunctionInfo &
arrangeCXXMethodType(const CXXRecordDecl * RD,const FunctionProtoType * FTP,const CXXMethodDecl * MD)256 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
257 const FunctionProtoType *FTP,
258 const CXXMethodDecl *MD) {
259 SmallVector<CanQualType, 16> argTypes;
260
261 // Add the 'this' pointer.
262 argTypes.push_back(DeriveThisType(RD, MD));
263
264 return ::arrangeLLVMFunctionInfo(
265 *this, true, argTypes,
266 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
267 }
268
269 /// Set calling convention for CUDA/HIP kernel.
setCUDAKernelCallingConvention(CanQualType & FTy,CodeGenModule & CGM,const FunctionDecl * FD)270 static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
271 const FunctionDecl *FD) {
272 if (FD->hasAttr<CUDAGlobalAttr>()) {
273 const FunctionType *FT = FTy->getAs<FunctionType>();
274 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
275 FTy = FT->getCanonicalTypeUnqualified();
276 }
277 }
278
279 /// Arrange the argument and result information for a declaration or
280 /// definition of the given C++ non-static member function. The
281 /// member function must be an ordinary function, i.e. not a
282 /// constructor or destructor.
283 const CGFunctionInfo &
arrangeCXXMethodDeclaration(const CXXMethodDecl * MD)284 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
285 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
286 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
287
288 CanQualType FT = GetFormalType(MD).getAs<Type>();
289 setCUDAKernelCallingConvention(FT, CGM, MD);
290 auto prototype = FT.getAs<FunctionProtoType>();
291
292 if (MD->isInstance()) {
293 // The abstract case is perfectly fine.
294 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
295 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
296 }
297
298 return arrangeFreeFunctionType(prototype);
299 }
300
inheritingCtorHasParams(const InheritedConstructor & Inherited,CXXCtorType Type)301 bool CodeGenTypes::inheritingCtorHasParams(
302 const InheritedConstructor &Inherited, CXXCtorType Type) {
303 // Parameters are unnecessary if we're constructing a base class subobject
304 // and the inherited constructor lives in a virtual base.
305 return Type == Ctor_Complete ||
306 !Inherited.getShadowDecl()->constructsVirtualBase() ||
307 !Target.getCXXABI().hasConstructorVariants();
308 }
309
310 const CGFunctionInfo &
arrangeCXXStructorDeclaration(GlobalDecl GD)311 CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
312 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
313
314 SmallVector<CanQualType, 16> argTypes;
315 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
316 argTypes.push_back(DeriveThisType(MD->getParent(), MD));
317
318 bool PassParams = true;
319
320 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
321 // A base class inheriting constructor doesn't get forwarded arguments
322 // needed to construct a virtual base (or base class thereof).
323 if (auto Inherited = CD->getInheritedConstructor())
324 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
325 }
326
327 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
328
329 // Add the formal parameters.
330 if (PassParams)
331 appendParameterTypes(*this, argTypes, paramInfos, FTP);
332
333 CGCXXABI::AddedStructorArgCounts AddedArgs =
334 TheCXXABI.buildStructorSignature(GD, argTypes);
335 if (!paramInfos.empty()) {
336 // Note: prefix implies after the first param.
337 if (AddedArgs.Prefix)
338 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
339 FunctionProtoType::ExtParameterInfo{});
340 if (AddedArgs.Suffix)
341 paramInfos.append(AddedArgs.Suffix,
342 FunctionProtoType::ExtParameterInfo{});
343 }
344
345 RequiredArgs required =
346 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
347 : RequiredArgs::All);
348
349 FunctionType::ExtInfo extInfo = FTP->getExtInfo();
350 CanQualType resultType = TheCXXABI.HasThisReturn(GD)
351 ? argTypes.front()
352 : TheCXXABI.hasMostDerivedReturn(GD)
353 ? CGM.getContext().VoidPtrTy
354 : Context.VoidTy;
355 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
356 /*chainCall=*/false, argTypes, extInfo,
357 paramInfos, required);
358 }
359
360 static SmallVector<CanQualType, 16>
getArgTypesForCall(ASTContext & ctx,const CallArgList & args)361 getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
362 SmallVector<CanQualType, 16> argTypes;
363 for (auto &arg : args)
364 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
365 return argTypes;
366 }
367
368 static SmallVector<CanQualType, 16>
getArgTypesForDeclaration(ASTContext & ctx,const FunctionArgList & args)369 getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
370 SmallVector<CanQualType, 16> argTypes;
371 for (auto &arg : args)
372 argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
373 return argTypes;
374 }
375
376 static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
getExtParameterInfosForCall(const FunctionProtoType * proto,unsigned prefixArgs,unsigned totalArgs)377 getExtParameterInfosForCall(const FunctionProtoType *proto,
378 unsigned prefixArgs, unsigned totalArgs) {
379 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
380 if (proto->hasExtParameterInfos()) {
381 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
382 }
383 return result;
384 }
385
386 /// Arrange a call to a C++ method, passing the given arguments.
387 ///
388 /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
389 /// parameter.
390 /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
391 /// args.
392 /// PassProtoArgs indicates whether `args` has args for the parameters in the
393 /// given CXXConstructorDecl.
394 const CGFunctionInfo &
arrangeCXXConstructorCall(const CallArgList & args,const CXXConstructorDecl * D,CXXCtorType CtorKind,unsigned ExtraPrefixArgs,unsigned ExtraSuffixArgs,bool PassProtoArgs)395 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
396 const CXXConstructorDecl *D,
397 CXXCtorType CtorKind,
398 unsigned ExtraPrefixArgs,
399 unsigned ExtraSuffixArgs,
400 bool PassProtoArgs) {
401 // FIXME: Kill copy.
402 SmallVector<CanQualType, 16> ArgTypes;
403 for (const auto &Arg : args)
404 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
405
406 // +1 for implicit this, which should always be args[0].
407 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
408
409 CanQual<FunctionProtoType> FPT = GetFormalType(D);
410 RequiredArgs Required = PassProtoArgs
411 ? RequiredArgs::forPrototypePlus(
412 FPT, TotalPrefixArgs + ExtraSuffixArgs)
413 : RequiredArgs::All;
414
415 GlobalDecl GD(D, CtorKind);
416 CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
417 ? ArgTypes.front()
418 : TheCXXABI.hasMostDerivedReturn(GD)
419 ? CGM.getContext().VoidPtrTy
420 : Context.VoidTy;
421
422 FunctionType::ExtInfo Info = FPT->getExtInfo();
423 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
424 // If the prototype args are elided, we should only have ABI-specific args,
425 // which never have param info.
426 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
427 // ABI-specific suffix arguments are treated the same as variadic arguments.
428 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
429 ArgTypes.size());
430 }
431 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
432 /*chainCall=*/false, ArgTypes, Info,
433 ParamInfos, Required);
434 }
435
436 /// Arrange the argument and result information for the declaration or
437 /// definition of the given function.
438 const CGFunctionInfo &
arrangeFunctionDeclaration(const FunctionDecl * FD)439 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
440 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
441 if (MD->isInstance())
442 return arrangeCXXMethodDeclaration(MD);
443
444 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
445
446 assert(isa<FunctionType>(FTy));
447 setCUDAKernelCallingConvention(FTy, CGM, FD);
448
449 // When declaring a function without a prototype, always use a
450 // non-variadic type.
451 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
452 return arrangeLLVMFunctionInfo(
453 noProto->getReturnType(), /*instanceMethod=*/false,
454 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
455 }
456
457 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
458 }
459
460 /// Arrange the argument and result information for the declaration or
461 /// definition of an Objective-C method.
462 const CGFunctionInfo &
arrangeObjCMethodDeclaration(const ObjCMethodDecl * MD)463 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
464 // It happens that this is the same as a call with no optional
465 // arguments, except also using the formal 'self' type.
466 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
467 }
468
469 /// Arrange the argument and result information for the function type
470 /// through which to perform a send to the given Objective-C method,
471 /// using the given receiver type. The receiver type is not always
472 /// the 'self' type of the method or even an Objective-C pointer type.
473 /// This is *not* the right method for actually performing such a
474 /// message send, due to the possibility of optional arguments.
475 const CGFunctionInfo &
arrangeObjCMessageSendSignature(const ObjCMethodDecl * MD,QualType receiverType)476 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
477 QualType receiverType) {
478 SmallVector<CanQualType, 16> argTys;
479 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
480 argTys.push_back(Context.getCanonicalParamType(receiverType));
481 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
482 // FIXME: Kill copy?
483 for (const auto *I : MD->parameters()) {
484 argTys.push_back(Context.getCanonicalParamType(I->getType()));
485 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
486 I->hasAttr<NoEscapeAttr>());
487 extParamInfos.push_back(extParamInfo);
488 }
489
490 FunctionType::ExtInfo einfo;
491 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
492 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
493
494 if (getContext().getLangOpts().ObjCAutoRefCount &&
495 MD->hasAttr<NSReturnsRetainedAttr>())
496 einfo = einfo.withProducesResult(true);
497
498 RequiredArgs required =
499 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
500
501 return arrangeLLVMFunctionInfo(
502 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
503 /*chainCall=*/false, argTys, einfo, extParamInfos, required);
504 }
505
506 const CGFunctionInfo &
arrangeUnprototypedObjCMessageSend(QualType returnType,const CallArgList & args)507 CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
508 const CallArgList &args) {
509 auto argTypes = getArgTypesForCall(Context, args);
510 FunctionType::ExtInfo einfo;
511
512 return arrangeLLVMFunctionInfo(
513 GetReturnType(returnType), /*instanceMethod=*/false,
514 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
515 }
516
517 const CGFunctionInfo &
arrangeGlobalDeclaration(GlobalDecl GD)518 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
519 // FIXME: Do we need to handle ObjCMethodDecl?
520 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
521
522 if (isa<CXXConstructorDecl>(GD.getDecl()) ||
523 isa<CXXDestructorDecl>(GD.getDecl()))
524 return arrangeCXXStructorDeclaration(GD);
525
526 return arrangeFunctionDeclaration(FD);
527 }
528
529 /// Arrange a thunk that takes 'this' as the first parameter followed by
530 /// varargs. Return a void pointer, regardless of the actual return type.
531 /// The body of the thunk will end in a musttail call to a function of the
532 /// correct type, and the caller will bitcast the function to the correct
533 /// prototype.
534 const CGFunctionInfo &
arrangeUnprototypedMustTailThunk(const CXXMethodDecl * MD)535 CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
536 assert(MD->isVirtual() && "only methods have thunks");
537 CanQual<FunctionProtoType> FTP = GetFormalType(MD);
538 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
539 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
540 /*chainCall=*/false, ArgTys,
541 FTP->getExtInfo(), {}, RequiredArgs(1));
542 }
543
544 const CGFunctionInfo &
arrangeMSCtorClosure(const CXXConstructorDecl * CD,CXXCtorType CT)545 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
546 CXXCtorType CT) {
547 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
548
549 CanQual<FunctionProtoType> FTP = GetFormalType(CD);
550 SmallVector<CanQualType, 2> ArgTys;
551 const CXXRecordDecl *RD = CD->getParent();
552 ArgTys.push_back(DeriveThisType(RD, CD));
553 if (CT == Ctor_CopyingClosure)
554 ArgTys.push_back(*FTP->param_type_begin());
555 if (RD->getNumVBases() > 0)
556 ArgTys.push_back(Context.IntTy);
557 CallingConv CC = Context.getDefaultCallingConvention(
558 /*IsVariadic=*/false, /*IsCXXMethod=*/true);
559 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
560 /*chainCall=*/false, ArgTys,
561 FunctionType::ExtInfo(CC), {},
562 RequiredArgs::All);
563 }
564
565 /// Arrange a call as unto a free function, except possibly with an
566 /// additional number of formal parameters considered required.
567 static const CGFunctionInfo &
arrangeFreeFunctionLikeCall(CodeGenTypes & CGT,CodeGenModule & CGM,const CallArgList & args,const FunctionType * fnType,unsigned numExtraRequiredArgs,bool chainCall)568 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
569 CodeGenModule &CGM,
570 const CallArgList &args,
571 const FunctionType *fnType,
572 unsigned numExtraRequiredArgs,
573 bool chainCall) {
574 assert(args.size() >= numExtraRequiredArgs);
575
576 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
577
578 // In most cases, there are no optional arguments.
579 RequiredArgs required = RequiredArgs::All;
580
581 // If we have a variadic prototype, the required arguments are the
582 // extra prefix plus the arguments in the prototype.
583 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
584 if (proto->isVariadic())
585 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
586
587 if (proto->hasExtParameterInfos())
588 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
589 args.size());
590
591 // If we don't have a prototype at all, but we're supposed to
592 // explicitly use the variadic convention for unprototyped calls,
593 // treat all of the arguments as required but preserve the nominal
594 // possibility of variadics.
595 } else if (CGM.getTargetCodeGenInfo()
596 .isNoProtoCallVariadic(args,
597 cast<FunctionNoProtoType>(fnType))) {
598 required = RequiredArgs(args.size());
599 }
600
601 // FIXME: Kill copy.
602 SmallVector<CanQualType, 16> argTypes;
603 for (const auto &arg : args)
604 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
605 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
606 /*instanceMethod=*/false, chainCall,
607 argTypes, fnType->getExtInfo(), paramInfos,
608 required);
609 }
610
611 /// Figure out the rules for calling a function with the given formal
612 /// type using the given arguments. The arguments are necessary
613 /// because the function might be unprototyped, in which case it's
614 /// target-dependent in crazy ways.
615 const CGFunctionInfo &
arrangeFreeFunctionCall(const CallArgList & args,const FunctionType * fnType,bool chainCall)616 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
617 const FunctionType *fnType,
618 bool chainCall) {
619 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
620 chainCall ? 1 : 0, chainCall);
621 }
622
623 /// A block function is essentially a free function with an
624 /// extra implicit argument.
625 const CGFunctionInfo &
arrangeBlockFunctionCall(const CallArgList & args,const FunctionType * fnType)626 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
627 const FunctionType *fnType) {
628 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
629 /*chainCall=*/false);
630 }
631
632 const CGFunctionInfo &
arrangeBlockFunctionDeclaration(const FunctionProtoType * proto,const FunctionArgList & params)633 CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
634 const FunctionArgList ¶ms) {
635 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
636 auto argTypes = getArgTypesForDeclaration(Context, params);
637
638 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
639 /*instanceMethod*/ false, /*chainCall*/ false,
640 argTypes, proto->getExtInfo(), paramInfos,
641 RequiredArgs::forPrototypePlus(proto, 1));
642 }
643
644 const CGFunctionInfo &
arrangeBuiltinFunctionCall(QualType resultType,const CallArgList & args)645 CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
646 const CallArgList &args) {
647 // FIXME: Kill copy.
648 SmallVector<CanQualType, 16> argTypes;
649 for (const auto &Arg : args)
650 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
651 return arrangeLLVMFunctionInfo(
652 GetReturnType(resultType), /*instanceMethod=*/false,
653 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
654 /*paramInfos=*/ {}, RequiredArgs::All);
655 }
656
657 const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(QualType resultType,const FunctionArgList & args)658 CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
659 const FunctionArgList &args) {
660 auto argTypes = getArgTypesForDeclaration(Context, args);
661
662 return arrangeLLVMFunctionInfo(
663 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
664 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
665 }
666
667 const CGFunctionInfo &
arrangeBuiltinFunctionDeclaration(CanQualType resultType,ArrayRef<CanQualType> argTypes)668 CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
669 ArrayRef<CanQualType> argTypes) {
670 return arrangeLLVMFunctionInfo(
671 resultType, /*instanceMethod=*/false, /*chainCall=*/false,
672 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
673 }
674
675 /// Arrange a call to a C++ method, passing the given arguments.
676 ///
677 /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
678 /// does not count `this`.
679 const CGFunctionInfo &
arrangeCXXMethodCall(const CallArgList & args,const FunctionProtoType * proto,RequiredArgs required,unsigned numPrefixArgs)680 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
681 const FunctionProtoType *proto,
682 RequiredArgs required,
683 unsigned numPrefixArgs) {
684 assert(numPrefixArgs + 1 <= args.size() &&
685 "Emitting a call with less args than the required prefix?");
686 // Add one to account for `this`. It's a bit awkward here, but we don't count
687 // `this` in similar places elsewhere.
688 auto paramInfos =
689 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
690
691 // FIXME: Kill copy.
692 auto argTypes = getArgTypesForCall(Context, args);
693
694 FunctionType::ExtInfo info = proto->getExtInfo();
695 return arrangeLLVMFunctionInfo(
696 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
697 /*chainCall=*/false, argTypes, info, paramInfos, required);
698 }
699
arrangeNullaryFunction()700 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
701 return arrangeLLVMFunctionInfo(
702 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
703 None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
704 }
705
706 const CGFunctionInfo &
arrangeCall(const CGFunctionInfo & signature,const CallArgList & args)707 CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
708 const CallArgList &args) {
709 assert(signature.arg_size() <= args.size());
710 if (signature.arg_size() == args.size())
711 return signature;
712
713 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
714 auto sigParamInfos = signature.getExtParameterInfos();
715 if (!sigParamInfos.empty()) {
716 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
717 paramInfos.resize(args.size());
718 }
719
720 auto argTypes = getArgTypesForCall(Context, args);
721
722 assert(signature.getRequiredArgs().allowsOptionalArgs());
723 return arrangeLLVMFunctionInfo(signature.getReturnType(),
724 signature.isInstanceMethod(),
725 signature.isChainCall(),
726 argTypes,
727 signature.getExtInfo(),
728 paramInfos,
729 signature.getRequiredArgs());
730 }
731
732 namespace clang {
733 namespace CodeGen {
734 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
735 }
736 }
737
738 /// Arrange the argument and result information for an abstract value
739 /// of a given function type. This is the method which all of the
740 /// above functions ultimately defer to.
741 const CGFunctionInfo &
arrangeLLVMFunctionInfo(CanQualType resultType,bool instanceMethod,bool chainCall,ArrayRef<CanQualType> argTypes,FunctionType::ExtInfo info,ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,RequiredArgs required)742 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
743 bool instanceMethod,
744 bool chainCall,
745 ArrayRef<CanQualType> argTypes,
746 FunctionType::ExtInfo info,
747 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
748 RequiredArgs required) {
749 assert(llvm::all_of(argTypes,
750 [](CanQualType T) { return T.isCanonicalAsParam(); }));
751
752 // Lookup or create unique function info.
753 llvm::FoldingSetNodeID ID;
754 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
755 required, resultType, argTypes);
756
757 void *insertPos = nullptr;
758 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
759 if (FI)
760 return *FI;
761
762 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
763
764 // Construct the function info. We co-allocate the ArgInfos.
765 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
766 paramInfos, resultType, argTypes, required);
767 FunctionInfos.InsertNode(FI, insertPos);
768
769 bool inserted = FunctionsBeingProcessed.insert(FI).second;
770 (void)inserted;
771 assert(inserted && "Recursively being processed?");
772
773 // Compute ABI information.
774 if (CC == llvm::CallingConv::SPIR_KERNEL) {
775 // Force target independent argument handling for the host visible
776 // kernel functions.
777 computeSPIRKernelABIInfo(CGM, *FI);
778 } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
779 swiftcall::computeABIInfo(CGM, *FI);
780 } else {
781 getABIInfo().computeInfo(*FI);
782 }
783
784 // Loop over all of the computed argument and return value info. If any of
785 // them are direct or extend without a specified coerce type, specify the
786 // default now.
787 ABIArgInfo &retInfo = FI->getReturnInfo();
788 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
789 retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
790
791 for (auto &I : FI->arguments())
792 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
793 I.info.setCoerceToType(ConvertType(I.type));
794
795 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
796 assert(erased && "Not in set?");
797
798 return *FI;
799 }
800
create(unsigned llvmCC,bool instanceMethod,bool chainCall,const FunctionType::ExtInfo & info,ArrayRef<ExtParameterInfo> paramInfos,CanQualType resultType,ArrayRef<CanQualType> argTypes,RequiredArgs required)801 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
802 bool instanceMethod,
803 bool chainCall,
804 const FunctionType::ExtInfo &info,
805 ArrayRef<ExtParameterInfo> paramInfos,
806 CanQualType resultType,
807 ArrayRef<CanQualType> argTypes,
808 RequiredArgs required) {
809 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
810 assert(!required.allowsOptionalArgs() ||
811 required.getNumRequiredArgs() <= argTypes.size());
812
813 void *buffer =
814 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
815 argTypes.size() + 1, paramInfos.size()));
816
817 CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
818 FI->CallingConvention = llvmCC;
819 FI->EffectiveCallingConvention = llvmCC;
820 FI->ASTCallingConvention = info.getCC();
821 FI->InstanceMethod = instanceMethod;
822 FI->ChainCall = chainCall;
823 FI->CmseNSCall = info.getCmseNSCall();
824 FI->NoReturn = info.getNoReturn();
825 FI->ReturnsRetained = info.getProducesResult();
826 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
827 FI->NoCfCheck = info.getNoCfCheck();
828 FI->Required = required;
829 FI->HasRegParm = info.getHasRegParm();
830 FI->RegParm = info.getRegParm();
831 FI->ArgStruct = nullptr;
832 FI->ArgStructAlign = 0;
833 FI->NumArgs = argTypes.size();
834 FI->HasExtParameterInfos = !paramInfos.empty();
835 FI->getArgsBuffer()[0].type = resultType;
836 for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
837 FI->getArgsBuffer()[i + 1].type = argTypes[i];
838 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
839 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
840 return FI;
841 }
842
843 /***/
844
845 namespace {
846 // ABIArgInfo::Expand implementation.
847
848 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
849 struct TypeExpansion {
850 enum TypeExpansionKind {
851 // Elements of constant arrays are expanded recursively.
852 TEK_ConstantArray,
853 // Record fields are expanded recursively (but if record is a union, only
854 // the field with the largest size is expanded).
855 TEK_Record,
856 // For complex types, real and imaginary parts are expanded recursively.
857 TEK_Complex,
858 // All other types are not expandable.
859 TEK_None
860 };
861
862 const TypeExpansionKind Kind;
863
TypeExpansion__anone30e957c0211::TypeExpansion864 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
~TypeExpansion__anone30e957c0211::TypeExpansion865 virtual ~TypeExpansion() {}
866 };
867
868 struct ConstantArrayExpansion : TypeExpansion {
869 QualType EltTy;
870 uint64_t NumElts;
871
ConstantArrayExpansion__anone30e957c0211::ConstantArrayExpansion872 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
873 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
classof__anone30e957c0211::ConstantArrayExpansion874 static bool classof(const TypeExpansion *TE) {
875 return TE->Kind == TEK_ConstantArray;
876 }
877 };
878
879 struct RecordExpansion : TypeExpansion {
880 SmallVector<const CXXBaseSpecifier *, 1> Bases;
881
882 SmallVector<const FieldDecl *, 1> Fields;
883
RecordExpansion__anone30e957c0211::RecordExpansion884 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
885 SmallVector<const FieldDecl *, 1> &&Fields)
886 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
887 Fields(std::move(Fields)) {}
classof__anone30e957c0211::RecordExpansion888 static bool classof(const TypeExpansion *TE) {
889 return TE->Kind == TEK_Record;
890 }
891 };
892
893 struct ComplexExpansion : TypeExpansion {
894 QualType EltTy;
895
ComplexExpansion__anone30e957c0211::ComplexExpansion896 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
classof__anone30e957c0211::ComplexExpansion897 static bool classof(const TypeExpansion *TE) {
898 return TE->Kind == TEK_Complex;
899 }
900 };
901
902 struct NoExpansion : TypeExpansion {
NoExpansion__anone30e957c0211::NoExpansion903 NoExpansion() : TypeExpansion(TEK_None) {}
classof__anone30e957c0211::NoExpansion904 static bool classof(const TypeExpansion *TE) {
905 return TE->Kind == TEK_None;
906 }
907 };
908 } // namespace
909
910 static std::unique_ptr<TypeExpansion>
getTypeExpansion(QualType Ty,const ASTContext & Context)911 getTypeExpansion(QualType Ty, const ASTContext &Context) {
912 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
913 return std::make_unique<ConstantArrayExpansion>(
914 AT->getElementType(), AT->getSize().getZExtValue());
915 }
916 if (const RecordType *RT = Ty->getAs<RecordType>()) {
917 SmallVector<const CXXBaseSpecifier *, 1> Bases;
918 SmallVector<const FieldDecl *, 1> Fields;
919 const RecordDecl *RD = RT->getDecl();
920 assert(!RD->hasFlexibleArrayMember() &&
921 "Cannot expand structure with flexible array.");
922 if (RD->isUnion()) {
923 // Unions can be here only in degenerative cases - all the fields are same
924 // after flattening. Thus we have to use the "largest" field.
925 const FieldDecl *LargestFD = nullptr;
926 CharUnits UnionSize = CharUnits::Zero();
927
928 for (const auto *FD : RD->fields()) {
929 if (FD->isZeroLengthBitField(Context))
930 continue;
931 assert(!FD->isBitField() &&
932 "Cannot expand structure with bit-field members.");
933 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
934 if (UnionSize < FieldSize) {
935 UnionSize = FieldSize;
936 LargestFD = FD;
937 }
938 }
939 if (LargestFD)
940 Fields.push_back(LargestFD);
941 } else {
942 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
943 assert(!CXXRD->isDynamicClass() &&
944 "cannot expand vtable pointers in dynamic classes");
945 for (const CXXBaseSpecifier &BS : CXXRD->bases())
946 Bases.push_back(&BS);
947 }
948
949 for (const auto *FD : RD->fields()) {
950 if (FD->isZeroLengthBitField(Context))
951 continue;
952 assert(!FD->isBitField() &&
953 "Cannot expand structure with bit-field members.");
954 Fields.push_back(FD);
955 }
956 }
957 return std::make_unique<RecordExpansion>(std::move(Bases),
958 std::move(Fields));
959 }
960 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
961 return std::make_unique<ComplexExpansion>(CT->getElementType());
962 }
963 return std::make_unique<NoExpansion>();
964 }
965
getExpansionSize(QualType Ty,const ASTContext & Context)966 static int getExpansionSize(QualType Ty, const ASTContext &Context) {
967 auto Exp = getTypeExpansion(Ty, Context);
968 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
969 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
970 }
971 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
972 int Res = 0;
973 for (auto BS : RExp->Bases)
974 Res += getExpansionSize(BS->getType(), Context);
975 for (auto FD : RExp->Fields)
976 Res += getExpansionSize(FD->getType(), Context);
977 return Res;
978 }
979 if (isa<ComplexExpansion>(Exp.get()))
980 return 2;
981 assert(isa<NoExpansion>(Exp.get()));
982 return 1;
983 }
984
985 void
getExpandedTypes(QualType Ty,SmallVectorImpl<llvm::Type * >::iterator & TI)986 CodeGenTypes::getExpandedTypes(QualType Ty,
987 SmallVectorImpl<llvm::Type *>::iterator &TI) {
988 auto Exp = getTypeExpansion(Ty, Context);
989 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
990 for (int i = 0, n = CAExp->NumElts; i < n; i++) {
991 getExpandedTypes(CAExp->EltTy, TI);
992 }
993 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
994 for (auto BS : RExp->Bases)
995 getExpandedTypes(BS->getType(), TI);
996 for (auto FD : RExp->Fields)
997 getExpandedTypes(FD->getType(), TI);
998 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
999 llvm::Type *EltTy = ConvertType(CExp->EltTy);
1000 *TI++ = EltTy;
1001 *TI++ = EltTy;
1002 } else {
1003 assert(isa<NoExpansion>(Exp.get()));
1004 *TI++ = ConvertType(Ty);
1005 }
1006 }
1007
forConstantArrayExpansion(CodeGenFunction & CGF,ConstantArrayExpansion * CAE,Address BaseAddr,llvm::function_ref<void (Address)> Fn)1008 static void forConstantArrayExpansion(CodeGenFunction &CGF,
1009 ConstantArrayExpansion *CAE,
1010 Address BaseAddr,
1011 llvm::function_ref<void(Address)> Fn) {
1012 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
1013 CharUnits EltAlign =
1014 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
1015
1016 for (int i = 0, n = CAE->NumElts; i < n; i++) {
1017 llvm::Value *EltAddr = CGF.Builder.CreateConstGEP2_32(
1018 BaseAddr.getElementType(), BaseAddr.getPointer(), 0, i);
1019 Fn(Address(EltAddr, EltAlign));
1020 }
1021 }
1022
ExpandTypeFromArgs(QualType Ty,LValue LV,llvm::Function::arg_iterator & AI)1023 void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1024 llvm::Function::arg_iterator &AI) {
1025 assert(LV.isSimple() &&
1026 "Unexpected non-simple lvalue during struct expansion.");
1027
1028 auto Exp = getTypeExpansion(Ty, getContext());
1029 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1030 forConstantArrayExpansion(
1031 *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
1032 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1033 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1034 });
1035 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1036 Address This = LV.getAddress(*this);
1037 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1038 // Perform a single step derived-to-base conversion.
1039 Address Base =
1040 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1041 /*NullCheckValue=*/false, SourceLocation());
1042 LValue SubLV = MakeAddrLValue(Base, BS->getType());
1043
1044 // Recurse onto bases.
1045 ExpandTypeFromArgs(BS->getType(), SubLV, AI);
1046 }
1047 for (auto FD : RExp->Fields) {
1048 // FIXME: What are the right qualifiers here?
1049 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1050 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1051 }
1052 } else if (isa<ComplexExpansion>(Exp.get())) {
1053 auto realValue = &*AI++;
1054 auto imagValue = &*AI++;
1055 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
1056 } else {
1057 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
1058 // primitive store.
1059 assert(isa<NoExpansion>(Exp.get()));
1060 llvm::Value *Arg = &*AI++;
1061 if (LV.isBitField()) {
1062 EmitStoreThroughLValue(RValue::get(Arg), LV);
1063 } else {
1064 // TODO: currently there are some places are inconsistent in what LLVM
1065 // pointer type they use (see D118744). Once clang uses opaque pointers
1066 // all LLVM pointer types will be the same and we can remove this check.
1067 if (Arg->getType()->isPointerTy()) {
1068 Address Addr = LV.getAddress(*this);
1069 Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
1070 }
1071 EmitStoreOfScalar(Arg, LV);
1072 }
1073 }
1074 }
1075
ExpandTypeToArgs(QualType Ty,CallArg Arg,llvm::FunctionType * IRFuncTy,SmallVectorImpl<llvm::Value * > & IRCallArgs,unsigned & IRCallArgPos)1076 void CodeGenFunction::ExpandTypeToArgs(
1077 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1078 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
1079 auto Exp = getTypeExpansion(Ty, getContext());
1080 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1081 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1082 : Arg.getKnownRValue().getAggregateAddress();
1083 forConstantArrayExpansion(
1084 *this, CAExp, Addr, [&](Address EltAddr) {
1085 CallArg EltArg = CallArg(
1086 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1087 CAExp->EltTy);
1088 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1089 IRCallArgPos);
1090 });
1091 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1092 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
1093 : Arg.getKnownRValue().getAggregateAddress();
1094 for (const CXXBaseSpecifier *BS : RExp->Bases) {
1095 // Perform a single step derived-to-base conversion.
1096 Address Base =
1097 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
1098 /*NullCheckValue=*/false, SourceLocation());
1099 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
1100
1101 // Recurse onto bases.
1102 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
1103 IRCallArgPos);
1104 }
1105
1106 LValue LV = MakeAddrLValue(This, Ty);
1107 for (auto FD : RExp->Fields) {
1108 CallArg FldArg =
1109 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1110 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1111 IRCallArgPos);
1112 }
1113 } else if (isa<ComplexExpansion>(Exp.get())) {
1114 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
1115 IRCallArgs[IRCallArgPos++] = CV.first;
1116 IRCallArgs[IRCallArgPos++] = CV.second;
1117 } else {
1118 assert(isa<NoExpansion>(Exp.get()));
1119 auto RV = Arg.getKnownRValue();
1120 assert(RV.isScalar() &&
1121 "Unexpected non-scalar rvalue during struct expansion.");
1122
1123 // Insert a bitcast as needed.
1124 llvm::Value *V = RV.getScalarVal();
1125 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1126 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1127 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
1128
1129 IRCallArgs[IRCallArgPos++] = V;
1130 }
1131 }
1132
1133 /// Create a temporary allocation for the purposes of coercion.
CreateTempAllocaForCoercion(CodeGenFunction & CGF,llvm::Type * Ty,CharUnits MinAlign,const Twine & Name="tmp")1134 static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
1135 CharUnits MinAlign,
1136 const Twine &Name = "tmp") {
1137 // Don't use an alignment that's worse than what LLVM would prefer.
1138 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
1139 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
1140
1141 return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
1142 }
1143
1144 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
1145 /// accessing some number of bytes out of it, try to gep into the struct to get
1146 /// at its inner goodness. Dive as deep as possible without entering an element
1147 /// with an in-memory size smaller than DstSize.
1148 static Address
EnterStructPointerForCoercedAccess(Address SrcPtr,llvm::StructType * SrcSTy,uint64_t DstSize,CodeGenFunction & CGF)1149 EnterStructPointerForCoercedAccess(Address SrcPtr,
1150 llvm::StructType *SrcSTy,
1151 uint64_t DstSize, CodeGenFunction &CGF) {
1152 // We can't dive into a zero-element struct.
1153 if (SrcSTy->getNumElements() == 0) return SrcPtr;
1154
1155 llvm::Type *FirstElt = SrcSTy->getElementType(0);
1156
1157 // If the first elt is at least as large as what we're looking for, or if the
1158 // first element is the same size as the whole struct, we can enter it. The
1159 // comparison must be made on the store size and not the alloca size. Using
1160 // the alloca size may overstate the size of the load.
1161 uint64_t FirstEltSize =
1162 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
1163 if (FirstEltSize < DstSize &&
1164 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
1165 return SrcPtr;
1166
1167 // GEP into the first element.
1168 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
1169
1170 // If the first element is a struct, recurse.
1171 llvm::Type *SrcTy = SrcPtr.getElementType();
1172 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1173 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
1174
1175 return SrcPtr;
1176 }
1177
1178 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
1179 /// are either integers or pointers. This does a truncation of the value if it
1180 /// is too large or a zero extension if it is too small.
1181 ///
1182 /// This behaves as if the value were coerced through memory, so on big-endian
1183 /// targets the high bits are preserved in a truncation, while little-endian
1184 /// targets preserve the low bits.
CoerceIntOrPtrToIntOrPtr(llvm::Value * Val,llvm::Type * Ty,CodeGenFunction & CGF)1185 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
1186 llvm::Type *Ty,
1187 CodeGenFunction &CGF) {
1188 if (Val->getType() == Ty)
1189 return Val;
1190
1191 if (isa<llvm::PointerType>(Val->getType())) {
1192 // If this is Pointer->Pointer avoid conversion to and from int.
1193 if (isa<llvm::PointerType>(Ty))
1194 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
1195
1196 // Convert the pointer to an integer so we can play with its width.
1197 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
1198 }
1199
1200 llvm::Type *DestIntTy = Ty;
1201 if (isa<llvm::PointerType>(DestIntTy))
1202 DestIntTy = CGF.IntPtrTy;
1203
1204 if (Val->getType() != DestIntTy) {
1205 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
1206 if (DL.isBigEndian()) {
1207 // Preserve the high bits on big-endian targets.
1208 // That is what memory coercion does.
1209 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1210 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1211
1212 if (SrcSize > DstSize) {
1213 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
1214 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
1215 } else {
1216 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
1217 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
1218 }
1219 } else {
1220 // Little-endian targets preserve the low bits. No shifts required.
1221 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
1222 }
1223 }
1224
1225 if (isa<llvm::PointerType>(Ty))
1226 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
1227 return Val;
1228 }
1229
1230
1231
1232 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1233 /// a pointer to an object of type \arg Ty, known to be aligned to
1234 /// \arg SrcAlign bytes.
1235 ///
1236 /// This safely handles the case when the src type is smaller than the
1237 /// destination type; in this situation the values of bits which not
1238 /// present in the src are undefined.
CreateCoercedLoad(Address Src,llvm::Type * Ty,CodeGenFunction & CGF)1239 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
1240 CodeGenFunction &CGF) {
1241 llvm::Type *SrcTy = Src.getElementType();
1242
1243 // If SrcTy and Ty are the same, just do a load.
1244 if (SrcTy == Ty)
1245 return CGF.Builder.CreateLoad(Src);
1246
1247 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
1248
1249 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1250 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
1251 DstSize.getFixedSize(), CGF);
1252 SrcTy = Src.getElementType();
1253 }
1254
1255 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1256
1257 // If the source and destination are integer or pointer types, just do an
1258 // extension or truncation to the desired type.
1259 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
1260 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
1261 llvm::Value *Load = CGF.Builder.CreateLoad(Src);
1262 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
1263 }
1264
1265 // If load is legal, just bitcast the src pointer.
1266 if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1267 SrcSize.getFixedSize() >= DstSize.getFixedSize()) {
1268 // Generally SrcSize is never greater than DstSize, since this means we are
1269 // losing bits. However, this can happen in cases where the structure has
1270 // additional padding, for example due to a user specified alignment.
1271 //
1272 // FIXME: Assert that we aren't truncating non-padding bits when have access
1273 // to that information.
1274 Src = CGF.Builder.CreateBitCast(Src,
1275 Ty->getPointerTo(Src.getAddressSpace()));
1276 return CGF.Builder.CreateLoad(Src);
1277 }
1278
1279 // If coercing a fixed vector to a scalable vector for ABI compatibility, and
1280 // the types match, use the llvm.experimental.vector.insert intrinsic to
1281 // perform the conversion.
1282 if (auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1283 if (auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1284 if (ScalableDst->getElementType() == FixedSrc->getElementType()) {
1285 auto *Load = CGF.Builder.CreateLoad(Src);
1286 auto *UndefVec = llvm::UndefValue::get(ScalableDst);
1287 auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
1288 return CGF.Builder.CreateInsertVector(ScalableDst, UndefVec, Load, Zero,
1289 "castScalableSve");
1290 }
1291 }
1292 }
1293
1294 // Otherwise do coercion through memory. This is stupid, but simple.
1295 Address Tmp =
1296 CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
1297 CGF.Builder.CreateMemCpy(
1298 Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
1299 Src.getAlignment().getAsAlign(),
1300 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinSize()));
1301 return CGF.Builder.CreateLoad(Tmp);
1302 }
1303
1304 // Function to store a first-class aggregate into memory. We prefer to
1305 // store the elements rather than the aggregate to be more friendly to
1306 // fast-isel.
1307 // FIXME: Do we need to recurse here?
EmitAggregateStore(llvm::Value * Val,Address Dest,bool DestIsVolatile)1308 void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
1309 bool DestIsVolatile) {
1310 // Prefer scalar stores to first-class aggregate stores.
1311 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
1312 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1313 Address EltPtr = Builder.CreateStructGEP(Dest, i);
1314 llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
1315 Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
1316 }
1317 } else {
1318 Builder.CreateStore(Val, Dest, DestIsVolatile);
1319 }
1320 }
1321
1322 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1323 /// where the source and destination may have different types. The
1324 /// destination is known to be aligned to \arg DstAlign bytes.
1325 ///
1326 /// This safely handles the case when the src type is larger than the
1327 /// destination type; the upper bits of the src will be lost.
CreateCoercedStore(llvm::Value * Src,Address Dst,bool DstIsVolatile,CodeGenFunction & CGF)1328 static void CreateCoercedStore(llvm::Value *Src,
1329 Address Dst,
1330 bool DstIsVolatile,
1331 CodeGenFunction &CGF) {
1332 llvm::Type *SrcTy = Src->getType();
1333 llvm::Type *DstTy = Dst.getElementType();
1334 if (SrcTy == DstTy) {
1335 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1336 return;
1337 }
1338
1339 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
1340
1341 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
1342 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
1343 SrcSize.getFixedSize(), CGF);
1344 DstTy = Dst.getElementType();
1345 }
1346
1347 llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
1348 llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
1349 if (SrcPtrTy && DstPtrTy &&
1350 SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
1351 Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
1352 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1353 return;
1354 }
1355
1356 // If the source and destination are integer or pointer types, just do an
1357 // extension or truncation to the desired type.
1358 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
1359 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
1360 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
1361 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
1362 return;
1363 }
1364
1365 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
1366
1367 // If store is legal, just bitcast the src pointer.
1368 if (isa<llvm::ScalableVectorType>(SrcTy) ||
1369 isa<llvm::ScalableVectorType>(DstTy) ||
1370 SrcSize.getFixedSize() <= DstSize.getFixedSize()) {
1371 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
1372 CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
1373 } else {
1374 // Otherwise do coercion through memory. This is stupid, but
1375 // simple.
1376
1377 // Generally SrcSize is never greater than DstSize, since this means we are
1378 // losing bits. However, this can happen in cases where the structure has
1379 // additional padding, for example due to a user specified alignment.
1380 //
1381 // FIXME: Assert that we aren't truncating non-padding bits when have access
1382 // to that information.
1383 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
1384 CGF.Builder.CreateStore(Src, Tmp);
1385 CGF.Builder.CreateMemCpy(
1386 Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
1387 Tmp.getAlignment().getAsAlign(),
1388 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedSize()));
1389 }
1390 }
1391
emitAddressAtOffset(CodeGenFunction & CGF,Address addr,const ABIArgInfo & info)1392 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
1393 const ABIArgInfo &info) {
1394 if (unsigned offset = info.getDirectOffset()) {
1395 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
1396 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
1397 CharUnits::fromQuantity(offset));
1398 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
1399 }
1400 return addr;
1401 }
1402
1403 namespace {
1404
1405 /// Encapsulates information about the way function arguments from
1406 /// CGFunctionInfo should be passed to actual LLVM IR function.
1407 class ClangToLLVMArgMapping {
1408 static const unsigned InvalidIndex = ~0U;
1409 unsigned InallocaArgNo;
1410 unsigned SRetArgNo;
1411 unsigned TotalIRArgs;
1412
1413 /// Arguments of LLVM IR function corresponding to single Clang argument.
1414 struct IRArgs {
1415 unsigned PaddingArgIndex;
1416 // Argument is expanded to IR arguments at positions
1417 // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
1418 unsigned FirstArgIndex;
1419 unsigned NumberOfArgs;
1420
IRArgs__anone30e957c0511::ClangToLLVMArgMapping::IRArgs1421 IRArgs()
1422 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1423 NumberOfArgs(0) {}
1424 };
1425
1426 SmallVector<IRArgs, 8> ArgInfo;
1427
1428 public:
ClangToLLVMArgMapping(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs=false)1429 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
1430 bool OnlyRequiredArgs = false)
1431 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1432 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1433 construct(Context, FI, OnlyRequiredArgs);
1434 }
1435
hasInallocaArg() const1436 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
getInallocaArgNo() const1437 unsigned getInallocaArgNo() const {
1438 assert(hasInallocaArg());
1439 return InallocaArgNo;
1440 }
1441
hasSRetArg() const1442 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
getSRetArgNo() const1443 unsigned getSRetArgNo() const {
1444 assert(hasSRetArg());
1445 return SRetArgNo;
1446 }
1447
totalIRArgs() const1448 unsigned totalIRArgs() const { return TotalIRArgs; }
1449
hasPaddingArg(unsigned ArgNo) const1450 bool hasPaddingArg(unsigned ArgNo) const {
1451 assert(ArgNo < ArgInfo.size());
1452 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1453 }
getPaddingArgNo(unsigned ArgNo) const1454 unsigned getPaddingArgNo(unsigned ArgNo) const {
1455 assert(hasPaddingArg(ArgNo));
1456 return ArgInfo[ArgNo].PaddingArgIndex;
1457 }
1458
1459 /// Returns index of first IR argument corresponding to ArgNo, and their
1460 /// quantity.
getIRArgs(unsigned ArgNo) const1461 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
1462 assert(ArgNo < ArgInfo.size());
1463 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1464 ArgInfo[ArgNo].NumberOfArgs);
1465 }
1466
1467 private:
1468 void construct(const ASTContext &Context, const CGFunctionInfo &FI,
1469 bool OnlyRequiredArgs);
1470 };
1471
construct(const ASTContext & Context,const CGFunctionInfo & FI,bool OnlyRequiredArgs)1472 void ClangToLLVMArgMapping::construct(const ASTContext &Context,
1473 const CGFunctionInfo &FI,
1474 bool OnlyRequiredArgs) {
1475 unsigned IRArgNo = 0;
1476 bool SwapThisWithSRet = false;
1477 const ABIArgInfo &RetAI = FI.getReturnInfo();
1478
1479 if (RetAI.getKind() == ABIArgInfo::Indirect) {
1480 SwapThisWithSRet = RetAI.isSRetAfterThis();
1481 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1482 }
1483
1484 unsigned ArgNo = 0;
1485 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
1486 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
1487 ++I, ++ArgNo) {
1488 assert(I != FI.arg_end());
1489 QualType ArgType = I->type;
1490 const ABIArgInfo &AI = I->info;
1491 // Collect data about IR arguments corresponding to Clang argument ArgNo.
1492 auto &IRArgs = ArgInfo[ArgNo];
1493
1494 if (AI.getPaddingType())
1495 IRArgs.PaddingArgIndex = IRArgNo++;
1496
1497 switch (AI.getKind()) {
1498 case ABIArgInfo::Extend:
1499 case ABIArgInfo::Direct: {
1500 // FIXME: handle sseregparm someday...
1501 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
1502 if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
1503 IRArgs.NumberOfArgs = STy->getNumElements();
1504 } else {
1505 IRArgs.NumberOfArgs = 1;
1506 }
1507 break;
1508 }
1509 case ABIArgInfo::Indirect:
1510 case ABIArgInfo::IndirectAliased:
1511 IRArgs.NumberOfArgs = 1;
1512 break;
1513 case ABIArgInfo::Ignore:
1514 case ABIArgInfo::InAlloca:
1515 // ignore and inalloca doesn't have matching LLVM parameters.
1516 IRArgs.NumberOfArgs = 0;
1517 break;
1518 case ABIArgInfo::CoerceAndExpand:
1519 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
1520 break;
1521 case ABIArgInfo::Expand:
1522 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
1523 break;
1524 }
1525
1526 if (IRArgs.NumberOfArgs > 0) {
1527 IRArgs.FirstArgIndex = IRArgNo;
1528 IRArgNo += IRArgs.NumberOfArgs;
1529 }
1530
1531 // Skip over the sret parameter when it comes second. We already handled it
1532 // above.
1533 if (IRArgNo == 1 && SwapThisWithSRet)
1534 IRArgNo++;
1535 }
1536 assert(ArgNo == ArgInfo.size());
1537
1538 if (FI.usesInAlloca())
1539 InallocaArgNo = IRArgNo++;
1540
1541 TotalIRArgs = IRArgNo;
1542 }
1543 } // namespace
1544
1545 /***/
1546
ReturnTypeUsesSRet(const CGFunctionInfo & FI)1547 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
1548 const auto &RI = FI.getReturnInfo();
1549 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
1550 }
1551
ReturnSlotInterferesWithArgs(const CGFunctionInfo & FI)1552 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
1553 return ReturnTypeUsesSRet(FI) &&
1554 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
1555 }
1556
ReturnTypeUsesFPRet(QualType ResultType)1557 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
1558 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
1559 switch (BT->getKind()) {
1560 default:
1561 return false;
1562 case BuiltinType::Float:
1563 return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
1564 case BuiltinType::Double:
1565 return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
1566 case BuiltinType::LongDouble:
1567 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
1568 }
1569 }
1570
1571 return false;
1572 }
1573
ReturnTypeUsesFP2Ret(QualType ResultType)1574 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
1575 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
1576 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
1577 if (BT->getKind() == BuiltinType::LongDouble)
1578 return getTarget().useObjCFP2RetForComplexLongDouble();
1579 }
1580 }
1581
1582 return false;
1583 }
1584
GetFunctionType(GlobalDecl GD)1585 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
1586 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
1587 return GetFunctionType(FI);
1588 }
1589
1590 llvm::FunctionType *
GetFunctionType(const CGFunctionInfo & FI)1591 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
1592
1593 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
1594 (void)Inserted;
1595 assert(Inserted && "Recursively being processed?");
1596
1597 llvm::Type *resultType = nullptr;
1598 const ABIArgInfo &retAI = FI.getReturnInfo();
1599 switch (retAI.getKind()) {
1600 case ABIArgInfo::Expand:
1601 case ABIArgInfo::IndirectAliased:
1602 llvm_unreachable("Invalid ABI kind for return argument");
1603
1604 case ABIArgInfo::Extend:
1605 case ABIArgInfo::Direct:
1606 resultType = retAI.getCoerceToType();
1607 break;
1608
1609 case ABIArgInfo::InAlloca:
1610 if (retAI.getInAllocaSRet()) {
1611 // sret things on win32 aren't void, they return the sret pointer.
1612 QualType ret = FI.getReturnType();
1613 llvm::Type *ty = ConvertType(ret);
1614 unsigned addressSpace = Context.getTargetAddressSpace(ret);
1615 resultType = llvm::PointerType::get(ty, addressSpace);
1616 } else {
1617 resultType = llvm::Type::getVoidTy(getLLVMContext());
1618 }
1619 break;
1620
1621 case ABIArgInfo::Indirect:
1622 case ABIArgInfo::Ignore:
1623 resultType = llvm::Type::getVoidTy(getLLVMContext());
1624 break;
1625
1626 case ABIArgInfo::CoerceAndExpand:
1627 resultType = retAI.getUnpaddedCoerceAndExpandType();
1628 break;
1629 }
1630
1631 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
1632 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
1633
1634 // Add type for sret argument.
1635 if (IRFunctionArgs.hasSRetArg()) {
1636 QualType Ret = FI.getReturnType();
1637 llvm::Type *Ty = ConvertType(Ret);
1638 unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
1639 ArgTypes[IRFunctionArgs.getSRetArgNo()] =
1640 llvm::PointerType::get(Ty, AddressSpace);
1641 }
1642
1643 // Add type for inalloca argument.
1644 if (IRFunctionArgs.hasInallocaArg()) {
1645 auto ArgStruct = FI.getArgStruct();
1646 assert(ArgStruct);
1647 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
1648 }
1649
1650 // Add in all of the required arguments.
1651 unsigned ArgNo = 0;
1652 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1653 ie = it + FI.getNumRequiredArgs();
1654 for (; it != ie; ++it, ++ArgNo) {
1655 const ABIArgInfo &ArgInfo = it->info;
1656
1657 // Insert a padding type to ensure proper alignment.
1658 if (IRFunctionArgs.hasPaddingArg(ArgNo))
1659 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
1660 ArgInfo.getPaddingType();
1661
1662 unsigned FirstIRArg, NumIRArgs;
1663 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
1664
1665 switch (ArgInfo.getKind()) {
1666 case ABIArgInfo::Ignore:
1667 case ABIArgInfo::InAlloca:
1668 assert(NumIRArgs == 0);
1669 break;
1670
1671 case ABIArgInfo::Indirect: {
1672 assert(NumIRArgs == 1);
1673 // indirect arguments are always on the stack, which is alloca addr space.
1674 llvm::Type *LTy = ConvertTypeForMem(it->type);
1675 ArgTypes[FirstIRArg] = LTy->getPointerTo(
1676 CGM.getDataLayout().getAllocaAddrSpace());
1677 break;
1678 }
1679 case ABIArgInfo::IndirectAliased: {
1680 assert(NumIRArgs == 1);
1681 llvm::Type *LTy = ConvertTypeForMem(it->type);
1682 ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
1683 break;
1684 }
1685 case ABIArgInfo::Extend:
1686 case ABIArgInfo::Direct: {
1687 // Fast-isel and the optimizer generally like scalar values better than
1688 // FCAs, so we flatten them if this is safe to do for this argument.
1689 llvm::Type *argType = ArgInfo.getCoerceToType();
1690 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
1691 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
1692 assert(NumIRArgs == st->getNumElements());
1693 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
1694 ArgTypes[FirstIRArg + i] = st->getElementType(i);
1695 } else {
1696 assert(NumIRArgs == 1);
1697 ArgTypes[FirstIRArg] = argType;
1698 }
1699 break;
1700 }
1701
1702 case ABIArgInfo::CoerceAndExpand: {
1703 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1704 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
1705 *ArgTypesIter++ = EltTy;
1706 }
1707 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1708 break;
1709 }
1710
1711 case ABIArgInfo::Expand:
1712 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
1713 getExpandedTypes(it->type, ArgTypesIter);
1714 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
1715 break;
1716 }
1717 }
1718
1719 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
1720 assert(Erased && "Not in set?");
1721
1722 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
1723 }
1724
GetFunctionTypeForVTable(GlobalDecl GD)1725 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
1726 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
1727 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
1728
1729 if (!isFuncTypeConvertible(FPT))
1730 return llvm::StructType::get(getLLVMContext());
1731
1732 return GetFunctionType(GD);
1733 }
1734
AddAttributesFromFunctionProtoType(ASTContext & Ctx,llvm::AttrBuilder & FuncAttrs,const FunctionProtoType * FPT)1735 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
1736 llvm::AttrBuilder &FuncAttrs,
1737 const FunctionProtoType *FPT) {
1738 if (!FPT)
1739 return;
1740
1741 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
1742 FPT->isNothrow())
1743 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1744 }
1745
MayDropFunctionReturn(const ASTContext & Context,QualType ReturnType)1746 bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
1747 QualType ReturnType) {
1748 // We can't just discard the return value for a record type with a
1749 // complex destructor or a non-trivially copyable type.
1750 if (const RecordType *RT =
1751 ReturnType.getCanonicalType()->getAs<RecordType>()) {
1752 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1753 return ClassDecl->hasTrivialDestructor();
1754 }
1755 return ReturnType.isTriviallyCopyableType(Context);
1756 }
1757
getDefaultFunctionAttributes(StringRef Name,bool HasOptnone,bool AttrOnCallSite,llvm::AttrBuilder & FuncAttrs)1758 void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
1759 bool HasOptnone,
1760 bool AttrOnCallSite,
1761 llvm::AttrBuilder &FuncAttrs) {
1762 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
1763 if (!HasOptnone) {
1764 if (CodeGenOpts.OptimizeSize)
1765 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
1766 if (CodeGenOpts.OptimizeSize == 2)
1767 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
1768 }
1769
1770 if (CodeGenOpts.DisableRedZone)
1771 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
1772 if (CodeGenOpts.IndirectTlsSegRefs)
1773 FuncAttrs.addAttribute("indirect-tls-seg-refs");
1774 if (CodeGenOpts.NoImplicitFloat)
1775 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
1776
1777 if (AttrOnCallSite) {
1778 // Attributes that should go on the call site only.
1779 if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
1780 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
1781 if (!CodeGenOpts.TrapFuncName.empty())
1782 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
1783 } else {
1784 StringRef FpKind;
1785 switch (CodeGenOpts.getFramePointer()) {
1786 case CodeGenOptions::FramePointerKind::None:
1787 FpKind = "none";
1788 break;
1789 case CodeGenOptions::FramePointerKind::NonLeaf:
1790 FpKind = "non-leaf";
1791 break;
1792 case CodeGenOptions::FramePointerKind::All:
1793 FpKind = "all";
1794 break;
1795 }
1796 FuncAttrs.addAttribute("frame-pointer", FpKind);
1797
1798 if (CodeGenOpts.LessPreciseFPMAD)
1799 FuncAttrs.addAttribute("less-precise-fpmad", "true");
1800
1801 if (CodeGenOpts.NullPointerIsValid)
1802 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
1803
1804 if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
1805 FuncAttrs.addAttribute("denormal-fp-math",
1806 CodeGenOpts.FPDenormalMode.str());
1807 if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
1808 FuncAttrs.addAttribute(
1809 "denormal-fp-math-f32",
1810 CodeGenOpts.FP32DenormalMode.str());
1811 }
1812
1813 if (LangOpts.getFPExceptionMode() == LangOptions::FPE_Ignore)
1814 FuncAttrs.addAttribute("no-trapping-math", "true");
1815
1816 // Strict (compliant) code is the default, so only add this attribute to
1817 // indicate that we are trying to workaround a problem case.
1818 if (!CodeGenOpts.StrictFloatCastOverflow)
1819 FuncAttrs.addAttribute("strict-float-cast-overflow", "false");
1820
1821 // TODO: Are these all needed?
1822 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
1823 if (LangOpts.NoHonorInfs)
1824 FuncAttrs.addAttribute("no-infs-fp-math", "true");
1825 if (LangOpts.NoHonorNaNs)
1826 FuncAttrs.addAttribute("no-nans-fp-math", "true");
1827 if (LangOpts.UnsafeFPMath)
1828 FuncAttrs.addAttribute("unsafe-fp-math", "true");
1829 if (CodeGenOpts.SoftFloat)
1830 FuncAttrs.addAttribute("use-soft-float", "true");
1831 FuncAttrs.addAttribute("stack-protector-buffer-size",
1832 llvm::utostr(CodeGenOpts.SSPBufferSize));
1833 if (LangOpts.NoSignedZero)
1834 FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
1835
1836 // TODO: Reciprocal estimate codegen options should apply to instructions?
1837 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
1838 if (!Recips.empty())
1839 FuncAttrs.addAttribute("reciprocal-estimates",
1840 llvm::join(Recips, ","));
1841
1842 if (!CodeGenOpts.PreferVectorWidth.empty() &&
1843 CodeGenOpts.PreferVectorWidth != "none")
1844 FuncAttrs.addAttribute("prefer-vector-width",
1845 CodeGenOpts.PreferVectorWidth);
1846
1847 if (CodeGenOpts.StackRealignment)
1848 FuncAttrs.addAttribute("stackrealign");
1849 if (CodeGenOpts.Backchain)
1850 FuncAttrs.addAttribute("backchain");
1851 if (CodeGenOpts.EnableSegmentedStacks)
1852 FuncAttrs.addAttribute("split-stack");
1853
1854 if (CodeGenOpts.SpeculativeLoadHardening)
1855 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
1856 }
1857
1858 if (getLangOpts().assumeFunctionsAreConvergent()) {
1859 // Conservatively, mark all functions and calls in CUDA and OpenCL as
1860 // convergent (meaning, they may call an intrinsically convergent op, such
1861 // as __syncthreads() / barrier(), and so can't have certain optimizations
1862 // applied around them). LLVM will remove this attribute where it safely
1863 // can.
1864 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
1865 }
1866
1867 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
1868 // Exceptions aren't supported in CUDA device code.
1869 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
1870 }
1871
1872 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
1873 StringRef Var, Value;
1874 std::tie(Var, Value) = Attr.split('=');
1875 FuncAttrs.addAttribute(Var, Value);
1876 }
1877 }
1878
addDefaultFunctionDefinitionAttributes(llvm::Function & F)1879 void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
1880 llvm::AttrBuilder FuncAttrs;
1881 getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
1882 /* AttrOnCallSite = */ false, FuncAttrs);
1883 // TODO: call GetCPUAndFeaturesAttributes?
1884 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1885 }
1886
addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder & attrs)1887 void CodeGenModule::addDefaultFunctionDefinitionAttributes(
1888 llvm::AttrBuilder &attrs) {
1889 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
1890 /*for call*/ false, attrs);
1891 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
1892 }
1893
addNoBuiltinAttributes(llvm::AttrBuilder & FuncAttrs,const LangOptions & LangOpts,const NoBuiltinAttr * NBA=nullptr)1894 static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
1895 const LangOptions &LangOpts,
1896 const NoBuiltinAttr *NBA = nullptr) {
1897 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
1898 SmallString<32> AttributeName;
1899 AttributeName += "no-builtin-";
1900 AttributeName += BuiltinName;
1901 FuncAttrs.addAttribute(AttributeName);
1902 };
1903
1904 // First, handle the language options passed through -fno-builtin.
1905 if (LangOpts.NoBuiltin) {
1906 // -fno-builtin disables them all.
1907 FuncAttrs.addAttribute("no-builtins");
1908 return;
1909 }
1910
1911 // Then, add attributes for builtins specified through -fno-builtin-<name>.
1912 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
1913
1914 // Now, let's check the __attribute__((no_builtin("...")) attribute added to
1915 // the source.
1916 if (!NBA)
1917 return;
1918
1919 // If there is a wildcard in the builtin names specified through the
1920 // attribute, disable them all.
1921 if (llvm::is_contained(NBA->builtinNames(), "*")) {
1922 FuncAttrs.addAttribute("no-builtins");
1923 return;
1924 }
1925
1926 // And last, add the rest of the builtin names.
1927 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
1928 }
1929
DetermineNoUndef(QualType QTy,CodeGenTypes & Types,const llvm::DataLayout & DL,const ABIArgInfo & AI,bool CheckCoerce=true)1930 static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
1931 const llvm::DataLayout &DL, const ABIArgInfo &AI,
1932 bool CheckCoerce = true) {
1933 llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
1934 if (AI.getKind() == ABIArgInfo::Indirect)
1935 return true;
1936 if (AI.getKind() == ABIArgInfo::Extend)
1937 return true;
1938 if (!DL.typeSizeEqualsStoreSize(Ty))
1939 // TODO: This will result in a modest amount of values not marked noundef
1940 // when they could be. We care about values that *invisibly* contain undef
1941 // bits from the perspective of LLVM IR.
1942 return false;
1943 if (CheckCoerce && AI.canHaveCoerceToType()) {
1944 llvm::Type *CoerceTy = AI.getCoerceToType();
1945 if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
1946 DL.getTypeSizeInBits(Ty)))
1947 // If we're coercing to a type with a greater size than the canonical one,
1948 // we're introducing new undef bits.
1949 // Coercing to a type of smaller or equal size is ok, as we know that
1950 // there's no internal padding (typeSizeEqualsStoreSize).
1951 return false;
1952 }
1953 if (QTy->isExtIntType())
1954 return true;
1955 if (QTy->isReferenceType())
1956 return true;
1957 if (QTy->isNullPtrType())
1958 return false;
1959 if (QTy->isMemberPointerType())
1960 // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
1961 // now, never mark them.
1962 return false;
1963 if (QTy->isScalarType()) {
1964 if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
1965 return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
1966 return true;
1967 }
1968 if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
1969 return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
1970 if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
1971 return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
1972 if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
1973 return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
1974
1975 // TODO: Some structs may be `noundef`, in specific situations.
1976 return false;
1977 }
1978
1979 /// Construct the IR attribute list of a function or call.
1980 ///
1981 /// When adding an attribute, please consider where it should be handled:
1982 ///
1983 /// - getDefaultFunctionAttributes is for attributes that are essentially
1984 /// part of the global target configuration (but perhaps can be
1985 /// overridden on a per-function basis). Adding attributes there
1986 /// will cause them to also be set in frontends that build on Clang's
1987 /// target-configuration logic, as well as for code defined in library
1988 /// modules such as CUDA's libdevice.
1989 ///
1990 /// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
1991 /// and adds declaration-specific, convention-specific, and
1992 /// frontend-specific logic. The last is of particular importance:
1993 /// attributes that restrict how the frontend generates code must be
1994 /// added here rather than getDefaultFunctionAttributes.
1995 ///
ConstructAttributeList(StringRef Name,const CGFunctionInfo & FI,CGCalleeInfo CalleeInfo,llvm::AttributeList & AttrList,unsigned & CallingConv,bool AttrOnCallSite,bool IsThunk)1996 void CodeGenModule::ConstructAttributeList(StringRef Name,
1997 const CGFunctionInfo &FI,
1998 CGCalleeInfo CalleeInfo,
1999 llvm::AttributeList &AttrList,
2000 unsigned &CallingConv,
2001 bool AttrOnCallSite, bool IsThunk) {
2002 llvm::AttrBuilder FuncAttrs;
2003 llvm::AttrBuilder RetAttrs;
2004
2005 // Collect function IR attributes from the CC lowering.
2006 // We'll collect the paramete and result attributes later.
2007 CallingConv = FI.getEffectiveCallingConvention();
2008 if (FI.isNoReturn())
2009 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2010 if (FI.isCmseNSCall())
2011 FuncAttrs.addAttribute("cmse_nonsecure_call");
2012
2013 // Collect function IR attributes from the callee prototype if we have one.
2014 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
2015 CalleeInfo.getCalleeFunctionProtoType());
2016
2017 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
2018
2019 bool HasOptnone = false;
2020 // The NoBuiltinAttr attached to the target FunctionDecl.
2021 const NoBuiltinAttr *NBA = nullptr;
2022
2023 // Collect function IR attributes based on declaration-specific
2024 // information.
2025 // FIXME: handle sseregparm someday...
2026 if (TargetDecl) {
2027 if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
2028 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2029 if (TargetDecl->hasAttr<NoThrowAttr>())
2030 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2031 if (TargetDecl->hasAttr<NoReturnAttr>())
2032 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2033 if (TargetDecl->hasAttr<ColdAttr>())
2034 FuncAttrs.addAttribute(llvm::Attribute::Cold);
2035 if (TargetDecl->hasAttr<HotAttr>())
2036 FuncAttrs.addAttribute(llvm::Attribute::Hot);
2037 if (TargetDecl->hasAttr<NoDuplicateAttr>())
2038 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2039 if (TargetDecl->hasAttr<ConvergentAttr>())
2040 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2041
2042 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2043 AddAttributesFromFunctionProtoType(
2044 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
2045 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2046 // A sane operator new returns a non-aliasing pointer.
2047 auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
2048 if (getCodeGenOpts().AssumeSaneOperatorNew &&
2049 (Kind == OO_New || Kind == OO_Array_New))
2050 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2051 }
2052 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
2053 const bool IsVirtualCall = MD && MD->isVirtual();
2054 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
2055 // virtual function. These attributes are not inherited by overloads.
2056 if (!(AttrOnCallSite && IsVirtualCall)) {
2057 if (Fn->isNoReturn())
2058 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2059 NBA = Fn->getAttr<NoBuiltinAttr>();
2060 }
2061 // Only place nomerge attribute on call sites, never functions. This
2062 // allows it to work on indirect virtual function calls.
2063 if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
2064 FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2065
2066 // Add known guaranteed alignment for allocation functions.
2067 if (unsigned BuiltinID = Fn->getBuiltinID()) {
2068 switch (BuiltinID) {
2069 case Builtin::BIaligned_alloc:
2070 case Builtin::BIcalloc:
2071 case Builtin::BImalloc:
2072 case Builtin::BImemalign:
2073 case Builtin::BIrealloc:
2074 case Builtin::BIstrdup:
2075 case Builtin::BIstrndup:
2076 RetAttrs.addAlignmentAttr(Context.getTargetInfo().getNewAlign() /
2077 Context.getTargetInfo().getCharWidth());
2078 break;
2079 default:
2080 break;
2081 }
2082 }
2083 }
2084
2085 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
2086 if (TargetDecl->hasAttr<ConstAttr>()) {
2087 FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
2088 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2089 // gcc specifies that 'const' functions have greater restrictions than
2090 // 'pure' functions, so they also cannot have infinite loops.
2091 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2092 } else if (TargetDecl->hasAttr<PureAttr>()) {
2093 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
2094 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2095 // gcc specifies that 'pure' functions cannot have infinite loops.
2096 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2097 } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
2098 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
2099 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2100 }
2101 if (TargetDecl->hasAttr<RestrictAttr>())
2102 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2103 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
2104 !CodeGenOpts.NullPointerIsValid)
2105 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2106 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2107 FuncAttrs.addAttribute("no_caller_saved_registers");
2108 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
2109 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2110 if (TargetDecl->hasAttr<LeafAttr>())
2111 FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2112
2113 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
2114 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
2115 Optional<unsigned> NumElemsParam;
2116 if (AllocSize->getNumElemsParam().isValid())
2117 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2118 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2119 NumElemsParam);
2120 }
2121
2122 if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
2123 if (getLangOpts().OpenCLVersion <= 120) {
2124 // OpenCL v1.2 Work groups are always uniform
2125 FuncAttrs.addAttribute("uniform-work-group-size", "true");
2126 } else {
2127 // OpenCL v2.0 Work groups may be whether uniform or not.
2128 // '-cl-uniform-work-group-size' compile option gets a hint
2129 // to the compiler that the global work-size be a multiple of
2130 // the work-group size specified to clEnqueueNDRangeKernel
2131 // (i.e. work groups are uniform).
2132 FuncAttrs.addAttribute("uniform-work-group-size",
2133 llvm::toStringRef(CodeGenOpts.UniformWGSize));
2134 }
2135 }
2136
2137 std::string AssumptionValueStr;
2138 for (AssumptionAttr *AssumptionA :
2139 TargetDecl->specific_attrs<AssumptionAttr>()) {
2140 std::string AS = AssumptionA->getAssumption().str();
2141 if (!AS.empty() && !AssumptionValueStr.empty())
2142 AssumptionValueStr += ",";
2143 AssumptionValueStr += AS;
2144 }
2145
2146 if (!AssumptionValueStr.empty())
2147 FuncAttrs.addAttribute(llvm::AssumptionAttrKey, AssumptionValueStr);
2148 }
2149
2150 // Attach "no-builtins" attributes to:
2151 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
2152 // * definitions: "no-builtins" or "no-builtin-<name>" only.
2153 // The attributes can come from:
2154 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
2155 // * FunctionDecl attributes: __attribute__((no_builtin(...)))
2156 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
2157
2158 // Collect function IR attributes based on global settiings.
2159 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2160
2161 // Override some default IR attributes based on declaration-specific
2162 // information.
2163 if (TargetDecl) {
2164 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
2165 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2166 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
2167 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2168 if (TargetDecl->hasAttr<NoSplitStackAttr>())
2169 FuncAttrs.removeAttribute("split-stack");
2170
2171 // Add NonLazyBind attribute to function declarations when -fno-plt
2172 // is used.
2173 // FIXME: what if we just haven't processed the function definition
2174 // yet, or if it's an external definition like C99 inline?
2175 if (CodeGenOpts.NoPLT) {
2176 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2177 if (!Fn->isDefined() && !AttrOnCallSite) {
2178 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2179 }
2180 }
2181 }
2182 }
2183
2184 // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
2185 // functions with -funique-internal-linkage-names.
2186 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2187 if (isa<FunctionDecl>(TargetDecl)) {
2188 if (this->getFunctionLinkage(CalleeInfo.getCalleeDecl()) ==
2189 llvm::GlobalValue::InternalLinkage)
2190 FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
2191 "selected");
2192 }
2193 }
2194
2195 // Collect non-call-site function IR attributes from declaration-specific
2196 // information.
2197 if (!AttrOnCallSite) {
2198 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
2199 FuncAttrs.addAttribute("cmse_nonsecure_entry");
2200
2201 // Whether tail calls are enabled.
2202 auto shouldDisableTailCalls = [&] {
2203 // Should this be honored in getDefaultFunctionAttributes?
2204 if (CodeGenOpts.DisableTailCalls)
2205 return true;
2206
2207 if (!TargetDecl)
2208 return false;
2209
2210 if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
2211 TargetDecl->hasAttr<AnyX86InterruptAttr>())
2212 return true;
2213
2214 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2215 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2216 if (!BD->doesNotEscape())
2217 return true;
2218 }
2219
2220 return false;
2221 };
2222 if (shouldDisableTailCalls())
2223 FuncAttrs.addAttribute("disable-tail-calls", "true");
2224
2225 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
2226 // handles these separately to set them based on the global defaults.
2227 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
2228 }
2229
2230 // Collect attributes from arguments and return values.
2231 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
2232
2233 QualType RetTy = FI.getReturnType();
2234 const ABIArgInfo &RetAI = FI.getReturnInfo();
2235 const llvm::DataLayout &DL = getDataLayout();
2236
2237 // C++ explicitly makes returning undefined values UB. C's rule only applies
2238 // to used values, so we never mark them noundef for now.
2239 bool HasStrictReturn = getLangOpts().CPlusPlus;
2240 if (TargetDecl) {
2241 if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl))
2242 HasStrictReturn &= !FDecl->isExternC();
2243 else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl))
2244 // Function pointer
2245 HasStrictReturn &= !VDecl->isExternC();
2246 }
2247
2248 // We don't want to be too aggressive with the return checking, unless
2249 // it's explicit in the code opts or we're using an appropriate sanitizer.
2250 // Try to respect what the programmer intended.
2251 HasStrictReturn &= getCodeGenOpts().StrictReturn ||
2252 !MayDropFunctionReturn(getContext(), RetTy) ||
2253 getLangOpts().Sanitize.has(SanitizerKind::Memory) ||
2254 getLangOpts().Sanitize.has(SanitizerKind::Return);
2255
2256 // Determine if the return type could be partially undef
2257 if (CodeGenOpts.EnableNoundefAttrs && HasStrictReturn) {
2258 if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
2259 DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
2260 RetAttrs.addAttribute(llvm::Attribute::NoUndef);
2261 }
2262
2263 switch (RetAI.getKind()) {
2264 case ABIArgInfo::Extend:
2265 if (RetAI.isSignExt())
2266 RetAttrs.addAttribute(llvm::Attribute::SExt);
2267 else
2268 RetAttrs.addAttribute(llvm::Attribute::ZExt);
2269 LLVM_FALLTHROUGH;
2270 case ABIArgInfo::Direct:
2271 if (RetAI.getInReg())
2272 RetAttrs.addAttribute(llvm::Attribute::InReg);
2273 break;
2274 case ABIArgInfo::Ignore:
2275 break;
2276
2277 case ABIArgInfo::InAlloca:
2278 case ABIArgInfo::Indirect: {
2279 // inalloca and sret disable readnone and readonly
2280 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2281 .removeAttribute(llvm::Attribute::ReadNone);
2282 break;
2283 }
2284
2285 case ABIArgInfo::CoerceAndExpand:
2286 break;
2287
2288 case ABIArgInfo::Expand:
2289 case ABIArgInfo::IndirectAliased:
2290 llvm_unreachable("Invalid ABI kind for return argument");
2291 }
2292
2293 if (!IsThunk) {
2294 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2295 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
2296 QualType PTy = RefTy->getPointeeType();
2297 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2298 RetAttrs.addDereferenceableAttr(
2299 getMinimumObjectSize(PTy).getQuantity());
2300 if (getContext().getTargetAddressSpace(PTy) == 0 &&
2301 !CodeGenOpts.NullPointerIsValid)
2302 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2303 if (PTy->isObjectType()) {
2304 llvm::Align Alignment =
2305 getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
2306 RetAttrs.addAlignmentAttr(Alignment);
2307 }
2308 }
2309 }
2310
2311 bool hasUsedSRet = false;
2312 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
2313
2314 // Attach attributes to sret.
2315 if (IRFunctionArgs.hasSRetArg()) {
2316 llvm::AttrBuilder SRETAttrs;
2317 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
2318 hasUsedSRet = true;
2319 if (RetAI.getInReg())
2320 SRETAttrs.addAttribute(llvm::Attribute::InReg);
2321 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
2322 ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
2323 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
2324 }
2325
2326 // Attach attributes to inalloca argument.
2327 if (IRFunctionArgs.hasInallocaArg()) {
2328 llvm::AttrBuilder Attrs;
2329 Attrs.addInAllocaAttr(FI.getArgStruct());
2330 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
2331 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2332 }
2333
2334 // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
2335 // unless this is a thunk function.
2336 // FIXME: fix this properly, https://reviews.llvm.org/D100388
2337 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
2338 !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
2339 auto IRArgs = IRFunctionArgs.getIRArgs(0);
2340
2341 assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
2342
2343 llvm::AttrBuilder Attrs;
2344
2345 QualType ThisTy =
2346 FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
2347
2348 if (!CodeGenOpts.NullPointerIsValid &&
2349 getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
2350 Attrs.addAttribute(llvm::Attribute::NonNull);
2351 Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
2352 } else {
2353 // FIXME dereferenceable should be correct here, regardless of
2354 // NullPointerIsValid. However, dereferenceable currently does not always
2355 // respect NullPointerIsValid and may imply nonnull and break the program.
2356 // See https://reviews.llvm.org/D66618 for discussions.
2357 Attrs.addDereferenceableOrNullAttr(
2358 getMinimumObjectSize(
2359 FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
2360 .getQuantity());
2361 }
2362
2363 llvm::Align Alignment =
2364 getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
2365 /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
2366 .getAsAlign();
2367 Attrs.addAlignmentAttr(Alignment);
2368
2369 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
2370 }
2371
2372 unsigned ArgNo = 0;
2373 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
2374 E = FI.arg_end();
2375 I != E; ++I, ++ArgNo) {
2376 QualType ParamType = I->type;
2377 const ABIArgInfo &AI = I->info;
2378 llvm::AttrBuilder Attrs;
2379
2380 // Add attribute for padding argument, if necessary.
2381 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
2382 if (AI.getPaddingInReg()) {
2383 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2384 llvm::AttributeSet::get(
2385 getLLVMContext(),
2386 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg));
2387 }
2388 }
2389
2390 // Decide whether the argument we're handling could be partially undef
2391 bool ArgNoUndef = DetermineNoUndef(ParamType, getTypes(), DL, AI);
2392 if (CodeGenOpts.EnableNoundefAttrs && ArgNoUndef)
2393 Attrs.addAttribute(llvm::Attribute::NoUndef);
2394
2395 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
2396 // have the corresponding parameter variable. It doesn't make
2397 // sense to do it here because parameters are so messed up.
2398 switch (AI.getKind()) {
2399 case ABIArgInfo::Extend:
2400 if (AI.isSignExt())
2401 Attrs.addAttribute(llvm::Attribute::SExt);
2402 else
2403 Attrs.addAttribute(llvm::Attribute::ZExt);
2404 LLVM_FALLTHROUGH;
2405 case ABIArgInfo::Direct:
2406 if (ArgNo == 0 && FI.isChainCall())
2407 Attrs.addAttribute(llvm::Attribute::Nest);
2408 else if (AI.getInReg())
2409 Attrs.addAttribute(llvm::Attribute::InReg);
2410 Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
2411 break;
2412
2413 case ABIArgInfo::Indirect: {
2414 if (AI.getInReg())
2415 Attrs.addAttribute(llvm::Attribute::InReg);
2416
2417 if (AI.getIndirectByVal())
2418 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
2419
2420 auto *Decl = ParamType->getAsRecordDecl();
2421 if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
2422 Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
2423 // When calling the function, the pointer passed in will be the only
2424 // reference to the underlying object. Mark it accordingly.
2425 Attrs.addAttribute(llvm::Attribute::NoAlias);
2426
2427 // TODO: We could add the byref attribute if not byval, but it would
2428 // require updating many testcases.
2429
2430 CharUnits Align = AI.getIndirectAlign();
2431
2432 // In a byval argument, it is important that the required
2433 // alignment of the type is honored, as LLVM might be creating a
2434 // *new* stack object, and needs to know what alignment to give
2435 // it. (Sometimes it can deduce a sensible alignment on its own,
2436 // but not if clang decides it must emit a packed struct, or the
2437 // user specifies increased alignment requirements.)
2438 //
2439 // This is different from indirect *not* byval, where the object
2440 // exists already, and the align attribute is purely
2441 // informative.
2442 assert(!Align.isZero());
2443
2444 // For now, only add this when we have a byval argument.
2445 // TODO: be less lazy about updating test cases.
2446 if (AI.getIndirectByVal())
2447 Attrs.addAlignmentAttr(Align.getQuantity());
2448
2449 // byval disables readnone and readonly.
2450 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2451 .removeAttribute(llvm::Attribute::ReadNone);
2452
2453 break;
2454 }
2455 case ABIArgInfo::IndirectAliased: {
2456 CharUnits Align = AI.getIndirectAlign();
2457 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
2458 Attrs.addAlignmentAttr(Align.getQuantity());
2459 break;
2460 }
2461 case ABIArgInfo::Ignore:
2462 case ABIArgInfo::Expand:
2463 case ABIArgInfo::CoerceAndExpand:
2464 break;
2465
2466 case ABIArgInfo::InAlloca:
2467 // inalloca disables readnone and readonly.
2468 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
2469 .removeAttribute(llvm::Attribute::ReadNone);
2470 continue;
2471 }
2472
2473 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
2474 QualType PTy = RefTy->getPointeeType();
2475 if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
2476 Attrs.addDereferenceableAttr(
2477 getMinimumObjectSize(PTy).getQuantity());
2478 if (getContext().getTargetAddressSpace(PTy) == 0 &&
2479 !CodeGenOpts.NullPointerIsValid)
2480 Attrs.addAttribute(llvm::Attribute::NonNull);
2481 if (PTy->isObjectType()) {
2482 llvm::Align Alignment =
2483 getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
2484 Attrs.addAlignmentAttr(Alignment);
2485 }
2486 }
2487
2488 switch (FI.getExtParameterInfo(ArgNo).getABI()) {
2489 case ParameterABI::Ordinary:
2490 break;
2491
2492 case ParameterABI::SwiftIndirectResult: {
2493 // Add 'sret' if we haven't already used it for something, but
2494 // only if the result is void.
2495 if (!hasUsedSRet && RetTy->isVoidType()) {
2496 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
2497 hasUsedSRet = true;
2498 }
2499
2500 // Add 'noalias' in either case.
2501 Attrs.addAttribute(llvm::Attribute::NoAlias);
2502
2503 // Add 'dereferenceable' and 'alignment'.
2504 auto PTy = ParamType->getPointeeType();
2505 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
2506 auto info = getContext().getTypeInfoInChars(PTy);
2507 Attrs.addDereferenceableAttr(info.Width.getQuantity());
2508 Attrs.addAlignmentAttr(info.Align.getAsAlign());
2509 }
2510 break;
2511 }
2512
2513 case ParameterABI::SwiftErrorResult:
2514 Attrs.addAttribute(llvm::Attribute::SwiftError);
2515 break;
2516
2517 case ParameterABI::SwiftContext:
2518 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
2519 break;
2520
2521 case ParameterABI::SwiftAsyncContext:
2522 Attrs.addAttribute(llvm::Attribute::SwiftAsync);
2523 break;
2524 }
2525
2526 if (FI.getExtParameterInfo(ArgNo).isNoEscape())
2527 Attrs.addAttribute(llvm::Attribute::NoCapture);
2528
2529 if (Attrs.hasAttributes()) {
2530 unsigned FirstIRArg, NumIRArgs;
2531 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2532 for (unsigned i = 0; i < NumIRArgs; i++)
2533 ArgAttrs[FirstIRArg + i] =
2534 llvm::AttributeSet::get(getLLVMContext(), Attrs);
2535 }
2536 }
2537 assert(ArgNo == FI.arg_size());
2538
2539 AttrList = llvm::AttributeList::get(
2540 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
2541 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
2542 }
2543
2544 /// An argument came in as a promoted argument; demote it back to its
2545 /// declared type.
emitArgumentDemotion(CodeGenFunction & CGF,const VarDecl * var,llvm::Value * value)2546 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
2547 const VarDecl *var,
2548 llvm::Value *value) {
2549 llvm::Type *varType = CGF.ConvertType(var->getType());
2550
2551 // This can happen with promotions that actually don't change the
2552 // underlying type, like the enum promotions.
2553 if (value->getType() == varType) return value;
2554
2555 assert((varType->isIntegerTy() || varType->isFloatingPointTy())
2556 && "unexpected promotion type");
2557
2558 if (isa<llvm::IntegerType>(varType))
2559 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
2560
2561 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
2562 }
2563
2564 /// Returns the attribute (either parameter attribute, or function
2565 /// attribute), which declares argument ArgNo to be non-null.
getNonNullAttr(const Decl * FD,const ParmVarDecl * PVD,QualType ArgType,unsigned ArgNo)2566 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
2567 QualType ArgType, unsigned ArgNo) {
2568 // FIXME: __attribute__((nonnull)) can also be applied to:
2569 // - references to pointers, where the pointee is known to be
2570 // nonnull (apparently a Clang extension)
2571 // - transparent unions containing pointers
2572 // In the former case, LLVM IR cannot represent the constraint. In
2573 // the latter case, we have no guarantee that the transparent union
2574 // is in fact passed as a pointer.
2575 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
2576 return nullptr;
2577 // First, check attribute on parameter itself.
2578 if (PVD) {
2579 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
2580 return ParmNNAttr;
2581 }
2582 // Check function attributes.
2583 if (!FD)
2584 return nullptr;
2585 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
2586 if (NNAttr->isNonNull(ArgNo))
2587 return NNAttr;
2588 }
2589 return nullptr;
2590 }
2591
2592 namespace {
2593 struct CopyBackSwiftError final : EHScopeStack::Cleanup {
2594 Address Temp;
2595 Address Arg;
CopyBackSwiftError__anone30e957c0811::CopyBackSwiftError2596 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
Emit__anone30e957c0811::CopyBackSwiftError2597 void Emit(CodeGenFunction &CGF, Flags flags) override {
2598 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
2599 CGF.Builder.CreateStore(errorValue, Arg);
2600 }
2601 };
2602 }
2603
EmitFunctionProlog(const CGFunctionInfo & FI,llvm::Function * Fn,const FunctionArgList & Args)2604 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
2605 llvm::Function *Fn,
2606 const FunctionArgList &Args) {
2607 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
2608 // Naked functions don't have prologues.
2609 return;
2610
2611 // If this is an implicit-return-zero function, go ahead and
2612 // initialize the return value. TODO: it might be nice to have
2613 // a more general mechanism for this that didn't require synthesized
2614 // return statements.
2615 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
2616 if (FD->hasImplicitReturnZero()) {
2617 QualType RetTy = FD->getReturnType().getUnqualifiedType();
2618 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
2619 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
2620 Builder.CreateStore(Zero, ReturnValue);
2621 }
2622 }
2623
2624 // FIXME: We no longer need the types from FunctionArgList; lift up and
2625 // simplify.
2626
2627 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
2628 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
2629
2630 // If we're using inalloca, all the memory arguments are GEPs off of the last
2631 // parameter, which is a pointer to the complete memory area.
2632 Address ArgStruct = Address::invalid();
2633 if (IRFunctionArgs.hasInallocaArg()) {
2634 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
2635 FI.getArgStructAlignment());
2636
2637 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
2638 }
2639
2640 // Name the struct return parameter.
2641 if (IRFunctionArgs.hasSRetArg()) {
2642 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
2643 AI->setName("agg.result");
2644 AI->addAttr(llvm::Attribute::NoAlias);
2645 }
2646
2647 // Track if we received the parameter as a pointer (indirect, byval, or
2648 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
2649 // into a local alloca for us.
2650 SmallVector<ParamValue, 16> ArgVals;
2651 ArgVals.reserve(Args.size());
2652
2653 // Create a pointer value for every parameter declaration. This usually
2654 // entails copying one or more LLVM IR arguments into an alloca. Don't push
2655 // any cleanups or do anything that might unwind. We do that separately, so
2656 // we can push the cleanups in the correct order for the ABI.
2657 assert(FI.arg_size() == Args.size() &&
2658 "Mismatch between function signature & arguments.");
2659 unsigned ArgNo = 0;
2660 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
2661 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
2662 i != e; ++i, ++info_it, ++ArgNo) {
2663 const VarDecl *Arg = *i;
2664 const ABIArgInfo &ArgI = info_it->info;
2665
2666 bool isPromoted =
2667 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
2668 // We are converting from ABIArgInfo type to VarDecl type directly, unless
2669 // the parameter is promoted. In this case we convert to
2670 // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
2671 QualType Ty = isPromoted ? info_it->type : Arg->getType();
2672 assert(hasScalarEvaluationKind(Ty) ==
2673 hasScalarEvaluationKind(Arg->getType()));
2674
2675 unsigned FirstIRArg, NumIRArgs;
2676 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2677
2678 switch (ArgI.getKind()) {
2679 case ABIArgInfo::InAlloca: {
2680 assert(NumIRArgs == 0);
2681 auto FieldIndex = ArgI.getInAllocaFieldIndex();
2682 Address V =
2683 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
2684 if (ArgI.getInAllocaIndirect())
2685 V = Address(Builder.CreateLoad(V),
2686 getContext().getTypeAlignInChars(Ty));
2687 ArgVals.push_back(ParamValue::forIndirect(V));
2688 break;
2689 }
2690
2691 case ABIArgInfo::Indirect:
2692 case ABIArgInfo::IndirectAliased: {
2693 assert(NumIRArgs == 1);
2694 Address ParamAddr =
2695 Address(Fn->getArg(FirstIRArg), ArgI.getIndirectAlign());
2696
2697 if (!hasScalarEvaluationKind(Ty)) {
2698 // Aggregates and complex variables are accessed by reference. All we
2699 // need to do is realign the value, if requested. Also, if the address
2700 // may be aliased, copy it to ensure that the parameter variable is
2701 // mutable and has a unique adress, as C requires.
2702 Address V = ParamAddr;
2703 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
2704 Address AlignedTemp = CreateMemTemp(Ty, "coerce");
2705
2706 // Copy from the incoming argument pointer to the temporary with the
2707 // appropriate alignment.
2708 //
2709 // FIXME: We should have a common utility for generating an aggregate
2710 // copy.
2711 CharUnits Size = getContext().getTypeSizeInChars(Ty);
2712 Builder.CreateMemCpy(
2713 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
2714 ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
2715 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
2716 V = AlignedTemp;
2717 }
2718 ArgVals.push_back(ParamValue::forIndirect(V));
2719 } else {
2720 // Load scalar value from indirect argument.
2721 llvm::Value *V =
2722 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
2723
2724 if (isPromoted)
2725 V = emitArgumentDemotion(*this, Arg, V);
2726 ArgVals.push_back(ParamValue::forDirect(V));
2727 }
2728 break;
2729 }
2730
2731 case ABIArgInfo::Extend:
2732 case ABIArgInfo::Direct: {
2733 auto AI = Fn->getArg(FirstIRArg);
2734 llvm::Type *LTy = ConvertType(Arg->getType());
2735
2736 // Prepare parameter attributes. So far, only attributes for pointer
2737 // parameters are prepared. See
2738 // http://llvm.org/docs/LangRef.html#paramattrs.
2739 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
2740 ArgI.getCoerceToType()->isPointerTy()) {
2741 assert(NumIRArgs == 1);
2742
2743 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
2744 // Set `nonnull` attribute if any.
2745 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
2746 PVD->getFunctionScopeIndex()) &&
2747 !CGM.getCodeGenOpts().NullPointerIsValid)
2748 AI->addAttr(llvm::Attribute::NonNull);
2749
2750 QualType OTy = PVD->getOriginalType();
2751 if (const auto *ArrTy =
2752 getContext().getAsConstantArrayType(OTy)) {
2753 // A C99 array parameter declaration with the static keyword also
2754 // indicates dereferenceability, and if the size is constant we can
2755 // use the dereferenceable attribute (which requires the size in
2756 // bytes).
2757 if (ArrTy->getSizeModifier() == ArrayType::Static) {
2758 QualType ETy = ArrTy->getElementType();
2759 llvm::Align Alignment =
2760 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2761 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2762 uint64_t ArrSize = ArrTy->getSize().getZExtValue();
2763 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
2764 ArrSize) {
2765 llvm::AttrBuilder Attrs;
2766 Attrs.addDereferenceableAttr(
2767 getContext().getTypeSizeInChars(ETy).getQuantity() *
2768 ArrSize);
2769 AI->addAttrs(Attrs);
2770 } else if (getContext().getTargetInfo().getNullPointerValue(
2771 ETy.getAddressSpace()) == 0 &&
2772 !CGM.getCodeGenOpts().NullPointerIsValid) {
2773 AI->addAttr(llvm::Attribute::NonNull);
2774 }
2775 }
2776 } else if (const auto *ArrTy =
2777 getContext().getAsVariableArrayType(OTy)) {
2778 // For C99 VLAs with the static keyword, we don't know the size so
2779 // we can't use the dereferenceable attribute, but in addrspace(0)
2780 // we know that it must be nonnull.
2781 if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
2782 QualType ETy = ArrTy->getElementType();
2783 llvm::Align Alignment =
2784 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
2785 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment));
2786 if (!getContext().getTargetAddressSpace(ETy) &&
2787 !CGM.getCodeGenOpts().NullPointerIsValid)
2788 AI->addAttr(llvm::Attribute::NonNull);
2789 }
2790 }
2791
2792 // Set `align` attribute if any.
2793 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
2794 if (!AVAttr)
2795 if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
2796 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
2797 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
2798 // If alignment-assumption sanitizer is enabled, we do *not* add
2799 // alignment attribute here, but emit normal alignment assumption,
2800 // so the UBSAN check could function.
2801 llvm::ConstantInt *AlignmentCI =
2802 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
2803 unsigned AlignmentInt =
2804 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
2805 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
2806 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
2807 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(
2808 llvm::Align(AlignmentInt)));
2809 }
2810 }
2811 }
2812
2813 // Set 'noalias' if an argument type has the `restrict` qualifier.
2814 if (Arg->getType().isRestrictQualified())
2815 AI->addAttr(llvm::Attribute::NoAlias);
2816 }
2817
2818 // Prepare the argument value. If we have the trivial case, handle it
2819 // with no muss and fuss.
2820 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
2821 ArgI.getCoerceToType() == ConvertType(Ty) &&
2822 ArgI.getDirectOffset() == 0) {
2823 assert(NumIRArgs == 1);
2824
2825 // LLVM expects swifterror parameters to be used in very restricted
2826 // ways. Copy the value into a less-restricted temporary.
2827 llvm::Value *V = AI;
2828 if (FI.getExtParameterInfo(ArgNo).getABI()
2829 == ParameterABI::SwiftErrorResult) {
2830 QualType pointeeTy = Ty->getPointeeType();
2831 assert(pointeeTy->isPointerType());
2832 Address temp =
2833 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
2834 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
2835 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
2836 Builder.CreateStore(incomingErrorValue, temp);
2837 V = temp.getPointer();
2838
2839 // Push a cleanup to copy the value back at the end of the function.
2840 // The convention does not guarantee that the value will be written
2841 // back if the function exits with an unwind exception.
2842 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
2843 }
2844
2845 // Ensure the argument is the correct type.
2846 if (V->getType() != ArgI.getCoerceToType())
2847 V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
2848
2849 if (isPromoted)
2850 V = emitArgumentDemotion(*this, Arg, V);
2851
2852 // Because of merging of function types from multiple decls it is
2853 // possible for the type of an argument to not match the corresponding
2854 // type in the function type. Since we are codegening the callee
2855 // in here, add a cast to the argument type.
2856 llvm::Type *LTy = ConvertType(Arg->getType());
2857 if (V->getType() != LTy)
2858 V = Builder.CreateBitCast(V, LTy);
2859
2860 ArgVals.push_back(ParamValue::forDirect(V));
2861 break;
2862 }
2863
2864 // VLST arguments are coerced to VLATs at the function boundary for
2865 // ABI consistency. If this is a VLST that was coerced to
2866 // a VLAT at the function boundary and the types match up, use
2867 // llvm.experimental.vector.extract to convert back to the original
2868 // VLST.
2869 if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
2870 auto *Coerced = Fn->getArg(FirstIRArg);
2871 if (auto *VecTyFrom =
2872 dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
2873 if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
2874 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2875
2876 assert(NumIRArgs == 1);
2877 Coerced->setName(Arg->getName() + ".coerce");
2878 ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
2879 VecTyTo, Coerced, Zero, "castFixedSve")));
2880 break;
2881 }
2882 }
2883 }
2884
2885 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
2886 Arg->getName());
2887
2888 // Pointer to store into.
2889 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
2890
2891 // Fast-isel and the optimizer generally like scalar values better than
2892 // FCAs, so we flatten them if this is safe to do for this argument.
2893 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
2894 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
2895 STy->getNumElements() > 1) {
2896 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
2897 llvm::Type *DstTy = Ptr.getElementType();
2898 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
2899
2900 Address AddrToStoreInto = Address::invalid();
2901 if (SrcSize <= DstSize) {
2902 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
2903 } else {
2904 AddrToStoreInto =
2905 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
2906 }
2907
2908 assert(STy->getNumElements() == NumIRArgs);
2909 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2910 auto AI = Fn->getArg(FirstIRArg + i);
2911 AI->setName(Arg->getName() + ".coerce" + Twine(i));
2912 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
2913 Builder.CreateStore(AI, EltPtr);
2914 }
2915
2916 if (SrcSize > DstSize) {
2917 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
2918 }
2919
2920 } else {
2921 // Simple case, just do a coerced store of the argument into the alloca.
2922 assert(NumIRArgs == 1);
2923 auto AI = Fn->getArg(FirstIRArg);
2924 AI->setName(Arg->getName() + ".coerce");
2925 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
2926 }
2927
2928 // Match to what EmitParmDecl is expecting for this type.
2929 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
2930 llvm::Value *V =
2931 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
2932 if (isPromoted)
2933 V = emitArgumentDemotion(*this, Arg, V);
2934 ArgVals.push_back(ParamValue::forDirect(V));
2935 } else {
2936 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2937 }
2938 break;
2939 }
2940
2941 case ABIArgInfo::CoerceAndExpand: {
2942 // Reconstruct into a temporary.
2943 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2944 ArgVals.push_back(ParamValue::forIndirect(alloca));
2945
2946 auto coercionType = ArgI.getCoerceAndExpandType();
2947 alloca = Builder.CreateElementBitCast(alloca, coercionType);
2948
2949 unsigned argIndex = FirstIRArg;
2950 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
2951 llvm::Type *eltType = coercionType->getElementType(i);
2952 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
2953 continue;
2954
2955 auto eltAddr = Builder.CreateStructGEP(alloca, i);
2956 auto elt = Fn->getArg(argIndex++);
2957 Builder.CreateStore(elt, eltAddr);
2958 }
2959 assert(argIndex == FirstIRArg + NumIRArgs);
2960 break;
2961 }
2962
2963 case ABIArgInfo::Expand: {
2964 // If this structure was expanded into multiple arguments then
2965 // we need to create a temporary and reconstruct it from the
2966 // arguments.
2967 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
2968 LValue LV = MakeAddrLValue(Alloca, Ty);
2969 ArgVals.push_back(ParamValue::forIndirect(Alloca));
2970
2971 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
2972 ExpandTypeFromArgs(Ty, LV, FnArgIter);
2973 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
2974 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
2975 auto AI = Fn->getArg(FirstIRArg + i);
2976 AI->setName(Arg->getName() + "." + Twine(i));
2977 }
2978 break;
2979 }
2980
2981 case ABIArgInfo::Ignore:
2982 assert(NumIRArgs == 0);
2983 // Initialize the local variable appropriately.
2984 if (!hasScalarEvaluationKind(Ty)) {
2985 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
2986 } else {
2987 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
2988 ArgVals.push_back(ParamValue::forDirect(U));
2989 }
2990 break;
2991 }
2992 }
2993
2994 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
2995 for (int I = Args.size() - 1; I >= 0; --I)
2996 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
2997 } else {
2998 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2999 EmitParmDecl(*Args[I], ArgVals[I], I + 1);
3000 }
3001 }
3002
eraseUnusedBitCasts(llvm::Instruction * insn)3003 static void eraseUnusedBitCasts(llvm::Instruction *insn) {
3004 while (insn->use_empty()) {
3005 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3006 if (!bitcast) return;
3007
3008 // This is "safe" because we would have used a ConstantExpr otherwise.
3009 insn = cast<llvm::Instruction>(bitcast->getOperand(0));
3010 bitcast->eraseFromParent();
3011 }
3012 }
3013
3014 /// Try to emit a fused autorelease of a return result.
tryEmitFusedAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)3015 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
3016 llvm::Value *result) {
3017 // We must be immediately followed the cast.
3018 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
3019 if (BB->empty()) return nullptr;
3020 if (&BB->back() != result) return nullptr;
3021
3022 llvm::Type *resultType = result->getType();
3023
3024 // result is in a BasicBlock and is therefore an Instruction.
3025 llvm::Instruction *generator = cast<llvm::Instruction>(result);
3026
3027 SmallVector<llvm::Instruction *, 4> InstsToKill;
3028
3029 // Look for:
3030 // %generator = bitcast %type1* %generator2 to %type2*
3031 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3032 // We would have emitted this as a constant if the operand weren't
3033 // an Instruction.
3034 generator = cast<llvm::Instruction>(bitcast->getOperand(0));
3035
3036 // Require the generator to be immediately followed by the cast.
3037 if (generator->getNextNode() != bitcast)
3038 return nullptr;
3039
3040 InstsToKill.push_back(bitcast);
3041 }
3042
3043 // Look for:
3044 // %generator = call i8* @objc_retain(i8* %originalResult)
3045 // or
3046 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
3047 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3048 if (!call) return nullptr;
3049
3050 bool doRetainAutorelease;
3051
3052 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
3053 doRetainAutorelease = true;
3054 } else if (call->getCalledOperand() ==
3055 CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
3056 doRetainAutorelease = false;
3057
3058 // If we emitted an assembly marker for this call (and the
3059 // ARCEntrypoints field should have been set if so), go looking
3060 // for that call. If we can't find it, we can't do this
3061 // optimization. But it should always be the immediately previous
3062 // instruction, unless we needed bitcasts around the call.
3063 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
3064 llvm::Instruction *prev = call->getPrevNode();
3065 assert(prev);
3066 if (isa<llvm::BitCastInst>(prev)) {
3067 prev = prev->getPrevNode();
3068 assert(prev);
3069 }
3070 assert(isa<llvm::CallInst>(prev));
3071 assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
3072 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
3073 InstsToKill.push_back(prev);
3074 }
3075 } else {
3076 return nullptr;
3077 }
3078
3079 result = call->getArgOperand(0);
3080 InstsToKill.push_back(call);
3081
3082 // Keep killing bitcasts, for sanity. Note that we no longer care
3083 // about precise ordering as long as there's exactly one use.
3084 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
3085 if (!bitcast->hasOneUse()) break;
3086 InstsToKill.push_back(bitcast);
3087 result = bitcast->getOperand(0);
3088 }
3089
3090 // Delete all the unnecessary instructions, from latest to earliest.
3091 for (auto *I : InstsToKill)
3092 I->eraseFromParent();
3093
3094 // Do the fused retain/autorelease if we were asked to.
3095 if (doRetainAutorelease)
3096 result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
3097
3098 // Cast back to the result type.
3099 return CGF.Builder.CreateBitCast(result, resultType);
3100 }
3101
3102 /// If this is a +1 of the value of an immutable 'self', remove it.
tryRemoveRetainOfSelf(CodeGenFunction & CGF,llvm::Value * result)3103 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
3104 llvm::Value *result) {
3105 // This is only applicable to a method with an immutable 'self'.
3106 const ObjCMethodDecl *method =
3107 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
3108 if (!method) return nullptr;
3109 const VarDecl *self = method->getSelfDecl();
3110 if (!self->getType().isConstQualified()) return nullptr;
3111
3112 // Look for a retain call.
3113 llvm::CallInst *retainCall =
3114 dyn_cast<llvm::CallInst>(result->stripPointerCasts());
3115 if (!retainCall || retainCall->getCalledOperand() !=
3116 CGF.CGM.getObjCEntrypoints().objc_retain)
3117 return nullptr;
3118
3119 // Look for an ordinary load of 'self'.
3120 llvm::Value *retainedValue = retainCall->getArgOperand(0);
3121 llvm::LoadInst *load =
3122 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
3123 if (!load || load->isAtomic() || load->isVolatile() ||
3124 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
3125 return nullptr;
3126
3127 // Okay! Burn it all down. This relies for correctness on the
3128 // assumption that the retain is emitted as part of the return and
3129 // that thereafter everything is used "linearly".
3130 llvm::Type *resultType = result->getType();
3131 eraseUnusedBitCasts(cast<llvm::Instruction>(result));
3132 assert(retainCall->use_empty());
3133 retainCall->eraseFromParent();
3134 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
3135
3136 return CGF.Builder.CreateBitCast(load, resultType);
3137 }
3138
3139 /// Emit an ARC autorelease of the result of a function.
3140 ///
3141 /// \return the value to actually return from the function
emitAutoreleaseOfResult(CodeGenFunction & CGF,llvm::Value * result)3142 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
3143 llvm::Value *result) {
3144 // If we're returning 'self', kill the initial retain. This is a
3145 // heuristic attempt to "encourage correctness" in the really unfortunate
3146 // case where we have a return of self during a dealloc and we desperately
3147 // need to avoid the possible autorelease.
3148 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
3149 return self;
3150
3151 // At -O0, try to emit a fused retain/autorelease.
3152 if (CGF.shouldUseFusedARCCalls())
3153 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
3154 return fused;
3155
3156 return CGF.EmitARCAutoreleaseReturnValue(result);
3157 }
3158
3159 /// Heuristically search for a dominating store to the return-value slot.
findDominatingStoreToReturnValue(CodeGenFunction & CGF)3160 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
3161 // Check if a User is a store which pointerOperand is the ReturnValue.
3162 // We are looking for stores to the ReturnValue, not for stores of the
3163 // ReturnValue to some other location.
3164 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
3165 auto *SI = dyn_cast<llvm::StoreInst>(U);
3166 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
3167 return nullptr;
3168 // These aren't actually possible for non-coerced returns, and we
3169 // only care about non-coerced returns on this code path.
3170 assert(!SI->isAtomic() && !SI->isVolatile());
3171 return SI;
3172 };
3173 // If there are multiple uses of the return-value slot, just check
3174 // for something immediately preceding the IP. Sometimes this can
3175 // happen with how we generate implicit-returns; it can also happen
3176 // with noreturn cleanups.
3177 if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
3178 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3179 if (IP->empty()) return nullptr;
3180 llvm::Instruction *I = &IP->back();
3181
3182 // Skip lifetime markers
3183 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
3184 IE = IP->rend();
3185 II != IE; ++II) {
3186 if (llvm::IntrinsicInst *Intrinsic =
3187 dyn_cast<llvm::IntrinsicInst>(&*II)) {
3188 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
3189 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
3190 ++II;
3191 if (II == IE)
3192 break;
3193 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
3194 continue;
3195 }
3196 }
3197 I = &*II;
3198 break;
3199 }
3200
3201 return GetStoreIfValid(I);
3202 }
3203
3204 llvm::StoreInst *store =
3205 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
3206 if (!store) return nullptr;
3207
3208 // Now do a first-and-dirty dominance check: just walk up the
3209 // single-predecessors chain from the current insertion point.
3210 llvm::BasicBlock *StoreBB = store->getParent();
3211 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
3212 while (IP != StoreBB) {
3213 if (!(IP = IP->getSinglePredecessor()))
3214 return nullptr;
3215 }
3216
3217 // Okay, the store's basic block dominates the insertion point; we
3218 // can do our thing.
3219 return store;
3220 }
3221
3222 // Helper functions for EmitCMSEClearRecord
3223
3224 // Set the bits corresponding to a field having width `BitWidth` and located at
3225 // offset `BitOffset` (from the least significant bit) within a storage unit of
3226 // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
3227 // Use little-endian layout, i.e.`Bits[0]` is the LSB.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int BitOffset,int BitWidth,int CharWidth)3228 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
3229 int BitWidth, int CharWidth) {
3230 assert(CharWidth <= 64);
3231 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
3232
3233 int Pos = 0;
3234 if (BitOffset >= CharWidth) {
3235 Pos += BitOffset / CharWidth;
3236 BitOffset = BitOffset % CharWidth;
3237 }
3238
3239 const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
3240 if (BitOffset + BitWidth >= CharWidth) {
3241 Bits[Pos++] |= (Used << BitOffset) & Used;
3242 BitWidth -= CharWidth - BitOffset;
3243 BitOffset = 0;
3244 }
3245
3246 while (BitWidth >= CharWidth) {
3247 Bits[Pos++] = Used;
3248 BitWidth -= CharWidth;
3249 }
3250
3251 if (BitWidth > 0)
3252 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
3253 }
3254
3255 // Set the bits corresponding to a field having width `BitWidth` and located at
3256 // offset `BitOffset` (from the least significant bit) within a storage unit of
3257 // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
3258 // `Bits` corresponds to one target byte. Use target endian layout.
setBitRange(SmallVectorImpl<uint64_t> & Bits,int StorageOffset,int StorageSize,int BitOffset,int BitWidth,int CharWidth,bool BigEndian)3259 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
3260 int StorageSize, int BitOffset, int BitWidth,
3261 int CharWidth, bool BigEndian) {
3262
3263 SmallVector<uint64_t, 8> TmpBits(StorageSize);
3264 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
3265
3266 if (BigEndian)
3267 std::reverse(TmpBits.begin(), TmpBits.end());
3268
3269 for (uint64_t V : TmpBits)
3270 Bits[StorageOffset++] |= V;
3271 }
3272
3273 static void setUsedBits(CodeGenModule &, QualType, int,
3274 SmallVectorImpl<uint64_t> &);
3275
3276 // Set the bits in `Bits`, which correspond to the value representations of
3277 // the actual members of the record type `RTy`. Note that this function does
3278 // not handle base classes, virtual tables, etc, since they cannot happen in
3279 // CMSE function arguments or return. The bit mask corresponds to the target
3280 // memory layout, i.e. it's endian dependent.
setUsedBits(CodeGenModule & CGM,const RecordType * RTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3281 static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
3282 SmallVectorImpl<uint64_t> &Bits) {
3283 ASTContext &Context = CGM.getContext();
3284 int CharWidth = Context.getCharWidth();
3285 const RecordDecl *RD = RTy->getDecl()->getDefinition();
3286 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
3287 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
3288
3289 int Idx = 0;
3290 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
3291 const FieldDecl *F = *I;
3292
3293 if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
3294 F->getType()->isIncompleteArrayType())
3295 continue;
3296
3297 if (F->isBitField()) {
3298 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
3299 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
3300 BFI.StorageSize / CharWidth, BFI.Offset,
3301 BFI.Size, CharWidth,
3302 CGM.getDataLayout().isBigEndian());
3303 continue;
3304 }
3305
3306 setUsedBits(CGM, F->getType(),
3307 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
3308 }
3309 }
3310
3311 // Set the bits in `Bits`, which correspond to the value representations of
3312 // the elements of an array type `ATy`.
setUsedBits(CodeGenModule & CGM,const ConstantArrayType * ATy,int Offset,SmallVectorImpl<uint64_t> & Bits)3313 static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
3314 int Offset, SmallVectorImpl<uint64_t> &Bits) {
3315 const ASTContext &Context = CGM.getContext();
3316
3317 QualType ETy = Context.getBaseElementType(ATy);
3318 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
3319 SmallVector<uint64_t, 4> TmpBits(Size);
3320 setUsedBits(CGM, ETy, 0, TmpBits);
3321
3322 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
3323 auto Src = TmpBits.begin();
3324 auto Dst = Bits.begin() + Offset + I * Size;
3325 for (int J = 0; J < Size; ++J)
3326 *Dst++ |= *Src++;
3327 }
3328 }
3329
3330 // Set the bits in `Bits`, which correspond to the value representations of
3331 // the type `QTy`.
setUsedBits(CodeGenModule & CGM,QualType QTy,int Offset,SmallVectorImpl<uint64_t> & Bits)3332 static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
3333 SmallVectorImpl<uint64_t> &Bits) {
3334 if (const auto *RTy = QTy->getAs<RecordType>())
3335 return setUsedBits(CGM, RTy, Offset, Bits);
3336
3337 ASTContext &Context = CGM.getContext();
3338 if (const auto *ATy = Context.getAsConstantArrayType(QTy))
3339 return setUsedBits(CGM, ATy, Offset, Bits);
3340
3341 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
3342 if (Size <= 0)
3343 return;
3344
3345 std::fill_n(Bits.begin() + Offset, Size,
3346 (uint64_t(1) << Context.getCharWidth()) - 1);
3347 }
3348
buildMultiCharMask(const SmallVectorImpl<uint64_t> & Bits,int Pos,int Size,int CharWidth,bool BigEndian)3349 static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
3350 int Pos, int Size, int CharWidth,
3351 bool BigEndian) {
3352 assert(Size > 0);
3353 uint64_t Mask = 0;
3354 if (BigEndian) {
3355 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
3356 ++P)
3357 Mask = (Mask << CharWidth) | *P;
3358 } else {
3359 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
3360 do
3361 Mask = (Mask << CharWidth) | *--P;
3362 while (P != End);
3363 }
3364 return Mask;
3365 }
3366
3367 // Emit code to clear the bits in a record, which aren't a part of any user
3368 // declared member, when the record is a function return.
EmitCMSEClearRecord(llvm::Value * Src,llvm::IntegerType * ITy,QualType QTy)3369 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3370 llvm::IntegerType *ITy,
3371 QualType QTy) {
3372 assert(Src->getType() == ITy);
3373 assert(ITy->getScalarSizeInBits() <= 64);
3374
3375 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3376 int Size = DataLayout.getTypeStoreSize(ITy);
3377 SmallVector<uint64_t, 4> Bits(Size);
3378 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3379
3380 int CharWidth = CGM.getContext().getCharWidth();
3381 uint64_t Mask =
3382 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
3383
3384 return Builder.CreateAnd(Src, Mask, "cmse.clear");
3385 }
3386
3387 // Emit code to clear the bits in a record, which aren't a part of any user
3388 // declared member, when the record is a function argument.
EmitCMSEClearRecord(llvm::Value * Src,llvm::ArrayType * ATy,QualType QTy)3389 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
3390 llvm::ArrayType *ATy,
3391 QualType QTy) {
3392 const llvm::DataLayout &DataLayout = CGM.getDataLayout();
3393 int Size = DataLayout.getTypeStoreSize(ATy);
3394 SmallVector<uint64_t, 16> Bits(Size);
3395 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
3396
3397 // Clear each element of the LLVM array.
3398 int CharWidth = CGM.getContext().getCharWidth();
3399 int CharsPerElt =
3400 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
3401 int MaskIndex = 0;
3402 llvm::Value *R = llvm::UndefValue::get(ATy);
3403 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
3404 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
3405 DataLayout.isBigEndian());
3406 MaskIndex += CharsPerElt;
3407 llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
3408 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
3409 R = Builder.CreateInsertValue(R, T1, I);
3410 }
3411
3412 return R;
3413 }
3414
EmitFunctionEpilog(const CGFunctionInfo & FI,bool EmitRetDbgLoc,SourceLocation EndLoc)3415 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
3416 bool EmitRetDbgLoc,
3417 SourceLocation EndLoc) {
3418 if (FI.isNoReturn()) {
3419 // Noreturn functions don't return.
3420 EmitUnreachable(EndLoc);
3421 return;
3422 }
3423
3424 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
3425 // Naked functions don't have epilogues.
3426 Builder.CreateUnreachable();
3427 return;
3428 }
3429
3430 // Functions with no result always return void.
3431 if (!ReturnValue.isValid()) {
3432 Builder.CreateRetVoid();
3433 return;
3434 }
3435
3436 llvm::DebugLoc RetDbgLoc;
3437 llvm::Value *RV = nullptr;
3438 QualType RetTy = FI.getReturnType();
3439 const ABIArgInfo &RetAI = FI.getReturnInfo();
3440
3441 switch (RetAI.getKind()) {
3442 case ABIArgInfo::InAlloca:
3443 // Aggregrates get evaluated directly into the destination. Sometimes we
3444 // need to return the sret value in a register, though.
3445 assert(hasAggregateEvaluationKind(RetTy));
3446 if (RetAI.getInAllocaSRet()) {
3447 llvm::Function::arg_iterator EI = CurFn->arg_end();
3448 --EI;
3449 llvm::Value *ArgStruct = &*EI;
3450 llvm::Value *SRet = Builder.CreateStructGEP(
3451 EI->getType()->getPointerElementType(), ArgStruct,
3452 RetAI.getInAllocaFieldIndex());
3453 llvm::Type *Ty =
3454 cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
3455 RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
3456 }
3457 break;
3458
3459 case ABIArgInfo::Indirect: {
3460 auto AI = CurFn->arg_begin();
3461 if (RetAI.isSRetAfterThis())
3462 ++AI;
3463 switch (getEvaluationKind(RetTy)) {
3464 case TEK_Complex: {
3465 ComplexPairTy RT =
3466 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
3467 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
3468 /*isInit*/ true);
3469 break;
3470 }
3471 case TEK_Aggregate:
3472 // Do nothing; aggregrates get evaluated directly into the destination.
3473 break;
3474 case TEK_Scalar:
3475 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
3476 MakeNaturalAlignAddrLValue(&*AI, RetTy),
3477 /*isInit*/ true);
3478 break;
3479 }
3480 break;
3481 }
3482
3483 case ABIArgInfo::Extend:
3484 case ABIArgInfo::Direct:
3485 if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
3486 RetAI.getDirectOffset() == 0) {
3487 // The internal return value temp always will have pointer-to-return-type
3488 // type, just do a load.
3489
3490 // If there is a dominating store to ReturnValue, we can elide
3491 // the load, zap the store, and usually zap the alloca.
3492 if (llvm::StoreInst *SI =
3493 findDominatingStoreToReturnValue(*this)) {
3494 // Reuse the debug location from the store unless there is
3495 // cleanup code to be emitted between the store and return
3496 // instruction.
3497 if (EmitRetDbgLoc && !AutoreleaseResult)
3498 RetDbgLoc = SI->getDebugLoc();
3499 // Get the stored value and nuke the now-dead store.
3500 RV = SI->getValueOperand();
3501 SI->eraseFromParent();
3502
3503 // Otherwise, we have to do a simple load.
3504 } else {
3505 RV = Builder.CreateLoad(ReturnValue);
3506 }
3507 } else {
3508 // If the value is offset in memory, apply the offset now.
3509 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
3510
3511 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
3512 }
3513
3514 // In ARC, end functions that return a retainable type with a call
3515 // to objc_autoreleaseReturnValue.
3516 if (AutoreleaseResult) {
3517 #ifndef NDEBUG
3518 // Type::isObjCRetainabletype has to be called on a QualType that hasn't
3519 // been stripped of the typedefs, so we cannot use RetTy here. Get the
3520 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
3521 // CurCodeDecl or BlockInfo.
3522 QualType RT;
3523
3524 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
3525 RT = FD->getReturnType();
3526 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
3527 RT = MD->getReturnType();
3528 else if (isa<BlockDecl>(CurCodeDecl))
3529 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
3530 else
3531 llvm_unreachable("Unexpected function/method type");
3532
3533 assert(getLangOpts().ObjCAutoRefCount &&
3534 !FI.isReturnsRetained() &&
3535 RT->isObjCRetainableType());
3536 #endif
3537 RV = emitAutoreleaseOfResult(*this, RV);
3538 }
3539
3540 break;
3541
3542 case ABIArgInfo::Ignore:
3543 break;
3544
3545 case ABIArgInfo::CoerceAndExpand: {
3546 auto coercionType = RetAI.getCoerceAndExpandType();
3547
3548 // Load all of the coerced elements out into results.
3549 llvm::SmallVector<llvm::Value*, 4> results;
3550 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
3551 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3552 auto coercedEltType = coercionType->getElementType(i);
3553 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
3554 continue;
3555
3556 auto eltAddr = Builder.CreateStructGEP(addr, i);
3557 auto elt = Builder.CreateLoad(eltAddr);
3558 results.push_back(elt);
3559 }
3560
3561 // If we have one result, it's the single direct result type.
3562 if (results.size() == 1) {
3563 RV = results[0];
3564
3565 // Otherwise, we need to make a first-class aggregate.
3566 } else {
3567 // Construct a return type that lacks padding elements.
3568 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
3569
3570 RV = llvm::UndefValue::get(returnType);
3571 for (unsigned i = 0, e = results.size(); i != e; ++i) {
3572 RV = Builder.CreateInsertValue(RV, results[i], i);
3573 }
3574 }
3575 break;
3576 }
3577 case ABIArgInfo::Expand:
3578 case ABIArgInfo::IndirectAliased:
3579 llvm_unreachable("Invalid ABI kind for return argument");
3580 }
3581
3582 llvm::Instruction *Ret;
3583 if (RV) {
3584 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
3585 // For certain return types, clear padding bits, as they may reveal
3586 // sensitive information.
3587 // Small struct/union types are passed as integers.
3588 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
3589 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
3590 RV = EmitCMSEClearRecord(RV, ITy, RetTy);
3591 }
3592 EmitReturnValueCheck(RV);
3593 Ret = Builder.CreateRet(RV);
3594 } else {
3595 Ret = Builder.CreateRetVoid();
3596 }
3597
3598 if (RetDbgLoc)
3599 Ret->setDebugLoc(std::move(RetDbgLoc));
3600 }
3601
EmitReturnValueCheck(llvm::Value * RV)3602 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
3603 // A current decl may not be available when emitting vtable thunks.
3604 if (!CurCodeDecl)
3605 return;
3606
3607 // If the return block isn't reachable, neither is this check, so don't emit
3608 // it.
3609 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
3610 return;
3611
3612 ReturnsNonNullAttr *RetNNAttr = nullptr;
3613 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
3614 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
3615
3616 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
3617 return;
3618
3619 // Prefer the returns_nonnull attribute if it's present.
3620 SourceLocation AttrLoc;
3621 SanitizerMask CheckKind;
3622 SanitizerHandler Handler;
3623 if (RetNNAttr) {
3624 assert(!requiresReturnValueNullabilityCheck() &&
3625 "Cannot check nullability and the nonnull attribute");
3626 AttrLoc = RetNNAttr->getLocation();
3627 CheckKind = SanitizerKind::ReturnsNonnullAttribute;
3628 Handler = SanitizerHandler::NonnullReturn;
3629 } else {
3630 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
3631 if (auto *TSI = DD->getTypeSourceInfo())
3632 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
3633 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
3634 CheckKind = SanitizerKind::NullabilityReturn;
3635 Handler = SanitizerHandler::NullabilityReturn;
3636 }
3637
3638 SanitizerScope SanScope(this);
3639
3640 // Make sure the "return" source location is valid. If we're checking a
3641 // nullability annotation, make sure the preconditions for the check are met.
3642 llvm::BasicBlock *Check = createBasicBlock("nullcheck");
3643 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
3644 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
3645 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
3646 if (requiresReturnValueNullabilityCheck())
3647 CanNullCheck =
3648 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
3649 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
3650 EmitBlock(Check);
3651
3652 // Now do the null check.
3653 llvm::Value *Cond = Builder.CreateIsNotNull(RV);
3654 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
3655 llvm::Value *DynamicData[] = {SLocPtr};
3656 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
3657
3658 EmitBlock(NoCheck);
3659
3660 #ifndef NDEBUG
3661 // The return location should not be used after the check has been emitted.
3662 ReturnLocation = Address::invalid();
3663 #endif
3664 }
3665
isInAllocaArgument(CGCXXABI & ABI,QualType type)3666 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
3667 const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
3668 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
3669 }
3670
createPlaceholderSlot(CodeGenFunction & CGF,QualType Ty)3671 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
3672 QualType Ty) {
3673 // FIXME: Generate IR in one pass, rather than going back and fixing up these
3674 // placeholders.
3675 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
3676 llvm::Type *IRPtrTy = IRTy->getPointerTo();
3677 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
3678
3679 // FIXME: When we generate this IR in one pass, we shouldn't need
3680 // this win32-specific alignment hack.
3681 CharUnits Align = CharUnits::fromQuantity(4);
3682 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
3683
3684 return AggValueSlot::forAddr(Address(Placeholder, Align),
3685 Ty.getQualifiers(),
3686 AggValueSlot::IsNotDestructed,
3687 AggValueSlot::DoesNotNeedGCBarriers,
3688 AggValueSlot::IsNotAliased,
3689 AggValueSlot::DoesNotOverlap);
3690 }
3691
EmitDelegateCallArg(CallArgList & args,const VarDecl * param,SourceLocation loc)3692 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
3693 const VarDecl *param,
3694 SourceLocation loc) {
3695 // StartFunction converted the ABI-lowered parameter(s) into a
3696 // local alloca. We need to turn that into an r-value suitable
3697 // for EmitCall.
3698 Address local = GetAddrOfLocalVar(param);
3699
3700 QualType type = param->getType();
3701
3702 if (isInAllocaArgument(CGM.getCXXABI(), type)) {
3703 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
3704 }
3705
3706 // GetAddrOfLocalVar returns a pointer-to-pointer for references,
3707 // but the argument needs to be the original pointer.
3708 if (type->isReferenceType()) {
3709 args.add(RValue::get(Builder.CreateLoad(local)), type);
3710
3711 // In ARC, move out of consumed arguments so that the release cleanup
3712 // entered by StartFunction doesn't cause an over-release. This isn't
3713 // optimal -O0 code generation, but it should get cleaned up when
3714 // optimization is enabled. This also assumes that delegate calls are
3715 // performed exactly once for a set of arguments, but that should be safe.
3716 } else if (getLangOpts().ObjCAutoRefCount &&
3717 param->hasAttr<NSConsumedAttr>() &&
3718 type->isObjCRetainableType()) {
3719 llvm::Value *ptr = Builder.CreateLoad(local);
3720 auto null =
3721 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
3722 Builder.CreateStore(null, local);
3723 args.add(RValue::get(ptr), type);
3724
3725 // For the most part, we just need to load the alloca, except that
3726 // aggregate r-values are actually pointers to temporaries.
3727 } else {
3728 args.add(convertTempToRValue(local, type, loc), type);
3729 }
3730
3731 // Deactivate the cleanup for the callee-destructed param that was pushed.
3732 if (type->isRecordType() && !CurFuncIsThunk &&
3733 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
3734 param->needsDestruction(getContext())) {
3735 EHScopeStack::stable_iterator cleanup =
3736 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
3737 assert(cleanup.isValid() &&
3738 "cleanup for callee-destructed param not recorded");
3739 // This unreachable is a temporary marker which will be removed later.
3740 llvm::Instruction *isActive = Builder.CreateUnreachable();
3741 args.addArgCleanupDeactivation(cleanup, isActive);
3742 }
3743 }
3744
isProvablyNull(llvm::Value * addr)3745 static bool isProvablyNull(llvm::Value *addr) {
3746 return isa<llvm::ConstantPointerNull>(addr);
3747 }
3748
3749 /// Emit the actual writing-back of a writeback.
emitWriteback(CodeGenFunction & CGF,const CallArgList::Writeback & writeback)3750 static void emitWriteback(CodeGenFunction &CGF,
3751 const CallArgList::Writeback &writeback) {
3752 const LValue &srcLV = writeback.Source;
3753 Address srcAddr = srcLV.getAddress(CGF);
3754 assert(!isProvablyNull(srcAddr.getPointer()) &&
3755 "shouldn't have writeback for provably null argument");
3756
3757 llvm::BasicBlock *contBB = nullptr;
3758
3759 // If the argument wasn't provably non-null, we need to null check
3760 // before doing the store.
3761 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3762 CGF.CGM.getDataLayout());
3763 if (!provablyNonNull) {
3764 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
3765 contBB = CGF.createBasicBlock("icr.done");
3766
3767 llvm::Value *isNull =
3768 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3769 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
3770 CGF.EmitBlock(writebackBB);
3771 }
3772
3773 // Load the value to writeback.
3774 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
3775
3776 // Cast it back, in case we're writing an id to a Foo* or something.
3777 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
3778 "icr.writeback-cast");
3779
3780 // Perform the writeback.
3781
3782 // If we have a "to use" value, it's something we need to emit a use
3783 // of. This has to be carefully threaded in: if it's done after the
3784 // release it's potentially undefined behavior (and the optimizer
3785 // will ignore it), and if it happens before the retain then the
3786 // optimizer could move the release there.
3787 if (writeback.ToUse) {
3788 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
3789
3790 // Retain the new value. No need to block-copy here: the block's
3791 // being passed up the stack.
3792 value = CGF.EmitARCRetainNonBlock(value);
3793
3794 // Emit the intrinsic use here.
3795 CGF.EmitARCIntrinsicUse(writeback.ToUse);
3796
3797 // Load the old value (primitively).
3798 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
3799
3800 // Put the new value in place (primitively).
3801 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
3802
3803 // Release the old value.
3804 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
3805
3806 // Otherwise, we can just do a normal lvalue store.
3807 } else {
3808 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
3809 }
3810
3811 // Jump to the continuation block.
3812 if (!provablyNonNull)
3813 CGF.EmitBlock(contBB);
3814 }
3815
emitWritebacks(CodeGenFunction & CGF,const CallArgList & args)3816 static void emitWritebacks(CodeGenFunction &CGF,
3817 const CallArgList &args) {
3818 for (const auto &I : args.writebacks())
3819 emitWriteback(CGF, I);
3820 }
3821
deactivateArgCleanupsBeforeCall(CodeGenFunction & CGF,const CallArgList & CallArgs)3822 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
3823 const CallArgList &CallArgs) {
3824 ArrayRef<CallArgList::CallArgCleanup> Cleanups =
3825 CallArgs.getCleanupsToDeactivate();
3826 // Iterate in reverse to increase the likelihood of popping the cleanup.
3827 for (const auto &I : llvm::reverse(Cleanups)) {
3828 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
3829 I.IsActiveIP->eraseFromParent();
3830 }
3831 }
3832
maybeGetUnaryAddrOfOperand(const Expr * E)3833 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
3834 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
3835 if (uop->getOpcode() == UO_AddrOf)
3836 return uop->getSubExpr();
3837 return nullptr;
3838 }
3839
3840 /// Emit an argument that's being passed call-by-writeback. That is,
3841 /// we are passing the address of an __autoreleased temporary; it
3842 /// might be copy-initialized with the current value of the given
3843 /// address, but it will definitely be copied out of after the call.
emitWritebackArg(CodeGenFunction & CGF,CallArgList & args,const ObjCIndirectCopyRestoreExpr * CRE)3844 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
3845 const ObjCIndirectCopyRestoreExpr *CRE) {
3846 LValue srcLV;
3847
3848 // Make an optimistic effort to emit the address as an l-value.
3849 // This can fail if the argument expression is more complicated.
3850 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
3851 srcLV = CGF.EmitLValue(lvExpr);
3852
3853 // Otherwise, just emit it as a scalar.
3854 } else {
3855 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
3856
3857 QualType srcAddrType =
3858 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3859 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
3860 }
3861 Address srcAddr = srcLV.getAddress(CGF);
3862
3863 // The dest and src types don't necessarily match in LLVM terms
3864 // because of the crazy ObjC compatibility rules.
3865
3866 llvm::PointerType *destType =
3867 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
3868
3869 // If the address is a constant null, just pass the appropriate null.
3870 if (isProvablyNull(srcAddr.getPointer())) {
3871 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
3872 CRE->getType());
3873 return;
3874 }
3875
3876 // Create the temporary.
3877 Address temp = CGF.CreateTempAlloca(destType->getElementType(),
3878 CGF.getPointerAlign(),
3879 "icr.temp");
3880 // Loading an l-value can introduce a cleanup if the l-value is __weak,
3881 // and that cleanup will be conditional if we can't prove that the l-value
3882 // isn't null, so we need to register a dominating point so that the cleanups
3883 // system will make valid IR.
3884 CodeGenFunction::ConditionalEvaluation condEval(CGF);
3885
3886 // Zero-initialize it if we're not doing a copy-initialization.
3887 bool shouldCopy = CRE->shouldCopy();
3888 if (!shouldCopy) {
3889 llvm::Value *null =
3890 llvm::ConstantPointerNull::get(
3891 cast<llvm::PointerType>(destType->getElementType()));
3892 CGF.Builder.CreateStore(null, temp);
3893 }
3894
3895 llvm::BasicBlock *contBB = nullptr;
3896 llvm::BasicBlock *originBB = nullptr;
3897
3898 // If the address is *not* known to be non-null, we need to switch.
3899 llvm::Value *finalArgument;
3900
3901 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
3902 CGF.CGM.getDataLayout());
3903 if (provablyNonNull) {
3904 finalArgument = temp.getPointer();
3905 } else {
3906 llvm::Value *isNull =
3907 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
3908
3909 finalArgument = CGF.Builder.CreateSelect(isNull,
3910 llvm::ConstantPointerNull::get(destType),
3911 temp.getPointer(), "icr.argument");
3912
3913 // If we need to copy, then the load has to be conditional, which
3914 // means we need control flow.
3915 if (shouldCopy) {
3916 originBB = CGF.Builder.GetInsertBlock();
3917 contBB = CGF.createBasicBlock("icr.cont");
3918 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
3919 CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
3920 CGF.EmitBlock(copyBB);
3921 condEval.begin(CGF);
3922 }
3923 }
3924
3925 llvm::Value *valueToUse = nullptr;
3926
3927 // Perform a copy if necessary.
3928 if (shouldCopy) {
3929 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
3930 assert(srcRV.isScalar());
3931
3932 llvm::Value *src = srcRV.getScalarVal();
3933 src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
3934 "icr.cast");
3935
3936 // Use an ordinary store, not a store-to-lvalue.
3937 CGF.Builder.CreateStore(src, temp);
3938
3939 // If optimization is enabled, and the value was held in a
3940 // __strong variable, we need to tell the optimizer that this
3941 // value has to stay alive until we're doing the store back.
3942 // This is because the temporary is effectively unretained,
3943 // and so otherwise we can violate the high-level semantics.
3944 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
3945 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
3946 valueToUse = src;
3947 }
3948 }
3949
3950 // Finish the control flow if we needed it.
3951 if (shouldCopy && !provablyNonNull) {
3952 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
3953 CGF.EmitBlock(contBB);
3954
3955 // Make a phi for the value to intrinsically use.
3956 if (valueToUse) {
3957 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
3958 "icr.to-use");
3959 phiToUse->addIncoming(valueToUse, copyBB);
3960 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
3961 originBB);
3962 valueToUse = phiToUse;
3963 }
3964
3965 condEval.end(CGF);
3966 }
3967
3968 args.addWriteback(srcLV, temp, valueToUse);
3969 args.add(RValue::get(finalArgument), CRE->getType());
3970 }
3971
allocateArgumentMemory(CodeGenFunction & CGF)3972 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
3973 assert(!StackBase);
3974
3975 // Save the stack.
3976 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
3977 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
3978 }
3979
freeArgumentMemory(CodeGenFunction & CGF) const3980 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
3981 if (StackBase) {
3982 // Restore the stack after the call.
3983 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
3984 CGF.Builder.CreateCall(F, StackBase);
3985 }
3986 }
3987
EmitNonNullArgCheck(RValue RV,QualType ArgType,SourceLocation ArgLoc,AbstractCallee AC,unsigned ParmNum)3988 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
3989 SourceLocation ArgLoc,
3990 AbstractCallee AC,
3991 unsigned ParmNum) {
3992 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
3993 SanOpts.has(SanitizerKind::NullabilityArg)))
3994 return;
3995
3996 // The param decl may be missing in a variadic function.
3997 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
3998 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
3999
4000 // Prefer the nonnull attribute if it's present.
4001 const NonNullAttr *NNAttr = nullptr;
4002 if (SanOpts.has(SanitizerKind::NonnullAttribute))
4003 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
4004
4005 bool CanCheckNullability = false;
4006 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
4007 auto Nullability = PVD->getType()->getNullability(getContext());
4008 CanCheckNullability = Nullability &&
4009 *Nullability == NullabilityKind::NonNull &&
4010 PVD->getTypeSourceInfo();
4011 }
4012
4013 if (!NNAttr && !CanCheckNullability)
4014 return;
4015
4016 SourceLocation AttrLoc;
4017 SanitizerMask CheckKind;
4018 SanitizerHandler Handler;
4019 if (NNAttr) {
4020 AttrLoc = NNAttr->getLocation();
4021 CheckKind = SanitizerKind::NonnullAttribute;
4022 Handler = SanitizerHandler::NonnullArg;
4023 } else {
4024 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
4025 CheckKind = SanitizerKind::NullabilityArg;
4026 Handler = SanitizerHandler::NullabilityArg;
4027 }
4028
4029 SanitizerScope SanScope(this);
4030 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
4031 llvm::Constant *StaticData[] = {
4032 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
4033 llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
4034 };
4035 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
4036 }
4037
4038 // Check if the call is going to use the inalloca convention. This needs to
4039 // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
4040 // later, so we can't check it directly.
hasInAllocaArgs(CodeGenModule & CGM,CallingConv ExplicitCC,ArrayRef<QualType> ArgTypes)4041 static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
4042 ArrayRef<QualType> ArgTypes) {
4043 // The Swift calling conventions don't go through the target-specific
4044 // argument classification, they never use inalloca.
4045 // TODO: Consider limiting inalloca use to only calling conventions supported
4046 // by MSVC.
4047 if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
4048 return false;
4049 if (!CGM.getTarget().getCXXABI().isMicrosoft())
4050 return false;
4051 return llvm::any_of(ArgTypes, [&](QualType Ty) {
4052 return isInAllocaArgument(CGM.getCXXABI(), Ty);
4053 });
4054 }
4055
4056 #ifndef NDEBUG
4057 // Determine whether the given argument is an Objective-C method
4058 // that may have type parameters in its signature.
isObjCMethodWithTypeParams(const ObjCMethodDecl * method)4059 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
4060 const DeclContext *dc = method->getDeclContext();
4061 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
4062 return classDecl->getTypeParamListAsWritten();
4063 }
4064
4065 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
4066 return catDecl->getTypeParamList();
4067 }
4068
4069 return false;
4070 }
4071 #endif
4072
4073 /// EmitCallArgs - Emit call arguments for a function.
EmitCallArgs(CallArgList & Args,PrototypeWrapper Prototype,llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,AbstractCallee AC,unsigned ParamsToSkip,EvaluationOrder Order)4074 void CodeGenFunction::EmitCallArgs(
4075 CallArgList &Args, PrototypeWrapper Prototype,
4076 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
4077 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
4078 SmallVector<QualType, 16> ArgTypes;
4079
4080 assert((ParamsToSkip == 0 || Prototype.P) &&
4081 "Can't skip parameters if type info is not provided");
4082
4083 // This variable only captures *explicitly* written conventions, not those
4084 // applied by default via command line flags or target defaults, such as
4085 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
4086 // require knowing if this is a C++ instance method or being able to see
4087 // unprototyped FunctionTypes.
4088 CallingConv ExplicitCC = CC_C;
4089
4090 // First, if a prototype was provided, use those argument types.
4091 bool IsVariadic = false;
4092 if (Prototype.P) {
4093 const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
4094 if (MD) {
4095 IsVariadic = MD->isVariadic();
4096 ExplicitCC = getCallingConventionForDecl(
4097 MD, CGM.getTarget().getTriple().isOSWindows());
4098 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
4099 MD->param_type_end());
4100 } else {
4101 const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
4102 IsVariadic = FPT->isVariadic();
4103 ExplicitCC = FPT->getExtInfo().getCC();
4104 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
4105 FPT->param_type_end());
4106 }
4107
4108 #ifndef NDEBUG
4109 // Check that the prototyped types match the argument expression types.
4110 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
4111 CallExpr::const_arg_iterator Arg = ArgRange.begin();
4112 for (QualType Ty : ArgTypes) {
4113 assert(Arg != ArgRange.end() && "Running over edge of argument list!");
4114 assert(
4115 (isGenericMethod || Ty->isVariablyModifiedType() ||
4116 Ty.getNonReferenceType()->isObjCRetainableType() ||
4117 getContext()
4118 .getCanonicalType(Ty.getNonReferenceType())
4119 .getTypePtr() ==
4120 getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
4121 "type mismatch in call argument!");
4122 ++Arg;
4123 }
4124
4125 // Either we've emitted all the call args, or we have a call to variadic
4126 // function.
4127 assert((Arg == ArgRange.end() || IsVariadic) &&
4128 "Extra arguments in non-variadic function!");
4129 #endif
4130 }
4131
4132 // If we still have any arguments, emit them using the type of the argument.
4133 for (auto *A : llvm::make_range(std::next(ArgRange.begin(), ArgTypes.size()),
4134 ArgRange.end()))
4135 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
4136 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
4137
4138 // We must evaluate arguments from right to left in the MS C++ ABI,
4139 // because arguments are destroyed left to right in the callee. As a special
4140 // case, there are certain language constructs that require left-to-right
4141 // evaluation, and in those cases we consider the evaluation order requirement
4142 // to trump the "destruction order is reverse construction order" guarantee.
4143 bool LeftToRight =
4144 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
4145 ? Order == EvaluationOrder::ForceLeftToRight
4146 : Order != EvaluationOrder::ForceRightToLeft;
4147
4148 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
4149 RValue EmittedArg) {
4150 if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
4151 return;
4152 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
4153 if (PS == nullptr)
4154 return;
4155
4156 const auto &Context = getContext();
4157 auto SizeTy = Context.getSizeType();
4158 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4159 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
4160 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
4161 EmittedArg.getScalarVal(),
4162 PS->isDynamic());
4163 Args.add(RValue::get(V), SizeTy);
4164 // If we're emitting args in reverse, be sure to do so with
4165 // pass_object_size, as well.
4166 if (!LeftToRight)
4167 std::swap(Args.back(), *(&Args.back() - 1));
4168 };
4169
4170 // Insert a stack save if we're going to need any inalloca args.
4171 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
4172 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
4173 "inalloca only supported on x86");
4174 Args.allocateArgumentMemory(*this);
4175 }
4176
4177 // Evaluate each argument in the appropriate order.
4178 size_t CallArgsStart = Args.size();
4179 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
4180 unsigned Idx = LeftToRight ? I : E - I - 1;
4181 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
4182 unsigned InitialArgSize = Args.size();
4183 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
4184 // the argument and parameter match or the objc method is parameterized.
4185 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
4186 getContext().hasSameUnqualifiedType((*Arg)->getType(),
4187 ArgTypes[Idx]) ||
4188 (isa<ObjCMethodDecl>(AC.getDecl()) &&
4189 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
4190 "Argument and parameter types don't match");
4191 EmitCallArg(Args, *Arg, ArgTypes[Idx]);
4192 // In particular, we depend on it being the last arg in Args, and the
4193 // objectsize bits depend on there only being one arg if !LeftToRight.
4194 assert(InitialArgSize + 1 == Args.size() &&
4195 "The code below depends on only adding one arg per EmitCallArg");
4196 (void)InitialArgSize;
4197 // Since pointer argument are never emitted as LValue, it is safe to emit
4198 // non-null argument check for r-value only.
4199 if (!Args.back().hasLValue()) {
4200 RValue RVArg = Args.back().getKnownRValue();
4201 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
4202 ParamsToSkip + Idx);
4203 // @llvm.objectsize should never have side-effects and shouldn't need
4204 // destruction/cleanups, so we can safely "emit" it after its arg,
4205 // regardless of right-to-leftness
4206 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
4207 }
4208 }
4209
4210 if (!LeftToRight) {
4211 // Un-reverse the arguments we just evaluated so they match up with the LLVM
4212 // IR function.
4213 std::reverse(Args.begin() + CallArgsStart, Args.end());
4214 }
4215 }
4216
4217 namespace {
4218
4219 struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
DestroyUnpassedArg__anone30e957c0c11::DestroyUnpassedArg4220 DestroyUnpassedArg(Address Addr, QualType Ty)
4221 : Addr(Addr), Ty(Ty) {}
4222
4223 Address Addr;
4224 QualType Ty;
4225
Emit__anone30e957c0c11::DestroyUnpassedArg4226 void Emit(CodeGenFunction &CGF, Flags flags) override {
4227 QualType::DestructionKind DtorKind = Ty.isDestructedType();
4228 if (DtorKind == QualType::DK_cxx_destructor) {
4229 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
4230 assert(!Dtor->isTrivial());
4231 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
4232 /*Delegating=*/false, Addr, Ty);
4233 } else {
4234 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
4235 }
4236 }
4237 };
4238
4239 struct DisableDebugLocationUpdates {
4240 CodeGenFunction &CGF;
4241 bool disabledDebugInfo;
DisableDebugLocationUpdates__anone30e957c0c11::DisableDebugLocationUpdates4242 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
4243 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
4244 CGF.disableDebugInfo();
4245 }
~DisableDebugLocationUpdates__anone30e957c0c11::DisableDebugLocationUpdates4246 ~DisableDebugLocationUpdates() {
4247 if (disabledDebugInfo)
4248 CGF.enableDebugInfo();
4249 }
4250 };
4251
4252 } // end anonymous namespace
4253
getRValue(CodeGenFunction & CGF) const4254 RValue CallArg::getRValue(CodeGenFunction &CGF) const {
4255 if (!HasLV)
4256 return RV;
4257 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
4258 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
4259 LV.isVolatile());
4260 IsUsed = true;
4261 return RValue::getAggregate(Copy.getAddress(CGF));
4262 }
4263
copyInto(CodeGenFunction & CGF,Address Addr) const4264 void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
4265 LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
4266 if (!HasLV && RV.isScalar())
4267 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
4268 else if (!HasLV && RV.isComplex())
4269 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
4270 else {
4271 auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
4272 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
4273 // We assume that call args are never copied into subobjects.
4274 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
4275 HasLV ? LV.isVolatileQualified()
4276 : RV.isVolatileQualified());
4277 }
4278 IsUsed = true;
4279 }
4280
EmitCallArg(CallArgList & args,const Expr * E,QualType type)4281 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
4282 QualType type) {
4283 DisableDebugLocationUpdates Dis(*this, E);
4284 if (const ObjCIndirectCopyRestoreExpr *CRE
4285 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
4286 assert(getLangOpts().ObjCAutoRefCount);
4287 return emitWritebackArg(*this, args, CRE);
4288 }
4289
4290 assert(type->isReferenceType() == E->isGLValue() &&
4291 "reference binding to unmaterialized r-value!");
4292
4293 if (E->isGLValue()) {
4294 assert(E->getObjectKind() == OK_Ordinary);
4295 return args.add(EmitReferenceBindingToExpr(E), type);
4296 }
4297
4298 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
4299
4300 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
4301 // However, we still have to push an EH-only cleanup in case we unwind before
4302 // we make it to the call.
4303 if (type->isRecordType() &&
4304 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
4305 // If we're using inalloca, use the argument memory. Otherwise, use a
4306 // temporary.
4307 AggValueSlot Slot;
4308 if (args.isUsingInAlloca())
4309 Slot = createPlaceholderSlot(*this, type);
4310 else
4311 Slot = CreateAggTemp(type, "agg.tmp");
4312
4313 bool DestroyedInCallee = true, NeedsEHCleanup = true;
4314 if (const auto *RD = type->getAsCXXRecordDecl())
4315 DestroyedInCallee = RD->hasNonTrivialDestructor();
4316 else
4317 NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
4318
4319 if (DestroyedInCallee)
4320 Slot.setExternallyDestructed();
4321
4322 EmitAggExpr(E, Slot);
4323 RValue RV = Slot.asRValue();
4324 args.add(RV, type);
4325
4326 if (DestroyedInCallee && NeedsEHCleanup) {
4327 // Create a no-op GEP between the placeholder and the cleanup so we can
4328 // RAUW it successfully. It also serves as a marker of the first
4329 // instruction where the cleanup is active.
4330 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
4331 type);
4332 // This unreachable is a temporary marker which will be removed later.
4333 llvm::Instruction *IsActive = Builder.CreateUnreachable();
4334 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
4335 }
4336 return;
4337 }
4338
4339 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
4340 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
4341 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
4342 assert(L.isSimple());
4343 args.addUncopiedAggregate(L, type);
4344 return;
4345 }
4346
4347 args.add(EmitAnyExprToTemp(E), type);
4348 }
4349
getVarArgType(const Expr * Arg)4350 QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
4351 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
4352 // implicitly widens null pointer constants that are arguments to varargs
4353 // functions to pointer-sized ints.
4354 if (!getTarget().getTriple().isOSWindows())
4355 return Arg->getType();
4356
4357 if (Arg->getType()->isIntegerType() &&
4358 getContext().getTypeSize(Arg->getType()) <
4359 getContext().getTargetInfo().getPointerWidth(0) &&
4360 Arg->isNullPointerConstant(getContext(),
4361 Expr::NPC_ValueDependentIsNotNull)) {
4362 return getContext().getIntPtrType();
4363 }
4364
4365 return Arg->getType();
4366 }
4367
4368 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4369 // optimizer it can aggressively ignore unwind edges.
4370 void
AddObjCARCExceptionMetadata(llvm::Instruction * Inst)4371 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
4372 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
4373 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
4374 Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
4375 CGM.getNoObjCARCExceptionsMetadata());
4376 }
4377
4378 /// Emits a call to the given no-arguments nounwind runtime function.
4379 llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)4380 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4381 const llvm::Twine &name) {
4382 return EmitNounwindRuntimeCall(callee, None, name);
4383 }
4384
4385 /// Emits a call to the given nounwind runtime function.
4386 llvm::CallInst *
EmitNounwindRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)4387 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
4388 ArrayRef<llvm::Value *> args,
4389 const llvm::Twine &name) {
4390 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
4391 call->setDoesNotThrow();
4392 return call;
4393 }
4394
4395 /// Emits a simple call (never an invoke) to the given no-arguments
4396 /// runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,const llvm::Twine & name)4397 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4398 const llvm::Twine &name) {
4399 return EmitRuntimeCall(callee, None, name);
4400 }
4401
4402 // Calls which may throw must have operand bundles indicating which funclet
4403 // they are nested within.
4404 SmallVector<llvm::OperandBundleDef, 1>
getBundlesForFunclet(llvm::Value * Callee)4405 CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
4406 SmallVector<llvm::OperandBundleDef, 1> BundleList;
4407 // There is no need for a funclet operand bundle if we aren't inside a
4408 // funclet.
4409 if (!CurrentFuncletPad)
4410 return BundleList;
4411
4412 // Skip intrinsics which cannot throw.
4413 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
4414 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
4415 return BundleList;
4416
4417 BundleList.emplace_back("funclet", CurrentFuncletPad);
4418 return BundleList;
4419 }
4420
4421 /// Emits a simple call (never an invoke) to the given runtime function.
EmitRuntimeCall(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const llvm::Twine & name)4422 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
4423 ArrayRef<llvm::Value *> args,
4424 const llvm::Twine &name) {
4425 llvm::CallInst *call = Builder.CreateCall(
4426 callee, args, getBundlesForFunclet(callee.getCallee()), name);
4427 call->setCallingConv(getRuntimeCC());
4428 return call;
4429 }
4430
4431 /// Emits a call or invoke to the given noreturn runtime function.
EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args)4432 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
4433 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
4434 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4435 getBundlesForFunclet(callee.getCallee());
4436
4437 if (getInvokeDest()) {
4438 llvm::InvokeInst *invoke =
4439 Builder.CreateInvoke(callee,
4440 getUnreachableBlock(),
4441 getInvokeDest(),
4442 args,
4443 BundleList);
4444 invoke->setDoesNotReturn();
4445 invoke->setCallingConv(getRuntimeCC());
4446 } else {
4447 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
4448 call->setDoesNotReturn();
4449 call->setCallingConv(getRuntimeCC());
4450 Builder.CreateUnreachable();
4451 }
4452 }
4453
4454 /// Emits a call or invoke instruction to the given nullary runtime function.
4455 llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,const Twine & name)4456 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4457 const Twine &name) {
4458 return EmitRuntimeCallOrInvoke(callee, None, name);
4459 }
4460
4461 /// Emits a call or invoke instruction to the given runtime function.
4462 llvm::CallBase *
EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,ArrayRef<llvm::Value * > args,const Twine & name)4463 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
4464 ArrayRef<llvm::Value *> args,
4465 const Twine &name) {
4466 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
4467 call->setCallingConv(getRuntimeCC());
4468 return call;
4469 }
4470
4471 /// Emits a call or invoke instruction to the given function, depending
4472 /// on the current state of the EH stack.
EmitCallOrInvoke(llvm::FunctionCallee Callee,ArrayRef<llvm::Value * > Args,const Twine & Name)4473 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
4474 ArrayRef<llvm::Value *> Args,
4475 const Twine &Name) {
4476 llvm::BasicBlock *InvokeDest = getInvokeDest();
4477 SmallVector<llvm::OperandBundleDef, 1> BundleList =
4478 getBundlesForFunclet(Callee.getCallee());
4479
4480 llvm::CallBase *Inst;
4481 if (!InvokeDest)
4482 Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
4483 else {
4484 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
4485 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
4486 Name);
4487 EmitBlock(ContBB);
4488 }
4489
4490 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
4491 // optimizer it can aggressively ignore unwind edges.
4492 if (CGM.getLangOpts().ObjCAutoRefCount)
4493 AddObjCARCExceptionMetadata(Inst);
4494
4495 return Inst;
4496 }
4497
deferPlaceholderReplacement(llvm::Instruction * Old,llvm::Value * New)4498 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
4499 llvm::Value *New) {
4500 DeferredReplacements.push_back(
4501 std::make_pair(llvm::WeakTrackingVH(Old), New));
4502 }
4503
4504 namespace {
4505
4506 /// Specify given \p NewAlign as the alignment of return value attribute. If
4507 /// such attribute already exists, re-set it to the maximal one of two options.
4508 LLVM_NODISCARD llvm::AttributeList
maybeRaiseRetAlignmentAttribute(llvm::LLVMContext & Ctx,const llvm::AttributeList & Attrs,llvm::Align NewAlign)4509 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
4510 const llvm::AttributeList &Attrs,
4511 llvm::Align NewAlign) {
4512 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
4513 if (CurAlign >= NewAlign)
4514 return Attrs;
4515 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
4516 return Attrs
4517 .removeAttribute(Ctx, llvm::AttributeList::ReturnIndex,
4518 llvm::Attribute::AttrKind::Alignment)
4519 .addAttribute(Ctx, llvm::AttributeList::ReturnIndex, AlignAttr);
4520 }
4521
4522 template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
4523 protected:
4524 CodeGenFunction &CGF;
4525
4526 /// We do nothing if this is, or becomes, nullptr.
4527 const AlignedAttrTy *AA = nullptr;
4528
4529 llvm::Value *Alignment = nullptr; // May or may not be a constant.
4530 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
4531
AbstractAssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4532 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4533 : CGF(CGF_) {
4534 if (!FuncDecl)
4535 return;
4536 AA = FuncDecl->getAttr<AlignedAttrTy>();
4537 }
4538
4539 public:
4540 /// If we can, materialize the alignment as an attribute on return value.
4541 LLVM_NODISCARD llvm::AttributeList
TryEmitAsCallSiteAttribute(const llvm::AttributeList & Attrs)4542 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
4543 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
4544 return Attrs;
4545 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
4546 if (!AlignmentCI)
4547 return Attrs;
4548 // We may legitimately have non-power-of-2 alignment here.
4549 // If so, this is UB land, emit it via `@llvm.assume` instead.
4550 if (!AlignmentCI->getValue().isPowerOf2())
4551 return Attrs;
4552 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
4553 CGF.getLLVMContext(), Attrs,
4554 llvm::Align(
4555 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
4556 AA = nullptr; // We're done. Disallow doing anything else.
4557 return NewAttrs;
4558 }
4559
4560 /// Emit alignment assumption.
4561 /// This is a general fallback that we take if either there is an offset,
4562 /// or the alignment is variable or we are sanitizing for alignment.
EmitAsAnAssumption(SourceLocation Loc,QualType RetTy,RValue & Ret)4563 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
4564 if (!AA)
4565 return;
4566 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
4567 AA->getLocation(), Alignment, OffsetCI);
4568 AA = nullptr; // We're done. Disallow doing anything else.
4569 }
4570 };
4571
4572 /// Helper data structure to emit `AssumeAlignedAttr`.
4573 class AssumeAlignedAttrEmitter final
4574 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
4575 public:
AssumeAlignedAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl)4576 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
4577 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4578 if (!AA)
4579 return;
4580 // It is guaranteed that the alignment/offset are constants.
4581 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
4582 if (Expr *Offset = AA->getOffset()) {
4583 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
4584 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
4585 OffsetCI = nullptr;
4586 }
4587 }
4588 };
4589
4590 /// Helper data structure to emit `AllocAlignAttr`.
4591 class AllocAlignAttrEmitter final
4592 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
4593 public:
AllocAlignAttrEmitter(CodeGenFunction & CGF_,const Decl * FuncDecl,const CallArgList & CallArgs)4594 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
4595 const CallArgList &CallArgs)
4596 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
4597 if (!AA)
4598 return;
4599 // Alignment may or may not be a constant, and that is okay.
4600 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
4601 .getRValue(CGF)
4602 .getScalarVal();
4603 }
4604 };
4605
4606 } // namespace
4607
EmitCall(const CGFunctionInfo & CallInfo,const CGCallee & Callee,ReturnValueSlot ReturnValue,const CallArgList & CallArgs,llvm::CallBase ** callOrInvoke,bool IsMustTail,SourceLocation Loc)4608 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
4609 const CGCallee &Callee,
4610 ReturnValueSlot ReturnValue,
4611 const CallArgList &CallArgs,
4612 llvm::CallBase **callOrInvoke, bool IsMustTail,
4613 SourceLocation Loc) {
4614 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
4615
4616 assert(Callee.isOrdinary() || Callee.isVirtual());
4617
4618 // Handle struct-return functions by passing a pointer to the
4619 // location that we would like to return into.
4620 QualType RetTy = CallInfo.getReturnType();
4621 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
4622
4623 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
4624
4625 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
4626 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
4627 // We can only guarantee that a function is called from the correct
4628 // context/function based on the appropriate target attributes,
4629 // so only check in the case where we have both always_inline and target
4630 // since otherwise we could be making a conditional call after a check for
4631 // the proper cpu features (and it won't cause code generation issues due to
4632 // function based code generation).
4633 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4634 TargetDecl->hasAttr<TargetAttr>())
4635 checkTargetFeatures(Loc, FD);
4636
4637 // Some architectures (such as x86-64) have the ABI changed based on
4638 // attribute-target/features. Give them a chance to diagnose.
4639 CGM.getTargetCodeGenInfo().checkFunctionCallABI(
4640 CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
4641 }
4642
4643 #ifndef NDEBUG
4644 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
4645 // For an inalloca varargs function, we don't expect CallInfo to match the
4646 // function pointer's type, because the inalloca struct a will have extra
4647 // fields in it for the varargs parameters. Code later in this function
4648 // bitcasts the function pointer to the type derived from CallInfo.
4649 //
4650 // In other cases, we assert that the types match up (until pointers stop
4651 // having pointee types).
4652 llvm::Type *TypeFromVal;
4653 if (Callee.isVirtual())
4654 TypeFromVal = Callee.getVirtualFunctionType();
4655 else
4656 TypeFromVal =
4657 Callee.getFunctionPointer()->getType()->getPointerElementType();
4658 assert(IRFuncTy == TypeFromVal);
4659 }
4660 #endif
4661
4662 // 1. Set up the arguments.
4663
4664 // If we're using inalloca, insert the allocation after the stack save.
4665 // FIXME: Do this earlier rather than hacking it in here!
4666 Address ArgMemory = Address::invalid();
4667 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
4668 const llvm::DataLayout &DL = CGM.getDataLayout();
4669 llvm::Instruction *IP = CallArgs.getStackBase();
4670 llvm::AllocaInst *AI;
4671 if (IP) {
4672 IP = IP->getNextNode();
4673 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
4674 "argmem", IP);
4675 } else {
4676 AI = CreateTempAlloca(ArgStruct, "argmem");
4677 }
4678 auto Align = CallInfo.getArgStructAlignment();
4679 AI->setAlignment(Align.getAsAlign());
4680 AI->setUsedWithInAlloca(true);
4681 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
4682 ArgMemory = Address(AI, Align);
4683 }
4684
4685 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
4686 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
4687
4688 // If the call returns a temporary with struct return, create a temporary
4689 // alloca to hold the result, unless one is given to us.
4690 Address SRetPtr = Address::invalid();
4691 Address SRetAlloca = Address::invalid();
4692 llvm::Value *UnusedReturnSizePtr = nullptr;
4693 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
4694 if (!ReturnValue.isNull()) {
4695 SRetPtr = ReturnValue.getValue();
4696 } else {
4697 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
4698 if (HaveInsertPoint() && ReturnValue.isUnused()) {
4699 llvm::TypeSize size =
4700 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
4701 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
4702 }
4703 }
4704 if (IRFunctionArgs.hasSRetArg()) {
4705 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
4706 } else if (RetAI.isInAlloca()) {
4707 Address Addr =
4708 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
4709 Builder.CreateStore(SRetPtr.getPointer(), Addr);
4710 }
4711 }
4712
4713 Address swiftErrorTemp = Address::invalid();
4714 Address swiftErrorArg = Address::invalid();
4715
4716 // When passing arguments using temporary allocas, we need to add the
4717 // appropriate lifetime markers. This vector keeps track of all the lifetime
4718 // markers that need to be ended right after the call.
4719 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
4720
4721 // Translate all of the arguments as necessary to match the IR lowering.
4722 assert(CallInfo.arg_size() == CallArgs.size() &&
4723 "Mismatch between function signature & arguments.");
4724 unsigned ArgNo = 0;
4725 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
4726 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
4727 I != E; ++I, ++info_it, ++ArgNo) {
4728 const ABIArgInfo &ArgInfo = info_it->info;
4729
4730 // Insert a padding argument to ensure proper alignment.
4731 if (IRFunctionArgs.hasPaddingArg(ArgNo))
4732 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
4733 llvm::UndefValue::get(ArgInfo.getPaddingType());
4734
4735 unsigned FirstIRArg, NumIRArgs;
4736 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
4737
4738 switch (ArgInfo.getKind()) {
4739 case ABIArgInfo::InAlloca: {
4740 assert(NumIRArgs == 0);
4741 assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
4742 if (I->isAggregate()) {
4743 Address Addr = I->hasLValue()
4744 ? I->getKnownLValue().getAddress(*this)
4745 : I->getKnownRValue().getAggregateAddress();
4746 llvm::Instruction *Placeholder =
4747 cast<llvm::Instruction>(Addr.getPointer());
4748
4749 if (!ArgInfo.getInAllocaIndirect()) {
4750 // Replace the placeholder with the appropriate argument slot GEP.
4751 CGBuilderTy::InsertPoint IP = Builder.saveIP();
4752 Builder.SetInsertPoint(Placeholder);
4753 Addr = Builder.CreateStructGEP(ArgMemory,
4754 ArgInfo.getInAllocaFieldIndex());
4755 Builder.restoreIP(IP);
4756 } else {
4757 // For indirect things such as overaligned structs, replace the
4758 // placeholder with a regular aggregate temporary alloca. Store the
4759 // address of this alloca into the struct.
4760 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
4761 Address ArgSlot = Builder.CreateStructGEP(
4762 ArgMemory, ArgInfo.getInAllocaFieldIndex());
4763 Builder.CreateStore(Addr.getPointer(), ArgSlot);
4764 }
4765 deferPlaceholderReplacement(Placeholder, Addr.getPointer());
4766 } else if (ArgInfo.getInAllocaIndirect()) {
4767 // Make a temporary alloca and store the address of it into the argument
4768 // struct.
4769 Address Addr = CreateMemTempWithoutCast(
4770 I->Ty, getContext().getTypeAlignInChars(I->Ty),
4771 "indirect-arg-temp");
4772 I->copyInto(*this, Addr);
4773 Address ArgSlot =
4774 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4775 Builder.CreateStore(Addr.getPointer(), ArgSlot);
4776 } else {
4777 // Store the RValue into the argument struct.
4778 Address Addr =
4779 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
4780 unsigned AS = Addr.getType()->getPointerAddressSpace();
4781 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
4782 // There are some cases where a trivial bitcast is not avoidable. The
4783 // definition of a type later in a translation unit may change it's type
4784 // from {}* to (%struct.foo*)*.
4785 if (Addr.getType() != MemType)
4786 Addr = Builder.CreateBitCast(Addr, MemType);
4787 I->copyInto(*this, Addr);
4788 }
4789 break;
4790 }
4791
4792 case ABIArgInfo::Indirect:
4793 case ABIArgInfo::IndirectAliased: {
4794 assert(NumIRArgs == 1);
4795 if (!I->isAggregate()) {
4796 // Make a temporary alloca to pass the argument.
4797 Address Addr = CreateMemTempWithoutCast(
4798 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
4799 IRCallArgs[FirstIRArg] = Addr.getPointer();
4800
4801 I->copyInto(*this, Addr);
4802 } else {
4803 // We want to avoid creating an unnecessary temporary+copy here;
4804 // however, we need one in three cases:
4805 // 1. If the argument is not byval, and we are required to copy the
4806 // source. (This case doesn't occur on any common architecture.)
4807 // 2. If the argument is byval, RV is not sufficiently aligned, and
4808 // we cannot force it to be sufficiently aligned.
4809 // 3. If the argument is byval, but RV is not located in default
4810 // or alloca address space.
4811 Address Addr = I->hasLValue()
4812 ? I->getKnownLValue().getAddress(*this)
4813 : I->getKnownRValue().getAggregateAddress();
4814 llvm::Value *V = Addr.getPointer();
4815 CharUnits Align = ArgInfo.getIndirectAlign();
4816 const llvm::DataLayout *TD = &CGM.getDataLayout();
4817
4818 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
4819 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
4820 TD->getAllocaAddrSpace()) &&
4821 "indirect argument must be in alloca address space");
4822
4823 bool NeedCopy = false;
4824
4825 if (Addr.getAlignment() < Align &&
4826 llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
4827 Align.getAsAlign()) {
4828 NeedCopy = true;
4829 } else if (I->hasLValue()) {
4830 auto LV = I->getKnownLValue();
4831 auto AS = LV.getAddressSpace();
4832
4833 if (!ArgInfo.getIndirectByVal() ||
4834 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
4835 NeedCopy = true;
4836 }
4837 if (!getLangOpts().OpenCL) {
4838 if ((ArgInfo.getIndirectByVal() &&
4839 (AS != LangAS::Default &&
4840 AS != CGM.getASTAllocaAddressSpace()))) {
4841 NeedCopy = true;
4842 }
4843 }
4844 // For OpenCL even if RV is located in default or alloca address space
4845 // we don't want to perform address space cast for it.
4846 else if ((ArgInfo.getIndirectByVal() &&
4847 Addr.getType()->getAddressSpace() != IRFuncTy->
4848 getParamType(FirstIRArg)->getPointerAddressSpace())) {
4849 NeedCopy = true;
4850 }
4851 }
4852
4853 if (NeedCopy) {
4854 // Create an aligned temporary, and copy to it.
4855 Address AI = CreateMemTempWithoutCast(
4856 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
4857 IRCallArgs[FirstIRArg] = AI.getPointer();
4858
4859 // Emit lifetime markers for the temporary alloca.
4860 llvm::TypeSize ByvalTempElementSize =
4861 CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
4862 llvm::Value *LifetimeSize =
4863 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
4864
4865 // Add cleanup code to emit the end lifetime marker after the call.
4866 if (LifetimeSize) // In case we disabled lifetime markers.
4867 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
4868
4869 // Generate the copy.
4870 I->copyInto(*this, AI);
4871 } else {
4872 // Skip the extra memcpy call.
4873 auto *T = V->getType()->getPointerElementType()->getPointerTo(
4874 CGM.getDataLayout().getAllocaAddrSpace());
4875 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
4876 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
4877 true);
4878 }
4879 }
4880 break;
4881 }
4882
4883 case ABIArgInfo::Ignore:
4884 assert(NumIRArgs == 0);
4885 break;
4886
4887 case ABIArgInfo::Extend:
4888 case ABIArgInfo::Direct: {
4889 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
4890 ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
4891 ArgInfo.getDirectOffset() == 0) {
4892 assert(NumIRArgs == 1);
4893 llvm::Value *V;
4894 if (!I->isAggregate())
4895 V = I->getKnownRValue().getScalarVal();
4896 else
4897 V = Builder.CreateLoad(
4898 I->hasLValue() ? I->getKnownLValue().getAddress(*this)
4899 : I->getKnownRValue().getAggregateAddress());
4900
4901 // Implement swifterror by copying into a new swifterror argument.
4902 // We'll write back in the normal path out of the call.
4903 if (CallInfo.getExtParameterInfo(ArgNo).getABI()
4904 == ParameterABI::SwiftErrorResult) {
4905 assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
4906
4907 QualType pointeeTy = I->Ty->getPointeeType();
4908 swiftErrorArg =
4909 Address(V, getContext().getTypeAlignInChars(pointeeTy));
4910
4911 swiftErrorTemp =
4912 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
4913 V = swiftErrorTemp.getPointer();
4914 cast<llvm::AllocaInst>(V)->setSwiftError(true);
4915
4916 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
4917 Builder.CreateStore(errorValue, swiftErrorTemp);
4918 }
4919
4920 // We might have to widen integers, but we should never truncate.
4921 if (ArgInfo.getCoerceToType() != V->getType() &&
4922 V->getType()->isIntegerTy())
4923 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
4924
4925 // If the argument doesn't match, perform a bitcast to coerce it. This
4926 // can happen due to trivial type mismatches.
4927 if (FirstIRArg < IRFuncTy->getNumParams() &&
4928 V->getType() != IRFuncTy->getParamType(FirstIRArg))
4929 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
4930
4931 IRCallArgs[FirstIRArg] = V;
4932 break;
4933 }
4934
4935 // FIXME: Avoid the conversion through memory if possible.
4936 Address Src = Address::invalid();
4937 if (!I->isAggregate()) {
4938 Src = CreateMemTemp(I->Ty, "coerce");
4939 I->copyInto(*this, Src);
4940 } else {
4941 Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
4942 : I->getKnownRValue().getAggregateAddress();
4943 }
4944
4945 // If the value is offset in memory, apply the offset now.
4946 Src = emitAddressAtOffset(*this, Src, ArgInfo);
4947
4948 // Fast-isel and the optimizer generally like scalar values better than
4949 // FCAs, so we flatten them if this is safe to do for this argument.
4950 llvm::StructType *STy =
4951 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
4952 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
4953 llvm::Type *SrcTy = Src.getElementType();
4954 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
4955 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
4956
4957 // If the source type is smaller than the destination type of the
4958 // coerce-to logic, copy the source value into a temp alloca the size
4959 // of the destination type to allow loading all of it. The bits past
4960 // the source value are left undef.
4961 if (SrcSize < DstSize) {
4962 Address TempAlloca
4963 = CreateTempAlloca(STy, Src.getAlignment(),
4964 Src.getName() + ".coerce");
4965 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
4966 Src = TempAlloca;
4967 } else {
4968 Src = Builder.CreateBitCast(Src,
4969 STy->getPointerTo(Src.getAddressSpace()));
4970 }
4971
4972 assert(NumIRArgs == STy->getNumElements());
4973 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
4974 Address EltPtr = Builder.CreateStructGEP(Src, i);
4975 llvm::Value *LI = Builder.CreateLoad(EltPtr);
4976 IRCallArgs[FirstIRArg + i] = LI;
4977 }
4978 } else {
4979 // In the simple case, just pass the coerced loaded value.
4980 assert(NumIRArgs == 1);
4981 llvm::Value *Load =
4982 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
4983
4984 if (CallInfo.isCmseNSCall()) {
4985 // For certain parameter types, clear padding bits, as they may reveal
4986 // sensitive information.
4987 // Small struct/union types are passed as integer arrays.
4988 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
4989 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
4990 Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
4991 }
4992 IRCallArgs[FirstIRArg] = Load;
4993 }
4994
4995 break;
4996 }
4997
4998 case ABIArgInfo::CoerceAndExpand: {
4999 auto coercionType = ArgInfo.getCoerceAndExpandType();
5000 auto layout = CGM.getDataLayout().getStructLayout(coercionType);
5001
5002 llvm::Value *tempSize = nullptr;
5003 Address addr = Address::invalid();
5004 Address AllocaAddr = Address::invalid();
5005 if (I->isAggregate()) {
5006 addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
5007 : I->getKnownRValue().getAggregateAddress();
5008
5009 } else {
5010 RValue RV = I->getKnownRValue();
5011 assert(RV.isScalar()); // complex should always just be direct
5012
5013 llvm::Type *scalarType = RV.getScalarVal()->getType();
5014 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
5015 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
5016
5017 // Materialize to a temporary.
5018 addr = CreateTempAlloca(
5019 RV.getScalarVal()->getType(),
5020 CharUnits::fromQuantity(std::max(
5021 (unsigned)layout->getAlignment().value(), scalarAlign)),
5022 "tmp",
5023 /*ArraySize=*/nullptr, &AllocaAddr);
5024 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
5025
5026 Builder.CreateStore(RV.getScalarVal(), addr);
5027 }
5028
5029 addr = Builder.CreateElementBitCast(addr, coercionType);
5030
5031 unsigned IRArgPos = FirstIRArg;
5032 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5033 llvm::Type *eltType = coercionType->getElementType(i);
5034 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5035 Address eltAddr = Builder.CreateStructGEP(addr, i);
5036 llvm::Value *elt = Builder.CreateLoad(eltAddr);
5037 IRCallArgs[IRArgPos++] = elt;
5038 }
5039 assert(IRArgPos == FirstIRArg + NumIRArgs);
5040
5041 if (tempSize) {
5042 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
5043 }
5044
5045 break;
5046 }
5047
5048 case ABIArgInfo::Expand: {
5049 unsigned IRArgPos = FirstIRArg;
5050 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
5051 assert(IRArgPos == FirstIRArg + NumIRArgs);
5052 break;
5053 }
5054 }
5055 }
5056
5057 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
5058 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
5059
5060 // If we're using inalloca, set up that argument.
5061 if (ArgMemory.isValid()) {
5062 llvm::Value *Arg = ArgMemory.getPointer();
5063 if (CallInfo.isVariadic()) {
5064 // When passing non-POD arguments by value to variadic functions, we will
5065 // end up with a variadic prototype and an inalloca call site. In such
5066 // cases, we can't do any parameter mismatch checks. Give up and bitcast
5067 // the callee.
5068 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
5069 CalleePtr =
5070 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
5071 } else {
5072 llvm::Type *LastParamTy =
5073 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
5074 if (Arg->getType() != LastParamTy) {
5075 #ifndef NDEBUG
5076 // Assert that these structs have equivalent element types.
5077 llvm::StructType *FullTy = CallInfo.getArgStruct();
5078 llvm::StructType *DeclaredTy = cast<llvm::StructType>(
5079 cast<llvm::PointerType>(LastParamTy)->getElementType());
5080 assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
5081 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
5082 DE = DeclaredTy->element_end(),
5083 FI = FullTy->element_begin();
5084 DI != DE; ++DI, ++FI)
5085 assert(*DI == *FI);
5086 #endif
5087 Arg = Builder.CreateBitCast(Arg, LastParamTy);
5088 }
5089 }
5090 assert(IRFunctionArgs.hasInallocaArg());
5091 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
5092 }
5093
5094 // 2. Prepare the function pointer.
5095
5096 // If the callee is a bitcast of a non-variadic function to have a
5097 // variadic function pointer type, check to see if we can remove the
5098 // bitcast. This comes up with unprototyped functions.
5099 //
5100 // This makes the IR nicer, but more importantly it ensures that we
5101 // can inline the function at -O0 if it is marked always_inline.
5102 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
5103 llvm::Value *Ptr) -> llvm::Function * {
5104 if (!CalleeFT->isVarArg())
5105 return nullptr;
5106
5107 // Get underlying value if it's a bitcast
5108 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
5109 if (CE->getOpcode() == llvm::Instruction::BitCast)
5110 Ptr = CE->getOperand(0);
5111 }
5112
5113 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
5114 if (!OrigFn)
5115 return nullptr;
5116
5117 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
5118
5119 // If the original type is variadic, or if any of the component types
5120 // disagree, we cannot remove the cast.
5121 if (OrigFT->isVarArg() ||
5122 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
5123 OrigFT->getReturnType() != CalleeFT->getReturnType())
5124 return nullptr;
5125
5126 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
5127 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
5128 return nullptr;
5129
5130 return OrigFn;
5131 };
5132
5133 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
5134 CalleePtr = OrigFn;
5135 IRFuncTy = OrigFn->getFunctionType();
5136 }
5137
5138 // 3. Perform the actual call.
5139
5140 // Deactivate any cleanups that we're supposed to do immediately before
5141 // the call.
5142 if (!CallArgs.getCleanupsToDeactivate().empty())
5143 deactivateArgCleanupsBeforeCall(*this, CallArgs);
5144
5145 // Assert that the arguments we computed match up. The IR verifier
5146 // will catch this, but this is a common enough source of problems
5147 // during IRGen changes that it's way better for debugging to catch
5148 // it ourselves here.
5149 #ifndef NDEBUG
5150 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
5151 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5152 // Inalloca argument can have different type.
5153 if (IRFunctionArgs.hasInallocaArg() &&
5154 i == IRFunctionArgs.getInallocaArgNo())
5155 continue;
5156 if (i < IRFuncTy->getNumParams())
5157 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
5158 }
5159 #endif
5160
5161 // Update the largest vector width if any arguments have vector types.
5162 for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
5163 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
5164 LargestVectorWidth =
5165 std::max((uint64_t)LargestVectorWidth,
5166 VT->getPrimitiveSizeInBits().getKnownMinSize());
5167 }
5168
5169 // Compute the calling convention and attributes.
5170 unsigned CallingConv;
5171 llvm::AttributeList Attrs;
5172 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
5173 Callee.getAbstractInfo(), Attrs, CallingConv,
5174 /*AttrOnCallSite=*/true,
5175 /*IsThunk=*/false);
5176
5177 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5178 if (FD->hasAttr<StrictFPAttr>())
5179 // All calls within a strictfp function are marked strictfp
5180 Attrs =
5181 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5182 llvm::Attribute::StrictFP);
5183
5184 // Add call-site nomerge attribute if exists.
5185 if (InNoMergeAttributedStmt)
5186 Attrs =
5187 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5188 llvm::Attribute::NoMerge);
5189
5190 // Apply some call-site-specific attributes.
5191 // TODO: work this into building the attribute set.
5192
5193 // Apply always_inline to all calls within flatten functions.
5194 // FIXME: should this really take priority over __try, below?
5195 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
5196 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
5197 Attrs =
5198 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5199 llvm::Attribute::AlwaysInline);
5200 }
5201
5202 // Disable inlining inside SEH __try blocks.
5203 if (isSEHTryScope()) {
5204 Attrs =
5205 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5206 llvm::Attribute::NoInline);
5207 }
5208
5209 // Decide whether to use a call or an invoke.
5210 bool CannotThrow;
5211 if (currentFunctionUsesSEHTry()) {
5212 // SEH cares about asynchronous exceptions, so everything can "throw."
5213 CannotThrow = false;
5214 } else if (isCleanupPadScope() &&
5215 EHPersonality::get(*this).isMSVCXXPersonality()) {
5216 // The MSVC++ personality will implicitly terminate the program if an
5217 // exception is thrown during a cleanup outside of a try/catch.
5218 // We don't need to model anything in IR to get this behavior.
5219 CannotThrow = true;
5220 } else {
5221 // Otherwise, nounwind call sites will never throw.
5222 CannotThrow = Attrs.hasFnAttribute(llvm::Attribute::NoUnwind);
5223
5224 if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
5225 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
5226 CannotThrow = true;
5227 }
5228
5229 // If we made a temporary, be sure to clean up after ourselves. Note that we
5230 // can't depend on being inside of an ExprWithCleanups, so we need to manually
5231 // pop this cleanup later on. Being eager about this is OK, since this
5232 // temporary is 'invisible' outside of the callee.
5233 if (UnusedReturnSizePtr)
5234 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
5235 UnusedReturnSizePtr);
5236
5237 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
5238
5239 SmallVector<llvm::OperandBundleDef, 1> BundleList =
5240 getBundlesForFunclet(CalleePtr);
5241
5242 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
5243 if (FD->hasAttr<StrictFPAttr>())
5244 // All calls within a strictfp function are marked strictfp
5245 Attrs =
5246 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
5247 llvm::Attribute::StrictFP);
5248
5249 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
5250 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5251
5252 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
5253 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
5254
5255 // Emit the actual call/invoke instruction.
5256 llvm::CallBase *CI;
5257 if (!InvokeDest) {
5258 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
5259 } else {
5260 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
5261 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
5262 BundleList);
5263 EmitBlock(Cont);
5264 }
5265 if (callOrInvoke)
5266 *callOrInvoke = CI;
5267
5268 // If this is within a function that has the guard(nocf) attribute and is an
5269 // indirect call, add the "guard_nocf" attribute to this call to indicate that
5270 // Control Flow Guard checks should not be added, even if the call is inlined.
5271 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
5272 if (const auto *A = FD->getAttr<CFGuardAttr>()) {
5273 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
5274 Attrs = Attrs.addAttribute(
5275 getLLVMContext(), llvm::AttributeList::FunctionIndex, "guard_nocf");
5276 }
5277 }
5278
5279 // Apply the attributes and calling convention.
5280 CI->setAttributes(Attrs);
5281 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
5282
5283 // Apply various metadata.
5284
5285 if (!CI->getType()->isVoidTy())
5286 CI->setName("call");
5287
5288 // Update largest vector width from the return type.
5289 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
5290 LargestVectorWidth =
5291 std::max((uint64_t)LargestVectorWidth,
5292 VT->getPrimitiveSizeInBits().getKnownMinSize());
5293
5294 // Insert instrumentation or attach profile metadata at indirect call sites.
5295 // For more details, see the comment before the definition of
5296 // IPVK_IndirectCallTarget in InstrProfData.inc.
5297 if (!CI->getCalledFunction())
5298 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
5299 CI, CalleePtr);
5300
5301 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
5302 // optimizer it can aggressively ignore unwind edges.
5303 if (CGM.getLangOpts().ObjCAutoRefCount)
5304 AddObjCARCExceptionMetadata(CI);
5305
5306 // Set tail call kind if necessary.
5307 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
5308 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
5309 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
5310 else if (IsMustTail)
5311 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
5312 }
5313
5314 // Add metadata for calls to MSAllocator functions
5315 if (getDebugInfo() && TargetDecl &&
5316 TargetDecl->hasAttr<MSAllocatorAttr>())
5317 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
5318
5319 // 4. Finish the call.
5320
5321 // If the call doesn't return, finish the basic block and clear the
5322 // insertion point; this allows the rest of IRGen to discard
5323 // unreachable code.
5324 if (CI->doesNotReturn()) {
5325 if (UnusedReturnSizePtr)
5326 PopCleanupBlock();
5327
5328 // Strip away the noreturn attribute to better diagnose unreachable UB.
5329 if (SanOpts.has(SanitizerKind::Unreachable)) {
5330 // Also remove from function since CallBase::hasFnAttr additionally checks
5331 // attributes of the called function.
5332 if (auto *F = CI->getCalledFunction())
5333 F->removeFnAttr(llvm::Attribute::NoReturn);
5334 CI->removeAttribute(llvm::AttributeList::FunctionIndex,
5335 llvm::Attribute::NoReturn);
5336
5337 // Avoid incompatibility with ASan which relies on the `noreturn`
5338 // attribute to insert handler calls.
5339 if (SanOpts.hasOneOf(SanitizerKind::Address |
5340 SanitizerKind::KernelAddress)) {
5341 SanitizerScope SanScope(this);
5342 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
5343 Builder.SetInsertPoint(CI);
5344 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
5345 llvm::FunctionCallee Fn =
5346 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
5347 EmitNounwindRuntimeCall(Fn);
5348 }
5349 }
5350
5351 EmitUnreachable(Loc);
5352 Builder.ClearInsertionPoint();
5353
5354 // FIXME: For now, emit a dummy basic block because expr emitters in
5355 // generally are not ready to handle emitting expressions at unreachable
5356 // points.
5357 EnsureInsertPoint();
5358
5359 // Return a reasonable RValue.
5360 return GetUndefRValue(RetTy);
5361 }
5362
5363 // If this is a musttail call, return immediately. We do not branch to the
5364 // epilogue in this case.
5365 if (IsMustTail) {
5366 for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
5367 ++it) {
5368 EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
5369 if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
5370 CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
5371 }
5372 if (CI->getType()->isVoidTy())
5373 Builder.CreateRetVoid();
5374 else
5375 Builder.CreateRet(CI);
5376 Builder.ClearInsertionPoint();
5377 EnsureInsertPoint();
5378 return GetUndefRValue(RetTy);
5379 }
5380
5381 // Perform the swifterror writeback.
5382 if (swiftErrorTemp.isValid()) {
5383 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
5384 Builder.CreateStore(errorResult, swiftErrorArg);
5385 }
5386
5387 // Emit any call-associated writebacks immediately. Arguably this
5388 // should happen after any return-value munging.
5389 if (CallArgs.hasWritebacks())
5390 emitWritebacks(*this, CallArgs);
5391
5392 // The stack cleanup for inalloca arguments has to run out of the normal
5393 // lexical order, so deactivate it and run it manually here.
5394 CallArgs.freeArgumentMemory(*this);
5395
5396 // Extract the return value.
5397 RValue Ret = [&] {
5398 switch (RetAI.getKind()) {
5399 case ABIArgInfo::CoerceAndExpand: {
5400 auto coercionType = RetAI.getCoerceAndExpandType();
5401
5402 Address addr = SRetPtr;
5403 addr = Builder.CreateElementBitCast(addr, coercionType);
5404
5405 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
5406 bool requiresExtract = isa<llvm::StructType>(CI->getType());
5407
5408 unsigned unpaddedIndex = 0;
5409 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
5410 llvm::Type *eltType = coercionType->getElementType(i);
5411 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
5412 Address eltAddr = Builder.CreateStructGEP(addr, i);
5413 llvm::Value *elt = CI;
5414 if (requiresExtract)
5415 elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
5416 else
5417 assert(unpaddedIndex == 0);
5418 Builder.CreateStore(elt, eltAddr);
5419 }
5420 // FALLTHROUGH
5421 LLVM_FALLTHROUGH;
5422 }
5423
5424 case ABIArgInfo::InAlloca:
5425 case ABIArgInfo::Indirect: {
5426 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
5427 if (UnusedReturnSizePtr)
5428 PopCleanupBlock();
5429 return ret;
5430 }
5431
5432 case ABIArgInfo::Ignore:
5433 // If we are ignoring an argument that had a result, make sure to
5434 // construct the appropriate return value for our caller.
5435 return GetUndefRValue(RetTy);
5436
5437 case ABIArgInfo::Extend:
5438 case ABIArgInfo::Direct: {
5439 llvm::Type *RetIRTy = ConvertType(RetTy);
5440 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
5441 switch (getEvaluationKind(RetTy)) {
5442 case TEK_Complex: {
5443 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
5444 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
5445 return RValue::getComplex(std::make_pair(Real, Imag));
5446 }
5447 case TEK_Aggregate: {
5448 Address DestPtr = ReturnValue.getValue();
5449 bool DestIsVolatile = ReturnValue.isVolatile();
5450
5451 if (!DestPtr.isValid()) {
5452 DestPtr = CreateMemTemp(RetTy, "agg.tmp");
5453 DestIsVolatile = false;
5454 }
5455 EmitAggregateStore(CI, DestPtr, DestIsVolatile);
5456 return RValue::getAggregate(DestPtr);
5457 }
5458 case TEK_Scalar: {
5459 // If the argument doesn't match, perform a bitcast to coerce it. This
5460 // can happen due to trivial type mismatches.
5461 llvm::Value *V = CI;
5462 if (V->getType() != RetIRTy)
5463 V = Builder.CreateBitCast(V, RetIRTy);
5464 return RValue::get(V);
5465 }
5466 }
5467 llvm_unreachable("bad evaluation kind");
5468 }
5469
5470 Address DestPtr = ReturnValue.getValue();
5471 bool DestIsVolatile = ReturnValue.isVolatile();
5472
5473 if (!DestPtr.isValid()) {
5474 DestPtr = CreateMemTemp(RetTy, "coerce");
5475 DestIsVolatile = false;
5476 }
5477
5478 // If the value is offset in memory, apply the offset now.
5479 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
5480 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
5481
5482 return convertTempToRValue(DestPtr, RetTy, SourceLocation());
5483 }
5484
5485 case ABIArgInfo::Expand:
5486 case ABIArgInfo::IndirectAliased:
5487 llvm_unreachable("Invalid ABI kind for return argument");
5488 }
5489
5490 llvm_unreachable("Unhandled ABIArgInfo::Kind");
5491 } ();
5492
5493 // Emit the assume_aligned check on the return value.
5494 if (Ret.isScalar() && TargetDecl) {
5495 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5496 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
5497 }
5498
5499 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
5500 // we can't use the full cleanup mechanism.
5501 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
5502 LifetimeEnd.Emit(*this, /*Flags=*/{});
5503
5504 if (!ReturnValue.isExternallyDestructed() &&
5505 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
5506 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
5507 RetTy);
5508
5509 return Ret;
5510 }
5511
prepareConcreteCallee(CodeGenFunction & CGF) const5512 CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
5513 if (isVirtual()) {
5514 const CallExpr *CE = getVirtualCallExpr();
5515 return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
5516 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
5517 CE ? CE->getBeginLoc() : SourceLocation());
5518 }
5519
5520 return *this;
5521 }
5522
5523 /* VarArg handling */
5524
EmitVAArg(VAArgExpr * VE,Address & VAListAddr)5525 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
5526 VAListAddr = VE->isMicrosoftABI()
5527 ? EmitMSVAListRef(VE->getSubExpr())
5528 : EmitVAListRef(VE->getSubExpr());
5529 QualType Ty = VE->getType();
5530 if (VE->isMicrosoftABI())
5531 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
5532 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
5533 }
5534