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