[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / CodeGen / CGExpr.cpp
blob54a1d300a9ac738a95b59577729fcf5e36b53a51
1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
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 // This contains code to emit Expr nodes as LLVM code.
11 //===----------------------------------------------------------------------===//
13 #include "CGCUDARuntime.h"
14 #include "CGCXXABI.h"
15 #include "CGCall.h"
16 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CGRecordLayout.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenModule.h"
23 #include "ConstantEmitter.h"
24 #include "TargetInfo.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/Attr.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/NSAPI.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/CodeGenOptions.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "llvm/ADT/Hashing.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/IntrinsicsWebAssembly.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/MatrixBuilder.h"
41 #include "llvm/Passes/OptimizationLevel.h"
42 #include "llvm/Support/ConvertUTF.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/SaveAndRestore.h"
46 #include "llvm/Support/xxhash.h"
47 #include "llvm/Transforms/Utils/SanitizerStats.h"
49 #include <optional>
50 #include <string>
52 using namespace clang;
53 using namespace CodeGen;
55 // Experiment to make sanitizers easier to debug
56 static llvm::cl::opt<bool> ClSanitizeDebugDeoptimization(
57 "ubsan-unique-traps", llvm::cl::Optional,
58 llvm::cl::desc("Deoptimize traps for UBSAN so there is 1 trap per check"),
59 llvm::cl::init(false));
61 //===--------------------------------------------------------------------===//
62 // Miscellaneous Helper Methods
63 //===--------------------------------------------------------------------===//
65 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
66 /// block.
67 Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
68 CharUnits Align,
69 const Twine &Name,
70 llvm::Value *ArraySize) {
71 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
72 Alloca->setAlignment(Align.getAsAlign());
73 return Address(Alloca, Ty, Align, KnownNonNull);
76 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
77 /// block. The alloca is casted to default address space if necessary.
78 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
79 const Twine &Name,
80 llvm::Value *ArraySize,
81 Address *AllocaAddr) {
82 auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
83 if (AllocaAddr)
84 *AllocaAddr = Alloca;
85 llvm::Value *V = Alloca.getPointer();
86 // Alloca always returns a pointer in alloca address space, which may
87 // be different from the type defined by the language. For example,
88 // in C++ the auto variables are in the default address space. Therefore
89 // cast alloca to the default address space when necessary.
90 if (getASTAllocaAddressSpace() != LangAS::Default) {
91 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
92 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
93 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
94 // otherwise alloca is inserted at the current insertion point of the
95 // builder.
96 if (!ArraySize)
97 Builder.SetInsertPoint(getPostAllocaInsertPoint());
98 V = getTargetHooks().performAddrSpaceCast(
99 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
100 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
103 return Address(V, Ty, Align, KnownNonNull);
106 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
107 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
108 /// insertion point of the builder.
109 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
110 const Twine &Name,
111 llvm::Value *ArraySize) {
112 if (ArraySize)
113 return Builder.CreateAlloca(Ty, ArraySize, Name);
114 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
115 ArraySize, Name, AllocaInsertPt);
118 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
119 /// default alignment of the corresponding LLVM type, which is *not*
120 /// guaranteed to be related in any way to the expected alignment of
121 /// an AST type that might have been lowered to Ty.
122 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
123 const Twine &Name) {
124 CharUnits Align =
125 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
126 return CreateTempAlloca(Ty, Align, Name);
129 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
130 CharUnits Align = getContext().getTypeAlignInChars(Ty);
131 return CreateTempAlloca(ConvertType(Ty), Align, Name);
134 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
135 Address *Alloca) {
136 // FIXME: Should we prefer the preferred type alignment here?
137 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
140 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
141 const Twine &Name, Address *Alloca) {
142 Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
143 /*ArraySize=*/nullptr, Alloca);
145 if (Ty->isConstantMatrixType()) {
146 auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
147 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
148 ArrayTy->getNumElements());
150 Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(),
151 KnownNonNull);
153 return Result;
156 Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
157 const Twine &Name) {
158 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
161 Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
162 const Twine &Name) {
163 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
164 Name);
167 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
168 /// expression and compare the result against zero, returning an Int1Ty value.
169 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
170 PGO.setCurrentStmt(E);
171 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
172 llvm::Value *MemPtr = EmitScalarExpr(E);
173 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
176 QualType BoolTy = getContext().BoolTy;
177 SourceLocation Loc = E->getExprLoc();
178 CGFPOptionsRAII FPOptsRAII(*this, E);
179 if (!E->getType()->isAnyComplexType())
180 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
182 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
183 Loc);
186 /// EmitIgnoredExpr - Emit code to compute the specified expression,
187 /// ignoring the result.
188 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
189 if (E->isPRValue())
190 return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
192 // if this is a bitfield-resulting conditional operator, we can special case
193 // emit this. The normal 'EmitLValue' version of this is particularly
194 // difficult to codegen for, since creating a single "LValue" for two
195 // different sized arguments here is not particularly doable.
196 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
197 E->IgnoreParenNoopCasts(getContext()))) {
198 if (CondOp->getObjectKind() == OK_BitField)
199 return EmitIgnoredConditionalOperator(CondOp);
202 // Just emit it as an l-value and drop the result.
203 EmitLValue(E);
206 /// EmitAnyExpr - Emit code to compute the specified expression which
207 /// can have any type. The result is returned as an RValue struct.
208 /// If this is an aggregate expression, AggSlot indicates where the
209 /// result should be returned.
210 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
211 AggValueSlot aggSlot,
212 bool ignoreResult) {
213 switch (getEvaluationKind(E->getType())) {
214 case TEK_Scalar:
215 return RValue::get(EmitScalarExpr(E, ignoreResult));
216 case TEK_Complex:
217 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
218 case TEK_Aggregate:
219 if (!ignoreResult && aggSlot.isIgnored())
220 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
221 EmitAggExpr(E, aggSlot);
222 return aggSlot.asRValue();
224 llvm_unreachable("bad evaluation kind");
227 /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
228 /// always be accessible even if no aggregate location is provided.
229 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
230 AggValueSlot AggSlot = AggValueSlot::ignored();
232 if (hasAggregateEvaluationKind(E->getType()))
233 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
234 return EmitAnyExpr(E, AggSlot);
237 /// EmitAnyExprToMem - Evaluate an expression into a given memory
238 /// location.
239 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
240 Address Location,
241 Qualifiers Quals,
242 bool IsInit) {
243 // FIXME: This function should take an LValue as an argument.
244 switch (getEvaluationKind(E->getType())) {
245 case TEK_Complex:
246 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
247 /*isInit*/ false);
248 return;
250 case TEK_Aggregate: {
251 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
252 AggValueSlot::IsDestructed_t(IsInit),
253 AggValueSlot::DoesNotNeedGCBarriers,
254 AggValueSlot::IsAliased_t(!IsInit),
255 AggValueSlot::MayOverlap));
256 return;
259 case TEK_Scalar: {
260 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
261 LValue LV = MakeAddrLValue(Location, E->getType());
262 EmitStoreThroughLValue(RV, LV);
263 return;
266 llvm_unreachable("bad evaluation kind");
269 static void
270 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
271 const Expr *E, Address ReferenceTemporary) {
272 // Objective-C++ ARC:
273 // If we are binding a reference to a temporary that has ownership, we
274 // need to perform retain/release operations on the temporary.
276 // FIXME: This should be looking at E, not M.
277 if (auto Lifetime = M->getType().getObjCLifetime()) {
278 switch (Lifetime) {
279 case Qualifiers::OCL_None:
280 case Qualifiers::OCL_ExplicitNone:
281 // Carry on to normal cleanup handling.
282 break;
284 case Qualifiers::OCL_Autoreleasing:
285 // Nothing to do; cleaned up by an autorelease pool.
286 return;
288 case Qualifiers::OCL_Strong:
289 case Qualifiers::OCL_Weak:
290 switch (StorageDuration Duration = M->getStorageDuration()) {
291 case SD_Static:
292 // Note: we intentionally do not register a cleanup to release
293 // the object on program termination.
294 return;
296 case SD_Thread:
297 // FIXME: We should probably register a cleanup in this case.
298 return;
300 case SD_Automatic:
301 case SD_FullExpression:
302 CodeGenFunction::Destroyer *Destroy;
303 CleanupKind CleanupKind;
304 if (Lifetime == Qualifiers::OCL_Strong) {
305 const ValueDecl *VD = M->getExtendingDecl();
306 bool Precise =
307 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
308 CleanupKind = CGF.getARCCleanupKind();
309 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
310 : &CodeGenFunction::destroyARCStrongImprecise;
311 } else {
312 // __weak objects always get EH cleanups; otherwise, exceptions
313 // could cause really nasty crashes instead of mere leaks.
314 CleanupKind = NormalAndEHCleanup;
315 Destroy = &CodeGenFunction::destroyARCWeak;
317 if (Duration == SD_FullExpression)
318 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
319 M->getType(), *Destroy,
320 CleanupKind & EHCleanup);
321 else
322 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
323 M->getType(),
324 *Destroy, CleanupKind & EHCleanup);
325 return;
327 case SD_Dynamic:
328 llvm_unreachable("temporary cannot have dynamic storage duration");
330 llvm_unreachable("unknown storage duration");
334 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
335 if (const RecordType *RT =
336 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
337 // Get the destructor for the reference temporary.
338 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
339 if (!ClassDecl->hasTrivialDestructor())
340 ReferenceTemporaryDtor = ClassDecl->getDestructor();
343 if (!ReferenceTemporaryDtor)
344 return;
346 // Call the destructor for the temporary.
347 switch (M->getStorageDuration()) {
348 case SD_Static:
349 case SD_Thread: {
350 llvm::FunctionCallee CleanupFn;
351 llvm::Constant *CleanupArg;
352 if (E->getType()->isArrayType()) {
353 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
354 ReferenceTemporary, E->getType(),
355 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
356 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
357 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
358 } else {
359 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
360 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
361 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
363 CGF.CGM.getCXXABI().registerGlobalDtor(
364 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
365 break;
368 case SD_FullExpression:
369 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
370 CodeGenFunction::destroyCXXObject,
371 CGF.getLangOpts().Exceptions);
372 break;
374 case SD_Automatic:
375 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
376 ReferenceTemporary, E->getType(),
377 CodeGenFunction::destroyCXXObject,
378 CGF.getLangOpts().Exceptions);
379 break;
381 case SD_Dynamic:
382 llvm_unreachable("temporary cannot have dynamic storage duration");
386 static Address createReferenceTemporary(CodeGenFunction &CGF,
387 const MaterializeTemporaryExpr *M,
388 const Expr *Inner,
389 Address *Alloca = nullptr) {
390 auto &TCG = CGF.getTargetHooks();
391 switch (M->getStorageDuration()) {
392 case SD_FullExpression:
393 case SD_Automatic: {
394 // If we have a constant temporary array or record try to promote it into a
395 // constant global under the same rules a normal constant would've been
396 // promoted. This is easier on the optimizer and generally emits fewer
397 // instructions.
398 QualType Ty = Inner->getType();
399 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
400 (Ty->isArrayType() || Ty->isRecordType()) &&
401 Ty.isConstantStorage(CGF.getContext(), true, false))
402 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
403 auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
404 auto *GV = new llvm::GlobalVariable(
405 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
406 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
407 llvm::GlobalValue::NotThreadLocal,
408 CGF.getContext().getTargetAddressSpace(AS));
409 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
410 GV->setAlignment(alignment.getAsAlign());
411 llvm::Constant *C = GV;
412 if (AS != LangAS::Default)
413 C = TCG.performAddrSpaceCast(
414 CGF.CGM, GV, AS, LangAS::Default,
415 GV->getValueType()->getPointerTo(
416 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
417 // FIXME: Should we put the new global into a COMDAT?
418 return Address(C, GV->getValueType(), alignment);
420 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
422 case SD_Thread:
423 case SD_Static:
424 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
426 case SD_Dynamic:
427 llvm_unreachable("temporary can't have dynamic storage duration");
429 llvm_unreachable("unknown storage duration");
432 /// Helper method to check if the underlying ABI is AAPCS
433 static bool isAAPCS(const TargetInfo &TargetInfo) {
434 return TargetInfo.getABI().startswith("aapcs");
437 LValue CodeGenFunction::
438 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
439 const Expr *E = M->getSubExpr();
441 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
442 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
443 "Reference should never be pseudo-strong!");
445 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
446 // as that will cause the lifetime adjustment to be lost for ARC
447 auto ownership = M->getType().getObjCLifetime();
448 if (ownership != Qualifiers::OCL_None &&
449 ownership != Qualifiers::OCL_ExplicitNone) {
450 Address Object = createReferenceTemporary(*this, M, E);
451 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
452 llvm::Type *Ty = ConvertTypeForMem(E->getType());
453 Object = Address(llvm::ConstantExpr::getBitCast(
454 Var, Ty->getPointerTo(Object.getAddressSpace())),
455 Ty, Object.getAlignment());
457 // createReferenceTemporary will promote the temporary to a global with a
458 // constant initializer if it can. It can only do this to a value of
459 // ARC-manageable type if the value is global and therefore "immune" to
460 // ref-counting operations. Therefore we have no need to emit either a
461 // dynamic initialization or a cleanup and we can just return the address
462 // of the temporary.
463 if (Var->hasInitializer())
464 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
466 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
468 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
469 AlignmentSource::Decl);
471 switch (getEvaluationKind(E->getType())) {
472 default: llvm_unreachable("expected scalar or aggregate expression");
473 case TEK_Scalar:
474 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
475 break;
476 case TEK_Aggregate: {
477 EmitAggExpr(E, AggValueSlot::forAddr(Object,
478 E->getType().getQualifiers(),
479 AggValueSlot::IsDestructed,
480 AggValueSlot::DoesNotNeedGCBarriers,
481 AggValueSlot::IsNotAliased,
482 AggValueSlot::DoesNotOverlap));
483 break;
487 pushTemporaryCleanup(*this, M, E, Object);
488 return RefTempDst;
491 SmallVector<const Expr *, 2> CommaLHSs;
492 SmallVector<SubobjectAdjustment, 2> Adjustments;
493 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
495 for (const auto &Ignored : CommaLHSs)
496 EmitIgnoredExpr(Ignored);
498 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
499 if (opaque->getType()->isRecordType()) {
500 assert(Adjustments.empty());
501 return EmitOpaqueValueLValue(opaque);
505 // Create and initialize the reference temporary.
506 Address Alloca = Address::invalid();
507 Address Object = createReferenceTemporary(*this, M, E, &Alloca);
508 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
509 Object.getPointer()->stripPointerCasts())) {
510 llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
511 Object = Address(llvm::ConstantExpr::getBitCast(
512 cast<llvm::Constant>(Object.getPointer()),
513 TemporaryType->getPointerTo()),
514 TemporaryType,
515 Object.getAlignment());
516 // If the temporary is a global and has a constant initializer or is a
517 // constant temporary that we promoted to a global, we may have already
518 // initialized it.
519 if (!Var->hasInitializer()) {
520 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
521 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
523 } else {
524 switch (M->getStorageDuration()) {
525 case SD_Automatic:
526 if (auto *Size = EmitLifetimeStart(
527 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
528 Alloca.getPointer())) {
529 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
530 Alloca, Size);
532 break;
534 case SD_FullExpression: {
535 if (!ShouldEmitLifetimeMarkers)
536 break;
538 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
539 // marker. Instead, start the lifetime of a conditional temporary earlier
540 // so that it's unconditional. Don't do this with sanitizers which need
541 // more precise lifetime marks. However when inside an "await.suspend"
542 // block, we should always avoid conditional cleanup because it creates
543 // boolean marker that lives across await_suspend, which can destroy coro
544 // frame.
545 ConditionalEvaluation *OldConditional = nullptr;
546 CGBuilderTy::InsertPoint OldIP;
547 if (isInConditionalBranch() && !E->getType().isDestructedType() &&
548 ((!SanOpts.has(SanitizerKind::HWAddress) &&
549 !SanOpts.has(SanitizerKind::Memory) &&
550 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
551 inSuspendBlock())) {
552 OldConditional = OutermostConditional;
553 OutermostConditional = nullptr;
555 OldIP = Builder.saveIP();
556 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
557 Builder.restoreIP(CGBuilderTy::InsertPoint(
558 Block, llvm::BasicBlock::iterator(Block->back())));
561 if (auto *Size = EmitLifetimeStart(
562 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
563 Alloca.getPointer())) {
564 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
565 Size);
568 if (OldConditional) {
569 OutermostConditional = OldConditional;
570 Builder.restoreIP(OldIP);
572 break;
575 default:
576 break;
578 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
580 pushTemporaryCleanup(*this, M, E, Object);
582 // Perform derived-to-base casts and/or field accesses, to get from the
583 // temporary object we created (and, potentially, for which we extended
584 // the lifetime) to the subobject we're binding the reference to.
585 for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
586 switch (Adjustment.Kind) {
587 case SubobjectAdjustment::DerivedToBaseAdjustment:
588 Object =
589 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
590 Adjustment.DerivedToBase.BasePath->path_begin(),
591 Adjustment.DerivedToBase.BasePath->path_end(),
592 /*NullCheckValue=*/ false, E->getExprLoc());
593 break;
595 case SubobjectAdjustment::FieldAdjustment: {
596 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
597 LV = EmitLValueForField(LV, Adjustment.Field);
598 assert(LV.isSimple() &&
599 "materialized temporary field is not a simple lvalue");
600 Object = LV.getAddress(*this);
601 break;
604 case SubobjectAdjustment::MemberPointerAdjustment: {
605 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
606 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
607 Adjustment.Ptr.MPT);
608 break;
613 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
616 RValue
617 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
618 // Emit the expression as an lvalue.
619 LValue LV = EmitLValue(E);
620 assert(LV.isSimple());
621 llvm::Value *Value = LV.getPointer(*this);
623 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
624 // C++11 [dcl.ref]p5 (as amended by core issue 453):
625 // If a glvalue to which a reference is directly bound designates neither
626 // an existing object or function of an appropriate type nor a region of
627 // storage of suitable size and alignment to contain an object of the
628 // reference's type, the behavior is undefined.
629 QualType Ty = E->getType();
630 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
633 return RValue::get(Value);
637 /// getAccessedFieldNo - Given an encoded value and a result number, return the
638 /// input field number being accessed.
639 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
640 const llvm::Constant *Elts) {
641 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
642 ->getZExtValue();
645 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
646 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
647 llvm::Value *High) {
648 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
649 llvm::Value *K47 = Builder.getInt64(47);
650 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
651 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
652 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
653 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
654 return Builder.CreateMul(B1, KMul);
657 bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
658 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
659 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
662 bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
663 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
664 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
665 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
666 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
667 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
670 bool CodeGenFunction::sanitizePerformTypeCheck() const {
671 return SanOpts.has(SanitizerKind::Null) ||
672 SanOpts.has(SanitizerKind::Alignment) ||
673 SanOpts.has(SanitizerKind::ObjectSize) ||
674 SanOpts.has(SanitizerKind::Vptr);
677 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
678 llvm::Value *Ptr, QualType Ty,
679 CharUnits Alignment,
680 SanitizerSet SkippedChecks,
681 llvm::Value *ArraySize) {
682 if (!sanitizePerformTypeCheck())
683 return;
685 // Don't check pointers outside the default address space. The null check
686 // isn't correct, the object-size check isn't supported by LLVM, and we can't
687 // communicate the addresses to the runtime handler for the vptr check.
688 if (Ptr->getType()->getPointerAddressSpace())
689 return;
691 // Don't check pointers to volatile data. The behavior here is implementation-
692 // defined.
693 if (Ty.isVolatileQualified())
694 return;
696 SanitizerScope SanScope(this);
698 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
699 llvm::BasicBlock *Done = nullptr;
701 // Quickly determine whether we have a pointer to an alloca. It's possible
702 // to skip null checks, and some alignment checks, for these pointers. This
703 // can reduce compile-time significantly.
704 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
706 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
707 llvm::Value *IsNonNull = nullptr;
708 bool IsGuaranteedNonNull =
709 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
710 bool AllowNullPointers = isNullPointerAllowed(TCK);
711 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
712 !IsGuaranteedNonNull) {
713 // The glvalue must not be an empty glvalue.
714 IsNonNull = Builder.CreateIsNotNull(Ptr);
716 // The IR builder can constant-fold the null check if the pointer points to
717 // a constant.
718 IsGuaranteedNonNull = IsNonNull == True;
720 // Skip the null check if the pointer is known to be non-null.
721 if (!IsGuaranteedNonNull) {
722 if (AllowNullPointers) {
723 // When performing pointer casts, it's OK if the value is null.
724 // Skip the remaining checks in that case.
725 Done = createBasicBlock("null");
726 llvm::BasicBlock *Rest = createBasicBlock("not.null");
727 Builder.CreateCondBr(IsNonNull, Rest, Done);
728 EmitBlock(Rest);
729 } else {
730 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
735 if (SanOpts.has(SanitizerKind::ObjectSize) &&
736 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
737 !Ty->isIncompleteType()) {
738 uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
739 llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
740 if (ArraySize)
741 Size = Builder.CreateMul(Size, ArraySize);
743 // Degenerate case: new X[0] does not need an objectsize check.
744 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
745 if (!ConstantSize || !ConstantSize->isNullValue()) {
746 // The glvalue must refer to a large enough storage region.
747 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
748 // to check this.
749 // FIXME: Get object address space
750 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
751 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
752 llvm::Value *Min = Builder.getFalse();
753 llvm::Value *NullIsUnknown = Builder.getFalse();
754 llvm::Value *Dynamic = Builder.getFalse();
755 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
756 Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
757 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
761 llvm::MaybeAlign AlignVal;
762 llvm::Value *PtrAsInt = nullptr;
764 if (SanOpts.has(SanitizerKind::Alignment) &&
765 !SkippedChecks.has(SanitizerKind::Alignment)) {
766 AlignVal = Alignment.getAsMaybeAlign();
767 if (!Ty->isIncompleteType() && !AlignVal)
768 AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
769 /*ForPointeeType=*/true)
770 .getAsMaybeAlign();
772 // The glvalue must be suitably aligned.
773 if (AlignVal && *AlignVal > llvm::Align(1) &&
774 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
775 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
776 llvm::Value *Align = Builder.CreateAnd(
777 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
778 llvm::Value *Aligned =
779 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
780 if (Aligned != True)
781 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
785 if (Checks.size() > 0) {
786 llvm::Constant *StaticData[] = {
787 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
788 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
789 llvm::ConstantInt::get(Int8Ty, TCK)};
790 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
791 PtrAsInt ? PtrAsInt : Ptr);
794 // If possible, check that the vptr indicates that there is a subobject of
795 // type Ty at offset zero within this object.
797 // C++11 [basic.life]p5,6:
798 // [For storage which does not refer to an object within its lifetime]
799 // The program has undefined behavior if:
800 // -- the [pointer or glvalue] is used to access a non-static data member
801 // or call a non-static member function
802 if (SanOpts.has(SanitizerKind::Vptr) &&
803 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
804 // Ensure that the pointer is non-null before loading it. If there is no
805 // compile-time guarantee, reuse the run-time null check or emit a new one.
806 if (!IsGuaranteedNonNull) {
807 if (!IsNonNull)
808 IsNonNull = Builder.CreateIsNotNull(Ptr);
809 if (!Done)
810 Done = createBasicBlock("vptr.null");
811 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
812 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
813 EmitBlock(VptrNotNull);
816 // Compute a hash of the mangled name of the type.
818 // FIXME: This is not guaranteed to be deterministic! Move to a
819 // fingerprinting mechanism once LLVM provides one. For the time
820 // being the implementation happens to be deterministic.
821 SmallString<64> MangledName;
822 llvm::raw_svector_ostream Out(MangledName);
823 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
824 Out);
826 // Contained in NoSanitizeList based on the mangled type.
827 if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
828 Out.str())) {
829 llvm::hash_code TypeHash = hash_value(Out.str());
831 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
832 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
833 Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign());
834 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
835 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
837 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
838 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
840 // Look the hash up in our cache.
841 const int CacheSize = 128;
842 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
843 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
844 "__ubsan_vptr_type_cache");
845 llvm::Value *Slot = Builder.CreateAnd(Hash,
846 llvm::ConstantInt::get(IntPtrTy,
847 CacheSize-1));
848 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
849 llvm::Value *CacheVal = Builder.CreateAlignedLoad(
850 IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
851 getPointerAlign());
853 // If the hash isn't in the cache, call a runtime handler to perform the
854 // hard work of checking whether the vptr is for an object of the right
855 // type. This will either fill in the cache and return, or produce a
856 // diagnostic.
857 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
858 llvm::Constant *StaticData[] = {
859 EmitCheckSourceLocation(Loc),
860 EmitCheckTypeDescriptor(Ty),
861 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
862 llvm::ConstantInt::get(Int8Ty, TCK)
864 llvm::Value *DynamicData[] = { Ptr, Hash };
865 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
866 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
867 DynamicData);
871 if (Done) {
872 Builder.CreateBr(Done);
873 EmitBlock(Done);
877 llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
878 QualType EltTy) {
879 ASTContext &C = getContext();
880 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
881 if (!EltSize)
882 return nullptr;
884 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
885 if (!ArrayDeclRef)
886 return nullptr;
888 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
889 if (!ParamDecl)
890 return nullptr;
892 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
893 if (!POSAttr)
894 return nullptr;
896 // Don't load the size if it's a lower bound.
897 int POSType = POSAttr->getType();
898 if (POSType != 0 && POSType != 1)
899 return nullptr;
901 // Find the implicit size parameter.
902 auto PassedSizeIt = SizeArguments.find(ParamDecl);
903 if (PassedSizeIt == SizeArguments.end())
904 return nullptr;
906 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
907 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
908 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
909 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
910 C.getSizeType(), E->getExprLoc());
911 llvm::Value *SizeOfElement =
912 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
913 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
916 /// If Base is known to point to the start of an array, return the length of
917 /// that array. Return 0 if the length cannot be determined.
918 static llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF,
919 const Expr *Base,
920 QualType &IndexedType,
921 LangOptions::StrictFlexArraysLevelKind
922 StrictFlexArraysLevel) {
923 // For the vector indexing extension, the bound is the number of elements.
924 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
925 IndexedType = Base->getType();
926 return CGF.Builder.getInt32(VT->getNumElements());
929 Base = Base->IgnoreParens();
931 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
932 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
933 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
934 StrictFlexArraysLevel)) {
935 CodeGenFunction::SanitizerScope SanScope(&CGF);
937 IndexedType = CE->getSubExpr()->getType();
938 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
939 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
940 return CGF.Builder.getInt(CAT->getSize());
942 if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
943 return CGF.getVLASize(VAT).NumElts;
944 // Ignore pass_object_size here. It's not applicable on decayed pointers.
947 if (FieldDecl *FD = CGF.FindCountedByField(Base, StrictFlexArraysLevel)) {
948 const auto *ME = dyn_cast<MemberExpr>(CE->getSubExpr());
949 IndexedType = Base->getType();
950 return CGF
951 .EmitAnyExprToTemp(MemberExpr::CreateImplicit(
952 CGF.getContext(), const_cast<Expr *>(ME->getBase()),
953 ME->isArrow(), FD, FD->getType(), VK_LValue, OK_Ordinary))
954 .getScalarVal();
958 CodeGenFunction::SanitizerScope SanScope(&CGF);
960 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
961 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
962 IndexedType = Base->getType();
963 return POS;
966 return nullptr;
969 FieldDecl *CodeGenFunction::FindCountedByField(
970 const Expr *Base,
971 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel) {
972 const ValueDecl *VD = nullptr;
974 Base = Base->IgnoreParenImpCasts();
976 if (const auto *ME = dyn_cast<MemberExpr>(Base)) {
977 VD = dyn_cast<ValueDecl>(ME->getMemberDecl());
978 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
979 // Pointing to the full structure.
980 VD = dyn_cast<ValueDecl>(DRE->getDecl());
982 QualType Ty = VD->getType();
983 if (Ty->isPointerType())
984 Ty = Ty->getPointeeType();
986 if (const auto *RD = Ty->getAsRecordDecl())
987 VD = RD->getLastField();
988 } else if (const auto *CE = dyn_cast<CastExpr>(Base)) {
989 if (const auto *ME = dyn_cast<MemberExpr>(CE->getSubExpr()))
990 VD = dyn_cast<ValueDecl>(ME->getMemberDecl());
993 const auto *FD = dyn_cast_if_present<FieldDecl>(VD);
994 if (!FD || !FD->getParent() ||
995 !Decl::isFlexibleArrayMemberLike(getContext(), FD, FD->getType(),
996 StrictFlexArraysLevel, true))
997 return nullptr;
999 const auto *CBA = FD->getAttr<CountedByAttr>();
1000 if (!CBA)
1001 return nullptr;
1003 StringRef FieldName = CBA->getCountedByField()->getName();
1004 auto It =
1005 llvm::find_if(FD->getParent()->fields(), [&](const FieldDecl *Field) {
1006 return FieldName == Field->getName();
1008 return It != FD->getParent()->field_end() ? *It : nullptr;
1011 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
1012 llvm::Value *Index, QualType IndexType,
1013 bool Accessed) {
1014 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
1015 "should not be called unless adding bounds checks");
1016 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
1017 getLangOpts().getStrictFlexArraysLevel();
1019 QualType IndexedType;
1020 llvm::Value *Bound =
1021 getArrayIndexingBound(*this, Base, IndexedType, StrictFlexArraysLevel);
1022 if (!Bound)
1023 return;
1025 SanitizerScope SanScope(this);
1027 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
1028 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
1029 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
1031 llvm::Constant *StaticData[] = {
1032 EmitCheckSourceLocation(E->getExprLoc()),
1033 EmitCheckTypeDescriptor(IndexedType),
1034 EmitCheckTypeDescriptor(IndexType)
1036 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
1037 : Builder.CreateICmpULE(IndexVal, BoundVal);
1038 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
1039 SanitizerHandler::OutOfBounds, StaticData, Index);
1043 CodeGenFunction::ComplexPairTy CodeGenFunction::
1044 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1045 bool isInc, bool isPre) {
1046 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1048 llvm::Value *NextVal;
1049 if (isa<llvm::IntegerType>(InVal.first->getType())) {
1050 uint64_t AmountVal = isInc ? 1 : -1;
1051 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1053 // Add the inc/dec to the real part.
1054 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1055 } else {
1056 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1057 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1058 if (!isInc)
1059 FVal.changeSign();
1060 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1062 // Add the inc/dec to the real part.
1063 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1066 ComplexPairTy IncVal(NextVal, InVal.second);
1068 // Store the updated result through the lvalue.
1069 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1070 if (getLangOpts().OpenMP)
1071 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1072 E->getSubExpr());
1074 // If this is a postinc, return the value read from memory, otherwise use the
1075 // updated value.
1076 return isPre ? IncVal : InVal;
1079 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1080 CodeGenFunction *CGF) {
1081 // Bind VLAs in the cast type.
1082 if (CGF && E->getType()->isVariablyModifiedType())
1083 CGF->EmitVariablyModifiedType(E->getType());
1085 if (CGDebugInfo *DI = getModuleDebugInfo())
1086 DI->EmitExplicitCastType(E->getType());
1089 //===----------------------------------------------------------------------===//
1090 // LValue Expression Emission
1091 //===----------------------------------------------------------------------===//
1093 static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo,
1094 TBAAAccessInfo *TBAAInfo,
1095 KnownNonNull_t IsKnownNonNull,
1096 CodeGenFunction &CGF) {
1097 // We allow this with ObjC object pointers because of fragile ABIs.
1098 assert(E->getType()->isPointerType() ||
1099 E->getType()->isObjCObjectPointerType());
1100 E = E->IgnoreParens();
1102 // Casts:
1103 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1104 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1105 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
1107 switch (CE->getCastKind()) {
1108 // Non-converting casts (but not C's implicit conversion from void*).
1109 case CK_BitCast:
1110 case CK_NoOp:
1111 case CK_AddressSpaceConversion:
1112 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1113 if (PtrTy->getPointeeType()->isVoidType())
1114 break;
1116 LValueBaseInfo InnerBaseInfo;
1117 TBAAAccessInfo InnerTBAAInfo;
1118 Address Addr = CGF.EmitPointerWithAlignment(
1119 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1120 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1121 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1123 if (isa<ExplicitCastExpr>(CE)) {
1124 LValueBaseInfo TargetTypeBaseInfo;
1125 TBAAAccessInfo TargetTypeTBAAInfo;
1126 CharUnits Align = CGF.CGM.getNaturalPointeeTypeAlignment(
1127 E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1128 if (TBAAInfo)
1129 *TBAAInfo =
1130 CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
1131 // If the source l-value is opaque, honor the alignment of the
1132 // casted-to type.
1133 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1134 if (BaseInfo)
1135 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1136 Addr = Address(Addr.getPointer(), Addr.getElementType(), Align,
1137 IsKnownNonNull);
1141 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1142 CE->getCastKind() == CK_BitCast) {
1143 if (auto PT = E->getType()->getAs<PointerType>())
1144 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
1145 /*MayBeNull=*/true,
1146 CodeGenFunction::CFITCK_UnrelatedCast,
1147 CE->getBeginLoc());
1150 llvm::Type *ElemTy =
1151 CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1152 Addr = Addr.withElementType(ElemTy);
1153 if (CE->getCastKind() == CK_AddressSpaceConversion)
1154 Addr = CGF.Builder.CreateAddrSpaceCast(Addr,
1155 CGF.ConvertType(E->getType()));
1156 return Addr;
1158 break;
1160 // Array-to-pointer decay.
1161 case CK_ArrayToPointerDecay:
1162 return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1164 // Derived-to-base conversions.
1165 case CK_UncheckedDerivedToBase:
1166 case CK_DerivedToBase: {
1167 // TODO: Support accesses to members of base classes in TBAA. For now, we
1168 // conservatively pretend that the complete object is of the base class
1169 // type.
1170 if (TBAAInfo)
1171 *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1172 Address Addr = CGF.EmitPointerWithAlignment(
1173 CE->getSubExpr(), BaseInfo, nullptr,
1174 (KnownNonNull_t)(IsKnownNonNull ||
1175 CE->getCastKind() == CK_UncheckedDerivedToBase));
1176 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1177 return CGF.GetAddressOfBaseClass(
1178 Addr, Derived, CE->path_begin(), CE->path_end(),
1179 CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1182 // TODO: Is there any reason to treat base-to-derived conversions
1183 // specially?
1184 default:
1185 break;
1189 // Unary &.
1190 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1191 if (UO->getOpcode() == UO_AddrOf) {
1192 LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1193 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1194 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1195 return LV.getAddress(CGF);
1199 // std::addressof and variants.
1200 if (auto *Call = dyn_cast<CallExpr>(E)) {
1201 switch (Call->getBuiltinCallee()) {
1202 default:
1203 break;
1204 case Builtin::BIaddressof:
1205 case Builtin::BI__addressof:
1206 case Builtin::BI__builtin_addressof: {
1207 LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
1208 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1209 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1210 return LV.getAddress(CGF);
1215 // TODO: conditional operators, comma.
1217 // Otherwise, use the alignment of the type.
1218 CharUnits Align =
1219 CGF.CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
1220 llvm::Type *ElemTy = CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1221 return Address(CGF.EmitScalarExpr(E), ElemTy, Align, IsKnownNonNull);
1224 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
1225 /// derive a more accurate bound on the alignment of the pointer.
1226 Address CodeGenFunction::EmitPointerWithAlignment(
1227 const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1228 KnownNonNull_t IsKnownNonNull) {
1229 Address Addr =
1230 ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1231 if (IsKnownNonNull && !Addr.isKnownNonNull())
1232 Addr.setKnownNonNull();
1233 return Addr;
1236 llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1237 llvm::Value *V = RV.getScalarVal();
1238 if (auto MPT = T->getAs<MemberPointerType>())
1239 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1240 return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1243 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1244 if (Ty->isVoidType())
1245 return RValue::get(nullptr);
1247 switch (getEvaluationKind(Ty)) {
1248 case TEK_Complex: {
1249 llvm::Type *EltTy =
1250 ConvertType(Ty->castAs<ComplexType>()->getElementType());
1251 llvm::Value *U = llvm::UndefValue::get(EltTy);
1252 return RValue::getComplex(std::make_pair(U, U));
1255 // If this is a use of an undefined aggregate type, the aggregate must have an
1256 // identifiable address. Just because the contents of the value are undefined
1257 // doesn't mean that the address can't be taken and compared.
1258 case TEK_Aggregate: {
1259 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1260 return RValue::getAggregate(DestPtr);
1263 case TEK_Scalar:
1264 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1266 llvm_unreachable("bad evaluation kind");
1269 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1270 const char *Name) {
1271 ErrorUnsupported(E, Name);
1272 return GetUndefRValue(E->getType());
1275 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1276 const char *Name) {
1277 ErrorUnsupported(E, Name);
1278 llvm::Type *ElTy = ConvertType(E->getType());
1279 llvm::Type *Ty = UnqualPtrTy;
1280 return MakeAddrLValue(
1281 Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
1284 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1285 const Expr *Base = Obj;
1286 while (!isa<CXXThisExpr>(Base)) {
1287 // The result of a dynamic_cast can be null.
1288 if (isa<CXXDynamicCastExpr>(Base))
1289 return false;
1291 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1292 Base = CE->getSubExpr();
1293 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1294 Base = PE->getSubExpr();
1295 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1296 if (UO->getOpcode() == UO_Extension)
1297 Base = UO->getSubExpr();
1298 else
1299 return false;
1300 } else {
1301 return false;
1304 return true;
1307 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1308 LValue LV;
1309 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1310 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1311 else
1312 LV = EmitLValue(E);
1313 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1314 SanitizerSet SkippedChecks;
1315 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1316 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1317 if (IsBaseCXXThis)
1318 SkippedChecks.set(SanitizerKind::Alignment, true);
1319 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1320 SkippedChecks.set(SanitizerKind::Null, true);
1322 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1323 LV.getAlignment(), SkippedChecks);
1325 return LV;
1328 /// EmitLValue - Emit code to compute a designator that specifies the location
1329 /// of the expression.
1331 /// This can return one of two things: a simple address or a bitfield reference.
1332 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1333 /// an LLVM pointer type.
1335 /// If this returns a bitfield reference, nothing about the pointee type of the
1336 /// LLVM value is known: For example, it may not be a pointer to an integer.
1338 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1339 /// this method guarantees that the returned pointer type will point to an LLVM
1340 /// type of the same size of the lvalue's type. If the lvalue has a variable
1341 /// length type, this is not possible.
1343 LValue CodeGenFunction::EmitLValue(const Expr *E,
1344 KnownNonNull_t IsKnownNonNull) {
1345 LValue LV = EmitLValueHelper(E, IsKnownNonNull);
1346 if (IsKnownNonNull && !LV.isKnownNonNull())
1347 LV.setKnownNonNull();
1348 return LV;
1351 LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1352 KnownNonNull_t IsKnownNonNull) {
1353 ApplyDebugLocation DL(*this, E);
1354 switch (E->getStmtClass()) {
1355 default: return EmitUnsupportedLValue(E, "l-value expression");
1357 case Expr::ObjCPropertyRefExprClass:
1358 llvm_unreachable("cannot emit a property reference directly");
1360 case Expr::ObjCSelectorExprClass:
1361 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1362 case Expr::ObjCIsaExprClass:
1363 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1364 case Expr::BinaryOperatorClass:
1365 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1366 case Expr::CompoundAssignOperatorClass: {
1367 QualType Ty = E->getType();
1368 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1369 Ty = AT->getValueType();
1370 if (!Ty->isAnyComplexType())
1371 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1372 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1374 case Expr::CallExprClass:
1375 case Expr::CXXMemberCallExprClass:
1376 case Expr::CXXOperatorCallExprClass:
1377 case Expr::UserDefinedLiteralClass:
1378 return EmitCallExprLValue(cast<CallExpr>(E));
1379 case Expr::CXXRewrittenBinaryOperatorClass:
1380 return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1381 IsKnownNonNull);
1382 case Expr::VAArgExprClass:
1383 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1384 case Expr::DeclRefExprClass:
1385 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1386 case Expr::ConstantExprClass: {
1387 const ConstantExpr *CE = cast<ConstantExpr>(E);
1388 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
1389 QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
1390 ->getCallReturnType(getContext())
1391 ->getPointeeType();
1392 return MakeNaturalAlignAddrLValue(Result, RetType);
1394 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
1396 case Expr::ParenExprClass:
1397 return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
1398 case Expr::GenericSelectionExprClass:
1399 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1400 IsKnownNonNull);
1401 case Expr::PredefinedExprClass:
1402 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1403 case Expr::StringLiteralClass:
1404 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1405 case Expr::ObjCEncodeExprClass:
1406 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1407 case Expr::PseudoObjectExprClass:
1408 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1409 case Expr::InitListExprClass:
1410 return EmitInitListLValue(cast<InitListExpr>(E));
1411 case Expr::CXXTemporaryObjectExprClass:
1412 case Expr::CXXConstructExprClass:
1413 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1414 case Expr::CXXBindTemporaryExprClass:
1415 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1416 case Expr::CXXUuidofExprClass:
1417 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1418 case Expr::LambdaExprClass:
1419 return EmitAggExprToLValue(E);
1421 case Expr::ExprWithCleanupsClass: {
1422 const auto *cleanups = cast<ExprWithCleanups>(E);
1423 RunCleanupsScope Scope(*this);
1424 LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1425 if (LV.isSimple()) {
1426 // Defend against branches out of gnu statement expressions surrounded by
1427 // cleanups.
1428 Address Addr = LV.getAddress(*this);
1429 llvm::Value *V = Addr.getPointer();
1430 Scope.ForceCleanup({&V});
1431 return LValue::MakeAddr(Addr.withPointer(V, Addr.isKnownNonNull()),
1432 LV.getType(), getContext(), LV.getBaseInfo(),
1433 LV.getTBAAInfo());
1435 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1436 // bitfield lvalue or some other non-simple lvalue?
1437 return LV;
1440 case Expr::CXXDefaultArgExprClass: {
1441 auto *DAE = cast<CXXDefaultArgExpr>(E);
1442 CXXDefaultArgExprScope Scope(*this, DAE);
1443 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1445 case Expr::CXXDefaultInitExprClass: {
1446 auto *DIE = cast<CXXDefaultInitExpr>(E);
1447 CXXDefaultInitExprScope Scope(*this, DIE);
1448 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1450 case Expr::CXXTypeidExprClass:
1451 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1453 case Expr::ObjCMessageExprClass:
1454 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1455 case Expr::ObjCIvarRefExprClass:
1456 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1457 case Expr::StmtExprClass:
1458 return EmitStmtExprLValue(cast<StmtExpr>(E));
1459 case Expr::UnaryOperatorClass:
1460 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1461 case Expr::ArraySubscriptExprClass:
1462 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1463 case Expr::MatrixSubscriptExprClass:
1464 return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
1465 case Expr::OMPArraySectionExprClass:
1466 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1467 case Expr::ExtVectorElementExprClass:
1468 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1469 case Expr::CXXThisExprClass:
1470 return MakeAddrLValue(LoadCXXThisAddress(), E->getType());
1471 case Expr::MemberExprClass:
1472 return EmitMemberExpr(cast<MemberExpr>(E));
1473 case Expr::CompoundLiteralExprClass:
1474 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1475 case Expr::ConditionalOperatorClass:
1476 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1477 case Expr::BinaryConditionalOperatorClass:
1478 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1479 case Expr::ChooseExprClass:
1480 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
1481 case Expr::OpaqueValueExprClass:
1482 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1483 case Expr::SubstNonTypeTemplateParmExprClass:
1484 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1485 IsKnownNonNull);
1486 case Expr::ImplicitCastExprClass:
1487 case Expr::CStyleCastExprClass:
1488 case Expr::CXXFunctionalCastExprClass:
1489 case Expr::CXXStaticCastExprClass:
1490 case Expr::CXXDynamicCastExprClass:
1491 case Expr::CXXReinterpretCastExprClass:
1492 case Expr::CXXConstCastExprClass:
1493 case Expr::CXXAddrspaceCastExprClass:
1494 case Expr::ObjCBridgedCastExprClass:
1495 return EmitCastLValue(cast<CastExpr>(E));
1497 case Expr::MaterializeTemporaryExprClass:
1498 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1500 case Expr::CoawaitExprClass:
1501 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1502 case Expr::CoyieldExprClass:
1503 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1507 /// Given an object of the given canonical type, can we safely copy a
1508 /// value out of it based on its initializer?
1509 static bool isConstantEmittableObjectType(QualType type) {
1510 assert(type.isCanonical());
1511 assert(!type->isReferenceType());
1513 // Must be const-qualified but non-volatile.
1514 Qualifiers qs = type.getLocalQualifiers();
1515 if (!qs.hasConst() || qs.hasVolatile()) return false;
1517 // Otherwise, all object types satisfy this except C++ classes with
1518 // mutable subobjects or non-trivial copy/destroy behavior.
1519 if (const auto *RT = dyn_cast<RecordType>(type))
1520 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1521 if (RD->hasMutableFields() || !RD->isTrivial())
1522 return false;
1524 return true;
1527 /// Can we constant-emit a load of a reference to a variable of the
1528 /// given type? This is different from predicates like
1529 /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1530 /// in situations that don't necessarily satisfy the language's rules
1531 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1532 /// to do this with const float variables even if those variables
1533 /// aren't marked 'constexpr'.
1534 enum ConstantEmissionKind {
1535 CEK_None,
1536 CEK_AsReferenceOnly,
1537 CEK_AsValueOrReference,
1538 CEK_AsValueOnly
1540 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1541 type = type.getCanonicalType();
1542 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1543 if (isConstantEmittableObjectType(ref->getPointeeType()))
1544 return CEK_AsValueOrReference;
1545 return CEK_AsReferenceOnly;
1547 if (isConstantEmittableObjectType(type))
1548 return CEK_AsValueOnly;
1549 return CEK_None;
1552 /// Try to emit a reference to the given value without producing it as
1553 /// an l-value. This is just an optimization, but it avoids us needing
1554 /// to emit global copies of variables if they're named without triggering
1555 /// a formal use in a context where we can't emit a direct reference to them,
1556 /// for instance if a block or lambda or a member of a local class uses a
1557 /// const int variable or constexpr variable from an enclosing function.
1558 CodeGenFunction::ConstantEmission
1559 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1560 ValueDecl *value = refExpr->getDecl();
1562 // The value needs to be an enum constant or a constant variable.
1563 ConstantEmissionKind CEK;
1564 if (isa<ParmVarDecl>(value)) {
1565 CEK = CEK_None;
1566 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1567 CEK = checkVarTypeForConstantEmission(var->getType());
1568 } else if (isa<EnumConstantDecl>(value)) {
1569 CEK = CEK_AsValueOnly;
1570 } else {
1571 CEK = CEK_None;
1573 if (CEK == CEK_None) return ConstantEmission();
1575 Expr::EvalResult result;
1576 bool resultIsReference;
1577 QualType resultType;
1579 // It's best to evaluate all the way as an r-value if that's permitted.
1580 if (CEK != CEK_AsReferenceOnly &&
1581 refExpr->EvaluateAsRValue(result, getContext())) {
1582 resultIsReference = false;
1583 resultType = refExpr->getType();
1585 // Otherwise, try to evaluate as an l-value.
1586 } else if (CEK != CEK_AsValueOnly &&
1587 refExpr->EvaluateAsLValue(result, getContext())) {
1588 resultIsReference = true;
1589 resultType = value->getType();
1591 // Failure.
1592 } else {
1593 return ConstantEmission();
1596 // In any case, if the initializer has side-effects, abandon ship.
1597 if (result.HasSideEffects)
1598 return ConstantEmission();
1600 // In CUDA/HIP device compilation, a lambda may capture a reference variable
1601 // referencing a global host variable by copy. In this case the lambda should
1602 // make a copy of the value of the global host variable. The DRE of the
1603 // captured reference variable cannot be emitted as load from the host
1604 // global variable as compile time constant, since the host variable is not
1605 // accessible on device. The DRE of the captured reference variable has to be
1606 // loaded from captures.
1607 if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1608 refExpr->refersToEnclosingVariableOrCapture()) {
1609 auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1610 if (MD && MD->getParent()->isLambda() &&
1611 MD->getOverloadedOperator() == OO_Call) {
1612 const APValue::LValueBase &base = result.Val.getLValueBase();
1613 if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1614 if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1615 if (!VD->hasAttr<CUDADeviceAttr>()) {
1616 return ConstantEmission();
1623 // Emit as a constant.
1624 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1625 result.Val, resultType);
1627 // Make sure we emit a debug reference to the global variable.
1628 // This should probably fire even for
1629 if (isa<VarDecl>(value)) {
1630 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1631 EmitDeclRefExprDbgValue(refExpr, result.Val);
1632 } else {
1633 assert(isa<EnumConstantDecl>(value));
1634 EmitDeclRefExprDbgValue(refExpr, result.Val);
1637 // If we emitted a reference constant, we need to dereference that.
1638 if (resultIsReference)
1639 return ConstantEmission::forReference(C);
1641 return ConstantEmission::forValue(C);
1644 static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1645 const MemberExpr *ME) {
1646 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1647 // Try to emit static variable member expressions as DREs.
1648 return DeclRefExpr::Create(
1649 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1650 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1651 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
1653 return nullptr;
1656 CodeGenFunction::ConstantEmission
1657 CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1658 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1659 return tryEmitAsConstant(DRE);
1660 return ConstantEmission();
1663 llvm::Value *CodeGenFunction::emitScalarConstant(
1664 const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1665 assert(Constant && "not a constant");
1666 if (Constant.isReference())
1667 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1668 E->getExprLoc())
1669 .getScalarVal();
1670 return Constant.getValue();
1673 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1674 SourceLocation Loc) {
1675 return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
1676 lvalue.getType(), Loc, lvalue.getBaseInfo(),
1677 lvalue.getTBAAInfo(), lvalue.isNontemporal());
1680 static bool hasBooleanRepresentation(QualType Ty) {
1681 if (Ty->isBooleanType())
1682 return true;
1684 if (const EnumType *ET = Ty->getAs<EnumType>())
1685 return ET->getDecl()->getIntegerType()->isBooleanType();
1687 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1688 return hasBooleanRepresentation(AT->getValueType());
1690 return false;
1693 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1694 llvm::APInt &Min, llvm::APInt &End,
1695 bool StrictEnums, bool IsBool) {
1696 const EnumType *ET = Ty->getAs<EnumType>();
1697 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1698 ET && !ET->getDecl()->isFixed();
1699 if (!IsBool && !IsRegularCPlusPlusEnum)
1700 return false;
1702 if (IsBool) {
1703 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1704 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1705 } else {
1706 const EnumDecl *ED = ET->getDecl();
1707 ED->getValueRange(End, Min);
1709 return true;
1712 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1713 llvm::APInt Min, End;
1714 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1715 hasBooleanRepresentation(Ty)))
1716 return nullptr;
1718 llvm::MDBuilder MDHelper(getLLVMContext());
1719 return MDHelper.createRange(Min, End);
1722 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1723 SourceLocation Loc) {
1724 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1725 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1726 if (!HasBoolCheck && !HasEnumCheck)
1727 return false;
1729 bool IsBool = hasBooleanRepresentation(Ty) ||
1730 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1731 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1732 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1733 if (!NeedsBoolCheck && !NeedsEnumCheck)
1734 return false;
1736 // Single-bit booleans don't need to be checked. Special-case this to avoid
1737 // a bit width mismatch when handling bitfield values. This is handled by
1738 // EmitFromMemory for the non-bitfield case.
1739 if (IsBool &&
1740 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1741 return false;
1743 llvm::APInt Min, End;
1744 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1745 return true;
1747 auto &Ctx = getLLVMContext();
1748 SanitizerScope SanScope(this);
1749 llvm::Value *Check;
1750 --End;
1751 if (!Min) {
1752 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1753 } else {
1754 llvm::Value *Upper =
1755 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1756 llvm::Value *Lower =
1757 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1758 Check = Builder.CreateAnd(Upper, Lower);
1760 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1761 EmitCheckTypeDescriptor(Ty)};
1762 SanitizerMask Kind =
1763 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1764 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1765 StaticArgs, EmitCheckValue(Value));
1766 return true;
1769 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1770 QualType Ty,
1771 SourceLocation Loc,
1772 LValueBaseInfo BaseInfo,
1773 TBAAAccessInfo TBAAInfo,
1774 bool isNontemporal) {
1775 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
1776 if (GV->isThreadLocal())
1777 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1778 NotKnownNonNull);
1780 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
1781 // Boolean vectors use `iN` as storage type.
1782 if (ClangVecTy->isExtVectorBoolType()) {
1783 llvm::Type *ValTy = ConvertType(Ty);
1784 unsigned ValNumElems =
1785 cast<llvm::FixedVectorType>(ValTy)->getNumElements();
1786 // Load the `iP` storage object (P is the padded vector size).
1787 auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
1788 const auto *RawIntTy = RawIntV->getType();
1789 assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
1790 // Bitcast iP --> <P x i1>.
1791 auto *PaddedVecTy = llvm::FixedVectorType::get(
1792 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
1793 llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
1794 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
1795 V = emitBoolVecConversion(V, ValNumElems, "extractvec");
1797 return EmitFromMemory(V, Ty);
1800 // Handle vectors of size 3 like size 4 for better performance.
1801 const llvm::Type *EltTy = Addr.getElementType();
1802 const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
1804 if (!CGM.getCodeGenOpts().PreserveVec3Type && VTy->getNumElements() == 3) {
1806 llvm::VectorType *vec4Ty =
1807 llvm::FixedVectorType::get(VTy->getElementType(), 4);
1808 Address Cast = Addr.withElementType(vec4Ty);
1809 // Now load value.
1810 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1812 // Shuffle vector to get vec3.
1813 V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2}, "extractVec");
1814 return EmitFromMemory(V, Ty);
1818 // Atomic operations have to be done on integral types.
1819 LValue AtomicLValue =
1820 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1821 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1822 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1825 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1826 if (isNontemporal) {
1827 llvm::MDNode *Node = llvm::MDNode::get(
1828 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1829 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
1832 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1834 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1835 // In order to prevent the optimizer from throwing away the check, don't
1836 // attach range metadata to the load.
1837 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1838 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
1839 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1840 Load->setMetadata(llvm::LLVMContext::MD_noundef,
1841 llvm::MDNode::get(getLLVMContext(), std::nullopt));
1844 return EmitFromMemory(Load, Ty);
1847 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1848 // Bool has a different representation in memory than in registers.
1849 if (hasBooleanRepresentation(Ty)) {
1850 // This should really always be an i1, but sometimes it's already
1851 // an i8, and it's awkward to track those cases down.
1852 if (Value->getType()->isIntegerTy(1))
1853 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1854 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1855 "wrong value rep of bool");
1858 return Value;
1861 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1862 // Bool has a different representation in memory than in registers.
1863 if (hasBooleanRepresentation(Ty)) {
1864 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1865 "wrong value rep of bool");
1866 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1868 if (Ty->isExtVectorBoolType()) {
1869 const auto *RawIntTy = Value->getType();
1870 // Bitcast iP --> <P x i1>.
1871 auto *PaddedVecTy = llvm::FixedVectorType::get(
1872 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
1873 auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
1874 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
1875 llvm::Type *ValTy = ConvertType(Ty);
1876 unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
1877 return emitBoolVecConversion(V, ValNumElems, "extractvec");
1880 return Value;
1883 // Convert the pointer of \p Addr to a pointer to a vector (the value type of
1884 // MatrixType), if it points to a array (the memory type of MatrixType).
1885 static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
1886 bool IsVector = true) {
1887 auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
1888 if (ArrayTy && IsVector) {
1889 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1890 ArrayTy->getNumElements());
1892 return Addr.withElementType(VectorTy);
1894 auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
1895 if (VectorTy && !IsVector) {
1896 auto *ArrayTy = llvm::ArrayType::get(
1897 VectorTy->getElementType(),
1898 cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
1900 return Addr.withElementType(ArrayTy);
1903 return Addr;
1906 // Emit a store of a matrix LValue. This may require casting the original
1907 // pointer to memory address (ArrayType) to a pointer to the value type
1908 // (VectorType).
1909 static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
1910 bool isInit, CodeGenFunction &CGF) {
1911 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
1912 value->getType()->isVectorTy());
1913 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
1914 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
1915 lvalue.isNontemporal());
1918 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1919 bool Volatile, QualType Ty,
1920 LValueBaseInfo BaseInfo,
1921 TBAAAccessInfo TBAAInfo,
1922 bool isInit, bool isNontemporal) {
1923 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
1924 if (GV->isThreadLocal())
1925 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1926 NotKnownNonNull);
1928 llvm::Type *SrcTy = Value->getType();
1929 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
1930 auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy);
1931 if (VecTy && ClangVecTy->isExtVectorBoolType()) {
1932 auto *MemIntTy = cast<llvm::IntegerType>(Addr.getElementType());
1933 // Expand to the memory bit width.
1934 unsigned MemNumElems = MemIntTy->getPrimitiveSizeInBits();
1935 // <N x i1> --> <P x i1>.
1936 Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
1937 // <P x i1> --> iP.
1938 Value = Builder.CreateBitCast(Value, MemIntTy);
1939 } else if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1940 // Handle vec3 special.
1941 if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
1942 // Our source is a vec3, do a shuffle vector to make it a vec4.
1943 Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
1944 "extractVec");
1945 SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
1947 if (Addr.getElementType() != SrcTy) {
1948 Addr = Addr.withElementType(SrcTy);
1953 Value = EmitToMemory(Value, Ty);
1955 LValue AtomicLValue =
1956 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1957 if (Ty->isAtomicType() ||
1958 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1959 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1960 return;
1963 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1964 if (isNontemporal) {
1965 llvm::MDNode *Node =
1966 llvm::MDNode::get(Store->getContext(),
1967 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1968 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
1971 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1974 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1975 bool isInit) {
1976 if (lvalue.getType()->isConstantMatrixType()) {
1977 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
1978 return;
1981 EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
1982 lvalue.getType(), lvalue.getBaseInfo(),
1983 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1986 // Emit a load of a LValue of matrix type. This may require casting the pointer
1987 // to memory address (ArrayType) to a pointer to the value type (VectorType).
1988 static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
1989 CodeGenFunction &CGF) {
1990 assert(LV.getType()->isConstantMatrixType());
1991 Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
1992 LV.setAddress(Addr);
1993 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
1996 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1997 /// method emits the address of the lvalue, then loads the result as an rvalue,
1998 /// returning the rvalue.
1999 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
2000 if (LV.isObjCWeak()) {
2001 // load of a __weak object.
2002 Address AddrWeakObj = LV.getAddress(*this);
2003 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
2004 AddrWeakObj));
2006 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
2007 // In MRC mode, we do a load+autorelease.
2008 if (!getLangOpts().ObjCAutoRefCount) {
2009 return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
2012 // In ARC mode, we load retained and then consume the value.
2013 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
2014 Object = EmitObjCConsumeObject(LV.getType(), Object);
2015 return RValue::get(Object);
2018 if (LV.isSimple()) {
2019 assert(!LV.getType()->isFunctionType());
2021 if (LV.getType()->isConstantMatrixType())
2022 return EmitLoadOfMatrixLValue(LV, Loc, *this);
2024 // Everything needs a load.
2025 return RValue::get(EmitLoadOfScalar(LV, Loc));
2028 if (LV.isVectorElt()) {
2029 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
2030 LV.isVolatileQualified());
2031 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
2032 "vecext"));
2035 // If this is a reference to a subset of the elements of a vector, either
2036 // shuffle the input or extract/insert them as appropriate.
2037 if (LV.isExtVectorElt()) {
2038 return EmitLoadOfExtVectorElementLValue(LV);
2041 // Global Register variables always invoke intrinsics
2042 if (LV.isGlobalReg())
2043 return EmitLoadOfGlobalRegLValue(LV);
2045 if (LV.isMatrixElt()) {
2046 llvm::Value *Idx = LV.getMatrixIdx();
2047 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2048 const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
2049 llvm::MatrixBuilder MB(Builder);
2050 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2052 llvm::LoadInst *Load =
2053 Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2054 return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
2057 assert(LV.isBitField() && "Unknown LValue type!");
2058 return EmitLoadOfBitfieldLValue(LV, Loc);
2061 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
2062 SourceLocation Loc) {
2063 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2065 // Get the output type.
2066 llvm::Type *ResLTy = ConvertType(LV.getType());
2068 Address Ptr = LV.getBitFieldAddress();
2069 llvm::Value *Val =
2070 Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2072 bool UseVolatile = LV.isVolatileQualified() &&
2073 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2074 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2075 const unsigned StorageSize =
2076 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2077 if (Info.IsSigned) {
2078 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2079 unsigned HighBits = StorageSize - Offset - Info.Size;
2080 if (HighBits)
2081 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2082 if (Offset + HighBits)
2083 Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2084 } else {
2085 if (Offset)
2086 Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2087 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2088 Val = Builder.CreateAnd(
2089 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2091 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2092 EmitScalarRangeCheck(Val, LV.getType(), Loc);
2093 return RValue::get(Val);
2096 // If this is a reference to a subset of the elements of a vector, create an
2097 // appropriate shufflevector.
2098 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
2099 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2100 LV.isVolatileQualified());
2102 const llvm::Constant *Elts = LV.getExtVectorElts();
2104 // If the result of the expression is a non-vector type, we must be extracting
2105 // a single element. Just codegen as an extractelement.
2106 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2107 if (!ExprVT) {
2108 unsigned InIdx = getAccessedFieldNo(0, Elts);
2109 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2110 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
2113 // Always use shuffle vector to try to retain the original program structure
2114 unsigned NumResultElts = ExprVT->getNumElements();
2116 SmallVector<int, 4> Mask;
2117 for (unsigned i = 0; i != NumResultElts; ++i)
2118 Mask.push_back(getAccessedFieldNo(i, Elts));
2120 Vec = Builder.CreateShuffleVector(Vec, Mask);
2121 return RValue::get(Vec);
2124 /// Generates lvalue for partial ext_vector access.
2125 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
2126 Address VectorAddress = LV.getExtVectorAddress();
2127 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2128 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2130 Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
2132 const llvm::Constant *Elts = LV.getExtVectorElts();
2133 unsigned ix = getAccessedFieldNo(0, Elts);
2135 Address VectorBasePtrPlusIx =
2136 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2137 "vector.elt");
2139 return VectorBasePtrPlusIx;
2142 /// Load of global gamed gegisters are always calls to intrinsics.
2143 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
2144 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2145 "Bad type for register variable");
2146 llvm::MDNode *RegName = cast<llvm::MDNode>(
2147 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2149 // We accept integer and pointer types only
2150 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2151 llvm::Type *Ty = OrigTy;
2152 if (OrigTy->isPointerTy())
2153 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2154 llvm::Type *Types[] = { Ty };
2156 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2157 llvm::Value *Call = Builder.CreateCall(
2158 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2159 if (OrigTy->isPointerTy())
2160 Call = Builder.CreateIntToPtr(Call, OrigTy);
2161 return RValue::get(Call);
2164 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2165 /// lvalue, where both are guaranteed to the have the same type, and that type
2166 /// is 'Ty'.
2167 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
2168 bool isInit) {
2169 if (!Dst.isSimple()) {
2170 if (Dst.isVectorElt()) {
2171 // Read/modify/write the vector, inserting the new element.
2172 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2173 Dst.isVolatileQualified());
2174 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2175 if (IRStoreTy) {
2176 auto *IRVecTy = llvm::FixedVectorType::get(
2177 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2178 Vec = Builder.CreateBitCast(Vec, IRVecTy);
2179 // iN --> <N x i1>.
2181 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2182 Dst.getVectorIdx(), "vecins");
2183 if (IRStoreTy) {
2184 // <N x i1> --> <iN>.
2185 Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2187 Builder.CreateStore(Vec, Dst.getVectorAddress(),
2188 Dst.isVolatileQualified());
2189 return;
2192 // If this is an update of extended vector elements, insert them as
2193 // appropriate.
2194 if (Dst.isExtVectorElt())
2195 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
2197 if (Dst.isGlobalReg())
2198 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2200 if (Dst.isMatrixElt()) {
2201 llvm::Value *Idx = Dst.getMatrixIdx();
2202 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2203 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2204 llvm::MatrixBuilder MB(Builder);
2205 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2207 llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2208 llvm::Value *Vec =
2209 Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
2210 Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2211 Dst.isVolatileQualified());
2212 return;
2215 assert(Dst.isBitField() && "Unknown LValue type");
2216 return EmitStoreThroughBitfieldLValue(Src, Dst);
2219 // There's special magic for assigning into an ARC-qualified l-value.
2220 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2221 switch (Lifetime) {
2222 case Qualifiers::OCL_None:
2223 llvm_unreachable("present but none");
2225 case Qualifiers::OCL_ExplicitNone:
2226 // nothing special
2227 break;
2229 case Qualifiers::OCL_Strong:
2230 if (isInit) {
2231 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2232 break;
2234 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2235 return;
2237 case Qualifiers::OCL_Weak:
2238 if (isInit)
2239 // Initialize and then skip the primitive store.
2240 EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
2241 else
2242 EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2243 /*ignore*/ true);
2244 return;
2246 case Qualifiers::OCL_Autoreleasing:
2247 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
2248 Src.getScalarVal()));
2249 // fall into the normal path
2250 break;
2254 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2255 // load of a __weak object.
2256 Address LvalueDst = Dst.getAddress(*this);
2257 llvm::Value *src = Src.getScalarVal();
2258 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2259 return;
2262 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2263 // load of a __strong object.
2264 Address LvalueDst = Dst.getAddress(*this);
2265 llvm::Value *src = Src.getScalarVal();
2266 if (Dst.isObjCIvar()) {
2267 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2268 llvm::Type *ResultType = IntPtrTy;
2269 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
2270 llvm::Value *RHS = dst.getPointer();
2271 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2272 llvm::Value *LHS =
2273 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
2274 "sub.ptr.lhs.cast");
2275 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2276 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
2277 BytesBetween);
2278 } else if (Dst.isGlobalObjCRef()) {
2279 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2280 Dst.isThreadLocalRef());
2282 else
2283 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2284 return;
2287 assert(Src.isScalar() && "Can't emit an agg store with this method");
2288 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2291 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2292 llvm::Value **Result) {
2293 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2294 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
2295 Address Ptr = Dst.getBitFieldAddress();
2297 // Get the source value, truncated to the width of the bit-field.
2298 llvm::Value *SrcVal = Src.getScalarVal();
2300 // Cast the source to the storage type and shift it into place.
2301 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2302 /*isSigned=*/false);
2303 llvm::Value *MaskedVal = SrcVal;
2305 const bool UseVolatile =
2306 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2307 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2308 const unsigned StorageSize =
2309 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2310 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2311 // See if there are other bits in the bitfield's storage we'll need to load
2312 // and mask together with source before storing.
2313 if (StorageSize != Info.Size) {
2314 assert(StorageSize > Info.Size && "Invalid bitfield size.");
2315 llvm::Value *Val =
2316 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2318 // Mask the source value as needed.
2319 if (!hasBooleanRepresentation(Dst.getType()))
2320 SrcVal = Builder.CreateAnd(
2321 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
2322 "bf.value");
2323 MaskedVal = SrcVal;
2324 if (Offset)
2325 SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
2327 // Mask out the original value.
2328 Val = Builder.CreateAnd(
2329 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
2330 "bf.clear");
2332 // Or together the unchanged values and the source value.
2333 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2334 } else {
2335 assert(Offset == 0);
2336 // According to the AACPS:
2337 // When a volatile bit-field is written, and its container does not overlap
2338 // with any non-bit-field member, its container must be read exactly once
2339 // and written exactly once using the access width appropriate to the type
2340 // of the container. The two accesses are not atomic.
2341 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
2342 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
2343 Builder.CreateLoad(Ptr, true, "bf.load");
2346 // Write the new value back out.
2347 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2349 // Return the new value of the bit-field, if requested.
2350 if (Result) {
2351 llvm::Value *ResultVal = MaskedVal;
2353 // Sign extend the value if needed.
2354 if (Info.IsSigned) {
2355 assert(Info.Size <= StorageSize);
2356 unsigned HighBits = StorageSize - Info.Size;
2357 if (HighBits) {
2358 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2359 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2363 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2364 "bf.result.cast");
2365 *Result = EmitFromMemory(ResultVal, Dst.getType());
2369 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2370 LValue Dst) {
2371 // This access turns into a read/modify/write of the vector. Load the input
2372 // value now.
2373 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2374 Dst.isVolatileQualified());
2375 const llvm::Constant *Elts = Dst.getExtVectorElts();
2377 llvm::Value *SrcVal = Src.getScalarVal();
2379 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2380 unsigned NumSrcElts = VTy->getNumElements();
2381 unsigned NumDstElts =
2382 cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
2383 if (NumDstElts == NumSrcElts) {
2384 // Use shuffle vector is the src and destination are the same number of
2385 // elements and restore the vector mask since it is on the side it will be
2386 // stored.
2387 SmallVector<int, 4> Mask(NumDstElts);
2388 for (unsigned i = 0; i != NumSrcElts; ++i)
2389 Mask[getAccessedFieldNo(i, Elts)] = i;
2391 Vec = Builder.CreateShuffleVector(SrcVal, Mask);
2392 } else if (NumDstElts > NumSrcElts) {
2393 // Extended the source vector to the same length and then shuffle it
2394 // into the destination.
2395 // FIXME: since we're shuffling with undef, can we just use the indices
2396 // into that? This could be simpler.
2397 SmallVector<int, 4> ExtMask;
2398 for (unsigned i = 0; i != NumSrcElts; ++i)
2399 ExtMask.push_back(i);
2400 ExtMask.resize(NumDstElts, -1);
2401 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
2402 // build identity
2403 SmallVector<int, 4> Mask;
2404 for (unsigned i = 0; i != NumDstElts; ++i)
2405 Mask.push_back(i);
2407 // When the vector size is odd and .odd or .hi is used, the last element
2408 // of the Elts constant array will be one past the size of the vector.
2409 // Ignore the last element here, if it is greater than the mask size.
2410 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2411 NumSrcElts--;
2413 // modify when what gets shuffled in
2414 for (unsigned i = 0; i != NumSrcElts; ++i)
2415 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
2416 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2417 } else {
2418 // We should never shorten the vector
2419 llvm_unreachable("unexpected shorten vector length");
2421 } else {
2422 // If the Src is a scalar (not a vector) it must be updating one element.
2423 unsigned InIdx = getAccessedFieldNo(0, Elts);
2424 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2425 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2428 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2429 Dst.isVolatileQualified());
2432 /// Store of global named registers are always calls to intrinsics.
2433 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2434 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2435 "Bad type for register variable");
2436 llvm::MDNode *RegName = cast<llvm::MDNode>(
2437 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2438 assert(RegName && "Register LValue is not metadata");
2440 // We accept integer and pointer types only
2441 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2442 llvm::Type *Ty = OrigTy;
2443 if (OrigTy->isPointerTy())
2444 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2445 llvm::Type *Types[] = { Ty };
2447 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2448 llvm::Value *Value = Src.getScalarVal();
2449 if (OrigTy->isPointerTy())
2450 Value = Builder.CreatePtrToInt(Value, Ty);
2451 Builder.CreateCall(
2452 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2455 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2456 // generating write-barries API. It is currently a global, ivar,
2457 // or neither.
2458 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2459 LValue &LV,
2460 bool IsMemberAccess=false) {
2461 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2462 return;
2464 if (isa<ObjCIvarRefExpr>(E)) {
2465 QualType ExpTy = E->getType();
2466 if (IsMemberAccess && ExpTy->isPointerType()) {
2467 // If ivar is a structure pointer, assigning to field of
2468 // this struct follows gcc's behavior and makes it a non-ivar
2469 // writer-barrier conservatively.
2470 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2471 if (ExpTy->isRecordType()) {
2472 LV.setObjCIvar(false);
2473 return;
2476 LV.setObjCIvar(true);
2477 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2478 LV.setBaseIvarExp(Exp->getBase());
2479 LV.setObjCArray(E->getType()->isArrayType());
2480 return;
2483 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2484 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2485 if (VD->hasGlobalStorage()) {
2486 LV.setGlobalObjCRef(true);
2487 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2490 LV.setObjCArray(E->getType()->isArrayType());
2491 return;
2494 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2495 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2496 return;
2499 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2500 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2501 if (LV.isObjCIvar()) {
2502 // If cast is to a structure pointer, follow gcc's behavior and make it
2503 // a non-ivar write-barrier.
2504 QualType ExpTy = E->getType();
2505 if (ExpTy->isPointerType())
2506 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2507 if (ExpTy->isRecordType())
2508 LV.setObjCIvar(false);
2510 return;
2513 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2514 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2515 return;
2518 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2519 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2520 return;
2523 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2524 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2525 return;
2528 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2529 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2530 return;
2533 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2534 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2535 if (LV.isObjCIvar() && !LV.isObjCArray())
2536 // Using array syntax to assigning to what an ivar points to is not
2537 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2538 LV.setObjCIvar(false);
2539 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2540 // Using array syntax to assigning to what global points to is not
2541 // same as assigning to the global itself. {id *G;} G[i] = 0;
2542 LV.setGlobalObjCRef(false);
2543 return;
2546 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2547 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2548 // We don't know if member is an 'ivar', but this flag is looked at
2549 // only in the context of LV.isObjCIvar().
2550 LV.setObjCArray(E->getType()->isArrayType());
2551 return;
2555 static LValue EmitThreadPrivateVarDeclLValue(
2556 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2557 llvm::Type *RealVarTy, SourceLocation Loc) {
2558 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
2559 Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
2560 CGF, VD, Addr, Loc);
2561 else
2562 Addr =
2563 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2565 Addr = Addr.withElementType(RealVarTy);
2566 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2569 static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
2570 const VarDecl *VD, QualType T) {
2571 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2572 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2573 // Return an invalid address if variable is MT_To (or MT_Enter starting with
2574 // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link
2575 // and MT_To (or MT_Enter) with unified memory, return a valid address.
2576 if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2577 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
2578 !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
2579 return Address::invalid();
2580 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2581 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2582 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
2583 CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
2584 "Expected link clause OR to clause with unified memory enabled.");
2585 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2586 Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2587 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
2590 Address
2591 CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2592 LValueBaseInfo *PointeeBaseInfo,
2593 TBAAAccessInfo *PointeeTBAAInfo) {
2594 llvm::LoadInst *Load =
2595 Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
2596 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2598 QualType PointeeType = RefLVal.getType()->getPointeeType();
2599 CharUnits Align = CGM.getNaturalTypeAlignment(
2600 PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
2601 /* forPointeeType= */ true);
2602 return Address(Load, ConvertTypeForMem(PointeeType), Align);
2605 LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2606 LValueBaseInfo PointeeBaseInfo;
2607 TBAAAccessInfo PointeeTBAAInfo;
2608 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2609 &PointeeTBAAInfo);
2610 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2611 PointeeBaseInfo, PointeeTBAAInfo);
2614 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2615 const PointerType *PtrTy,
2616 LValueBaseInfo *BaseInfo,
2617 TBAAAccessInfo *TBAAInfo) {
2618 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2619 return Address(Addr, ConvertTypeForMem(PtrTy->getPointeeType()),
2620 CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), BaseInfo,
2621 TBAAInfo,
2622 /*forPointeeType=*/true));
2625 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2626 const PointerType *PtrTy) {
2627 LValueBaseInfo BaseInfo;
2628 TBAAAccessInfo TBAAInfo;
2629 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2630 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2633 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2634 const Expr *E, const VarDecl *VD) {
2635 QualType T = E->getType();
2637 // If it's thread_local, emit a call to its wrapper function instead.
2638 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2639 CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
2640 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2641 // Check if the variable is marked as declare target with link clause in
2642 // device codegen.
2643 if (CGF.getLangOpts().OpenMPIsTargetDevice) {
2644 Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
2645 if (Addr.isValid())
2646 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2649 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2651 if (VD->getTLSKind() != VarDecl::TLS_None)
2652 V = CGF.Builder.CreateThreadLocalAddress(V);
2654 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2655 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2656 Address Addr(V, RealVarTy, Alignment);
2657 // Emit reference to the private copy of the variable if it is an OpenMP
2658 // threadprivate variable.
2659 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2660 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2661 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2662 E->getExprLoc());
2664 LValue LV = VD->getType()->isReferenceType() ?
2665 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2666 AlignmentSource::Decl) :
2667 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2668 setObjCGCLValueClass(CGF.getContext(), E, LV);
2669 return LV;
2672 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2673 GlobalDecl GD) {
2674 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2675 if (FD->hasAttr<WeakRefAttr>()) {
2676 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2677 return aliasee.getPointer();
2680 llvm::Constant *V = CGM.GetAddrOfFunction(GD);
2681 if (!FD->hasPrototype()) {
2682 if (const FunctionProtoType *Proto =
2683 FD->getType()->getAs<FunctionProtoType>()) {
2684 // Ugly case: for a K&R-style definition, the type of the definition
2685 // isn't the same as the type of a use. Correct for this with a
2686 // bitcast.
2687 QualType NoProtoType =
2688 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2689 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2690 V = llvm::ConstantExpr::getBitCast(V,
2691 CGM.getTypes().ConvertType(NoProtoType));
2694 return V;
2697 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
2698 GlobalDecl GD) {
2699 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2700 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
2701 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2702 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2703 AlignmentSource::Decl);
2706 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2707 llvm::Value *ThisValue) {
2709 return CGF.EmitLValueForLambdaField(FD, ThisValue);
2712 /// Named Registers are named metadata pointing to the register name
2713 /// which will be read from/written to as an argument to the intrinsic
2714 /// @llvm.read/write_register.
2715 /// So far, only the name is being passed down, but other options such as
2716 /// register type, allocation type or even optimization options could be
2717 /// passed down via the metadata node.
2718 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2719 SmallString<64> Name("llvm.named.register.");
2720 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2721 assert(Asm->getLabel().size() < 64-Name.size() &&
2722 "Register name too big");
2723 Name.append(Asm->getLabel());
2724 llvm::NamedMDNode *M =
2725 CGM.getModule().getOrInsertNamedMetadata(Name);
2726 if (M->getNumOperands() == 0) {
2727 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2728 Asm->getLabel());
2729 llvm::Metadata *Ops[] = {Str};
2730 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2733 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2735 llvm::Value *Ptr =
2736 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2737 return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
2740 /// Determine whether we can emit a reference to \p VD from the current
2741 /// context, despite not necessarily having seen an odr-use of the variable in
2742 /// this context.
2743 static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
2744 const DeclRefExpr *E,
2745 const VarDecl *VD) {
2746 // For a variable declared in an enclosing scope, do not emit a spurious
2747 // reference even if we have a capture, as that will emit an unwarranted
2748 // reference to our capture state, and will likely generate worse code than
2749 // emitting a local copy.
2750 if (E->refersToEnclosingVariableOrCapture())
2751 return false;
2753 // For a local declaration declared in this function, we can always reference
2754 // it even if we don't have an odr-use.
2755 if (VD->hasLocalStorage()) {
2756 return VD->getDeclContext() ==
2757 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2760 // For a global declaration, we can emit a reference to it if we know
2761 // for sure that we are able to emit a definition of it.
2762 VD = VD->getDefinition(CGF.getContext());
2763 if (!VD)
2764 return false;
2766 // Don't emit a spurious reference if it might be to a variable that only
2767 // exists on a different device / target.
2768 // FIXME: This is unnecessarily broad. Check whether this would actually be a
2769 // cross-target reference.
2770 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
2771 CGF.getLangOpts().OpenCL) {
2772 return false;
2775 // We can emit a spurious reference only if the linkage implies that we'll
2776 // be emitting a non-interposable symbol that will be retained until link
2777 // time.
2778 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
2779 case llvm::GlobalValue::ExternalLinkage:
2780 case llvm::GlobalValue::LinkOnceODRLinkage:
2781 case llvm::GlobalValue::WeakODRLinkage:
2782 case llvm::GlobalValue::InternalLinkage:
2783 case llvm::GlobalValue::PrivateLinkage:
2784 return true;
2785 default:
2786 return false;
2790 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2791 const NamedDecl *ND = E->getDecl();
2792 QualType T = E->getType();
2794 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
2795 "should not emit an unevaluated operand");
2797 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2798 // Global Named registers access via intrinsics only
2799 if (VD->getStorageClass() == SC_Register &&
2800 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2801 return EmitGlobalNamedRegister(VD, CGM);
2803 // If this DeclRefExpr does not constitute an odr-use of the variable,
2804 // we're not permitted to emit a reference to it in general, and it might
2805 // not be captured if capture would be necessary for a use. Emit the
2806 // constant value directly instead.
2807 if (E->isNonOdrUse() == NOUR_Constant &&
2808 (VD->getType()->isReferenceType() ||
2809 !canEmitSpuriousReferenceToVariable(*this, E, VD))) {
2810 VD->getAnyInitializer(VD);
2811 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
2812 E->getLocation(), *VD->evaluateValue(), VD->getType());
2813 assert(Val && "failed to emit constant expression");
2815 Address Addr = Address::invalid();
2816 if (!VD->getType()->isReferenceType()) {
2817 // Spill the constant value to a global.
2818 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
2819 getContext().getDeclAlign(VD));
2820 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2821 auto *PTy = llvm::PointerType::get(
2822 VarTy, getTypes().getTargetAddressSpace(VD->getType()));
2823 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
2824 } else {
2825 // Should we be using the alignment of the constant pointer we emitted?
2826 CharUnits Alignment =
2827 CGM.getNaturalTypeAlignment(E->getType(),
2828 /* BaseInfo= */ nullptr,
2829 /* TBAAInfo= */ nullptr,
2830 /* forPointeeType= */ true);
2831 Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
2833 return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2836 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
2838 // Check for captured variables.
2839 if (E->refersToEnclosingVariableOrCapture()) {
2840 VD = VD->getCanonicalDecl();
2841 if (auto *FD = LambdaCaptureFields.lookup(VD))
2842 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2843 if (CapturedStmtInfo) {
2844 auto I = LocalDeclMap.find(VD);
2845 if (I != LocalDeclMap.end()) {
2846 LValue CapLVal;
2847 if (VD->getType()->isReferenceType())
2848 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
2849 AlignmentSource::Decl);
2850 else
2851 CapLVal = MakeAddrLValue(I->second, T);
2852 // Mark lvalue as nontemporal if the variable is marked as nontemporal
2853 // in simd context.
2854 if (getLangOpts().OpenMP &&
2855 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2856 CapLVal.setNontemporal(/*Value=*/true);
2857 return CapLVal;
2859 LValue CapLVal =
2860 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2861 CapturedStmtInfo->getContextValue());
2862 Address LValueAddress = CapLVal.getAddress(*this);
2863 CapLVal = MakeAddrLValue(
2864 Address(LValueAddress.getPointer(), LValueAddress.getElementType(),
2865 getContext().getDeclAlign(VD)),
2866 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2867 CapLVal.getTBAAInfo());
2868 // Mark lvalue as nontemporal if the variable is marked as nontemporal
2869 // in simd context.
2870 if (getLangOpts().OpenMP &&
2871 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2872 CapLVal.setNontemporal(/*Value=*/true);
2873 return CapLVal;
2876 assert(isa<BlockDecl>(CurCodeDecl));
2877 Address addr = GetAddrOfBlockDecl(VD);
2878 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2882 // FIXME: We should be able to assert this for FunctionDecls as well!
2883 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2884 // those with a valid source location.
2885 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
2886 !E->getLocation().isValid()) &&
2887 "Should not use decl without marking it used!");
2889 if (ND->hasAttr<WeakRefAttr>()) {
2890 const auto *VD = cast<ValueDecl>(ND);
2891 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2892 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2895 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2896 // Check if this is a global variable.
2897 if (VD->hasLinkage() || VD->isStaticDataMember())
2898 return EmitGlobalVarDeclLValue(*this, E, VD);
2900 Address addr = Address::invalid();
2902 // The variable should generally be present in the local decl map.
2903 auto iter = LocalDeclMap.find(VD);
2904 if (iter != LocalDeclMap.end()) {
2905 addr = iter->second;
2907 // Otherwise, it might be static local we haven't emitted yet for
2908 // some reason; most likely, because it's in an outer function.
2909 } else if (VD->isStaticLocal()) {
2910 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
2911 *VD, CGM.getLLVMLinkageVarDefinition(VD));
2912 addr = Address(
2913 var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
2915 // No other cases for now.
2916 } else {
2917 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2920 // Handle threadlocal function locals.
2921 if (VD->getTLSKind() != VarDecl::TLS_None)
2922 addr = addr.withPointer(
2923 Builder.CreateThreadLocalAddress(addr.getPointer()), NotKnownNonNull);
2925 // Check for OpenMP threadprivate variables.
2926 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2927 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2928 return EmitThreadPrivateVarDeclLValue(
2929 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2930 E->getExprLoc());
2933 // Drill into block byref variables.
2934 bool isBlockByref = VD->isEscapingByref();
2935 if (isBlockByref) {
2936 addr = emitBlockByrefAddress(addr, VD);
2939 // Drill into reference types.
2940 LValue LV = VD->getType()->isReferenceType() ?
2941 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2942 MakeAddrLValue(addr, T, AlignmentSource::Decl);
2944 bool isLocalStorage = VD->hasLocalStorage();
2946 bool NonGCable = isLocalStorage &&
2947 !VD->getType()->isReferenceType() &&
2948 !isBlockByref;
2949 if (NonGCable) {
2950 LV.getQuals().removeObjCGCAttr();
2951 LV.setNonGC(true);
2954 bool isImpreciseLifetime =
2955 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2956 if (isImpreciseLifetime)
2957 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2958 setObjCGCLValueClass(getContext(), E, LV);
2959 return LV;
2962 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2963 LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2965 // Emit debuginfo for the function declaration if the target wants to.
2966 if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2967 if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2968 auto *Fn =
2969 cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2970 if (!Fn->getSubprogram())
2971 DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2975 return LV;
2978 // FIXME: While we're emitting a binding from an enclosing scope, all other
2979 // DeclRefExprs we see should be implicitly treated as if they also refer to
2980 // an enclosing scope.
2981 if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
2982 if (E->refersToEnclosingVariableOrCapture()) {
2983 auto *FD = LambdaCaptureFields.lookup(BD);
2984 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2986 return EmitLValue(BD->getBinding());
2989 // We can form DeclRefExprs naming GUID declarations when reconstituting
2990 // non-type template parameters into expressions.
2991 if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
2992 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
2993 AlignmentSource::Decl);
2995 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2996 return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2997 AlignmentSource::Decl);
2999 llvm_unreachable("Unhandled DeclRefExpr");
3002 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
3003 // __extension__ doesn't affect lvalue-ness.
3004 if (E->getOpcode() == UO_Extension)
3005 return EmitLValue(E->getSubExpr());
3007 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
3008 switch (E->getOpcode()) {
3009 default: llvm_unreachable("Unknown unary operator lvalue!");
3010 case UO_Deref: {
3011 QualType T = E->getSubExpr()->getType()->getPointeeType();
3012 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3014 LValueBaseInfo BaseInfo;
3015 TBAAAccessInfo TBAAInfo;
3016 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
3017 &TBAAInfo);
3018 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
3019 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
3021 // We should not generate __weak write barrier on indirect reference
3022 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
3023 // But, we continue to generate __strong write barrier on indirect write
3024 // into a pointer to object.
3025 if (getLangOpts().ObjC &&
3026 getLangOpts().getGC() != LangOptions::NonGC &&
3027 LV.isObjCWeak())
3028 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3029 return LV;
3031 case UO_Real:
3032 case UO_Imag: {
3033 LValue LV = EmitLValue(E->getSubExpr());
3034 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3036 // __real is valid on scalars. This is a faster way of testing that.
3037 // __imag can only produce an rvalue on scalars.
3038 if (E->getOpcode() == UO_Real &&
3039 !LV.getAddress(*this).getElementType()->isStructTy()) {
3040 assert(E->getSubExpr()->getType()->isArithmeticType());
3041 return LV;
3044 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3046 Address Component =
3047 (E->getOpcode() == UO_Real
3048 ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
3049 : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
3050 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
3051 CGM.getTBAAInfoForSubobject(LV, T));
3052 ElemLV.getQuals().addQualifiers(LV.getQuals());
3053 return ElemLV;
3055 case UO_PreInc:
3056 case UO_PreDec: {
3057 LValue LV = EmitLValue(E->getSubExpr());
3058 bool isInc = E->getOpcode() == UO_PreInc;
3060 if (E->getType()->isAnyComplexType())
3061 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3062 else
3063 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3064 return LV;
3069 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
3070 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
3071 E->getType(), AlignmentSource::Decl);
3074 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
3075 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
3076 E->getType(), AlignmentSource::Decl);
3079 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
3080 auto SL = E->getFunctionName();
3081 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3082 StringRef FnName = CurFn->getName();
3083 if (FnName.startswith("\01"))
3084 FnName = FnName.substr(1);
3085 StringRef NameItems[] = {
3086 PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
3087 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3088 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3089 std::string Name = std::string(SL->getString());
3090 if (!Name.empty()) {
3091 unsigned Discriminator =
3092 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
3093 if (Discriminator)
3094 Name += "_" + Twine(Discriminator + 1).str();
3095 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
3096 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3097 } else {
3098 auto C =
3099 CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
3100 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3103 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3104 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3107 /// Emit a type description suitable for use by a runtime sanitizer library. The
3108 /// format of a type descriptor is
3110 /// \code
3111 /// { i16 TypeKind, i16 TypeInfo }
3112 /// \endcode
3114 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
3115 /// integer, 1 for a floating point value, and -1 for anything else.
3116 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
3117 // Only emit each type's descriptor once.
3118 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3119 return C;
3121 uint16_t TypeKind = -1;
3122 uint16_t TypeInfo = 0;
3124 if (T->isIntegerType()) {
3125 TypeKind = 0;
3126 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3127 (T->isSignedIntegerType() ? 1 : 0);
3128 } else if (T->isFloatingType()) {
3129 TypeKind = 1;
3130 TypeInfo = getContext().getTypeSize(T);
3133 // Format the type name as if for a diagnostic, including quotes and
3134 // optionally an 'aka'.
3135 SmallString<32> Buffer;
3136 CGM.getDiags().ConvertArgToString(
3137 DiagnosticsEngine::ak_qualtype, (intptr_t)T.getAsOpaquePtr(), StringRef(),
3138 StringRef(), std::nullopt, Buffer, std::nullopt);
3140 llvm::Constant *Components[] = {
3141 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3142 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3144 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3146 auto *GV = new llvm::GlobalVariable(
3147 CGM.getModule(), Descriptor->getType(),
3148 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3149 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3150 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3152 // Remember the descriptor for this type.
3153 CGM.setTypeDescriptorInMap(T, GV);
3155 return GV;
3158 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3159 llvm::Type *TargetTy = IntPtrTy;
3161 if (V->getType() == TargetTy)
3162 return V;
3164 // Floating-point types which fit into intptr_t are bitcast to integers
3165 // and then passed directly (after zero-extension, if necessary).
3166 if (V->getType()->isFloatingPointTy()) {
3167 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
3168 if (Bits <= TargetTy->getIntegerBitWidth())
3169 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
3170 Bits));
3173 // Integers which fit in intptr_t are zero-extended and passed directly.
3174 if (V->getType()->isIntegerTy() &&
3175 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
3176 return Builder.CreateZExt(V, TargetTy);
3178 // Pointers are passed directly, everything else is passed by address.
3179 if (!V->getType()->isPointerTy()) {
3180 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
3181 Builder.CreateStore(V, Ptr);
3182 V = Ptr.getPointer();
3184 return Builder.CreatePtrToInt(V, TargetTy);
3187 /// Emit a representation of a SourceLocation for passing to a handler
3188 /// in a sanitizer runtime library. The format for this data is:
3189 /// \code
3190 /// struct SourceLocation {
3191 /// const char *Filename;
3192 /// int32_t Line, Column;
3193 /// };
3194 /// \endcode
3195 /// For an invalid SourceLocation, the Filename pointer is null.
3196 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
3197 llvm::Constant *Filename;
3198 int Line, Column;
3200 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
3201 if (PLoc.isValid()) {
3202 StringRef FilenameString = PLoc.getFilename();
3204 int PathComponentsToStrip =
3205 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3206 if (PathComponentsToStrip < 0) {
3207 assert(PathComponentsToStrip != INT_MIN);
3208 int PathComponentsToKeep = -PathComponentsToStrip;
3209 auto I = llvm::sys::path::rbegin(FilenameString);
3210 auto E = llvm::sys::path::rend(FilenameString);
3211 while (I != E && --PathComponentsToKeep)
3212 ++I;
3214 FilenameString = FilenameString.substr(I - E);
3215 } else if (PathComponentsToStrip > 0) {
3216 auto I = llvm::sys::path::begin(FilenameString);
3217 auto E = llvm::sys::path::end(FilenameString);
3218 while (I != E && PathComponentsToStrip--)
3219 ++I;
3221 if (I != E)
3222 FilenameString =
3223 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3224 else
3225 FilenameString = llvm::sys::path::filename(FilenameString);
3228 auto FilenameGV =
3229 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3230 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3231 cast<llvm::GlobalVariable>(
3232 FilenameGV.getPointer()->stripPointerCasts()));
3233 Filename = FilenameGV.getPointer();
3234 Line = PLoc.getLine();
3235 Column = PLoc.getColumn();
3236 } else {
3237 Filename = llvm::Constant::getNullValue(Int8PtrTy);
3238 Line = Column = 0;
3241 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3242 Builder.getInt32(Column)};
3244 return llvm::ConstantStruct::getAnon(Data);
3247 namespace {
3248 /// Specify under what conditions this check can be recovered
3249 enum class CheckRecoverableKind {
3250 /// Always terminate program execution if this check fails.
3251 Unrecoverable,
3252 /// Check supports recovering, runtime has both fatal (noreturn) and
3253 /// non-fatal handlers for this check.
3254 Recoverable,
3255 /// Runtime conditionally aborts, always need to support recovery.
3256 AlwaysRecoverable
3260 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
3261 assert(Kind.countPopulation() == 1);
3262 if (Kind == SanitizerKind::Vptr)
3263 return CheckRecoverableKind::AlwaysRecoverable;
3264 else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
3265 return CheckRecoverableKind::Unrecoverable;
3266 else
3267 return CheckRecoverableKind::Recoverable;
3270 namespace {
3271 struct SanitizerHandlerInfo {
3272 char const *const Name;
3273 unsigned Version;
3277 const SanitizerHandlerInfo SanitizerHandlers[] = {
3278 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
3279 LIST_SANITIZER_CHECKS
3280 #undef SANITIZER_CHECK
3283 static void emitCheckHandlerCall(CodeGenFunction &CGF,
3284 llvm::FunctionType *FnType,
3285 ArrayRef<llvm::Value *> FnArgs,
3286 SanitizerHandler CheckHandler,
3287 CheckRecoverableKind RecoverKind, bool IsFatal,
3288 llvm::BasicBlock *ContBB) {
3289 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3290 std::optional<ApplyDebugLocation> DL;
3291 if (!CGF.Builder.getCurrentDebugLocation()) {
3292 // Ensure that the call has at least an artificial debug location.
3293 DL.emplace(CGF, SourceLocation());
3295 bool NeedsAbortSuffix =
3296 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
3297 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3298 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3299 const StringRef CheckName = CheckInfo.Name;
3300 std::string FnName = "__ubsan_handle_" + CheckName.str();
3301 if (CheckInfo.Version && !MinimalRuntime)
3302 FnName += "_v" + llvm::utostr(CheckInfo.Version);
3303 if (MinimalRuntime)
3304 FnName += "_minimal";
3305 if (NeedsAbortSuffix)
3306 FnName += "_abort";
3307 bool MayReturn =
3308 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3310 llvm::AttrBuilder B(CGF.getLLVMContext());
3311 if (!MayReturn) {
3312 B.addAttribute(llvm::Attribute::NoReturn)
3313 .addAttribute(llvm::Attribute::NoUnwind);
3315 B.addUWTableAttr(llvm::UWTableKind::Default);
3317 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3318 FnType, FnName,
3319 llvm::AttributeList::get(CGF.getLLVMContext(),
3320 llvm::AttributeList::FunctionIndex, B),
3321 /*Local=*/true);
3322 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3323 if (!MayReturn) {
3324 HandlerCall->setDoesNotReturn();
3325 CGF.Builder.CreateUnreachable();
3326 } else {
3327 CGF.Builder.CreateBr(ContBB);
3331 void CodeGenFunction::EmitCheck(
3332 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3333 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3334 ArrayRef<llvm::Value *> DynamicArgs) {
3335 assert(IsSanitizerScope);
3336 assert(Checked.size() > 0);
3337 assert(CheckHandler >= 0 &&
3338 size_t(CheckHandler) < std::size(SanitizerHandlers));
3339 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3341 llvm::Value *FatalCond = nullptr;
3342 llvm::Value *RecoverableCond = nullptr;
3343 llvm::Value *TrapCond = nullptr;
3344 for (int i = 0, n = Checked.size(); i < n; ++i) {
3345 llvm::Value *Check = Checked[i].first;
3346 // -fsanitize-trap= overrides -fsanitize-recover=.
3347 llvm::Value *&Cond =
3348 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3349 ? TrapCond
3350 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
3351 ? RecoverableCond
3352 : FatalCond;
3353 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
3356 if (TrapCond)
3357 EmitTrapCheck(TrapCond, CheckHandler);
3358 if (!FatalCond && !RecoverableCond)
3359 return;
3361 llvm::Value *JointCond;
3362 if (FatalCond && RecoverableCond)
3363 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3364 else
3365 JointCond = FatalCond ? FatalCond : RecoverableCond;
3366 assert(JointCond);
3368 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3369 assert(SanOpts.has(Checked[0].second));
3370 #ifndef NDEBUG
3371 for (int i = 1, n = Checked.size(); i < n; ++i) {
3372 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3373 "All recoverable kinds in a single check must be same!");
3374 assert(SanOpts.has(Checked[i].second));
3376 #endif
3378 llvm::BasicBlock *Cont = createBasicBlock("cont");
3379 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3380 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3381 // Give hint that we very much don't expect to execute the handler
3382 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
3383 llvm::MDBuilder MDHelper(getLLVMContext());
3384 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3385 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3386 EmitBlock(Handlers);
3388 // Handler functions take an i8* pointing to the (handler-specific) static
3389 // information block, followed by a sequence of intptr_t arguments
3390 // representing operand values.
3391 SmallVector<llvm::Value *, 4> Args;
3392 SmallVector<llvm::Type *, 4> ArgTypes;
3393 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3394 Args.reserve(DynamicArgs.size() + 1);
3395 ArgTypes.reserve(DynamicArgs.size() + 1);
3397 // Emit handler arguments and create handler function type.
3398 if (!StaticArgs.empty()) {
3399 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3400 auto *InfoPtr = new llvm::GlobalVariable(
3401 CGM.getModule(), Info->getType(), false,
3402 llvm::GlobalVariable::PrivateLinkage, Info, "", nullptr,
3403 llvm::GlobalVariable::NotThreadLocal,
3404 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
3405 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3406 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3407 Args.push_back(InfoPtr);
3408 ArgTypes.push_back(Args.back()->getType());
3411 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3412 Args.push_back(EmitCheckValue(DynamicArgs[i]));
3413 ArgTypes.push_back(IntPtrTy);
3417 llvm::FunctionType *FnType =
3418 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
3420 if (!FatalCond || !RecoverableCond) {
3421 // Simple case: we need to generate a single handler call, either
3422 // fatal, or non-fatal.
3423 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
3424 (FatalCond != nullptr), Cont);
3425 } else {
3426 // Emit two handler calls: first one for set of unrecoverable checks,
3427 // another one for recoverable.
3428 llvm::BasicBlock *NonFatalHandlerBB =
3429 createBasicBlock("non_fatal." + CheckName);
3430 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3431 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3432 EmitBlock(FatalHandlerBB);
3433 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
3434 NonFatalHandlerBB);
3435 EmitBlock(NonFatalHandlerBB);
3436 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
3437 Cont);
3440 EmitBlock(Cont);
3443 void CodeGenFunction::EmitCfiSlowPathCheck(
3444 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3445 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
3446 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3448 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3449 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3451 llvm::MDBuilder MDHelper(getLLVMContext());
3452 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3453 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3455 EmitBlock(CheckBB);
3457 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3459 llvm::CallInst *CheckCall;
3460 llvm::FunctionCallee SlowPathFn;
3461 if (WithDiag) {
3462 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3463 auto *InfoPtr =
3464 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3465 llvm::GlobalVariable::PrivateLinkage, Info);
3466 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3467 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3469 SlowPathFn = CGM.getModule().getOrInsertFunction(
3470 "__cfi_slowpath_diag",
3471 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3472 false));
3473 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
3474 } else {
3475 SlowPathFn = CGM.getModule().getOrInsertFunction(
3476 "__cfi_slowpath",
3477 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3478 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3481 CGM.setDSOLocal(
3482 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
3483 CheckCall->setDoesNotThrow();
3485 EmitBlock(Cont);
3488 // Emit a stub for __cfi_check function so that the linker knows about this
3489 // symbol in LTO mode.
3490 void CodeGenFunction::EmitCfiCheckStub() {
3491 llvm::Module *M = &CGM.getModule();
3492 auto &Ctx = M->getContext();
3493 llvm::Function *F = llvm::Function::Create(
3494 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3495 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3496 F->setAlignment(llvm::Align(4096));
3497 CGM.setDSOLocal(F);
3498 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3499 // CrossDSOCFI pass is not executed if there is no executable code.
3500 SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)};
3501 llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB);
3502 llvm::ReturnInst::Create(Ctx, nullptr, BB);
3505 // This function is basically a switch over the CFI failure kind, which is
3506 // extracted from CFICheckFailData (1st function argument). Each case is either
3507 // llvm.trap or a call to one of the two runtime handlers, based on
3508 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
3509 // failure kind) traps, but this should really never happen. CFICheckFailData
3510 // can be nullptr if the calling module has -fsanitize-trap behavior for this
3511 // check kind; in this case __cfi_check_fail traps as well.
3512 void CodeGenFunction::EmitCfiCheckFail() {
3513 SanitizerScope SanScope(this);
3514 FunctionArgList Args;
3515 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3516 ImplicitParamDecl::Other);
3517 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3518 ImplicitParamDecl::Other);
3519 Args.push_back(&ArgData);
3520 Args.push_back(&ArgAddr);
3522 const CGFunctionInfo &FI =
3523 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3525 llvm::Function *F = llvm::Function::Create(
3526 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3527 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3529 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3530 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
3531 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3533 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3534 SourceLocation());
3536 // This function is not affected by NoSanitizeList. This function does
3537 // not have a source location, but "src:*" would still apply. Revert any
3538 // changes to SanOpts made in StartFunction.
3539 SanOpts = CGM.getLangOpts().Sanitize;
3541 llvm::Value *Data =
3542 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3543 CGM.getContext().VoidPtrTy, ArgData.getLocation());
3544 llvm::Value *Addr =
3545 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3546 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3548 // Data == nullptr means the calling module has trap behaviour for this check.
3549 llvm::Value *DataIsNotNullPtr =
3550 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3551 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
3553 llvm::StructType *SourceLocationTy =
3554 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3555 llvm::StructType *CfiCheckFailDataTy =
3556 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3558 llvm::Value *V = Builder.CreateConstGEP2_32(
3559 CfiCheckFailDataTy,
3560 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3563 Address CheckKindAddr(V, Int8Ty, getIntAlign());
3564 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3566 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3567 CGM.getLLVMContext(),
3568 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3569 llvm::Value *ValidVtable = Builder.CreateZExt(
3570 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3571 {Addr, AllVtables}),
3572 IntPtrTy);
3574 const std::pair<int, SanitizerMask> CheckKinds[] = {
3575 {CFITCK_VCall, SanitizerKind::CFIVCall},
3576 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3577 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3578 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3579 {CFITCK_ICall, SanitizerKind::CFIICall}};
3581 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3582 for (auto CheckKindMaskPair : CheckKinds) {
3583 int Kind = CheckKindMaskPair.first;
3584 SanitizerMask Mask = CheckKindMaskPair.second;
3585 llvm::Value *Cond =
3586 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3587 if (CGM.getLangOpts().Sanitize.has(Mask))
3588 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3589 {Data, Addr, ValidVtable});
3590 else
3591 EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
3594 FinishFunction();
3595 // The only reference to this function will be created during LTO link.
3596 // Make sure it survives until then.
3597 CGM.addUsedGlobal(F);
3600 void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3601 if (SanOpts.has(SanitizerKind::Unreachable)) {
3602 SanitizerScope SanScope(this);
3603 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3604 SanitizerKind::Unreachable),
3605 SanitizerHandler::BuiltinUnreachable,
3606 EmitCheckSourceLocation(Loc), std::nullopt);
3608 Builder.CreateUnreachable();
3611 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3612 SanitizerHandler CheckHandlerID) {
3613 llvm::BasicBlock *Cont = createBasicBlock("cont");
3615 // If we're optimizing, collapse all calls to trap down to just one per
3616 // check-type per function to save on code size.
3617 if (TrapBBs.size() <= CheckHandlerID)
3618 TrapBBs.resize(CheckHandlerID + 1);
3620 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3622 if (!ClSanitizeDebugDeoptimization &&
3623 CGM.getCodeGenOpts().OptimizationLevel && TrapBB &&
3624 (!CurCodeDecl || !CurCodeDecl->hasAttr<OptimizeNoneAttr>())) {
3625 auto Call = TrapBB->begin();
3626 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3628 Call->applyMergedLocation(Call->getDebugLoc(),
3629 Builder.getCurrentDebugLocation());
3630 Builder.CreateCondBr(Checked, Cont, TrapBB);
3631 } else {
3632 TrapBB = createBasicBlock("trap");
3633 Builder.CreateCondBr(Checked, Cont, TrapBB);
3634 EmitBlock(TrapBB);
3636 llvm::CallInst *TrapCall = Builder.CreateCall(
3637 CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3638 llvm::ConstantInt::get(CGM.Int8Ty, ClSanitizeDebugDeoptimization
3639 ? TrapBB->getParent()->size()
3640 : CheckHandlerID));
3642 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3643 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3644 CGM.getCodeGenOpts().TrapFuncName);
3645 TrapCall->addFnAttr(A);
3647 TrapCall->setDoesNotReturn();
3648 TrapCall->setDoesNotThrow();
3649 Builder.CreateUnreachable();
3652 EmitBlock(Cont);
3655 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3656 llvm::CallInst *TrapCall =
3657 Builder.CreateCall(CGM.getIntrinsic(IntrID));
3659 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3660 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3661 CGM.getCodeGenOpts().TrapFuncName);
3662 TrapCall->addFnAttr(A);
3665 return TrapCall;
3668 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3669 LValueBaseInfo *BaseInfo,
3670 TBAAAccessInfo *TBAAInfo) {
3671 assert(E->getType()->isArrayType() &&
3672 "Array to pointer decay must have array source type!");
3674 // Expressions of array type can't be bitfields or vector elements.
3675 LValue LV = EmitLValue(E);
3676 Address Addr = LV.getAddress(*this);
3678 // If the array type was an incomplete type, we need to make sure
3679 // the decay ends up being the right type.
3680 llvm::Type *NewTy = ConvertType(E->getType());
3681 Addr = Addr.withElementType(NewTy);
3683 // Note that VLA pointers are always decayed, so we don't need to do
3684 // anything here.
3685 if (!E->getType()->isVariableArrayType()) {
3686 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3687 "Expected pointer to array");
3688 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3691 // The result of this decay conversion points to an array element within the
3692 // base lvalue. However, since TBAA currently does not support representing
3693 // accesses to elements of member arrays, we conservatively represent accesses
3694 // to the pointee object as if it had no any base lvalue specified.
3695 // TODO: Support TBAA for member arrays.
3696 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3697 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3698 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3700 return Addr.withElementType(ConvertTypeForMem(EltType));
3703 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3704 /// array to pointer, return the array subexpression.
3705 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3706 // If this isn't just an array->pointer decay, bail out.
3707 const auto *CE = dyn_cast<CastExpr>(E);
3708 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3709 return nullptr;
3711 // If this is a decay from variable width array, bail out.
3712 const Expr *SubExpr = CE->getSubExpr();
3713 if (SubExpr->getType()->isVariableArrayType())
3714 return nullptr;
3716 return SubExpr;
3719 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3720 llvm::Type *elemType,
3721 llvm::Value *ptr,
3722 ArrayRef<llvm::Value*> indices,
3723 bool inbounds,
3724 bool signedIndices,
3725 SourceLocation loc,
3726 const llvm::Twine &name = "arrayidx") {
3727 if (inbounds) {
3728 return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
3729 CodeGenFunction::NotSubtraction, loc,
3730 name);
3731 } else {
3732 return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
3736 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3737 llvm::Value *idx,
3738 CharUnits eltSize) {
3739 // If we have a constant index, we can use the exact offset of the
3740 // element we're accessing.
3741 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3742 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3743 return arrayAlign.alignmentAtOffset(offset);
3745 // Otherwise, use the worst-case alignment for any element.
3746 } else {
3747 return arrayAlign.alignmentOfArrayElement(eltSize);
3751 static QualType getFixedSizeElementType(const ASTContext &ctx,
3752 const VariableArrayType *vla) {
3753 QualType eltType;
3754 do {
3755 eltType = vla->getElementType();
3756 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3757 return eltType;
3760 /// Given an array base, check whether its member access belongs to a record
3761 /// with preserve_access_index attribute or not.
3762 static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3763 if (!ArrayBase || !CGF.getDebugInfo())
3764 return false;
3766 // Only support base as either a MemberExpr or DeclRefExpr.
3767 // DeclRefExpr to cover cases like:
3768 // struct s { int a; int b[10]; };
3769 // struct s *p;
3770 // p[1].a
3771 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3772 // p->b[5] is a MemberExpr example.
3773 const Expr *E = ArrayBase->IgnoreImpCasts();
3774 if (const auto *ME = dyn_cast<MemberExpr>(E))
3775 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3777 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3778 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3779 if (!VarDef)
3780 return false;
3782 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3783 if (!PtrT)
3784 return false;
3786 const auto *PointeeT = PtrT->getPointeeType()
3787 ->getUnqualifiedDesugaredType();
3788 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3789 return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3790 return false;
3793 return false;
3796 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3797 ArrayRef<llvm::Value *> indices,
3798 QualType eltType, bool inbounds,
3799 bool signedIndices, SourceLocation loc,
3800 QualType *arrayType = nullptr,
3801 const Expr *Base = nullptr,
3802 const llvm::Twine &name = "arrayidx") {
3803 // All the indices except that last must be zero.
3804 #ifndef NDEBUG
3805 for (auto *idx : indices.drop_back())
3806 assert(isa<llvm::ConstantInt>(idx) &&
3807 cast<llvm::ConstantInt>(idx)->isZero());
3808 #endif
3810 // Determine the element size of the statically-sized base. This is
3811 // the thing that the indices are expressed in terms of.
3812 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3813 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3816 // We can use that to compute the best alignment of the element.
3817 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3818 CharUnits eltAlign =
3819 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3821 llvm::Value *eltPtr;
3822 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3823 if (!LastIndex ||
3824 (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
3825 eltPtr = emitArraySubscriptGEP(
3826 CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3827 signedIndices, loc, name);
3828 } else {
3829 // Remember the original array subscript for bpf target
3830 unsigned idx = LastIndex->getZExtValue();
3831 llvm::DIType *DbgInfo = nullptr;
3832 if (arrayType)
3833 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3834 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3835 addr.getPointer(),
3836 indices.size() - 1,
3837 idx, DbgInfo);
3840 return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
3843 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3844 bool Accessed) {
3845 // The index must always be an integer, which is not an aggregate. Emit it
3846 // in lexical order (this complexity is, sadly, required by C++17).
3847 llvm::Value *IdxPre =
3848 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3849 bool SignedIndices = false;
3850 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3851 auto *Idx = IdxPre;
3852 if (E->getLHS() != E->getIdx()) {
3853 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3854 Idx = EmitScalarExpr(E->getIdx());
3857 QualType IdxTy = E->getIdx()->getType();
3858 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3859 SignedIndices |= IdxSigned;
3861 if (SanOpts.has(SanitizerKind::ArrayBounds))
3862 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3864 // Extend or truncate the index type to 32 or 64-bits.
3865 if (Promote && Idx->getType() != IntPtrTy)
3866 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3868 return Idx;
3870 IdxPre = nullptr;
3872 // If the base is a vector type, then we are forming a vector element lvalue
3873 // with this subscript.
3874 if (E->getBase()->getType()->isVectorType() &&
3875 !isa<ExtVectorElementExpr>(E->getBase())) {
3876 // Emit the vector as an lvalue to get its address.
3877 LValue LHS = EmitLValue(E->getBase());
3878 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3879 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3880 return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3881 E->getBase()->getType(), LHS.getBaseInfo(),
3882 TBAAAccessInfo());
3885 // All the other cases basically behave like simple offsetting.
3887 // Handle the extvector case we ignored above.
3888 if (isa<ExtVectorElementExpr>(E->getBase())) {
3889 LValue LV = EmitLValue(E->getBase());
3890 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3891 Address Addr = EmitExtVectorElementLValue(LV);
3893 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3894 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3895 SignedIndices, E->getExprLoc());
3896 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3897 CGM.getTBAAInfoForSubobject(LV, EltType));
3900 LValueBaseInfo EltBaseInfo;
3901 TBAAAccessInfo EltTBAAInfo;
3902 Address Addr = Address::invalid();
3903 if (const VariableArrayType *vla =
3904 getContext().getAsVariableArrayType(E->getType())) {
3905 // The base must be a pointer, which is not an aggregate. Emit
3906 // it. It needs to be emitted first in case it's what captures
3907 // the VLA bounds.
3908 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3909 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3911 // The element count here is the total number of non-VLA elements.
3912 llvm::Value *numElements = getVLASize(vla).NumElts;
3914 // Effectively, the multiply by the VLA size is part of the GEP.
3915 // GEP indexes are signed, and scaling an index isn't permitted to
3916 // signed-overflow, so we use the same semantics for our explicit
3917 // multiply. We suppress this if overflow is not undefined behavior.
3918 if (getLangOpts().isSignedOverflowDefined()) {
3919 Idx = Builder.CreateMul(Idx, numElements);
3920 } else {
3921 Idx = Builder.CreateNSWMul(Idx, numElements);
3924 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3925 !getLangOpts().isSignedOverflowDefined(),
3926 SignedIndices, E->getExprLoc());
3928 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3929 // Indexing over an interface, as in "NSString *P; P[4];"
3931 // Emit the base pointer.
3932 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3933 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3935 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3936 llvm::Value *InterfaceSizeVal =
3937 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3939 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3941 // We don't necessarily build correct LLVM struct types for ObjC
3942 // interfaces, so we can't rely on GEP to do this scaling
3943 // correctly, so we need to cast to i8*. FIXME: is this actually
3944 // true? A lot of other things in the fragile ABI would break...
3945 llvm::Type *OrigBaseElemTy = Addr.getElementType();
3947 // Do the GEP.
3948 CharUnits EltAlign =
3949 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3950 llvm::Value *EltPtr =
3951 emitArraySubscriptGEP(*this, Int8Ty, Addr.getPointer(), ScaledIdx,
3952 false, SignedIndices, E->getExprLoc());
3953 Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
3954 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3955 // If this is A[i] where A is an array, the frontend will have decayed the
3956 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3957 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3958 // "gep x, i" here. Emit one "gep A, 0, i".
3959 assert(Array->getType()->isArrayType() &&
3960 "Array to pointer decay must have array source type!");
3961 LValue ArrayLV;
3962 // For simple multidimensional array indexing, set the 'accessed' flag for
3963 // better bounds-checking of the base expression.
3964 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3965 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3966 else
3967 ArrayLV = EmitLValue(Array);
3968 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3970 // Propagate the alignment from the array itself to the result.
3971 QualType arrayType = Array->getType();
3972 Addr = emitArraySubscriptGEP(
3973 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
3974 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3975 E->getExprLoc(), &arrayType, E->getBase());
3976 EltBaseInfo = ArrayLV.getBaseInfo();
3977 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3978 } else {
3979 // The base must be a pointer; emit it with an estimate of its alignment.
3980 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3981 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3982 QualType ptrType = E->getBase()->getType();
3983 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3984 !getLangOpts().isSignedOverflowDefined(),
3985 SignedIndices, E->getExprLoc(), &ptrType,
3986 E->getBase());
3989 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3991 if (getLangOpts().ObjC &&
3992 getLangOpts().getGC() != LangOptions::NonGC) {
3993 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3994 setObjCGCLValueClass(getContext(), E, LV);
3996 return LV;
3999 LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
4000 assert(
4001 !E->isIncomplete() &&
4002 "incomplete matrix subscript expressions should be rejected during Sema");
4003 LValue Base = EmitLValue(E->getBase());
4004 llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
4005 llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
4006 llvm::Value *NumRows = Builder.getIntN(
4007 RowIdx->getType()->getScalarSizeInBits(),
4008 E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
4009 llvm::Value *FinalIdx =
4010 Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
4011 return LValue::MakeMatrixElt(
4012 MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
4013 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
4016 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
4017 LValueBaseInfo &BaseInfo,
4018 TBAAAccessInfo &TBAAInfo,
4019 QualType BaseTy, QualType ElTy,
4020 bool IsLowerBound) {
4021 LValue BaseLVal;
4022 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
4023 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
4024 if (BaseTy->isArrayType()) {
4025 Address Addr = BaseLVal.getAddress(CGF);
4026 BaseInfo = BaseLVal.getBaseInfo();
4028 // If the array type was an incomplete type, we need to make sure
4029 // the decay ends up being the right type.
4030 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
4031 Addr = Addr.withElementType(NewTy);
4033 // Note that VLA pointers are always decayed, so we don't need to do
4034 // anything here.
4035 if (!BaseTy->isVariableArrayType()) {
4036 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4037 "Expected pointer to array");
4038 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4041 return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
4043 LValueBaseInfo TypeBaseInfo;
4044 TBAAAccessInfo TypeTBAAInfo;
4045 CharUnits Align =
4046 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
4047 BaseInfo.mergeForCast(TypeBaseInfo);
4048 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
4049 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)),
4050 CGF.ConvertTypeForMem(ElTy), Align);
4052 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
4055 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
4056 bool IsLowerBound) {
4057 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
4058 QualType ResultExprTy;
4059 if (auto *AT = getContext().getAsArrayType(BaseTy))
4060 ResultExprTy = AT->getElementType();
4061 else
4062 ResultExprTy = BaseTy->getPointeeType();
4063 llvm::Value *Idx = nullptr;
4064 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
4065 // Requesting lower bound or upper bound, but without provided length and
4066 // without ':' symbol for the default length -> length = 1.
4067 // Idx = LowerBound ?: 0;
4068 if (auto *LowerBound = E->getLowerBound()) {
4069 Idx = Builder.CreateIntCast(
4070 EmitScalarExpr(LowerBound), IntPtrTy,
4071 LowerBound->getType()->hasSignedIntegerRepresentation());
4072 } else
4073 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
4074 } else {
4075 // Try to emit length or lower bound as constant. If this is possible, 1
4076 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
4077 // IR (LB + Len) - 1.
4078 auto &C = CGM.getContext();
4079 auto *Length = E->getLength();
4080 llvm::APSInt ConstLength;
4081 if (Length) {
4082 // Idx = LowerBound + Length - 1;
4083 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4084 ConstLength = CL->zextOrTrunc(PointerWidthInBits);
4085 Length = nullptr;
4087 auto *LowerBound = E->getLowerBound();
4088 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4089 if (LowerBound) {
4090 if (std::optional<llvm::APSInt> LB =
4091 LowerBound->getIntegerConstantExpr(C)) {
4092 ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
4093 LowerBound = nullptr;
4096 if (!Length)
4097 --ConstLength;
4098 else if (!LowerBound)
4099 --ConstLowerBound;
4101 if (Length || LowerBound) {
4102 auto *LowerBoundVal =
4103 LowerBound
4104 ? Builder.CreateIntCast(
4105 EmitScalarExpr(LowerBound), IntPtrTy,
4106 LowerBound->getType()->hasSignedIntegerRepresentation())
4107 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
4108 auto *LengthVal =
4109 Length
4110 ? Builder.CreateIntCast(
4111 EmitScalarExpr(Length), IntPtrTy,
4112 Length->getType()->hasSignedIntegerRepresentation())
4113 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
4114 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
4115 /*HasNUW=*/false,
4116 !getLangOpts().isSignedOverflowDefined());
4117 if (Length && LowerBound) {
4118 Idx = Builder.CreateSub(
4119 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
4120 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4122 } else
4123 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
4124 } else {
4125 // Idx = ArraySize - 1;
4126 QualType ArrayTy = BaseTy->isPointerType()
4127 ? E->getBase()->IgnoreParenImpCasts()->getType()
4128 : BaseTy;
4129 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
4130 Length = VAT->getSizeExpr();
4131 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4132 ConstLength = *L;
4133 Length = nullptr;
4135 } else {
4136 auto *CAT = C.getAsConstantArrayType(ArrayTy);
4137 assert(CAT && "unexpected type for array initializer");
4138 ConstLength = CAT->getSize();
4140 if (Length) {
4141 auto *LengthVal = Builder.CreateIntCast(
4142 EmitScalarExpr(Length), IntPtrTy,
4143 Length->getType()->hasSignedIntegerRepresentation());
4144 Idx = Builder.CreateSub(
4145 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
4146 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4147 } else {
4148 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
4149 --ConstLength;
4150 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
4154 assert(Idx);
4156 Address EltPtr = Address::invalid();
4157 LValueBaseInfo BaseInfo;
4158 TBAAAccessInfo TBAAInfo;
4159 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
4160 // The base must be a pointer, which is not an aggregate. Emit
4161 // it. It needs to be emitted first in case it's what captures
4162 // the VLA bounds.
4163 Address Base =
4164 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
4165 BaseTy, VLA->getElementType(), IsLowerBound);
4166 // The element count here is the total number of non-VLA elements.
4167 llvm::Value *NumElements = getVLASize(VLA).NumElts;
4169 // Effectively, the multiply by the VLA size is part of the GEP.
4170 // GEP indexes are signed, and scaling an index isn't permitted to
4171 // signed-overflow, so we use the same semantics for our explicit
4172 // multiply. We suppress this if overflow is not undefined behavior.
4173 if (getLangOpts().isSignedOverflowDefined())
4174 Idx = Builder.CreateMul(Idx, NumElements);
4175 else
4176 Idx = Builder.CreateNSWMul(Idx, NumElements);
4177 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
4178 !getLangOpts().isSignedOverflowDefined(),
4179 /*signedIndices=*/false, E->getExprLoc());
4180 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4181 // If this is A[i] where A is an array, the frontend will have decayed the
4182 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
4183 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4184 // "gep x, i" here. Emit one "gep A, 0, i".
4185 assert(Array->getType()->isArrayType() &&
4186 "Array to pointer decay must have array source type!");
4187 LValue ArrayLV;
4188 // For simple multidimensional array indexing, set the 'accessed' flag for
4189 // better bounds-checking of the base expression.
4190 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4191 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4192 else
4193 ArrayLV = EmitLValue(Array);
4195 // Propagate the alignment from the array itself to the result.
4196 EltPtr = emitArraySubscriptGEP(
4197 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
4198 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
4199 /*signedIndices=*/false, E->getExprLoc());
4200 BaseInfo = ArrayLV.getBaseInfo();
4201 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
4202 } else {
4203 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
4204 TBAAInfo, BaseTy, ResultExprTy,
4205 IsLowerBound);
4206 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
4207 !getLangOpts().isSignedOverflowDefined(),
4208 /*signedIndices=*/false, E->getExprLoc());
4211 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
4214 LValue CodeGenFunction::
4215 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
4216 // Emit the base vector as an l-value.
4217 LValue Base;
4219 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
4220 if (E->isArrow()) {
4221 // If it is a pointer to a vector, emit the address and form an lvalue with
4222 // it.
4223 LValueBaseInfo BaseInfo;
4224 TBAAAccessInfo TBAAInfo;
4225 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4226 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
4227 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
4228 Base.getQuals().removeObjCGCAttr();
4229 } else if (E->getBase()->isGLValue()) {
4230 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
4231 // emit the base as an lvalue.
4232 assert(E->getBase()->getType()->isVectorType());
4233 Base = EmitLValue(E->getBase());
4234 } else {
4235 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
4236 assert(E->getBase()->getType()->isVectorType() &&
4237 "Result must be a vector");
4238 llvm::Value *Vec = EmitScalarExpr(E->getBase());
4240 // Store the vector to memory (because LValue wants an address).
4241 Address VecMem = CreateMemTemp(E->getBase()->getType());
4242 Builder.CreateStore(Vec, VecMem);
4243 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
4244 AlignmentSource::Decl);
4247 QualType type =
4248 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
4250 // Encode the element access list into a vector of unsigned indices.
4251 SmallVector<uint32_t, 4> Indices;
4252 E->getEncodedElementAccess(Indices);
4254 if (Base.isSimple()) {
4255 llvm::Constant *CV =
4256 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4257 return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
4258 Base.getBaseInfo(), TBAAAccessInfo());
4260 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
4262 llvm::Constant *BaseElts = Base.getExtVectorElts();
4263 SmallVector<llvm::Constant *, 4> CElts;
4265 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
4266 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
4267 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
4268 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
4269 Base.getBaseInfo(), TBAAAccessInfo());
4272 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
4273 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
4274 EmitIgnoredExpr(E->getBase());
4275 return EmitDeclRefLValue(DRE);
4278 Expr *BaseExpr = E->getBase();
4279 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
4280 LValue BaseLV;
4281 if (E->isArrow()) {
4282 LValueBaseInfo BaseInfo;
4283 TBAAAccessInfo TBAAInfo;
4284 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
4285 QualType PtrTy = BaseExpr->getType()->getPointeeType();
4286 SanitizerSet SkippedChecks;
4287 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
4288 if (IsBaseCXXThis)
4289 SkippedChecks.set(SanitizerKind::Alignment, true);
4290 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
4291 SkippedChecks.set(SanitizerKind::Null, true);
4292 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
4293 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
4294 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
4295 } else
4296 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
4298 NamedDecl *ND = E->getMemberDecl();
4299 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
4300 LValue LV = EmitLValueForField(BaseLV, Field);
4301 setObjCGCLValueClass(getContext(), E, LV);
4302 if (getLangOpts().OpenMP) {
4303 // If the member was explicitly marked as nontemporal, mark it as
4304 // nontemporal. If the base lvalue is marked as nontemporal, mark access
4305 // to children as nontemporal too.
4306 if ((IsWrappedCXXThis(BaseExpr) &&
4307 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4308 BaseLV.isNontemporal())
4309 LV.setNontemporal(/*Value=*/true);
4311 return LV;
4314 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
4315 return EmitFunctionDeclLValue(*this, E, FD);
4317 llvm_unreachable("Unhandled member declaration!");
4320 /// Given that we are currently emitting a lambda, emit an l-value for
4321 /// one of its members.
4323 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field,
4324 llvm::Value *ThisValue) {
4325 bool HasExplicitObjectParameter = false;
4326 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl)) {
4327 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
4328 assert(MD->getParent()->isLambda());
4329 assert(MD->getParent() == Field->getParent());
4331 LValue LambdaLV;
4332 if (HasExplicitObjectParameter) {
4333 const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0);
4334 auto It = LocalDeclMap.find(D);
4335 assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
4336 Address AddrOfExplicitObject = It->getSecond();
4337 if (D->getType()->isReferenceType())
4338 LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(),
4339 AlignmentSource::Decl);
4340 else
4341 LambdaLV = MakeNaturalAlignAddrLValue(AddrOfExplicitObject.getPointer(),
4342 D->getType().getNonReferenceType());
4343 } else {
4344 QualType LambdaTagType = getContext().getTagDeclType(Field->getParent());
4345 LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
4347 return EmitLValueForField(LambdaLV, Field);
4350 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4351 return EmitLValueForLambdaField(Field, CXXABIThisValue);
4354 /// Get the field index in the debug info. The debug info structure/union
4355 /// will ignore the unnamed bitfields.
4356 unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
4357 unsigned FieldIndex) {
4358 unsigned I = 0, Skipped = 0;
4360 for (auto *F : Rec->getDefinition()->fields()) {
4361 if (I == FieldIndex)
4362 break;
4363 if (F->isUnnamedBitfield())
4364 Skipped++;
4365 I++;
4368 return FieldIndex - Skipped;
4371 /// Get the address of a zero-sized field within a record. The resulting
4372 /// address doesn't necessarily have the right type.
4373 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
4374 const FieldDecl *Field) {
4375 CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
4376 CGF.getContext().getFieldOffset(Field));
4377 if (Offset.isZero())
4378 return Base;
4379 Base = Base.withElementType(CGF.Int8Ty);
4380 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4383 /// Drill down to the storage of a field without walking into
4384 /// reference types.
4386 /// The resulting address doesn't necessarily have the right type.
4387 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
4388 const FieldDecl *field) {
4389 if (field->isZeroSize(CGF.getContext()))
4390 return emitAddrOfZeroSizeField(CGF, base, field);
4392 const RecordDecl *rec = field->getParent();
4394 unsigned idx =
4395 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4397 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
4400 static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
4401 Address addr, const FieldDecl *field) {
4402 const RecordDecl *rec = field->getParent();
4403 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
4404 base.getType(), rec->getLocation());
4406 unsigned idx =
4407 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4409 return CGF.Builder.CreatePreserveStructAccessIndex(
4410 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
4413 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4414 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4415 if (!RD)
4416 return false;
4418 if (RD->isDynamicClass())
4419 return true;
4421 for (const auto &Base : RD->bases())
4422 if (hasAnyVptr(Base.getType(), Context))
4423 return true;
4425 for (const FieldDecl *Field : RD->fields())
4426 if (hasAnyVptr(Field->getType(), Context))
4427 return true;
4429 return false;
4432 LValue CodeGenFunction::EmitLValueForField(LValue base,
4433 const FieldDecl *field) {
4434 LValueBaseInfo BaseInfo = base.getBaseInfo();
4436 if (field->isBitField()) {
4437 const CGRecordLayout &RL =
4438 CGM.getTypes().getCGRecordLayout(field->getParent());
4439 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4440 const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4441 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4442 Info.VolatileStorageSize != 0 &&
4443 field->getType()
4444 .withCVRQualifiers(base.getVRQualifiers())
4445 .isVolatileQualified();
4446 Address Addr = base.getAddress(*this);
4447 unsigned Idx = RL.getLLVMFieldNo(field);
4448 const RecordDecl *rec = field->getParent();
4449 if (!UseVolatile) {
4450 if (!IsInPreservedAIRegion &&
4451 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4452 if (Idx != 0)
4453 // For structs, we GEP to the field that the record layout suggests.
4454 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4455 } else {
4456 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4457 getContext().getRecordType(rec), rec->getLocation());
4458 Addr = Builder.CreatePreserveStructAccessIndex(
4459 Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4460 DbgInfo);
4463 const unsigned SS =
4464 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
4465 // Get the access type.
4466 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4467 Addr = Addr.withElementType(FieldIntTy);
4468 if (UseVolatile) {
4469 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4470 if (VolatileOffset)
4471 Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4474 QualType fieldType =
4475 field->getType().withCVRQualifiers(base.getVRQualifiers());
4476 // TODO: Support TBAA for bit fields.
4477 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
4478 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
4479 TBAAAccessInfo());
4482 // Fields of may-alias structures are may-alias themselves.
4483 // FIXME: this should get propagated down through anonymous structs
4484 // and unions.
4485 QualType FieldType = field->getType();
4486 const RecordDecl *rec = field->getParent();
4487 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
4488 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
4489 TBAAAccessInfo FieldTBAAInfo;
4490 if (base.getTBAAInfo().isMayAlias() ||
4491 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
4492 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4493 } else if (rec->isUnion()) {
4494 // TODO: Support TBAA for unions.
4495 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4496 } else {
4497 // If no base type been assigned for the base access, then try to generate
4498 // one for this base lvalue.
4499 FieldTBAAInfo = base.getTBAAInfo();
4500 if (!FieldTBAAInfo.BaseType) {
4501 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4502 assert(!FieldTBAAInfo.Offset &&
4503 "Nonzero offset for an access with no base type!");
4506 // Adjust offset to be relative to the base type.
4507 const ASTRecordLayout &Layout =
4508 getContext().getASTRecordLayout(field->getParent());
4509 unsigned CharWidth = getContext().getCharWidth();
4510 if (FieldTBAAInfo.BaseType)
4511 FieldTBAAInfo.Offset +=
4512 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
4514 // Update the final access type and size.
4515 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
4516 FieldTBAAInfo.Size =
4517 getContext().getTypeSizeInChars(FieldType).getQuantity();
4520 Address addr = base.getAddress(*this);
4521 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4522 if (CGM.getCodeGenOpts().StrictVTablePointers &&
4523 ClassDef->isDynamicClass()) {
4524 // Getting to any field of dynamic object requires stripping dynamic
4525 // information provided by invariant.group. This is because accessing
4526 // fields may leak the real address of dynamic object, which could result
4527 // in miscompilation when leaked pointer would be compared.
4528 auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
4529 addr = Address(stripped, addr.getElementType(), addr.getAlignment());
4533 unsigned RecordCVR = base.getVRQualifiers();
4534 if (rec->isUnion()) {
4535 // For unions, there is no pointer adjustment.
4536 if (CGM.getCodeGenOpts().StrictVTablePointers &&
4537 hasAnyVptr(FieldType, getContext()))
4538 // Because unions can easily skip invariant.barriers, we need to add
4539 // a barrier every time CXXRecord field with vptr is referenced.
4540 addr = Builder.CreateLaunderInvariantGroup(addr);
4542 if (IsInPreservedAIRegion ||
4543 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4544 // Remember the original union field index
4545 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
4546 rec->getLocation());
4547 addr = Address(
4548 Builder.CreatePreserveUnionAccessIndex(
4549 addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
4550 addr.getElementType(), addr.getAlignment());
4553 if (FieldType->isReferenceType())
4554 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
4555 } else {
4556 if (!IsInPreservedAIRegion &&
4557 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
4558 // For structs, we GEP to the field that the record layout suggests.
4559 addr = emitAddrOfFieldStorage(*this, addr, field);
4560 else
4561 // Remember the original struct field index
4562 addr = emitPreserveStructAccess(*this, base, addr, field);
4565 // If this is a reference field, load the reference right now.
4566 if (FieldType->isReferenceType()) {
4567 LValue RefLVal =
4568 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4569 if (RecordCVR & Qualifiers::Volatile)
4570 RefLVal.getQuals().addVolatile();
4571 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
4573 // Qualifiers on the struct don't apply to the referencee.
4574 RecordCVR = 0;
4575 FieldType = FieldType->getPointeeType();
4578 // Make sure that the address is pointing to the right type. This is critical
4579 // for both unions and structs.
4580 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
4582 if (field->hasAttr<AnnotateAttr>())
4583 addr = EmitFieldAnnotations(field, addr);
4585 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4586 LV.getQuals().addCVRQualifiers(RecordCVR);
4588 // __weak attribute on a field is ignored.
4589 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
4590 LV.getQuals().removeObjCGCAttr();
4592 return LV;
4595 LValue
4596 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
4597 const FieldDecl *Field) {
4598 QualType FieldType = Field->getType();
4600 if (!FieldType->isReferenceType())
4601 return EmitLValueForField(Base, Field);
4603 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
4605 // Make sure that the address is pointing to the right type.
4606 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4607 V = V.withElementType(llvmType);
4609 // TODO: Generate TBAA information that describes this access as a structure
4610 // member access and not just an access to an object of the field's type. This
4611 // should be similar to what we do in EmitLValueForField().
4612 LValueBaseInfo BaseInfo = Base.getBaseInfo();
4613 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4614 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
4615 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
4616 CGM.getTBAAInfoForSubobject(Base, FieldType));
4619 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
4620 if (E->isFileScope()) {
4621 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
4622 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
4624 if (E->getType()->isVariablyModifiedType())
4625 // make sure to emit the VLA size.
4626 EmitVariablyModifiedType(E->getType());
4628 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
4629 const Expr *InitExpr = E->getInitializer();
4630 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
4632 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4633 /*Init*/ true);
4635 // Block-scope compound literals are destroyed at the end of the enclosing
4636 // scope in C.
4637 if (!getLangOpts().CPlusPlus)
4638 if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
4639 pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
4640 E->getType(), getDestroyer(DtorKind),
4641 DtorKind & EHCleanup);
4643 return Result;
4646 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4647 if (!E->isGLValue())
4648 // Initializing an aggregate temporary in C++11: T{...}.
4649 return EmitAggExprToLValue(E);
4651 // An lvalue initializer list must be initializing a reference.
4652 assert(E->isTransparent() && "non-transparent glvalue init list");
4653 return EmitLValue(E->getInit(0));
4656 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
4657 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4658 /// LValue is returned and the current block has been terminated.
4659 static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4660 const Expr *Operand) {
4661 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4662 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4663 return std::nullopt;
4666 return CGF.EmitLValue(Operand);
4669 namespace {
4670 // Handle the case where the condition is a constant evaluatable simple integer,
4671 // which means we don't have to separately handle the true/false blocks.
4672 std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
4673 CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
4674 const Expr *condExpr = E->getCond();
4675 bool CondExprBool;
4676 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4677 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
4678 if (!CondExprBool)
4679 std::swap(Live, Dead);
4681 if (!CGF.ContainsLabel(Dead)) {
4682 // If the true case is live, we need to track its region.
4683 if (CondExprBool)
4684 CGF.incrementProfileCounter(E);
4685 // If a throw expression we emit it and return an undefined lvalue
4686 // because it can't be used.
4687 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
4688 CGF.EmitCXXThrowExpr(ThrowExpr);
4689 llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
4690 llvm::Type *Ty = CGF.UnqualPtrTy;
4691 return CGF.MakeAddrLValue(
4692 Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
4693 Dead->getType());
4695 return CGF.EmitLValue(Live);
4698 return std::nullopt;
4700 struct ConditionalInfo {
4701 llvm::BasicBlock *lhsBlock, *rhsBlock;
4702 std::optional<LValue> LHS, RHS;
4705 // Create and generate the 3 blocks for a conditional operator.
4706 // Leaves the 'current block' in the continuation basic block.
4707 template<typename FuncTy>
4708 ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
4709 const AbstractConditionalOperator *E,
4710 const FuncTy &BranchGenFunc) {
4711 ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
4712 CGF.createBasicBlock("cond.false"), std::nullopt,
4713 std::nullopt};
4714 llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
4716 CodeGenFunction::ConditionalEvaluation eval(CGF);
4717 CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
4718 CGF.getProfileCount(E));
4720 // Any temporaries created here are conditional.
4721 CGF.EmitBlock(Info.lhsBlock);
4722 CGF.incrementProfileCounter(E);
4723 eval.begin(CGF);
4724 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
4725 eval.end(CGF);
4726 Info.lhsBlock = CGF.Builder.GetInsertBlock();
4728 if (Info.LHS)
4729 CGF.Builder.CreateBr(endBlock);
4731 // Any temporaries created here are conditional.
4732 CGF.EmitBlock(Info.rhsBlock);
4733 eval.begin(CGF);
4734 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
4735 eval.end(CGF);
4736 Info.rhsBlock = CGF.Builder.GetInsertBlock();
4737 CGF.EmitBlock(endBlock);
4739 return Info;
4741 } // namespace
4743 void CodeGenFunction::EmitIgnoredConditionalOperator(
4744 const AbstractConditionalOperator *E) {
4745 if (!E->isGLValue()) {
4746 // ?: here should be an aggregate.
4747 assert(hasAggregateEvaluationKind(E->getType()) &&
4748 "Unexpected conditional operator!");
4749 return (void)EmitAggExprToLValue(E);
4752 OpaqueValueMapping binding(*this, E);
4753 if (HandleConditionalOperatorLValueSimpleCase(*this, E))
4754 return;
4756 EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
4757 CGF.EmitIgnoredExpr(E);
4758 return LValue{};
4761 LValue CodeGenFunction::EmitConditionalOperatorLValue(
4762 const AbstractConditionalOperator *expr) {
4763 if (!expr->isGLValue()) {
4764 // ?: here should be an aggregate.
4765 assert(hasAggregateEvaluationKind(expr->getType()) &&
4766 "Unexpected conditional operator!");
4767 return EmitAggExprToLValue(expr);
4770 OpaqueValueMapping binding(*this, expr);
4771 if (std::optional<LValue> Res =
4772 HandleConditionalOperatorLValueSimpleCase(*this, expr))
4773 return *Res;
4775 ConditionalInfo Info = EmitConditionalBlocks(
4776 *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
4777 return EmitLValueOrThrowExpression(CGF, E);
4780 if ((Info.LHS && !Info.LHS->isSimple()) ||
4781 (Info.RHS && !Info.RHS->isSimple()))
4782 return EmitUnsupportedLValue(expr, "conditional operator");
4784 if (Info.LHS && Info.RHS) {
4785 Address lhsAddr = Info.LHS->getAddress(*this);
4786 Address rhsAddr = Info.RHS->getAddress(*this);
4787 llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
4788 phi->addIncoming(lhsAddr.getPointer(), Info.lhsBlock);
4789 phi->addIncoming(rhsAddr.getPointer(), Info.rhsBlock);
4790 Address result(phi, lhsAddr.getElementType(),
4791 std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
4792 AlignmentSource alignSource =
4793 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
4794 Info.RHS->getBaseInfo().getAlignmentSource());
4795 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4796 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
4797 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4798 TBAAInfo);
4799 } else {
4800 assert((Info.LHS || Info.RHS) &&
4801 "both operands of glvalue conditional are throw-expressions?");
4802 return Info.LHS ? *Info.LHS : *Info.RHS;
4806 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4807 /// type. If the cast is to a reference, we can have the usual lvalue result,
4808 /// otherwise if a cast is needed by the code generator in an lvalue context,
4809 /// then it must mean that we need the address of an aggregate in order to
4810 /// access one of its members. This can happen for all the reasons that casts
4811 /// are permitted with aggregate result, including noop aggregate casts, and
4812 /// cast from scalar to union.
4813 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
4814 switch (E->getCastKind()) {
4815 case CK_ToVoid:
4816 case CK_BitCast:
4817 case CK_LValueToRValueBitCast:
4818 case CK_ArrayToPointerDecay:
4819 case CK_FunctionToPointerDecay:
4820 case CK_NullToMemberPointer:
4821 case CK_NullToPointer:
4822 case CK_IntegralToPointer:
4823 case CK_PointerToIntegral:
4824 case CK_PointerToBoolean:
4825 case CK_VectorSplat:
4826 case CK_IntegralCast:
4827 case CK_BooleanToSignedIntegral:
4828 case CK_IntegralToBoolean:
4829 case CK_IntegralToFloating:
4830 case CK_FloatingToIntegral:
4831 case CK_FloatingToBoolean:
4832 case CK_FloatingCast:
4833 case CK_FloatingRealToComplex:
4834 case CK_FloatingComplexToReal:
4835 case CK_FloatingComplexToBoolean:
4836 case CK_FloatingComplexCast:
4837 case CK_FloatingComplexToIntegralComplex:
4838 case CK_IntegralRealToComplex:
4839 case CK_IntegralComplexToReal:
4840 case CK_IntegralComplexToBoolean:
4841 case CK_IntegralComplexCast:
4842 case CK_IntegralComplexToFloatingComplex:
4843 case CK_DerivedToBaseMemberPointer:
4844 case CK_BaseToDerivedMemberPointer:
4845 case CK_MemberPointerToBoolean:
4846 case CK_ReinterpretMemberPointer:
4847 case CK_AnyPointerToBlockPointerCast:
4848 case CK_ARCProduceObject:
4849 case CK_ARCConsumeObject:
4850 case CK_ARCReclaimReturnedObject:
4851 case CK_ARCExtendBlockObject:
4852 case CK_CopyAndAutoreleaseBlockObject:
4853 case CK_IntToOCLSampler:
4854 case CK_FloatingToFixedPoint:
4855 case CK_FixedPointToFloating:
4856 case CK_FixedPointCast:
4857 case CK_FixedPointToBoolean:
4858 case CK_FixedPointToIntegral:
4859 case CK_IntegralToFixedPoint:
4860 case CK_MatrixCast:
4861 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4863 case CK_Dependent:
4864 llvm_unreachable("dependent cast kind in IR gen!");
4866 case CK_BuiltinFnToFnPtr:
4867 llvm_unreachable("builtin functions are handled elsewhere");
4869 // These are never l-values; just use the aggregate emission code.
4870 case CK_NonAtomicToAtomic:
4871 case CK_AtomicToNonAtomic:
4872 return EmitAggExprToLValue(E);
4874 case CK_Dynamic: {
4875 LValue LV = EmitLValue(E->getSubExpr());
4876 Address V = LV.getAddress(*this);
4877 const auto *DCE = cast<CXXDynamicCastExpr>(E);
4878 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4881 case CK_ConstructorConversion:
4882 case CK_UserDefinedConversion:
4883 case CK_CPointerToObjCPointerCast:
4884 case CK_BlockPointerToObjCPointerCast:
4885 case CK_LValueToRValue:
4886 return EmitLValue(E->getSubExpr());
4888 case CK_NoOp: {
4889 // CK_NoOp can model a qualification conversion, which can remove an array
4890 // bound and change the IR type.
4891 // FIXME: Once pointee types are removed from IR, remove this.
4892 LValue LV = EmitLValue(E->getSubExpr());
4893 // Propagate the volatile qualifer to LValue, if exist in E.
4894 if (E->changesVolatileQualification())
4895 LV.getQuals() = E->getType().getQualifiers();
4896 if (LV.isSimple()) {
4897 Address V = LV.getAddress(*this);
4898 if (V.isValid()) {
4899 llvm::Type *T = ConvertTypeForMem(E->getType());
4900 if (V.getElementType() != T)
4901 LV.setAddress(V.withElementType(T));
4904 return LV;
4907 case CK_UncheckedDerivedToBase:
4908 case CK_DerivedToBase: {
4909 const auto *DerivedClassTy =
4910 E->getSubExpr()->getType()->castAs<RecordType>();
4911 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4913 LValue LV = EmitLValue(E->getSubExpr());
4914 Address This = LV.getAddress(*this);
4916 // Perform the derived-to-base conversion
4917 Address Base = GetAddressOfBaseClass(
4918 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4919 /*NullCheckValue=*/false, E->getExprLoc());
4921 // TODO: Support accesses to members of base classes in TBAA. For now, we
4922 // conservatively pretend that the complete object is of the base class
4923 // type.
4924 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4925 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4927 case CK_ToUnion:
4928 return EmitAggExprToLValue(E);
4929 case CK_BaseToDerived: {
4930 const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
4931 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4933 LValue LV = EmitLValue(E->getSubExpr());
4935 // Perform the base-to-derived conversion
4936 Address Derived = GetAddressOfDerivedClass(
4937 LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
4938 /*NullCheckValue=*/false);
4940 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4941 // performed and the object is not of the derived type.
4942 if (sanitizePerformTypeCheck())
4943 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4944 Derived.getPointer(), E->getType());
4946 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4947 EmitVTablePtrCheckForCast(E->getType(), Derived,
4948 /*MayBeNull=*/false, CFITCK_DerivedCast,
4949 E->getBeginLoc());
4951 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4952 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4954 case CK_LValueBitCast: {
4955 // This must be a reinterpret_cast (or c-style equivalent).
4956 const auto *CE = cast<ExplicitCastExpr>(E);
4958 CGM.EmitExplicitCastExprType(CE, this);
4959 LValue LV = EmitLValue(E->getSubExpr());
4960 Address V = LV.getAddress(*this).withElementType(
4961 ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
4963 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4964 EmitVTablePtrCheckForCast(E->getType(), V,
4965 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4966 E->getBeginLoc());
4968 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4969 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4971 case CK_AddressSpaceConversion: {
4972 LValue LV = EmitLValue(E->getSubExpr());
4973 QualType DestTy = getContext().getPointerType(E->getType());
4974 llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4975 *this, LV.getPointer(*this),
4976 E->getSubExpr()->getType().getAddressSpace(),
4977 E->getType().getAddressSpace(), ConvertType(DestTy));
4978 return MakeAddrLValue(Address(V, ConvertTypeForMem(E->getType()),
4979 LV.getAddress(*this).getAlignment()),
4980 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
4982 case CK_ObjCObjectLValueCast: {
4983 LValue LV = EmitLValue(E->getSubExpr());
4984 Address V = LV.getAddress(*this).withElementType(ConvertType(E->getType()));
4985 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4986 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4988 case CK_ZeroToOCLOpaqueType:
4989 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
4992 llvm_unreachable("Unhandled lvalue cast kind?");
4995 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4996 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4997 return getOrCreateOpaqueLValueMapping(e);
5000 LValue
5001 CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
5002 assert(OpaqueValueMapping::shouldBindAsLValue(e));
5004 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
5005 it = OpaqueLValues.find(e);
5007 if (it != OpaqueLValues.end())
5008 return it->second;
5010 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
5011 return EmitLValue(e->getSourceExpr());
5014 RValue
5015 CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
5016 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
5018 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
5019 it = OpaqueRValues.find(e);
5021 if (it != OpaqueRValues.end())
5022 return it->second;
5024 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
5025 return EmitAnyExpr(e->getSourceExpr());
5028 RValue CodeGenFunction::EmitRValueForField(LValue LV,
5029 const FieldDecl *FD,
5030 SourceLocation Loc) {
5031 QualType FT = FD->getType();
5032 LValue FieldLV = EmitLValueForField(LV, FD);
5033 switch (getEvaluationKind(FT)) {
5034 case TEK_Complex:
5035 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
5036 case TEK_Aggregate:
5037 return FieldLV.asAggregateRValue(*this);
5038 case TEK_Scalar:
5039 // This routine is used to load fields one-by-one to perform a copy, so
5040 // don't load reference fields.
5041 if (FD->getType()->isReferenceType())
5042 return RValue::get(FieldLV.getPointer(*this));
5043 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
5044 // primitive load.
5045 if (FieldLV.isBitField())
5046 return EmitLoadOfLValue(FieldLV, Loc);
5047 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
5049 llvm_unreachable("bad evaluation kind");
5052 //===--------------------------------------------------------------------===//
5053 // Expression Emission
5054 //===--------------------------------------------------------------------===//
5056 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
5057 ReturnValueSlot ReturnValue) {
5058 // Builtins never have block type.
5059 if (E->getCallee()->getType()->isBlockPointerType())
5060 return EmitBlockCallExpr(E, ReturnValue);
5062 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
5063 return EmitCXXMemberCallExpr(CE, ReturnValue);
5065 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
5066 return EmitCUDAKernelCallExpr(CE, ReturnValue);
5068 // A CXXOperatorCallExpr is created even for explicit object methods, but
5069 // these should be treated like static function call.
5070 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
5071 if (const auto *MD =
5072 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
5073 MD && MD->isImplicitObjectMemberFunction())
5074 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
5076 CGCallee callee = EmitCallee(E->getCallee());
5078 if (callee.isBuiltin()) {
5079 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
5080 E, ReturnValue);
5083 if (callee.isPseudoDestructor()) {
5084 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
5087 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
5090 /// Emit a CallExpr without considering whether it might be a subclass.
5091 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
5092 ReturnValueSlot ReturnValue) {
5093 CGCallee Callee = EmitCallee(E->getCallee());
5094 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
5097 // Detect the unusual situation where an inline version is shadowed by a
5098 // non-inline version. In that case we should pick the external one
5099 // everywhere. That's GCC behavior too.
5100 static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) {
5101 for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
5102 if (!PD->isInlineBuiltinDeclaration())
5103 return false;
5104 return true;
5107 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
5108 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
5110 if (auto builtinID = FD->getBuiltinID()) {
5111 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
5112 std::string NoBuiltins = "no-builtins";
5114 StringRef Ident = CGF.CGM.getMangledName(GD);
5115 std::string FDInlineName = (Ident + ".inline").str();
5117 bool IsPredefinedLibFunction =
5118 CGF.getContext().BuiltinInfo.isPredefinedLibFunction(builtinID);
5119 bool HasAttributeNoBuiltin =
5120 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
5121 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
5123 // When directing calling an inline builtin, call it through it's mangled
5124 // name to make it clear it's not the actual builtin.
5125 if (CGF.CurFn->getName() != FDInlineName &&
5126 OnlyHasInlineBuiltinDeclaration(FD)) {
5127 llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5128 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
5129 llvm::Module *M = Fn->getParent();
5130 llvm::Function *Clone = M->getFunction(FDInlineName);
5131 if (!Clone) {
5132 Clone = llvm::Function::Create(Fn->getFunctionType(),
5133 llvm::GlobalValue::InternalLinkage,
5134 Fn->getAddressSpace(), FDInlineName, M);
5135 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
5137 return CGCallee::forDirect(Clone, GD);
5140 // Replaceable builtins provide their own implementation of a builtin. If we
5141 // are in an inline builtin implementation, avoid trivial infinite
5142 // recursion. Honor __attribute__((no_builtin("foo"))) or
5143 // __attribute__((no_builtin)) on the current function unless foo is
5144 // not a predefined library function which means we must generate the
5145 // builtin no matter what.
5146 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
5147 return CGCallee::forBuiltin(builtinID, FD);
5150 llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5151 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
5152 FD->hasAttr<CUDAGlobalAttr>())
5153 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
5154 cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
5156 return CGCallee::forDirect(CalleePtr, GD);
5159 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
5160 E = E->IgnoreParens();
5162 // Look through function-to-pointer decay.
5163 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
5164 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
5165 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
5166 return EmitCallee(ICE->getSubExpr());
5169 // Resolve direct calls.
5170 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
5171 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
5172 return EmitDirectCallee(*this, FD);
5174 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
5175 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
5176 EmitIgnoredExpr(ME->getBase());
5177 return EmitDirectCallee(*this, FD);
5180 // Look through template substitutions.
5181 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
5182 return EmitCallee(NTTP->getReplacement());
5184 // Treat pseudo-destructor calls differently.
5185 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
5186 return CGCallee::forPseudoDestructor(PDE);
5189 // Otherwise, we have an indirect reference.
5190 llvm::Value *calleePtr;
5191 QualType functionType;
5192 if (auto ptrType = E->getType()->getAs<PointerType>()) {
5193 calleePtr = EmitScalarExpr(E);
5194 functionType = ptrType->getPointeeType();
5195 } else {
5196 functionType = E->getType();
5197 calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
5199 assert(functionType->isFunctionType());
5201 GlobalDecl GD;
5202 if (const auto *VD =
5203 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
5204 GD = GlobalDecl(VD);
5206 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
5207 CGCallee callee(calleeInfo, calleePtr);
5208 return callee;
5211 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
5212 // Comma expressions just emit their LHS then their RHS as an l-value.
5213 if (E->getOpcode() == BO_Comma) {
5214 EmitIgnoredExpr(E->getLHS());
5215 EnsureInsertPoint();
5216 return EmitLValue(E->getRHS());
5219 if (E->getOpcode() == BO_PtrMemD ||
5220 E->getOpcode() == BO_PtrMemI)
5221 return EmitPointerToDataMemberBinaryExpr(E);
5223 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
5225 // Note that in all of these cases, __block variables need the RHS
5226 // evaluated first just in case the variable gets moved by the RHS.
5228 switch (getEvaluationKind(E->getType())) {
5229 case TEK_Scalar: {
5230 switch (E->getLHS()->getType().getObjCLifetime()) {
5231 case Qualifiers::OCL_Strong:
5232 return EmitARCStoreStrong(E, /*ignored*/ false).first;
5234 case Qualifiers::OCL_Autoreleasing:
5235 return EmitARCStoreAutoreleasing(E).first;
5237 // No reason to do any of these differently.
5238 case Qualifiers::OCL_None:
5239 case Qualifiers::OCL_ExplicitNone:
5240 case Qualifiers::OCL_Weak:
5241 break;
5244 RValue RV = EmitAnyExpr(E->getRHS());
5245 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
5246 if (RV.isScalar())
5247 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
5248 EmitStoreThroughLValue(RV, LV);
5249 if (getLangOpts().OpenMP)
5250 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
5251 E->getLHS());
5252 return LV;
5255 case TEK_Complex:
5256 return EmitComplexAssignmentLValue(E);
5258 case TEK_Aggregate:
5259 return EmitAggExprToLValue(E);
5261 llvm_unreachable("bad evaluation kind");
5264 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
5265 RValue RV = EmitCallExpr(E);
5267 if (!RV.isScalar())
5268 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5269 AlignmentSource::Decl);
5271 assert(E->getCallReturnType(getContext())->isReferenceType() &&
5272 "Can't have a scalar return unless the return type is a "
5273 "reference type!");
5275 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5278 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
5279 // FIXME: This shouldn't require another copy.
5280 return EmitAggExprToLValue(E);
5283 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
5284 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
5285 && "binding l-value to type which needs a temporary");
5286 AggValueSlot Slot = CreateAggTemp(E->getType());
5287 EmitCXXConstructExpr(E, Slot);
5288 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5291 LValue
5292 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
5293 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
5296 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
5297 return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
5298 .withElementType(ConvertType(E->getType()));
5301 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
5302 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
5303 AlignmentSource::Decl);
5306 LValue
5307 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
5308 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
5309 Slot.setExternallyDestructed();
5310 EmitAggExpr(E->getSubExpr(), Slot);
5311 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
5312 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5315 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
5316 RValue RV = EmitObjCMessageExpr(E);
5318 if (!RV.isScalar())
5319 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5320 AlignmentSource::Decl);
5322 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
5323 "Can't have a scalar return unless the return type is a "
5324 "reference type!");
5326 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5329 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
5330 Address V =
5331 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
5332 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
5335 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
5336 const ObjCIvarDecl *Ivar) {
5337 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
5340 llvm::Value *
5341 CodeGenFunction::EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
5342 const ObjCIvarDecl *Ivar) {
5343 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
5344 QualType PointerDiffType = getContext().getPointerDiffType();
5345 return Builder.CreateZExtOrTrunc(OffsetValue,
5346 getTypes().ConvertType(PointerDiffType));
5349 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
5350 llvm::Value *BaseValue,
5351 const ObjCIvarDecl *Ivar,
5352 unsigned CVRQualifiers) {
5353 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
5354 Ivar, CVRQualifiers);
5357 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
5358 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
5359 llvm::Value *BaseValue = nullptr;
5360 const Expr *BaseExpr = E->getBase();
5361 Qualifiers BaseQuals;
5362 QualType ObjectTy;
5363 if (E->isArrow()) {
5364 BaseValue = EmitScalarExpr(BaseExpr);
5365 ObjectTy = BaseExpr->getType()->getPointeeType();
5366 BaseQuals = ObjectTy.getQualifiers();
5367 } else {
5368 LValue BaseLV = EmitLValue(BaseExpr);
5369 BaseValue = BaseLV.getPointer(*this);
5370 ObjectTy = BaseExpr->getType();
5371 BaseQuals = ObjectTy.getQualifiers();
5374 LValue LV =
5375 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
5376 BaseQuals.getCVRQualifiers());
5377 setObjCGCLValueClass(getContext(), E, LV);
5378 return LV;
5381 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
5382 // Can only get l-value for message expression returning aggregate type
5383 RValue RV = EmitAnyExprToTemp(E);
5384 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5385 AlignmentSource::Decl);
5388 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
5389 const CallExpr *E, ReturnValueSlot ReturnValue,
5390 llvm::Value *Chain) {
5391 // Get the actual function type. The callee type will always be a pointer to
5392 // function type or a block pointer type.
5393 assert(CalleeType->isFunctionPointerType() &&
5394 "Call must have function pointer type!");
5396 const Decl *TargetDecl =
5397 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
5399 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
5400 !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
5401 "trying to emit a call to an immediate function");
5403 CalleeType = getContext().getCanonicalType(CalleeType);
5405 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
5407 CGCallee Callee = OrigCallee;
5409 if (SanOpts.has(SanitizerKind::Function) &&
5410 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
5411 !isa<FunctionNoProtoType>(PointeeType)) {
5412 if (llvm::Constant *PrefixSig =
5413 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
5414 SanitizerScope SanScope(this);
5415 auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
5417 llvm::Type *PrefixSigType = PrefixSig->getType();
5418 llvm::StructType *PrefixStructTy = llvm::StructType::get(
5419 CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
5421 llvm::Value *CalleePtr = Callee.getFunctionPointer();
5423 // On 32-bit Arm, the low bit of a function pointer indicates whether
5424 // it's using the Arm or Thumb instruction set. The actual first
5425 // instruction lives at the same address either way, so we must clear
5426 // that low bit before using the function address to find the prefix
5427 // structure.
5429 // This applies to both Arm and Thumb target triples, because
5430 // either one could be used in an interworking context where it
5431 // might be passed function pointers of both types.
5432 llvm::Value *AlignedCalleePtr;
5433 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
5434 llvm::Value *CalleeAddress =
5435 Builder.CreatePtrToInt(CalleePtr, IntPtrTy);
5436 llvm::Value *Mask = llvm::ConstantInt::get(IntPtrTy, ~1);
5437 llvm::Value *AlignedCalleeAddress =
5438 Builder.CreateAnd(CalleeAddress, Mask);
5439 AlignedCalleePtr =
5440 Builder.CreateIntToPtr(AlignedCalleeAddress, CalleePtr->getType());
5441 } else {
5442 AlignedCalleePtr = CalleePtr;
5445 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
5446 llvm::Value *CalleeSigPtr =
5447 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
5448 llvm::Value *CalleeSig =
5449 Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
5450 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
5452 llvm::BasicBlock *Cont = createBasicBlock("cont");
5453 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
5454 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
5456 EmitBlock(TypeCheck);
5457 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
5458 Int32Ty,
5459 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
5460 getPointerAlign());
5461 llvm::Value *CalleeTypeHashMatch =
5462 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
5463 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
5464 EmitCheckTypeDescriptor(CalleeType)};
5465 EmitCheck(std::make_pair(CalleeTypeHashMatch, SanitizerKind::Function),
5466 SanitizerHandler::FunctionTypeMismatch, StaticData,
5467 {CalleePtr});
5469 Builder.CreateBr(Cont);
5470 EmitBlock(Cont);
5474 const auto *FnType = cast<FunctionType>(PointeeType);
5476 // If we are checking indirect calls and this call is indirect, check that the
5477 // function pointer is a member of the bit set for the function type.
5478 if (SanOpts.has(SanitizerKind::CFIICall) &&
5479 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5480 SanitizerScope SanScope(this);
5481 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
5483 llvm::Metadata *MD;
5484 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
5485 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
5486 else
5487 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
5489 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
5491 llvm::Value *CalleePtr = Callee.getFunctionPointer();
5492 llvm::Value *TypeTest = Builder.CreateCall(
5493 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
5495 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
5496 llvm::Constant *StaticData[] = {
5497 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
5498 EmitCheckSourceLocation(E->getBeginLoc()),
5499 EmitCheckTypeDescriptor(QualType(FnType, 0)),
5501 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
5502 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
5503 CalleePtr, StaticData);
5504 } else {
5505 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
5506 SanitizerHandler::CFICheckFail, StaticData,
5507 {CalleePtr, llvm::UndefValue::get(IntPtrTy)});
5511 CallArgList Args;
5512 if (Chain)
5513 Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy);
5515 // C++17 requires that we evaluate arguments to a call using assignment syntax
5516 // right-to-left, and that we evaluate arguments to certain other operators
5517 // left-to-right. Note that we allow this to override the order dictated by
5518 // the calling convention on the MS ABI, which means that parameter
5519 // destruction order is not necessarily reverse construction order.
5520 // FIXME: Revisit this based on C++ committee response to unimplementability.
5521 EvaluationOrder Order = EvaluationOrder::Default;
5522 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
5523 if (OCE->isAssignmentOp())
5524 Order = EvaluationOrder::ForceRightToLeft;
5525 else {
5526 switch (OCE->getOperator()) {
5527 case OO_LessLess:
5528 case OO_GreaterGreater:
5529 case OO_AmpAmp:
5530 case OO_PipePipe:
5531 case OO_Comma:
5532 case OO_ArrowStar:
5533 Order = EvaluationOrder::ForceLeftToRight;
5534 break;
5535 default:
5536 break;
5541 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
5542 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
5544 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
5545 Args, FnType, /*ChainCall=*/Chain);
5547 // C99 6.5.2.2p6:
5548 // If the expression that denotes the called function has a type
5549 // that does not include a prototype, [the default argument
5550 // promotions are performed]. If the number of arguments does not
5551 // equal the number of parameters, the behavior is undefined. If
5552 // the function is defined with a type that includes a prototype,
5553 // and either the prototype ends with an ellipsis (, ...) or the
5554 // types of the arguments after promotion are not compatible with
5555 // the types of the parameters, the behavior is undefined. If the
5556 // function is defined with a type that does not include a
5557 // prototype, and the types of the arguments after promotion are
5558 // not compatible with those of the parameters after promotion,
5559 // the behavior is undefined [except in some trivial cases].
5560 // That is, in the general case, we should assume that a call
5561 // through an unprototyped function type works like a *non-variadic*
5562 // call. The way we make this work is to cast to the exact type
5563 // of the promoted arguments.
5565 // Chain calls use this same code path to add the invisible chain parameter
5566 // to the function type.
5567 if (isa<FunctionNoProtoType>(FnType) || Chain) {
5568 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
5569 int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
5570 CalleeTy = CalleeTy->getPointerTo(AS);
5572 llvm::Value *CalleePtr = Callee.getFunctionPointer();
5573 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
5574 Callee.setFunctionPointer(CalleePtr);
5577 // HIP function pointer contains kernel handle when it is used in triple
5578 // chevron. The kernel stub needs to be loaded from kernel handle and used
5579 // as callee.
5580 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5581 isa<CUDAKernelCallExpr>(E) &&
5582 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5583 llvm::Value *Handle = Callee.getFunctionPointer();
5584 auto *Stub = Builder.CreateLoad(
5585 Address(Handle, Handle->getType(), CGM.getPointerAlign()));
5586 Callee.setFunctionPointer(Stub);
5588 llvm::CallBase *CallOrInvoke = nullptr;
5589 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5590 E == MustTailCall, E->getExprLoc());
5592 // Generate function declaration DISuprogram in order to be used
5593 // in debug info about call sites.
5594 if (CGDebugInfo *DI = getDebugInfo()) {
5595 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5596 FunctionArgList Args;
5597 QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
5598 DI->EmitFuncDeclForCallSite(CallOrInvoke,
5599 DI->getFunctionType(CalleeDecl, ResTy, Args),
5600 CalleeDecl);
5604 return Call;
5607 LValue CodeGenFunction::
5608 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
5609 Address BaseAddr = Address::invalid();
5610 if (E->getOpcode() == BO_PtrMemI) {
5611 BaseAddr = EmitPointerWithAlignment(E->getLHS());
5612 } else {
5613 BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
5616 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5617 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
5619 LValueBaseInfo BaseInfo;
5620 TBAAAccessInfo TBAAInfo;
5621 Address MemberAddr =
5622 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
5623 &TBAAInfo);
5625 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
5628 /// Given the address of a temporary variable, produce an r-value of
5629 /// its type.
5630 RValue CodeGenFunction::convertTempToRValue(Address addr,
5631 QualType type,
5632 SourceLocation loc) {
5633 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
5634 switch (getEvaluationKind(type)) {
5635 case TEK_Complex:
5636 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
5637 case TEK_Aggregate:
5638 return lvalue.asAggregateRValue(*this);
5639 case TEK_Scalar:
5640 return RValue::get(EmitLoadOfScalar(lvalue, loc));
5642 llvm_unreachable("bad evaluation kind");
5645 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
5646 assert(Val->getType()->isFPOrFPVectorTy());
5647 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
5648 return;
5650 llvm::MDBuilder MDHelper(getLLVMContext());
5651 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
5653 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
5656 void CodeGenFunction::SetSqrtFPAccuracy(llvm::Value *Val) {
5657 llvm::Type *EltTy = Val->getType()->getScalarType();
5658 if (!EltTy->isFloatTy())
5659 return;
5661 if ((getLangOpts().OpenCL &&
5662 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
5663 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
5664 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
5665 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 3ulp
5667 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
5668 // build option allows an application to specify that single precision
5669 // floating-point divide (x/y and 1/x) and sqrt used in the program
5670 // source are correctly rounded.
5672 // TODO: CUDA has a prec-sqrt flag
5673 SetFPAccuracy(Val, 3.0f);
5677 void CodeGenFunction::SetDivFPAccuracy(llvm::Value *Val) {
5678 llvm::Type *EltTy = Val->getType()->getScalarType();
5679 if (!EltTy->isFloatTy())
5680 return;
5682 if ((getLangOpts().OpenCL &&
5683 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
5684 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
5685 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
5686 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
5688 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
5689 // build option allows an application to specify that single precision
5690 // floating-point divide (x/y and 1/x) and sqrt used in the program
5691 // source are correctly rounded.
5693 // TODO: CUDA has a prec-div flag
5694 SetFPAccuracy(Val, 2.5f);
5698 namespace {
5699 struct LValueOrRValue {
5700 LValue LV;
5701 RValue RV;
5705 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
5706 const PseudoObjectExpr *E,
5707 bool forLValue,
5708 AggValueSlot slot) {
5709 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
5711 // Find the result expression, if any.
5712 const Expr *resultExpr = E->getResultExpr();
5713 LValueOrRValue result;
5715 for (PseudoObjectExpr::const_semantics_iterator
5716 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
5717 const Expr *semantic = *i;
5719 // If this semantic expression is an opaque value, bind it
5720 // to the result of its source expression.
5721 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
5722 // Skip unique OVEs.
5723 if (ov->isUnique()) {
5724 assert(ov != resultExpr &&
5725 "A unique OVE cannot be used as the result expression");
5726 continue;
5729 // If this is the result expression, we may need to evaluate
5730 // directly into the slot.
5731 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
5732 OVMA opaqueData;
5733 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
5734 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
5735 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
5736 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
5737 AlignmentSource::Decl);
5738 opaqueData = OVMA::bind(CGF, ov, LV);
5739 result.RV = slot.asRValue();
5741 // Otherwise, emit as normal.
5742 } else {
5743 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
5745 // If this is the result, also evaluate the result now.
5746 if (ov == resultExpr) {
5747 if (forLValue)
5748 result.LV = CGF.EmitLValue(ov);
5749 else
5750 result.RV = CGF.EmitAnyExpr(ov, slot);
5754 opaques.push_back(opaqueData);
5756 // Otherwise, if the expression is the result, evaluate it
5757 // and remember the result.
5758 } else if (semantic == resultExpr) {
5759 if (forLValue)
5760 result.LV = CGF.EmitLValue(semantic);
5761 else
5762 result.RV = CGF.EmitAnyExpr(semantic, slot);
5764 // Otherwise, evaluate the expression in an ignored context.
5765 } else {
5766 CGF.EmitIgnoredExpr(semantic);
5770 // Unbind all the opaques now.
5771 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
5772 opaques[i].unbind(CGF);
5774 return result;
5777 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
5778 AggValueSlot slot) {
5779 return emitPseudoObjectExpr(*this, E, false, slot).RV;
5782 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
5783 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;