Debian Codegraph @

clang/lib/CIR/CodeGen/CIRGenCall.cpp

raw
1 //===--- CIRGenCall.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 definition used
10 // to handle ABI compliancy.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CIRGenCall.h"
15 #include "CIRGenCXXABI.h"
16 #include "CIRGenFunction.h"
17 #include "CIRGenFunctionInfo.h"
18 #include "clang/CIR/MissingFeatures.h"
19
20 using namespace clang;
21 using namespace clang::CIRGen;
22
23 CIRGenFunctionInfo *
24 CIRGenFunctionInfo::create(CanQualType resultType,
25 llvm::ArrayRef<CanQualType> argTypes,
26 RequiredArgs required) {
27 // The first slot allocated for arg type slot is for the return value.
28 void *buffer = operator new(
29 totalSizeToAlloc<CanQualType>(argTypes.size() + 1));
30
31 assert(!cir::MissingFeatures::opCallCIRGenFuncInfoParamInfo());
32
33 CIRGenFunctionInfo *fi = new (buffer) CIRGenFunctionInfo();
34
35 fi->required = required;
36 fi->numArgs = argTypes.size();
37
38 fi->getArgTypes()[0] = resultType;
39 std::copy(argTypes.begin(), argTypes.end(), fi->argTypesBegin());
40 assert(!cir::MissingFeatures::opCallCIRGenFuncInfoExtParamInfo());
41
42 return fi;
43 }
44
45 cir::FuncType CIRGenTypes::getFunctionType(GlobalDecl gd) {
46 const CIRGenFunctionInfo &fi = arrangeGlobalDeclaration(gd);
47 return getFunctionType(fi);
48 }
49
50 cir::FuncType CIRGenTypes::getFunctionType(const CIRGenFunctionInfo &info) {
51 mlir::Type resultType = convertType(info.getReturnType());
52 SmallVector<mlir::Type, 8> argTypes;
53 argTypes.reserve(info.getNumRequiredArgs());
54
55 for (const CanQualType &argType : info.requiredArguments())
56 argTypes.push_back(convertType(argType));
57
58 return cir::FuncType::get(argTypes,
59 (resultType ? resultType : builder.getVoidTy()),
60 info.isVariadic());
61 }
62
63 cir::FuncType CIRGenTypes::getFunctionTypeForVTable(GlobalDecl gd) {
64 const CXXMethodDecl *md = cast<CXXMethodDecl>(gd.getDecl());
65 const FunctionProtoType *fpt = md->getType()->getAs<FunctionProtoType>();
66
67 if (!isFuncTypeConvertible(fpt))
68 cgm.errorNYI("getFunctionTypeForVTable: non-convertible function type");
69
70 return getFunctionType(gd);
71 }
72
73 CIRGenCallee CIRGenCallee::prepareConcreteCallee(CIRGenFunction &cgf) const {
74 if (isVirtual()) {
75 const CallExpr *ce = getVirtualCallExpr();
76 return cgf.cgm.getCXXABI().getVirtualFunctionPointer(
77 cgf, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
78 ce ? ce->getBeginLoc() : SourceLocation());
79 }
80 return *this;
81 }
82
83 void CIRGenFunction::emitAggregateStore(mlir::Value value, Address dest) {
84 // In classic codegen:
85 // Function to store a first-class aggregate into memory. We prefer to
86 // store the elements rather than the aggregate to be more friendly to
87 // fast-isel.
88 // In CIR codegen:
89 // Emit the most simple cir.store possible (e.g. a store for a whole
90 // record), which can later be broken down in other CIR levels (or prior
91 // to dialect codegen).
92
93 // Stored result for the callers of this function expected to be in the same
94 // scope as the value, don't make assumptions about current insertion point.
95 mlir::OpBuilder::InsertionGuard guard(builder);
96 builder.setInsertionPointAfter(value.getDefiningOp());
97 builder.createStore(*currSrcLoc, value, dest);
98 }
99
100 static void addAttributesFromFunctionProtoType(CIRGenBuilderTy &builder,
101 mlir::NamedAttrList &attrs,
102 const FunctionProtoType *fpt) {
103 if (!fpt)
104 return;
105
106 if (!isUnresolvedExceptionSpec(fpt->getExceptionSpecType()) &&
107 fpt->isNothrow())
108 attrs.set(cir::CIRDialect::getNoThrowAttrName(),
109 mlir::UnitAttr::get(builder.getContext()));
110 }
111
112 /// Construct the CIR attribute list of a function or call.
113 void CIRGenModule::constructAttributeList(CIRGenCalleeInfo calleeInfo,
114 mlir::NamedAttrList &attrs) {
115 assert(!cir::MissingFeatures::opCallCallConv());
116 auto sideEffect = cir::SideEffect::All;
117
118 addAttributesFromFunctionProtoType(getBuilder(), attrs,
119 calleeInfo.getCalleeFunctionProtoType());
120
121 const Decl *targetDecl = calleeInfo.getCalleeDecl().getDecl();
122
123 if (targetDecl) {
124 if (targetDecl->hasAttr<NoThrowAttr>())
125 attrs.set(cir::CIRDialect::getNoThrowAttrName(),
126 mlir::UnitAttr::get(&getMLIRContext()));
127
128 if (const FunctionDecl *func = dyn_cast<FunctionDecl>(targetDecl)) {
129 addAttributesFromFunctionProtoType(
130 getBuilder(), attrs, func->getType()->getAs<FunctionProtoType>());
131 assert(!cir::MissingFeatures::opCallAttrs());
132 }
133
134 assert(!cir::MissingFeatures::opCallAttrs());
135
136 // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
137 if (targetDecl->hasAttr<ConstAttr>()) {
138 // gcc specifies that 'const' functions have greater restrictions than
139 // 'pure' functions, so they also cannot have infinite loops.
140 sideEffect = cir::SideEffect::Const;
141 } else if (targetDecl->hasAttr<PureAttr>()) {
142 // gcc specifies that 'pure' functions cannot have infinite loops.
143 sideEffect = cir::SideEffect::Pure;
144 }
145
146 assert(!cir::MissingFeatures::opCallAttrs());
147 }
148
149 assert(!cir::MissingFeatures::opCallAttrs());
150
151 attrs.set(cir::CIRDialect::getSideEffectAttrName(),
152 cir::SideEffectAttr::get(&getMLIRContext(), sideEffect));
153 }
154
155 /// Returns the canonical formal type of the given C++ method.
156 static CanQual<FunctionProtoType> getFormalType(const CXXMethodDecl *md) {
157 return md->getType()
158 ->getCanonicalTypeUnqualified()
159 .getAs<FunctionProtoType>();
160 }
161
162 /// Adds the formal parameters in FPT to the given prefix. If any parameter in
163 /// FPT has pass_object_size_attrs, then we'll add parameters for those, too.
164 /// TODO(cir): this should be shared with LLVM codegen
165 static void appendParameterTypes(const CIRGenTypes &cgt,
166 SmallVectorImpl<CanQualType> &prefix,
167 CanQual<FunctionProtoType> fpt) {
168 assert(!cir::MissingFeatures::opCallExtParameterInfo());
169 // Fast path: don't touch param info if we don't need to.
170 if (!fpt->hasExtParameterInfos()) {
171 prefix.append(fpt->param_type_begin(), fpt->param_type_end());
172 return;
173 }
174
175 cgt.getCGModule().errorNYI("appendParameterTypes: hasExtParameterInfos");
176 }
177
178 const CIRGenFunctionInfo &
179 CIRGenTypes::arrangeCXXStructorDeclaration(GlobalDecl gd) {
180 auto *md = cast<CXXMethodDecl>(gd.getDecl());
181
182 llvm::SmallVector<CanQualType, 16> argTypes;
183 argTypes.push_back(deriveThisType(md->getParent(), md));
184
185 bool passParams = true;
186
187 if (auto *cd = dyn_cast<CXXConstructorDecl>(md)) {
188 // A base class inheriting constructor doesn't get forwarded arguments
189 // needed to construct a virtual base (or base class thereof)
190 if (cd->getInheritedConstructor())
191 cgm.errorNYI(cd->getSourceRange(),
192 "arrangeCXXStructorDeclaration: inheriting constructor");
193 }
194
195 CanQual<FunctionProtoType> fpt = getFormalType(md);
196
197 if (passParams)
198 appendParameterTypes(*this, argTypes, fpt);
199
200 // The structor signature may include implicit parameters.
201 [[maybe_unused]] CIRGenCXXABI::AddedStructorArgCounts addedArgs =
202 theCXXABI.buildStructorSignature(gd, argTypes);
203 assert(!cir::MissingFeatures::opCallCIRGenFuncInfoExtParamInfo());
204
205 RequiredArgs required =
206 (passParams && md->isVariadic() ? RequiredArgs(argTypes.size())
207 : RequiredArgs::All);
208
209 CanQualType resultType = theCXXABI.hasThisReturn(gd) ? argTypes.front()
210 : theCXXABI.hasMostDerivedReturn(gd)
211 ? astContext.VoidPtrTy
212 : astContext.VoidTy;
213
214 assert(!theCXXABI.hasThisReturn(gd) &&
215 "Please send PR with a test and remove this");
216
217 assert(!cir::MissingFeatures::opCallCIRGenFuncInfoExtParamInfo());
218 assert(!cir::MissingFeatures::opCallFnInfoOpts());
219
220 return arrangeCIRFunctionInfo(resultType, argTypes, required);
221 }
222
223 /// Derives the 'this' type for CIRGen purposes, i.e. ignoring method CVR
224 /// qualification. Either or both of `rd` and `md` may be null. A null `rd`
225 /// indicates that there is no meaningful 'this' type, and a null `md` can occur
226 /// when calling a method pointer.
227 CanQualType CIRGenTypes::deriveThisType(const CXXRecordDecl *rd,
228 const CXXMethodDecl *md) {
229 CanQualType recTy;
230 if (rd) {
231 recTy = getASTContext().getCanonicalTagType(rd);
232 } else {
233 // This can happen with the MS ABI. It shouldn't need anything more than
234 // setting recTy to VoidTy here, but we're flagging it for now because we
235 // don't have the full handling implemented.
236 cgm.errorNYI("deriveThisType: no record decl");
237 recTy = getASTContext().VoidTy;
238 }
239
240 if (md)
241 recTy = CanQualType::CreateUnsafe(getASTContext().getAddrSpaceQualType(
242 recTy, md->getMethodQualifiers().getAddressSpace()));
243 return getASTContext().getPointerType(recTy);
244 }
245
246 /// Arrange the CIR function layout for a value of the given function type, on
247 /// top of any implicit parameters already stored.
248 static const CIRGenFunctionInfo &
249 arrangeCIRFunctionInfo(CIRGenTypes &cgt, SmallVectorImpl<CanQualType> &prefix,
250 CanQual<FunctionProtoType> fpt) {
251 assert(!cir::MissingFeatures::opCallFnInfoOpts());
252 RequiredArgs required =
253 RequiredArgs::getFromProtoWithExtraSlots(fpt, prefix.size());
254 assert(!cir::MissingFeatures::opCallExtParameterInfo());
255 appendParameterTypes(cgt, prefix, fpt);
256 CanQualType resultType = fpt->getReturnType().getUnqualifiedType();
257 return cgt.arrangeCIRFunctionInfo(resultType, prefix, required);
258 }
259
260 void CIRGenFunction::emitDelegateCallArg(CallArgList &args,
261 const VarDecl *param,
262 SourceLocation loc) {
263 // StartFunction converted the ABI-lowered parameter(s) into a local alloca.
264 // We need to turn that into an r-value suitable for emitCall
265 Address local = getAddrOfLocalVar(param);
266
267 QualType type = param->getType();
268
269 if (type->getAsCXXRecordDecl()) {
270 cgm.errorNYI(param->getSourceRange(),
271 "emitDelegateCallArg: record argument");
272 return;
273 }
274
275 // GetAddrOfLocalVar returns a pointer-to-pointer for references, but the
276 // argument needs to be the original pointer.
277 if (type->isReferenceType()) {
278 args.add(
279 RValue::get(builder.createLoad(getLoc(param->getSourceRange()), local)),
280 type);
281 } else if (getLangOpts().ObjCAutoRefCount) {
282 cgm.errorNYI(param->getSourceRange(),
283 "emitDelegateCallArg: ObjCAutoRefCount");
284 // For the most part, we just need to load the alloca, except that aggregate
285 // r-values are actually pointers to temporaries.
286 } else {
287 args.add(convertTempToRValue(local, type, loc), type);
288 }
289
290 // Deactivate the cleanup for the callee-destructed param that was pushed.
291 assert(!cir::MissingFeatures::thunks());
292 if (type->isRecordType() &&
293 type->castAsRecordDecl()->isParamDestroyedInCallee() &&
294 param->needsDestruction(getContext())) {
295 cgm.errorNYI(param->getSourceRange(),
296 "emitDelegateCallArg: callee-destructed param");
297 }
298 }
299
300 static const CIRGenFunctionInfo &
301 arrangeFreeFunctionLikeCall(CIRGenTypes &cgt, CIRGenModule &cgm,
302 const CallArgList &args,
303 const FunctionType *fnType) {
304
305 RequiredArgs required = RequiredArgs::All;
306
307 if (const auto *proto = dyn_cast<FunctionProtoType>(fnType)) {
308 if (proto->isVariadic())
309 required = RequiredArgs::getFromProtoWithExtraSlots(proto, 0);
310 if (proto->hasExtParameterInfos())
311 cgm.errorNYI("call to functions with extra parameter info");
312 } else if (cgm.getTargetCIRGenInfo().isNoProtoCallVariadic(
313 cast<FunctionNoProtoType>(fnType)))
314 cgm.errorNYI("call to function without a prototype");
315
316 SmallVector<CanQualType, 16> argTypes;
317 for (const CallArg &arg : args)
318 argTypes.push_back(cgt.getASTContext().getCanonicalParamType(arg.ty));
319
320 CanQualType retType = fnType->getReturnType()->getCanonicalTypeUnqualified();
321
322 assert(!cir::MissingFeatures::opCallFnInfoOpts());
323 return cgt.arrangeCIRFunctionInfo(retType, argTypes, required);
324 }
325
326 /// Arrange a call to a C++ method, passing the given arguments.
327 ///
328 /// extraPrefixArgs is the number of ABI-specific args passed after the `this`
329 /// parameter.
330 /// passProtoArgs indicates whether `args` has args for the parameters in the
331 /// given CXXConstructorDecl.
332 const CIRGenFunctionInfo &CIRGenTypes::arrangeCXXConstructorCall(
333 const CallArgList &args, const CXXConstructorDecl *d, CXXCtorType ctorKind,
334 unsigned extraPrefixArgs, unsigned extraSuffixArgs, bool passProtoArgs) {
335
336 // FIXME: Kill copy.
337 llvm::SmallVector<CanQualType, 16> argTypes;
338 for (const auto &arg : args)
339 argTypes.push_back(astContext.getCanonicalParamType(arg.ty));
340
341 // +1 for implicit this, which should always be args[0]
342 unsigned totalPrefixArgs = 1 + extraPrefixArgs;
343
344 CanQual<FunctionProtoType> fpt = getFormalType(d);
345 RequiredArgs required = passProtoArgs
346 ? RequiredArgs::getFromProtoWithExtraSlots(
347 fpt, totalPrefixArgs + extraSuffixArgs)
348 : RequiredArgs::All;
349
350 GlobalDecl gd(d, ctorKind);
351 if (theCXXABI.hasThisReturn(gd))
352 cgm.errorNYI(d->getSourceRange(),
353 "arrangeCXXConstructorCall: hasThisReturn");
354 if (theCXXABI.hasMostDerivedReturn(gd))
355 cgm.errorNYI(d->getSourceRange(),
356 "arrangeCXXConstructorCall: hasMostDerivedReturn");
357 CanQualType resultType = astContext.VoidTy;
358
359 assert(!cir::MissingFeatures::opCallFnInfoOpts());
360 assert(!cir::MissingFeatures::opCallCIRGenFuncInfoExtParamInfo());
361
362 return arrangeCIRFunctionInfo(resultType, argTypes, required);
363 }
364
365 /// Arrange a call to a C++ method, passing the given arguments.
366 ///
367 /// numPrefixArgs is the number of the ABI-specific prefix arguments we have. It
368 /// does not count `this`.
369 const CIRGenFunctionInfo &CIRGenTypes::arrangeCXXMethodCall(
370 const CallArgList &args, const FunctionProtoType *proto,
371 RequiredArgs required, unsigned numPrefixArgs) {
372 assert(!cir::MissingFeatures::opCallExtParameterInfo());
373 assert(numPrefixArgs + 1 <= args.size() &&
374 "Emitting a call with less args than the required prefix?");
375
376 // FIXME: Kill copy.
377 llvm::SmallVector<CanQualType, 16> argTypes;
378 for (const CallArg &arg : args)
379 argTypes.push_back(astContext.getCanonicalParamType(arg.ty));
380
381 assert(!cir::MissingFeatures::opCallFnInfoOpts());
382 return arrangeCIRFunctionInfo(
383 proto->getReturnType()->getCanonicalTypeUnqualified(), argTypes,
384 required);
385 }
386
387 const CIRGenFunctionInfo &
388 CIRGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
389 const FunctionType *fnType) {
390 return arrangeFreeFunctionLikeCall(*this, cgm, args, fnType);
391 }
392
393 /// Arrange the argument and result information for a declaration or definition
394 /// of the given C++ non-static member function. The member function must be an
395 /// ordinary function, i.e. not a constructor or destructor.
396 const CIRGenFunctionInfo &
397 CIRGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *md) {
398 assert(!isa<CXXConstructorDecl>(md) && "wrong method for constructors!");
399 assert(!isa<CXXDestructorDecl>(md) && "wrong method for destructors!");
400
401 auto prototype =
402 md->getType()->getCanonicalTypeUnqualified().getAs<FunctionProtoType>();
403 assert(!cir::MissingFeatures::cudaSupport());
404
405 if (md->isInstance()) {
406 // The abstract case is perfectly fine.
407 auto *thisType = theCXXABI.getThisArgumentTypeForMethod(md);
408 return arrangeCXXMethodType(thisType, prototype.getTypePtr(), md);
409 }
410
411 return arrangeFreeFunctionType(prototype);
412 }
413
414 /// Arrange the argument and result information for a call to an unknown C++
415 /// non-static member function of the given abstract type. (A null RD means we
416 /// don't have any meaningful "this" argument type, so fall back to a generic
417 /// pointer type). The member fucntion must be an ordinary function, i.e. not a
418 /// constructor or destructor.
419 const CIRGenFunctionInfo &
420 CIRGenTypes::arrangeCXXMethodType(const CXXRecordDecl *rd,
421 const FunctionProtoType *fpt,
422 const CXXMethodDecl *md) {
423 llvm::SmallVector<CanQualType, 16> argTypes;
424
425 // Add the 'this' pointer.
426 argTypes.push_back(deriveThisType(rd, md));
427
428 assert(!cir::MissingFeatures::opCallFnInfoOpts());
429 return ::arrangeCIRFunctionInfo(
430 *this, argTypes,
431 fpt->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
432 }
433
434 /// Arrange the argument and result information for the declaration or
435 /// definition of the given function.
436 const CIRGenFunctionInfo &
437 CIRGenTypes::arrangeFunctionDeclaration(const FunctionDecl *fd) {
438 if (const auto *md = dyn_cast<CXXMethodDecl>(fd))
439 if (md->isInstance())
440 return arrangeCXXMethodDeclaration(md);
441
442 CanQualType funcTy = fd->getType()->getCanonicalTypeUnqualified();
443
444 assert(isa<FunctionType>(funcTy));
445 // TODO: setCUDAKernelCallingConvention
446 assert(!cir::MissingFeatures::cudaSupport());
447
448 // When declaring a function without a prototype, always use a non-variadic
449 // type.
450 if (CanQual<FunctionNoProtoType> noProto =
451 funcTy.getAs<FunctionNoProtoType>()) {
452 assert(!cir::MissingFeatures::opCallCIRGenFuncInfoExtParamInfo());
453 assert(!cir::MissingFeatures::opCallFnInfoOpts());
454 return arrangeCIRFunctionInfo(noProto->getReturnType(), {},
455 RequiredArgs::All);
456 }
457
458 return arrangeFreeFunctionType(funcTy.castAs<FunctionProtoType>());
459 }
460
461 static cir::CIRCallOpInterface
462 emitCallLikeOp(CIRGenFunction &cgf, mlir::Location callLoc,
463 cir::FuncType indirectFuncTy, mlir::Value indirectFuncVal,
464 cir::FuncOp directFuncOp,
465 const SmallVectorImpl<mlir::Value> &cirCallArgs, bool isInvoke,
466 const mlir::NamedAttrList &attrs) {
467 CIRGenBuilderTy &builder = cgf.getBuilder();
468
469 assert(!cir::MissingFeatures::opCallSurroundingTry());
470
471 if (isInvoke) {
472 // This call may throw and requires catch and/or cleanup handling.
473 // If this call does not appear within the `try` region of an existing
474 // TryOp, we must create a synthetic TryOp to contain the call. This
475 // happens when a call that may throw appears within a cleanup
476 // scope.
477
478 // In OG, we build the landing pad for this scope. In CIR, we emit a
479 // synthetic cir.try because this didn't come from code generating from a
480 // try/catch in C++.
481 assert(cgf.curLexScope && "expected scope");
482 cir::TryOp tryOp = cgf.curLexScope->getClosestTryParent();
483 if (!tryOp) {
484 cgf.cgm.errorNYI(
485 "emitCallLikeOp: call does not have an associated cir.try");
486 return {};
487 }
488
489 if (tryOp.getSynthetic()) {
490 cgf.cgm.errorNYI("emitCallLikeOp: tryOp synthetic");
491 return {};
492 }
493
494 cir::CallOp callOpWithExceptions;
495 if (indirectFuncTy) {
496 cgf.cgm.errorNYI("emitCallLikeOp: indirect function type");
497 return {};
498 }
499
500 callOpWithExceptions =
501 builder.createCallOp(callLoc, directFuncOp, cirCallArgs);
502
503 cgf.populateCatchHandlersIfRequired(tryOp);
504 return callOpWithExceptions;
505 }
506
507 assert(builder.getInsertionBlock() && "expected valid basic block");
508
509 cir::CallOp op;
510 if (indirectFuncTy) {
511 // TODO(cir): Set calling convention for indirect calls.
512 assert(!cir::MissingFeatures::opCallCallConv());
513 op = builder.createIndirectCallOp(callLoc, indirectFuncVal, indirectFuncTy,
514 cirCallArgs, attrs);
515 } else {
516 op = builder.createCallOp(callLoc, directFuncOp, cirCallArgs, attrs);
517 }
518
519 return op;
520 }
521
522 const CIRGenFunctionInfo &
523 CIRGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> fpt) {
524 SmallVector<CanQualType, 16> argTypes;
525 assert(!cir::MissingFeatures::opCallFnInfoOpts());
526 return ::arrangeCIRFunctionInfo(*this, argTypes, fpt);
527 }
528
529 const CIRGenFunctionInfo &
530 CIRGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> fnpt) {
531 CanQualType resultType = fnpt->getReturnType().getUnqualifiedType();
532 assert(!cir::MissingFeatures::opCallFnInfoOpts());
533 return arrangeCIRFunctionInfo(resultType, {}, RequiredArgs(0));
534 }
535
536 RValue CIRGenFunction::emitCall(const CIRGenFunctionInfo &funcInfo,
537 const CIRGenCallee &callee,
538 ReturnValueSlot returnValue,
539 const CallArgList &args,
540 cir::CIRCallOpInterface *callOp,
541 mlir::Location loc) {
542 QualType retTy = funcInfo.getReturnType();
543 cir::FuncType cirFuncTy = getTypes().getFunctionType(funcInfo);
544
545 SmallVector<mlir::Value, 16> cirCallArgs(args.size());
546
547 assert(!cir::MissingFeatures::emitLifetimeMarkers());
548
549 // Translate all of the arguments as necessary to match the CIR lowering.
550 for (auto [argNo, arg, canQualArgType] :
551 llvm::enumerate(args, funcInfo.argTypes())) {
552
553 // Insert a padding argument to ensure proper alignment.
554 assert(!cir::MissingFeatures::opCallPaddingArgs());
555
556 mlir::Type argType = convertType(canQualArgType);
557 if (!mlir::isa<cir::RecordType>(argType) &&
558 !mlir::isa<cir::ComplexType>(argType)) {
559 mlir::Value v;
560 if (arg.isAggregate())
561 cgm.errorNYI(loc, "emitCall: aggregate call argument");
562 v = arg.getKnownRValue().getValue();
563
564 // We might have to widen integers, but we should never truncate.
565 if (argType != v.getType() && mlir::isa<cir::IntType>(v.getType()))
566 cgm.errorNYI(loc, "emitCall: widening integer call argument");
567
568 // If the argument doesn't match, perform a bitcast to coerce it. This
569 // can happen due to trivial type mismatches.
570 // TODO(cir): When getFunctionType is added, assert that this isn't
571 // needed.
572 assert(!cir::MissingFeatures::opCallBitcastArg());
573 cirCallArgs[argNo] = v;
574 } else {
575 Address src = Address::invalid();
576 if (!arg.isAggregate()) {
577 src = createMemTemp(arg.ty, loc, "coerce");
578 arg.copyInto(*this, src, loc);
579 } else {
580 src = arg.hasLValue() ? arg.getKnownLValue().getAddress()
581 : arg.getKnownRValue().getAggregateAddress();
582 }
583
584 // Fast-isel and the optimizer generally like scalar values better than
585 // FCAs, so we flatten them if this is safe to do for this argument.
586 mlir::Type srcTy = src.getElementType();
587 // FIXME(cir): get proper location for each argument.
588 mlir::Location argLoc = loc;
589
590 // If the source type is smaller than the destination type of the
591 // coerce-to logic, copy the source value into a temp alloca the size
592 // of the destination type to allow loading all of it. The bits past
593 // the source value are left undef.
594 // FIXME(cir): add data layout info and compare sizes instead of
595 // matching the types.
596 //
597 // uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
598 // uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
599 // if (SrcSize < DstSize) {
600 assert(!cir::MissingFeatures::dataLayoutTypeAllocSize());
601 if (srcTy != argType) {
602 cgm.errorNYI(loc, "emitCall: source type does not match argument type");
603 } else {
604 // FIXME(cir): this currently only runs when the types are exactly the
605 // same, but should be when alloc sizes are the same, fix this as soon
606 // as datalayout gets introduced.
607 assert(!cir::MissingFeatures::dataLayoutTypeAllocSize());
608 }
609
610 // assert(NumCIRArgs == STy.getMembers().size());
611 // In LLVMGen: Still only pass the struct without any gaps but mark it
612 // as such somehow.
613 //
614 // In CIRGen: Emit a load from the "whole" struct,
615 // which shall be broken later by some lowering step into multiple
616 // loads.
617 assert(!cir::MissingFeatures::lowerAggregateLoadStore());
618 cirCallArgs[argNo] = builder.createLoad(argLoc, src);
619 }
620 }
621
622 const CIRGenCallee &concreteCallee = callee.prepareConcreteCallee(*this);
623 mlir::Operation *calleePtr = concreteCallee.getFunctionPointer();
624
625 assert(!cir::MissingFeatures::opCallInAlloca());
626
627 mlir::NamedAttrList attrs;
628 StringRef funcName;
629 if (auto calleeFuncOp = dyn_cast<cir::FuncOp>(calleePtr))
630 funcName = calleeFuncOp.getName();
631
632 assert(!cir::MissingFeatures::opCallCallConv());
633 assert(!cir::MissingFeatures::opCallAttrs());
634 cgm.constructAttributeList(callee.getAbstractInfo(), attrs);
635
636 cir::FuncType indirectFuncTy;
637 mlir::Value indirectFuncVal;
638 cir::FuncOp directFuncOp;
639 if (auto fnOp = dyn_cast<cir::FuncOp>(calleePtr)) {
640 directFuncOp = fnOp;
641 } else if (auto getGlobalOp = mlir::dyn_cast<cir::GetGlobalOp>(calleePtr)) {
642 // FIXME(cir): This peephole optimization avoids indirect calls for
643 // builtins. This should be fixed in the builtin declaration instead by
644 // not emitting an unecessary get_global in the first place.
645 // However, this is also used for no-prototype functions.
646 mlir::Operation *globalOp = cgm.getGlobalValue(getGlobalOp.getName());
647 assert(globalOp && "undefined global function");
648 directFuncOp = mlir::cast<cir::FuncOp>(globalOp);
649 } else {
650 [[maybe_unused]] mlir::ValueTypeRange<mlir::ResultRange> resultTypes =
651 calleePtr->getResultTypes();
652 [[maybe_unused]] auto funcPtrTy =
653 mlir::dyn_cast<cir::PointerType>(resultTypes.front());
654 assert(funcPtrTy && mlir::isa<cir::FuncType>(funcPtrTy.getPointee()) &&
655 "expected pointer to function");
656
657 indirectFuncTy = cirFuncTy;
658 indirectFuncVal = calleePtr->getResult(0);
659 }
660
661 assert(!cir::MissingFeatures::msvcCXXPersonality());
662 assert(!cir::MissingFeatures::functionUsesSEHTry());
663 assert(!cir::MissingFeatures::nothrowAttr());
664
665 bool cannotThrow = attrs.getNamed("nothrow").has_value();
666 bool isInvoke = !cannotThrow && isCatchOrCleanupRequired();
667
668 mlir::Location callLoc = loc;
669 cir::CIRCallOpInterface theCall =
670 emitCallLikeOp(*this, loc, indirectFuncTy, indirectFuncVal, directFuncOp,
671 cirCallArgs, isInvoke, attrs);
672
673 if (callOp)
674 *callOp = theCall;
675
676 assert(!cir::MissingFeatures::opCallMustTail());
677 assert(!cir::MissingFeatures::opCallReturn());
678
679 mlir::Type retCIRTy = convertType(retTy);
680 if (isa<cir::VoidType>(retCIRTy))
681 return getUndefRValue(retTy);
682 switch (getEvaluationKind(retTy)) {
683 case cir::TEK_Aggregate: {
684 Address destPtr = returnValue.getValue();
685
686 if (!destPtr.isValid())
687 destPtr = createMemTemp(retTy, callLoc, getCounterAggTmpAsString());
688
689 mlir::ResultRange results = theCall->getOpResults();
690 assert(results.size() <= 1 && "multiple returns from a call");
691
692 SourceLocRAIIObject loc{*this, callLoc};
693 emitAggregateStore(results[0], destPtr);
694 return RValue::getAggregate(destPtr);
695 }
696 case cir::TEK_Scalar: {
697 mlir::ResultRange results = theCall->getOpResults();
698 assert(results.size() == 1 && "unexpected number of returns");
699
700 // If the argument doesn't match, perform a bitcast to coerce it. This
701 // can happen due to trivial type mismatches.
702 if (results[0].getType() != retCIRTy)
703 cgm.errorNYI(loc, "bitcast on function return value");
704
705 mlir::Region *region = builder.getBlock()->getParent();
706 if (region != theCall->getParentRegion())
707 cgm.errorNYI(loc, "function calls with cleanup");
708
709 return RValue::get(results[0]);
710 }
711 case cir::TEK_Complex: {
712 mlir::ResultRange results = theCall->getOpResults();
713 assert(!results.empty() &&
714 "Expected at least one result for complex rvalue");
715 return RValue::getComplex(results[0]);
716 }
717 }
718 llvm_unreachable("Invalid evaluation kind");
719 }
720
721 void CallArg::copyInto(CIRGenFunction &cgf, Address addr,
722 mlir::Location loc) const {
723 LValue dst = cgf.makeAddrLValue(addr, ty);
724 if (!hasLV && rv.isScalar())
725 cgf.cgm.errorNYI(loc, "copyInto scalar value");
726 else if (!hasLV && rv.isComplex())
727 cgf.emitStoreOfComplex(loc, rv.getComplexValue(), dst, /*isInit=*/true);
728 else
729 cgf.cgm.errorNYI(loc, "copyInto hasLV");
730 isUsed = true;
731 }
732
733 mlir::Value CIRGenFunction::emitRuntimeCall(mlir::Location loc,
734 cir::FuncOp callee,
735 ArrayRef<mlir::Value> args) {
736 // TODO(cir): set the calling convention to this runtime call.
737 assert(!cir::MissingFeatures::opFuncCallingConv());
738
739 cir::CallOp call = builder.createCallOp(loc, callee, args);
740 assert(call->getNumResults() <= 1 &&
741 "runtime functions have at most 1 result");
742
743 if (call->getNumResults() == 0)
744 return nullptr;
745
746 return call->getResult(0);
747 }
748
749 void CIRGenFunction::emitCallArg(CallArgList &args, const clang::Expr *e,
750 clang::QualType argType) {
751 assert(argType->isReferenceType() == e->isGLValue() &&
752 "reference binding to unmaterialized r-value!");
753
754 if (e->isGLValue()) {
755 assert(e->getObjectKind() == OK_Ordinary);
756 return args.add(emitReferenceBindingToExpr(e), argType);
757 }
758
759 bool hasAggregateEvalKind = hasAggregateEvaluationKind(argType);
760
761 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
762 // However, we still have to push an EH-only cleanup in case we unwind before
763 // we make it to the call.
764 if (argType->isRecordType() &&
765 argType->castAsRecordDecl()->isParamDestroyedInCallee()) {
766 assert(!cir::MissingFeatures::msabi());
767 cgm.errorNYI(e->getSourceRange(), "emitCallArg: msabi is NYI");
768 }
769
770 if (hasAggregateEvalKind && isa<ImplicitCastExpr>(e) &&
771 cast<CastExpr>(e)->getCastKind() == CK_LValueToRValue) {
772 LValue lv = emitLValue(cast<CastExpr>(e)->getSubExpr());
773 assert(lv.isSimple());
774 args.addUncopiedAggregate(lv, argType);
775 return;
776 }
777
778 args.add(emitAnyExprToTemp(e), argType);
779 }
780
781 QualType CIRGenFunction::getVarArgType(const Expr *arg) {
782 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
783 // implicitly widens null pointer constants that are arguments to varargs
784 // functions to pointer-sized ints.
785 if (!getTarget().getTriple().isOSWindows())
786 return arg->getType();
787
788 assert(!cir::MissingFeatures::msabi());
789 cgm.errorNYI(arg->getSourceRange(), "getVarArgType: NYI for Windows target");
790 return arg->getType();
791 }
792
793 /// Similar to emitAnyExpr(), however, the result will always be accessible
794 /// even if no aggregate location is provided.
795 RValue CIRGenFunction::emitAnyExprToTemp(const Expr *e) {
796 AggValueSlot aggSlot = AggValueSlot::ignored();
797
798 if (hasAggregateEvaluationKind(e->getType()))
799 aggSlot = createAggTemp(e->getType(), getLoc(e->getSourceRange()),
800 getCounterAggTmpAsString());
801
802 return emitAnyExpr(e, aggSlot);
803 }
804
805 void CIRGenFunction::emitCallArgs(
806 CallArgList &args, PrototypeWrapper prototype,
807 llvm::iterator_range<clang::CallExpr::const_arg_iterator> argRange,
808 AbstractCallee callee, unsigned paramsToSkip) {
809 llvm::SmallVector<QualType, 16> argTypes;
810
811 assert(!cir::MissingFeatures::opCallCallConv());
812
813 // First, if a prototype was provided, use those argument types.
814 bool isVariadic = false;
815 if (prototype.p) {
816 assert(!cir::MissingFeatures::opCallObjCMethod());
817
818 const auto *fpt = cast<const FunctionProtoType *>(prototype.p);
819 isVariadic = fpt->isVariadic();
820 assert(!cir::MissingFeatures::opCallCallConv());
821 argTypes.assign(fpt->param_type_begin() + paramsToSkip,
822 fpt->param_type_end());
823 }
824
825 // If we still have any arguments, emit them using the type of the argument.
826 for (const clang::Expr *a : llvm::drop_begin(argRange, argTypes.size()))
827 argTypes.push_back(isVariadic ? getVarArgType(a) : a->getType());
828 assert(argTypes.size() == (size_t)(argRange.end() - argRange.begin()));
829
830 // We must evaluate arguments from right to left in the MS C++ ABI, because
831 // arguments are destroyed left to right in the callee. As a special case,
832 // there are certain language constructs taht require left-to-right
833 // evaluation, and in those cases we consider the evaluation order requirement
834 // to trump the "destruction order is reverse construction order" guarantee.
835 auto leftToRight = true;
836 assert(!cir::MissingFeatures::msabi());
837
838 auto maybeEmitImplicitObjectSize = [&](size_t i, const Expr *arg,
839 RValue emittedArg) {
840 if (!callee.hasFunctionDecl() || i >= callee.getNumParams())
841 return;
842 auto *ps = callee.getParamDecl(i)->getAttr<PassObjectSizeAttr>();
843 if (!ps)
844 return;
845
846 assert(!cir::MissingFeatures::opCallImplicitObjectSizeArgs());
847 cgm.errorNYI("emit implicit object size for call arg");
848 };
849
850 // Evaluate each argument in the appropriate order.
851 size_t callArgsStart = args.size();
852 for (size_t i = 0; i != argTypes.size(); ++i) {
853 size_t idx = leftToRight ? i : argTypes.size() - i - 1;
854 CallExpr::const_arg_iterator currentArg = argRange.begin() + idx;
855 size_t initialArgSize = args.size();
856
857 emitCallArg(args, *currentArg, argTypes[idx]);
858
859 // In particular, we depend on it being the last arg in Args, and the
860 // objectsize bits depend on there only being one arg if !LeftToRight.
861 assert(initialArgSize + 1 == args.size() &&
862 "The code below depends on only adding one arg per emitCallArg");
863 (void)initialArgSize;
864
865 // Since pointer argument are never emitted as LValue, it is safe to emit
866 // non-null argument check for r-value only.
867 if (!args.back().hasLValue()) {
868 RValue rvArg = args.back().getKnownRValue();
869 assert(!cir::MissingFeatures::sanitizers());
870 maybeEmitImplicitObjectSize(idx, *currentArg, rvArg);
871 }
872
873 if (!leftToRight)
874 std::reverse(args.begin() + callArgsStart, args.end());
875 }
876 }