[AMDGPU][AsmParser][NFC] Get rid of custom default operand handlers.
[llvm-project.git] / clang / lib / CodeGen / CGExpr.cpp
blob2afdc6abb104aeed150d837bffde79eb684000ea
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/StringExtras.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/IntrinsicsWebAssembly.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/MDBuilder.h"
39 #include "llvm/IR/MatrixBuilder.h"
40 #include "llvm/Passes/OptimizationLevel.h"
41 #include "llvm/Support/ConvertUTF.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/SaveAndRestore.h"
45 #include "llvm/Support/xxhash.h"
46 #include "llvm/Transforms/Utils/SanitizerStats.h"
48 #include <optional>
49 #include <string>
51 using namespace clang;
52 using namespace CodeGen;
54 //===--------------------------------------------------------------------===//
55 // Miscellaneous Helper Methods
56 //===--------------------------------------------------------------------===//
58 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
59 unsigned addressSpace =
60 cast<llvm::PointerType>(value->getType())->getAddressSpace();
62 llvm::PointerType *destType = Int8PtrTy;
63 if (addressSpace)
64 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
66 if (value->getType() == destType) return value;
67 return Builder.CreateBitCast(value, destType);
70 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
71 /// block.
72 Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
73 CharUnits Align,
74 const Twine &Name,
75 llvm::Value *ArraySize) {
76 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
77 Alloca->setAlignment(Align.getAsAlign());
78 return Address(Alloca, Ty, Align, KnownNonNull);
81 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
82 /// block. The alloca is casted to default address space if necessary.
83 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
84 const Twine &Name,
85 llvm::Value *ArraySize,
86 Address *AllocaAddr) {
87 auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
88 if (AllocaAddr)
89 *AllocaAddr = Alloca;
90 llvm::Value *V = Alloca.getPointer();
91 // Alloca always returns a pointer in alloca address space, which may
92 // be different from the type defined by the language. For example,
93 // in C++ the auto variables are in the default address space. Therefore
94 // cast alloca to the default address space when necessary.
95 if (getASTAllocaAddressSpace() != LangAS::Default) {
96 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
97 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
98 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
99 // otherwise alloca is inserted at the current insertion point of the
100 // builder.
101 if (!ArraySize)
102 Builder.SetInsertPoint(getPostAllocaInsertPoint());
103 V = getTargetHooks().performAddrSpaceCast(
104 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
105 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
108 return Address(V, Ty, Align, KnownNonNull);
111 /// CreateTempAlloca - This creates an alloca and inserts it into the entry
112 /// block if \p ArraySize is nullptr, otherwise inserts it at the current
113 /// insertion point of the builder.
114 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
115 const Twine &Name,
116 llvm::Value *ArraySize) {
117 if (ArraySize)
118 return Builder.CreateAlloca(Ty, ArraySize, Name);
119 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
120 ArraySize, Name, AllocaInsertPt);
123 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
124 /// default alignment of the corresponding LLVM type, which is *not*
125 /// guaranteed to be related in any way to the expected alignment of
126 /// an AST type that might have been lowered to Ty.
127 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
128 const Twine &Name) {
129 CharUnits Align =
130 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
131 return CreateTempAlloca(Ty, Align, Name);
134 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
135 CharUnits Align = getContext().getTypeAlignInChars(Ty);
136 return CreateTempAlloca(ConvertType(Ty), Align, Name);
139 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
140 Address *Alloca) {
141 // FIXME: Should we prefer the preferred type alignment here?
142 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
145 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
146 const Twine &Name, Address *Alloca) {
147 Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
148 /*ArraySize=*/nullptr, Alloca);
150 if (Ty->isConstantMatrixType()) {
151 auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
152 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
153 ArrayTy->getNumElements());
155 Result = Address(
156 Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
157 VectorTy, Result.getAlignment(), KnownNonNull);
159 return Result;
162 Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
163 const Twine &Name) {
164 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
167 Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
168 const Twine &Name) {
169 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
170 Name);
173 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
174 /// expression and compare the result against zero, returning an Int1Ty value.
175 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
176 PGO.setCurrentStmt(E);
177 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
178 llvm::Value *MemPtr = EmitScalarExpr(E);
179 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
182 QualType BoolTy = getContext().BoolTy;
183 SourceLocation Loc = E->getExprLoc();
184 CGFPOptionsRAII FPOptsRAII(*this, E);
185 if (!E->getType()->isAnyComplexType())
186 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
188 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
189 Loc);
192 /// EmitIgnoredExpr - Emit code to compute the specified expression,
193 /// ignoring the result.
194 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
195 if (E->isPRValue())
196 return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
198 // if this is a bitfield-resulting conditional operator, we can special case
199 // emit this. The normal 'EmitLValue' version of this is particularly
200 // difficult to codegen for, since creating a single "LValue" for two
201 // different sized arguments here is not particularly doable.
202 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
203 E->IgnoreParenNoopCasts(getContext()))) {
204 if (CondOp->getObjectKind() == OK_BitField)
205 return EmitIgnoredConditionalOperator(CondOp);
208 // Just emit it as an l-value and drop the result.
209 EmitLValue(E);
212 /// EmitAnyExpr - Emit code to compute the specified expression which
213 /// can have any type. The result is returned as an RValue struct.
214 /// If this is an aggregate expression, AggSlot indicates where the
215 /// result should be returned.
216 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
217 AggValueSlot aggSlot,
218 bool ignoreResult) {
219 switch (getEvaluationKind(E->getType())) {
220 case TEK_Scalar:
221 return RValue::get(EmitScalarExpr(E, ignoreResult));
222 case TEK_Complex:
223 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
224 case TEK_Aggregate:
225 if (!ignoreResult && aggSlot.isIgnored())
226 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
227 EmitAggExpr(E, aggSlot);
228 return aggSlot.asRValue();
230 llvm_unreachable("bad evaluation kind");
233 /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
234 /// always be accessible even if no aggregate location is provided.
235 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
236 AggValueSlot AggSlot = AggValueSlot::ignored();
238 if (hasAggregateEvaluationKind(E->getType()))
239 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
240 return EmitAnyExpr(E, AggSlot);
243 /// EmitAnyExprToMem - Evaluate an expression into a given memory
244 /// location.
245 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
246 Address Location,
247 Qualifiers Quals,
248 bool IsInit) {
249 // FIXME: This function should take an LValue as an argument.
250 switch (getEvaluationKind(E->getType())) {
251 case TEK_Complex:
252 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
253 /*isInit*/ false);
254 return;
256 case TEK_Aggregate: {
257 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
258 AggValueSlot::IsDestructed_t(IsInit),
259 AggValueSlot::DoesNotNeedGCBarriers,
260 AggValueSlot::IsAliased_t(!IsInit),
261 AggValueSlot::MayOverlap));
262 return;
265 case TEK_Scalar: {
266 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
267 LValue LV = MakeAddrLValue(Location, E->getType());
268 EmitStoreThroughLValue(RV, LV);
269 return;
272 llvm_unreachable("bad evaluation kind");
275 static void
276 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
277 const Expr *E, Address ReferenceTemporary) {
278 // Objective-C++ ARC:
279 // If we are binding a reference to a temporary that has ownership, we
280 // need to perform retain/release operations on the temporary.
282 // FIXME: This should be looking at E, not M.
283 if (auto Lifetime = M->getType().getObjCLifetime()) {
284 switch (Lifetime) {
285 case Qualifiers::OCL_None:
286 case Qualifiers::OCL_ExplicitNone:
287 // Carry on to normal cleanup handling.
288 break;
290 case Qualifiers::OCL_Autoreleasing:
291 // Nothing to do; cleaned up by an autorelease pool.
292 return;
294 case Qualifiers::OCL_Strong:
295 case Qualifiers::OCL_Weak:
296 switch (StorageDuration Duration = M->getStorageDuration()) {
297 case SD_Static:
298 // Note: we intentionally do not register a cleanup to release
299 // the object on program termination.
300 return;
302 case SD_Thread:
303 // FIXME: We should probably register a cleanup in this case.
304 return;
306 case SD_Automatic:
307 case SD_FullExpression:
308 CodeGenFunction::Destroyer *Destroy;
309 CleanupKind CleanupKind;
310 if (Lifetime == Qualifiers::OCL_Strong) {
311 const ValueDecl *VD = M->getExtendingDecl();
312 bool Precise =
313 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
314 CleanupKind = CGF.getARCCleanupKind();
315 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
316 : &CodeGenFunction::destroyARCStrongImprecise;
317 } else {
318 // __weak objects always get EH cleanups; otherwise, exceptions
319 // could cause really nasty crashes instead of mere leaks.
320 CleanupKind = NormalAndEHCleanup;
321 Destroy = &CodeGenFunction::destroyARCWeak;
323 if (Duration == SD_FullExpression)
324 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
325 M->getType(), *Destroy,
326 CleanupKind & EHCleanup);
327 else
328 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
329 M->getType(),
330 *Destroy, CleanupKind & EHCleanup);
331 return;
333 case SD_Dynamic:
334 llvm_unreachable("temporary cannot have dynamic storage duration");
336 llvm_unreachable("unknown storage duration");
340 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
341 if (const RecordType *RT =
342 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
343 // Get the destructor for the reference temporary.
344 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
345 if (!ClassDecl->hasTrivialDestructor())
346 ReferenceTemporaryDtor = ClassDecl->getDestructor();
349 if (!ReferenceTemporaryDtor)
350 return;
352 // Call the destructor for the temporary.
353 switch (M->getStorageDuration()) {
354 case SD_Static:
355 case SD_Thread: {
356 llvm::FunctionCallee CleanupFn;
357 llvm::Constant *CleanupArg;
358 if (E->getType()->isArrayType()) {
359 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
360 ReferenceTemporary, E->getType(),
361 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
362 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
363 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
364 } else {
365 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
366 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
367 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
369 CGF.CGM.getCXXABI().registerGlobalDtor(
370 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
371 break;
374 case SD_FullExpression:
375 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
376 CodeGenFunction::destroyCXXObject,
377 CGF.getLangOpts().Exceptions);
378 break;
380 case SD_Automatic:
381 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
382 ReferenceTemporary, E->getType(),
383 CodeGenFunction::destroyCXXObject,
384 CGF.getLangOpts().Exceptions);
385 break;
387 case SD_Dynamic:
388 llvm_unreachable("temporary cannot have dynamic storage duration");
392 static Address createReferenceTemporary(CodeGenFunction &CGF,
393 const MaterializeTemporaryExpr *M,
394 const Expr *Inner,
395 Address *Alloca = nullptr) {
396 auto &TCG = CGF.getTargetHooks();
397 switch (M->getStorageDuration()) {
398 case SD_FullExpression:
399 case SD_Automatic: {
400 // If we have a constant temporary array or record try to promote it into a
401 // constant global under the same rules a normal constant would've been
402 // promoted. This is easier on the optimizer and generally emits fewer
403 // instructions.
404 QualType Ty = Inner->getType();
405 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
406 (Ty->isArrayType() || Ty->isRecordType()) &&
407 CGF.CGM.isTypeConstant(Ty, true, false))
408 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
409 auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
410 auto *GV = new llvm::GlobalVariable(
411 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
412 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
413 llvm::GlobalValue::NotThreadLocal,
414 CGF.getContext().getTargetAddressSpace(AS));
415 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
416 GV->setAlignment(alignment.getAsAlign());
417 llvm::Constant *C = GV;
418 if (AS != LangAS::Default)
419 C = TCG.performAddrSpaceCast(
420 CGF.CGM, GV, AS, LangAS::Default,
421 GV->getValueType()->getPointerTo(
422 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
423 // FIXME: Should we put the new global into a COMDAT?
424 return Address(C, GV->getValueType(), alignment);
426 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
428 case SD_Thread:
429 case SD_Static:
430 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
432 case SD_Dynamic:
433 llvm_unreachable("temporary can't have dynamic storage duration");
435 llvm_unreachable("unknown storage duration");
438 /// Helper method to check if the underlying ABI is AAPCS
439 static bool isAAPCS(const TargetInfo &TargetInfo) {
440 return TargetInfo.getABI().startswith("aapcs");
443 LValue CodeGenFunction::
444 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
445 const Expr *E = M->getSubExpr();
447 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
448 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
449 "Reference should never be pseudo-strong!");
451 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
452 // as that will cause the lifetime adjustment to be lost for ARC
453 auto ownership = M->getType().getObjCLifetime();
454 if (ownership != Qualifiers::OCL_None &&
455 ownership != Qualifiers::OCL_ExplicitNone) {
456 Address Object = createReferenceTemporary(*this, M, E);
457 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
458 llvm::Type *Ty = ConvertTypeForMem(E->getType());
459 Object = Address(llvm::ConstantExpr::getBitCast(
460 Var, Ty->getPointerTo(Object.getAddressSpace())),
461 Ty, Object.getAlignment());
463 // createReferenceTemporary will promote the temporary to a global with a
464 // constant initializer if it can. It can only do this to a value of
465 // ARC-manageable type if the value is global and therefore "immune" to
466 // ref-counting operations. Therefore we have no need to emit either a
467 // dynamic initialization or a cleanup and we can just return the address
468 // of the temporary.
469 if (Var->hasInitializer())
470 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
472 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
474 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
475 AlignmentSource::Decl);
477 switch (getEvaluationKind(E->getType())) {
478 default: llvm_unreachable("expected scalar or aggregate expression");
479 case TEK_Scalar:
480 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
481 break;
482 case TEK_Aggregate: {
483 EmitAggExpr(E, AggValueSlot::forAddr(Object,
484 E->getType().getQualifiers(),
485 AggValueSlot::IsDestructed,
486 AggValueSlot::DoesNotNeedGCBarriers,
487 AggValueSlot::IsNotAliased,
488 AggValueSlot::DoesNotOverlap));
489 break;
493 pushTemporaryCleanup(*this, M, E, Object);
494 return RefTempDst;
497 SmallVector<const Expr *, 2> CommaLHSs;
498 SmallVector<SubobjectAdjustment, 2> Adjustments;
499 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
501 for (const auto &Ignored : CommaLHSs)
502 EmitIgnoredExpr(Ignored);
504 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
505 if (opaque->getType()->isRecordType()) {
506 assert(Adjustments.empty());
507 return EmitOpaqueValueLValue(opaque);
511 // Create and initialize the reference temporary.
512 Address Alloca = Address::invalid();
513 Address Object = createReferenceTemporary(*this, M, E, &Alloca);
514 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
515 Object.getPointer()->stripPointerCasts())) {
516 llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
517 Object = Address(llvm::ConstantExpr::getBitCast(
518 cast<llvm::Constant>(Object.getPointer()),
519 TemporaryType->getPointerTo()),
520 TemporaryType,
521 Object.getAlignment());
522 // If the temporary is a global and has a constant initializer or is a
523 // constant temporary that we promoted to a global, we may have already
524 // initialized it.
525 if (!Var->hasInitializer()) {
526 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
527 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
529 } else {
530 switch (M->getStorageDuration()) {
531 case SD_Automatic:
532 if (auto *Size = EmitLifetimeStart(
533 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
534 Alloca.getPointer())) {
535 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
536 Alloca, Size);
538 break;
540 case SD_FullExpression: {
541 if (!ShouldEmitLifetimeMarkers)
542 break;
544 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
545 // marker. Instead, start the lifetime of a conditional temporary earlier
546 // so that it's unconditional. Don't do this with sanitizers which need
547 // more precise lifetime marks. However when inside an "await.suspend"
548 // block, we should always avoid conditional cleanup because it creates
549 // boolean marker that lives across await_suspend, which can destroy coro
550 // frame.
551 ConditionalEvaluation *OldConditional = nullptr;
552 CGBuilderTy::InsertPoint OldIP;
553 if (isInConditionalBranch() && !E->getType().isDestructedType() &&
554 ((!SanOpts.has(SanitizerKind::HWAddress) &&
555 !SanOpts.has(SanitizerKind::Memory) &&
556 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
557 inSuspendBlock())) {
558 OldConditional = OutermostConditional;
559 OutermostConditional = nullptr;
561 OldIP = Builder.saveIP();
562 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
563 Builder.restoreIP(CGBuilderTy::InsertPoint(
564 Block, llvm::BasicBlock::iterator(Block->back())));
567 if (auto *Size = EmitLifetimeStart(
568 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
569 Alloca.getPointer())) {
570 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
571 Size);
574 if (OldConditional) {
575 OutermostConditional = OldConditional;
576 Builder.restoreIP(OldIP);
578 break;
581 default:
582 break;
584 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
586 pushTemporaryCleanup(*this, M, E, Object);
588 // Perform derived-to-base casts and/or field accesses, to get from the
589 // temporary object we created (and, potentially, for which we extended
590 // the lifetime) to the subobject we're binding the reference to.
591 for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
592 switch (Adjustment.Kind) {
593 case SubobjectAdjustment::DerivedToBaseAdjustment:
594 Object =
595 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
596 Adjustment.DerivedToBase.BasePath->path_begin(),
597 Adjustment.DerivedToBase.BasePath->path_end(),
598 /*NullCheckValue=*/ false, E->getExprLoc());
599 break;
601 case SubobjectAdjustment::FieldAdjustment: {
602 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
603 LV = EmitLValueForField(LV, Adjustment.Field);
604 assert(LV.isSimple() &&
605 "materialized temporary field is not a simple lvalue");
606 Object = LV.getAddress(*this);
607 break;
610 case SubobjectAdjustment::MemberPointerAdjustment: {
611 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
612 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
613 Adjustment.Ptr.MPT);
614 break;
619 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
622 RValue
623 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
624 // Emit the expression as an lvalue.
625 LValue LV = EmitLValue(E);
626 assert(LV.isSimple());
627 llvm::Value *Value = LV.getPointer(*this);
629 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
630 // C++11 [dcl.ref]p5 (as amended by core issue 453):
631 // If a glvalue to which a reference is directly bound designates neither
632 // an existing object or function of an appropriate type nor a region of
633 // storage of suitable size and alignment to contain an object of the
634 // reference's type, the behavior is undefined.
635 QualType Ty = E->getType();
636 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
639 return RValue::get(Value);
643 /// getAccessedFieldNo - Given an encoded value and a result number, return the
644 /// input field number being accessed.
645 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
646 const llvm::Constant *Elts) {
647 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
648 ->getZExtValue();
651 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
652 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
653 llvm::Value *High) {
654 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
655 llvm::Value *K47 = Builder.getInt64(47);
656 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
657 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
658 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
659 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
660 return Builder.CreateMul(B1, KMul);
663 bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
664 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
665 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
668 bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
669 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
670 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
671 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
672 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
673 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
676 bool CodeGenFunction::sanitizePerformTypeCheck() const {
677 return SanOpts.has(SanitizerKind::Null) ||
678 SanOpts.has(SanitizerKind::Alignment) ||
679 SanOpts.has(SanitizerKind::ObjectSize) ||
680 SanOpts.has(SanitizerKind::Vptr);
683 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
684 llvm::Value *Ptr, QualType Ty,
685 CharUnits Alignment,
686 SanitizerSet SkippedChecks,
687 llvm::Value *ArraySize) {
688 if (!sanitizePerformTypeCheck())
689 return;
691 // Don't check pointers outside the default address space. The null check
692 // isn't correct, the object-size check isn't supported by LLVM, and we can't
693 // communicate the addresses to the runtime handler for the vptr check.
694 if (Ptr->getType()->getPointerAddressSpace())
695 return;
697 // Don't check pointers to volatile data. The behavior here is implementation-
698 // defined.
699 if (Ty.isVolatileQualified())
700 return;
702 SanitizerScope SanScope(this);
704 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
705 llvm::BasicBlock *Done = nullptr;
707 // Quickly determine whether we have a pointer to an alloca. It's possible
708 // to skip null checks, and some alignment checks, for these pointers. This
709 // can reduce compile-time significantly.
710 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
712 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
713 llvm::Value *IsNonNull = nullptr;
714 bool IsGuaranteedNonNull =
715 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
716 bool AllowNullPointers = isNullPointerAllowed(TCK);
717 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
718 !IsGuaranteedNonNull) {
719 // The glvalue must not be an empty glvalue.
720 IsNonNull = Builder.CreateIsNotNull(Ptr);
722 // The IR builder can constant-fold the null check if the pointer points to
723 // a constant.
724 IsGuaranteedNonNull = IsNonNull == True;
726 // Skip the null check if the pointer is known to be non-null.
727 if (!IsGuaranteedNonNull) {
728 if (AllowNullPointers) {
729 // When performing pointer casts, it's OK if the value is null.
730 // Skip the remaining checks in that case.
731 Done = createBasicBlock("null");
732 llvm::BasicBlock *Rest = createBasicBlock("not.null");
733 Builder.CreateCondBr(IsNonNull, Rest, Done);
734 EmitBlock(Rest);
735 } else {
736 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
741 if (SanOpts.has(SanitizerKind::ObjectSize) &&
742 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
743 !Ty->isIncompleteType()) {
744 uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
745 llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
746 if (ArraySize)
747 Size = Builder.CreateMul(Size, ArraySize);
749 // Degenerate case: new X[0] does not need an objectsize check.
750 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
751 if (!ConstantSize || !ConstantSize->isNullValue()) {
752 // The glvalue must refer to a large enough storage region.
753 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
754 // to check this.
755 // FIXME: Get object address space
756 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
757 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
758 llvm::Value *Min = Builder.getFalse();
759 llvm::Value *NullIsUnknown = Builder.getFalse();
760 llvm::Value *Dynamic = Builder.getFalse();
761 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
762 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
763 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
764 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
768 llvm::MaybeAlign AlignVal;
769 llvm::Value *PtrAsInt = nullptr;
771 if (SanOpts.has(SanitizerKind::Alignment) &&
772 !SkippedChecks.has(SanitizerKind::Alignment)) {
773 AlignVal = Alignment.getAsMaybeAlign();
774 if (!Ty->isIncompleteType() && !AlignVal)
775 AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
776 /*ForPointeeType=*/true)
777 .getAsMaybeAlign();
779 // The glvalue must be suitably aligned.
780 if (AlignVal && *AlignVal > llvm::Align(1) &&
781 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
782 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
783 llvm::Value *Align = Builder.CreateAnd(
784 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
785 llvm::Value *Aligned =
786 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
787 if (Aligned != True)
788 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
792 if (Checks.size() > 0) {
793 llvm::Constant *StaticData[] = {
794 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
795 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
796 llvm::ConstantInt::get(Int8Ty, TCK)};
797 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
798 PtrAsInt ? PtrAsInt : Ptr);
801 // If possible, check that the vptr indicates that there is a subobject of
802 // type Ty at offset zero within this object.
804 // C++11 [basic.life]p5,6:
805 // [For storage which does not refer to an object within its lifetime]
806 // The program has undefined behavior if:
807 // -- the [pointer or glvalue] is used to access a non-static data member
808 // or call a non-static member function
809 if (SanOpts.has(SanitizerKind::Vptr) &&
810 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
811 // Ensure that the pointer is non-null before loading it. If there is no
812 // compile-time guarantee, reuse the run-time null check or emit a new one.
813 if (!IsGuaranteedNonNull) {
814 if (!IsNonNull)
815 IsNonNull = Builder.CreateIsNotNull(Ptr);
816 if (!Done)
817 Done = createBasicBlock("vptr.null");
818 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
819 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
820 EmitBlock(VptrNotNull);
823 // Compute a hash of the mangled name of the type.
825 // FIXME: This is not guaranteed to be deterministic! Move to a
826 // fingerprinting mechanism once LLVM provides one. For the time
827 // being the implementation happens to be deterministic.
828 SmallString<64> MangledName;
829 llvm::raw_svector_ostream Out(MangledName);
830 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
831 Out);
833 // Contained in NoSanitizeList based on the mangled type.
834 if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
835 Out.str())) {
836 llvm::hash_code TypeHash = hash_value(Out.str());
838 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
839 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
840 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
841 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), IntPtrTy,
842 getPointerAlign());
843 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
844 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
846 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
847 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
849 // Look the hash up in our cache.
850 const int CacheSize = 128;
851 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
852 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
853 "__ubsan_vptr_type_cache");
854 llvm::Value *Slot = Builder.CreateAnd(Hash,
855 llvm::ConstantInt::get(IntPtrTy,
856 CacheSize-1));
857 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
858 llvm::Value *CacheVal = Builder.CreateAlignedLoad(
859 IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
860 getPointerAlign());
862 // If the hash isn't in the cache, call a runtime handler to perform the
863 // hard work of checking whether the vptr is for an object of the right
864 // type. This will either fill in the cache and return, or produce a
865 // diagnostic.
866 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
867 llvm::Constant *StaticData[] = {
868 EmitCheckSourceLocation(Loc),
869 EmitCheckTypeDescriptor(Ty),
870 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
871 llvm::ConstantInt::get(Int8Ty, TCK)
873 llvm::Value *DynamicData[] = { Ptr, Hash };
874 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
875 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
876 DynamicData);
880 if (Done) {
881 Builder.CreateBr(Done);
882 EmitBlock(Done);
886 llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
887 QualType EltTy) {
888 ASTContext &C = getContext();
889 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
890 if (!EltSize)
891 return nullptr;
893 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
894 if (!ArrayDeclRef)
895 return nullptr;
897 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
898 if (!ParamDecl)
899 return nullptr;
901 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
902 if (!POSAttr)
903 return nullptr;
905 // Don't load the size if it's a lower bound.
906 int POSType = POSAttr->getType();
907 if (POSType != 0 && POSType != 1)
908 return nullptr;
910 // Find the implicit size parameter.
911 auto PassedSizeIt = SizeArguments.find(ParamDecl);
912 if (PassedSizeIt == SizeArguments.end())
913 return nullptr;
915 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
916 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
917 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
918 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
919 C.getSizeType(), E->getExprLoc());
920 llvm::Value *SizeOfElement =
921 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
922 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
925 /// If Base is known to point to the start of an array, return the length of
926 /// that array. Return 0 if the length cannot be determined.
927 static llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF,
928 const Expr *Base,
929 QualType &IndexedType,
930 LangOptions::StrictFlexArraysLevelKind
931 StrictFlexArraysLevel) {
932 // For the vector indexing extension, the bound is the number of elements.
933 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
934 IndexedType = Base->getType();
935 return CGF.Builder.getInt32(VT->getNumElements());
938 Base = Base->IgnoreParens();
940 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
941 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
942 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
943 StrictFlexArraysLevel)) {
944 IndexedType = CE->getSubExpr()->getType();
945 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
946 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
947 return CGF.Builder.getInt(CAT->getSize());
948 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
949 return CGF.getVLASize(VAT).NumElts;
950 // Ignore pass_object_size here. It's not applicable on decayed pointers.
954 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
955 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
956 IndexedType = Base->getType();
957 return POS;
960 return nullptr;
963 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
964 llvm::Value *Index, QualType IndexType,
965 bool Accessed) {
966 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
967 "should not be called unless adding bounds checks");
968 SanitizerScope SanScope(this);
970 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
971 getLangOpts().getStrictFlexArraysLevel();
973 QualType IndexedType;
974 llvm::Value *Bound =
975 getArrayIndexingBound(*this, Base, IndexedType, StrictFlexArraysLevel);
976 if (!Bound)
977 return;
979 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
980 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
981 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
983 llvm::Constant *StaticData[] = {
984 EmitCheckSourceLocation(E->getExprLoc()),
985 EmitCheckTypeDescriptor(IndexedType),
986 EmitCheckTypeDescriptor(IndexType)
988 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
989 : Builder.CreateICmpULE(IndexVal, BoundVal);
990 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
991 SanitizerHandler::OutOfBounds, StaticData, Index);
995 CodeGenFunction::ComplexPairTy CodeGenFunction::
996 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
997 bool isInc, bool isPre) {
998 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1000 llvm::Value *NextVal;
1001 if (isa<llvm::IntegerType>(InVal.first->getType())) {
1002 uint64_t AmountVal = isInc ? 1 : -1;
1003 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1005 // Add the inc/dec to the real part.
1006 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1007 } else {
1008 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1009 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1010 if (!isInc)
1011 FVal.changeSign();
1012 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1014 // Add the inc/dec to the real part.
1015 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1018 ComplexPairTy IncVal(NextVal, InVal.second);
1020 // Store the updated result through the lvalue.
1021 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1022 if (getLangOpts().OpenMP)
1023 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1024 E->getSubExpr());
1026 // If this is a postinc, return the value read from memory, otherwise use the
1027 // updated value.
1028 return isPre ? IncVal : InVal;
1031 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1032 CodeGenFunction *CGF) {
1033 // Bind VLAs in the cast type.
1034 if (CGF && E->getType()->isVariablyModifiedType())
1035 CGF->EmitVariablyModifiedType(E->getType());
1037 if (CGDebugInfo *DI = getModuleDebugInfo())
1038 DI->EmitExplicitCastType(E->getType());
1041 //===----------------------------------------------------------------------===//
1042 // LValue Expression Emission
1043 //===----------------------------------------------------------------------===//
1045 static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo,
1046 TBAAAccessInfo *TBAAInfo,
1047 KnownNonNull_t IsKnownNonNull,
1048 CodeGenFunction &CGF) {
1049 // We allow this with ObjC object pointers because of fragile ABIs.
1050 assert(E->getType()->isPointerType() ||
1051 E->getType()->isObjCObjectPointerType());
1052 E = E->IgnoreParens();
1054 // Casts:
1055 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1056 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1057 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
1059 switch (CE->getCastKind()) {
1060 // Non-converting casts (but not C's implicit conversion from void*).
1061 case CK_BitCast:
1062 case CK_NoOp:
1063 case CK_AddressSpaceConversion:
1064 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1065 if (PtrTy->getPointeeType()->isVoidType())
1066 break;
1068 LValueBaseInfo InnerBaseInfo;
1069 TBAAAccessInfo InnerTBAAInfo;
1070 Address Addr = CGF.EmitPointerWithAlignment(
1071 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1072 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1073 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1075 if (isa<ExplicitCastExpr>(CE)) {
1076 LValueBaseInfo TargetTypeBaseInfo;
1077 TBAAAccessInfo TargetTypeTBAAInfo;
1078 CharUnits Align = CGF.CGM.getNaturalPointeeTypeAlignment(
1079 E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1080 if (TBAAInfo)
1081 *TBAAInfo =
1082 CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
1083 // If the source l-value is opaque, honor the alignment of the
1084 // casted-to type.
1085 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1086 if (BaseInfo)
1087 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1088 Addr = Address(Addr.getPointer(), Addr.getElementType(), Align,
1089 IsKnownNonNull);
1093 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1094 CE->getCastKind() == CK_BitCast) {
1095 if (auto PT = E->getType()->getAs<PointerType>())
1096 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
1097 /*MayBeNull=*/true,
1098 CodeGenFunction::CFITCK_UnrelatedCast,
1099 CE->getBeginLoc());
1102 llvm::Type *ElemTy =
1103 CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1104 Addr = CGF.Builder.CreateElementBitCast(Addr, ElemTy);
1105 if (CE->getCastKind() == CK_AddressSpaceConversion)
1106 Addr = CGF.Builder.CreateAddrSpaceCast(Addr,
1107 CGF.ConvertType(E->getType()));
1108 return Addr;
1110 break;
1112 // Array-to-pointer decay.
1113 case CK_ArrayToPointerDecay:
1114 return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1116 // Derived-to-base conversions.
1117 case CK_UncheckedDerivedToBase:
1118 case CK_DerivedToBase: {
1119 // TODO: Support accesses to members of base classes in TBAA. For now, we
1120 // conservatively pretend that the complete object is of the base class
1121 // type.
1122 if (TBAAInfo)
1123 *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1124 Address Addr = CGF.EmitPointerWithAlignment(
1125 CE->getSubExpr(), BaseInfo, nullptr,
1126 (KnownNonNull_t)(IsKnownNonNull ||
1127 CE->getCastKind() == CK_UncheckedDerivedToBase));
1128 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1129 return CGF.GetAddressOfBaseClass(
1130 Addr, Derived, CE->path_begin(), CE->path_end(),
1131 CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1134 // TODO: Is there any reason to treat base-to-derived conversions
1135 // specially?
1136 default:
1137 break;
1141 // Unary &.
1142 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1143 if (UO->getOpcode() == UO_AddrOf) {
1144 LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1145 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1146 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1147 return LV.getAddress(CGF);
1151 // std::addressof and variants.
1152 if (auto *Call = dyn_cast<CallExpr>(E)) {
1153 switch (Call->getBuiltinCallee()) {
1154 default:
1155 break;
1156 case Builtin::BIaddressof:
1157 case Builtin::BI__addressof:
1158 case Builtin::BI__builtin_addressof: {
1159 LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
1160 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1161 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1162 return LV.getAddress(CGF);
1167 // TODO: conditional operators, comma.
1169 // Otherwise, use the alignment of the type.
1170 CharUnits Align =
1171 CGF.CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
1172 llvm::Type *ElemTy = CGF.ConvertTypeForMem(E->getType()->getPointeeType());
1173 return Address(CGF.EmitScalarExpr(E), ElemTy, Align, IsKnownNonNull);
1176 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
1177 /// derive a more accurate bound on the alignment of the pointer.
1178 Address CodeGenFunction::EmitPointerWithAlignment(
1179 const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1180 KnownNonNull_t IsKnownNonNull) {
1181 Address Addr =
1182 ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1183 if (IsKnownNonNull && !Addr.isKnownNonNull())
1184 Addr.setKnownNonNull();
1185 return Addr;
1188 llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1189 llvm::Value *V = RV.getScalarVal();
1190 if (auto MPT = T->getAs<MemberPointerType>())
1191 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1192 return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1195 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1196 if (Ty->isVoidType())
1197 return RValue::get(nullptr);
1199 switch (getEvaluationKind(Ty)) {
1200 case TEK_Complex: {
1201 llvm::Type *EltTy =
1202 ConvertType(Ty->castAs<ComplexType>()->getElementType());
1203 llvm::Value *U = llvm::UndefValue::get(EltTy);
1204 return RValue::getComplex(std::make_pair(U, U));
1207 // If this is a use of an undefined aggregate type, the aggregate must have an
1208 // identifiable address. Just because the contents of the value are undefined
1209 // doesn't mean that the address can't be taken and compared.
1210 case TEK_Aggregate: {
1211 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1212 return RValue::getAggregate(DestPtr);
1215 case TEK_Scalar:
1216 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1218 llvm_unreachable("bad evaluation kind");
1221 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1222 const char *Name) {
1223 ErrorUnsupported(E, Name);
1224 return GetUndefRValue(E->getType());
1227 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1228 const char *Name) {
1229 ErrorUnsupported(E, Name);
1230 llvm::Type *ElTy = ConvertType(E->getType());
1231 llvm::Type *Ty = llvm::PointerType::getUnqual(ElTy);
1232 return MakeAddrLValue(
1233 Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
1236 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1237 const Expr *Base = Obj;
1238 while (!isa<CXXThisExpr>(Base)) {
1239 // The result of a dynamic_cast can be null.
1240 if (isa<CXXDynamicCastExpr>(Base))
1241 return false;
1243 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1244 Base = CE->getSubExpr();
1245 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1246 Base = PE->getSubExpr();
1247 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1248 if (UO->getOpcode() == UO_Extension)
1249 Base = UO->getSubExpr();
1250 else
1251 return false;
1252 } else {
1253 return false;
1256 return true;
1259 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1260 LValue LV;
1261 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1262 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1263 else
1264 LV = EmitLValue(E);
1265 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1266 SanitizerSet SkippedChecks;
1267 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1268 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1269 if (IsBaseCXXThis)
1270 SkippedChecks.set(SanitizerKind::Alignment, true);
1271 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1272 SkippedChecks.set(SanitizerKind::Null, true);
1274 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1275 LV.getAlignment(), SkippedChecks);
1277 return LV;
1280 /// EmitLValue - Emit code to compute a designator that specifies the location
1281 /// of the expression.
1283 /// This can return one of two things: a simple address or a bitfield reference.
1284 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1285 /// an LLVM pointer type.
1287 /// If this returns a bitfield reference, nothing about the pointee type of the
1288 /// LLVM value is known: For example, it may not be a pointer to an integer.
1290 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1291 /// this method guarantees that the returned pointer type will point to an LLVM
1292 /// type of the same size of the lvalue's type. If the lvalue has a variable
1293 /// length type, this is not possible.
1295 LValue CodeGenFunction::EmitLValue(const Expr *E,
1296 KnownNonNull_t IsKnownNonNull) {
1297 LValue LV = EmitLValueHelper(E, IsKnownNonNull);
1298 if (IsKnownNonNull && !LV.isKnownNonNull())
1299 LV.setKnownNonNull();
1300 return LV;
1303 LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1304 KnownNonNull_t IsKnownNonNull) {
1305 ApplyDebugLocation DL(*this, E);
1306 switch (E->getStmtClass()) {
1307 default: return EmitUnsupportedLValue(E, "l-value expression");
1309 case Expr::ObjCPropertyRefExprClass:
1310 llvm_unreachable("cannot emit a property reference directly");
1312 case Expr::ObjCSelectorExprClass:
1313 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1314 case Expr::ObjCIsaExprClass:
1315 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1316 case Expr::BinaryOperatorClass:
1317 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1318 case Expr::CompoundAssignOperatorClass: {
1319 QualType Ty = E->getType();
1320 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1321 Ty = AT->getValueType();
1322 if (!Ty->isAnyComplexType())
1323 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1324 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1326 case Expr::CallExprClass:
1327 case Expr::CXXMemberCallExprClass:
1328 case Expr::CXXOperatorCallExprClass:
1329 case Expr::UserDefinedLiteralClass:
1330 return EmitCallExprLValue(cast<CallExpr>(E));
1331 case Expr::CXXRewrittenBinaryOperatorClass:
1332 return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1333 IsKnownNonNull);
1334 case Expr::VAArgExprClass:
1335 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1336 case Expr::DeclRefExprClass:
1337 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1338 case Expr::ConstantExprClass: {
1339 const ConstantExpr *CE = cast<ConstantExpr>(E);
1340 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
1341 QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
1342 ->getCallReturnType(getContext())
1343 ->getPointeeType();
1344 return MakeNaturalAlignAddrLValue(Result, RetType);
1346 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
1348 case Expr::ParenExprClass:
1349 return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
1350 case Expr::GenericSelectionExprClass:
1351 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1352 IsKnownNonNull);
1353 case Expr::PredefinedExprClass:
1354 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1355 case Expr::StringLiteralClass:
1356 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1357 case Expr::ObjCEncodeExprClass:
1358 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1359 case Expr::PseudoObjectExprClass:
1360 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1361 case Expr::InitListExprClass:
1362 return EmitInitListLValue(cast<InitListExpr>(E));
1363 case Expr::CXXTemporaryObjectExprClass:
1364 case Expr::CXXConstructExprClass:
1365 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1366 case Expr::CXXBindTemporaryExprClass:
1367 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1368 case Expr::CXXUuidofExprClass:
1369 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1370 case Expr::LambdaExprClass:
1371 return EmitAggExprToLValue(E);
1373 case Expr::ExprWithCleanupsClass: {
1374 const auto *cleanups = cast<ExprWithCleanups>(E);
1375 RunCleanupsScope Scope(*this);
1376 LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1377 if (LV.isSimple()) {
1378 // Defend against branches out of gnu statement expressions surrounded by
1379 // cleanups.
1380 Address Addr = LV.getAddress(*this);
1381 llvm::Value *V = Addr.getPointer();
1382 Scope.ForceCleanup({&V});
1383 return LValue::MakeAddr(Addr.withPointer(V, Addr.isKnownNonNull()),
1384 LV.getType(), getContext(), LV.getBaseInfo(),
1385 LV.getTBAAInfo());
1387 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1388 // bitfield lvalue or some other non-simple lvalue?
1389 return LV;
1392 case Expr::CXXDefaultArgExprClass: {
1393 auto *DAE = cast<CXXDefaultArgExpr>(E);
1394 CXXDefaultArgExprScope Scope(*this, DAE);
1395 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1397 case Expr::CXXDefaultInitExprClass: {
1398 auto *DIE = cast<CXXDefaultInitExpr>(E);
1399 CXXDefaultInitExprScope Scope(*this, DIE);
1400 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1402 case Expr::CXXTypeidExprClass:
1403 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1405 case Expr::ObjCMessageExprClass:
1406 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1407 case Expr::ObjCIvarRefExprClass:
1408 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1409 case Expr::StmtExprClass:
1410 return EmitStmtExprLValue(cast<StmtExpr>(E));
1411 case Expr::UnaryOperatorClass:
1412 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1413 case Expr::ArraySubscriptExprClass:
1414 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1415 case Expr::MatrixSubscriptExprClass:
1416 return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
1417 case Expr::OMPArraySectionExprClass:
1418 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1419 case Expr::ExtVectorElementExprClass:
1420 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1421 case Expr::CXXThisExprClass:
1422 return MakeAddrLValue(LoadCXXThisAddress(), E->getType());
1423 case Expr::MemberExprClass:
1424 return EmitMemberExpr(cast<MemberExpr>(E));
1425 case Expr::CompoundLiteralExprClass:
1426 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1427 case Expr::ConditionalOperatorClass:
1428 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1429 case Expr::BinaryConditionalOperatorClass:
1430 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1431 case Expr::ChooseExprClass:
1432 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
1433 case Expr::OpaqueValueExprClass:
1434 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1435 case Expr::SubstNonTypeTemplateParmExprClass:
1436 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1437 IsKnownNonNull);
1438 case Expr::ImplicitCastExprClass:
1439 case Expr::CStyleCastExprClass:
1440 case Expr::CXXFunctionalCastExprClass:
1441 case Expr::CXXStaticCastExprClass:
1442 case Expr::CXXDynamicCastExprClass:
1443 case Expr::CXXReinterpretCastExprClass:
1444 case Expr::CXXConstCastExprClass:
1445 case Expr::CXXAddrspaceCastExprClass:
1446 case Expr::ObjCBridgedCastExprClass:
1447 return EmitCastLValue(cast<CastExpr>(E));
1449 case Expr::MaterializeTemporaryExprClass:
1450 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1452 case Expr::CoawaitExprClass:
1453 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1454 case Expr::CoyieldExprClass:
1455 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1459 /// Given an object of the given canonical type, can we safely copy a
1460 /// value out of it based on its initializer?
1461 static bool isConstantEmittableObjectType(QualType type) {
1462 assert(type.isCanonical());
1463 assert(!type->isReferenceType());
1465 // Must be const-qualified but non-volatile.
1466 Qualifiers qs = type.getLocalQualifiers();
1467 if (!qs.hasConst() || qs.hasVolatile()) return false;
1469 // Otherwise, all object types satisfy this except C++ classes with
1470 // mutable subobjects or non-trivial copy/destroy behavior.
1471 if (const auto *RT = dyn_cast<RecordType>(type))
1472 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1473 if (RD->hasMutableFields() || !RD->isTrivial())
1474 return false;
1476 return true;
1479 /// Can we constant-emit a load of a reference to a variable of the
1480 /// given type? This is different from predicates like
1481 /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1482 /// in situations that don't necessarily satisfy the language's rules
1483 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1484 /// to do this with const float variables even if those variables
1485 /// aren't marked 'constexpr'.
1486 enum ConstantEmissionKind {
1487 CEK_None,
1488 CEK_AsReferenceOnly,
1489 CEK_AsValueOrReference,
1490 CEK_AsValueOnly
1492 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1493 type = type.getCanonicalType();
1494 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1495 if (isConstantEmittableObjectType(ref->getPointeeType()))
1496 return CEK_AsValueOrReference;
1497 return CEK_AsReferenceOnly;
1499 if (isConstantEmittableObjectType(type))
1500 return CEK_AsValueOnly;
1501 return CEK_None;
1504 /// Try to emit a reference to the given value without producing it as
1505 /// an l-value. This is just an optimization, but it avoids us needing
1506 /// to emit global copies of variables if they're named without triggering
1507 /// a formal use in a context where we can't emit a direct reference to them,
1508 /// for instance if a block or lambda or a member of a local class uses a
1509 /// const int variable or constexpr variable from an enclosing function.
1510 CodeGenFunction::ConstantEmission
1511 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1512 ValueDecl *value = refExpr->getDecl();
1514 // The value needs to be an enum constant or a constant variable.
1515 ConstantEmissionKind CEK;
1516 if (isa<ParmVarDecl>(value)) {
1517 CEK = CEK_None;
1518 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1519 CEK = checkVarTypeForConstantEmission(var->getType());
1520 } else if (isa<EnumConstantDecl>(value)) {
1521 CEK = CEK_AsValueOnly;
1522 } else {
1523 CEK = CEK_None;
1525 if (CEK == CEK_None) return ConstantEmission();
1527 Expr::EvalResult result;
1528 bool resultIsReference;
1529 QualType resultType;
1531 // It's best to evaluate all the way as an r-value if that's permitted.
1532 if (CEK != CEK_AsReferenceOnly &&
1533 refExpr->EvaluateAsRValue(result, getContext())) {
1534 resultIsReference = false;
1535 resultType = refExpr->getType();
1537 // Otherwise, try to evaluate as an l-value.
1538 } else if (CEK != CEK_AsValueOnly &&
1539 refExpr->EvaluateAsLValue(result, getContext())) {
1540 resultIsReference = true;
1541 resultType = value->getType();
1543 // Failure.
1544 } else {
1545 return ConstantEmission();
1548 // In any case, if the initializer has side-effects, abandon ship.
1549 if (result.HasSideEffects)
1550 return ConstantEmission();
1552 // In CUDA/HIP device compilation, a lambda may capture a reference variable
1553 // referencing a global host variable by copy. In this case the lambda should
1554 // make a copy of the value of the global host variable. The DRE of the
1555 // captured reference variable cannot be emitted as load from the host
1556 // global variable as compile time constant, since the host variable is not
1557 // accessible on device. The DRE of the captured reference variable has to be
1558 // loaded from captures.
1559 if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1560 refExpr->refersToEnclosingVariableOrCapture()) {
1561 auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1562 if (MD && MD->getParent()->isLambda() &&
1563 MD->getOverloadedOperator() == OO_Call) {
1564 const APValue::LValueBase &base = result.Val.getLValueBase();
1565 if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1566 if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1567 if (!VD->hasAttr<CUDADeviceAttr>()) {
1568 return ConstantEmission();
1575 // Emit as a constant.
1576 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1577 result.Val, resultType);
1579 // Make sure we emit a debug reference to the global variable.
1580 // This should probably fire even for
1581 if (isa<VarDecl>(value)) {
1582 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1583 EmitDeclRefExprDbgValue(refExpr, result.Val);
1584 } else {
1585 assert(isa<EnumConstantDecl>(value));
1586 EmitDeclRefExprDbgValue(refExpr, result.Val);
1589 // If we emitted a reference constant, we need to dereference that.
1590 if (resultIsReference)
1591 return ConstantEmission::forReference(C);
1593 return ConstantEmission::forValue(C);
1596 static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1597 const MemberExpr *ME) {
1598 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1599 // Try to emit static variable member expressions as DREs.
1600 return DeclRefExpr::Create(
1601 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1602 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1603 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
1605 return nullptr;
1608 CodeGenFunction::ConstantEmission
1609 CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1610 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1611 return tryEmitAsConstant(DRE);
1612 return ConstantEmission();
1615 llvm::Value *CodeGenFunction::emitScalarConstant(
1616 const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1617 assert(Constant && "not a constant");
1618 if (Constant.isReference())
1619 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1620 E->getExprLoc())
1621 .getScalarVal();
1622 return Constant.getValue();
1625 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1626 SourceLocation Loc) {
1627 return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
1628 lvalue.getType(), Loc, lvalue.getBaseInfo(),
1629 lvalue.getTBAAInfo(), lvalue.isNontemporal());
1632 static bool hasBooleanRepresentation(QualType Ty) {
1633 if (Ty->isBooleanType())
1634 return true;
1636 if (const EnumType *ET = Ty->getAs<EnumType>())
1637 return ET->getDecl()->getIntegerType()->isBooleanType();
1639 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1640 return hasBooleanRepresentation(AT->getValueType());
1642 return false;
1645 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1646 llvm::APInt &Min, llvm::APInt &End,
1647 bool StrictEnums, bool IsBool) {
1648 const EnumType *ET = Ty->getAs<EnumType>();
1649 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1650 ET && !ET->getDecl()->isFixed();
1651 if (!IsBool && !IsRegularCPlusPlusEnum)
1652 return false;
1654 if (IsBool) {
1655 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1656 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1657 } else {
1658 const EnumDecl *ED = ET->getDecl();
1659 ED->getValueRange(End, Min);
1661 return true;
1664 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1665 llvm::APInt Min, End;
1666 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1667 hasBooleanRepresentation(Ty)))
1668 return nullptr;
1670 llvm::MDBuilder MDHelper(getLLVMContext());
1671 return MDHelper.createRange(Min, End);
1674 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1675 SourceLocation Loc) {
1676 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1677 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1678 if (!HasBoolCheck && !HasEnumCheck)
1679 return false;
1681 bool IsBool = hasBooleanRepresentation(Ty) ||
1682 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1683 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1684 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1685 if (!NeedsBoolCheck && !NeedsEnumCheck)
1686 return false;
1688 // Single-bit booleans don't need to be checked. Special-case this to avoid
1689 // a bit width mismatch when handling bitfield values. This is handled by
1690 // EmitFromMemory for the non-bitfield case.
1691 if (IsBool &&
1692 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1693 return false;
1695 llvm::APInt Min, End;
1696 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1697 return true;
1699 auto &Ctx = getLLVMContext();
1700 SanitizerScope SanScope(this);
1701 llvm::Value *Check;
1702 --End;
1703 if (!Min) {
1704 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1705 } else {
1706 llvm::Value *Upper =
1707 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1708 llvm::Value *Lower =
1709 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1710 Check = Builder.CreateAnd(Upper, Lower);
1712 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1713 EmitCheckTypeDescriptor(Ty)};
1714 SanitizerMask Kind =
1715 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1716 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1717 StaticArgs, EmitCheckValue(Value));
1718 return true;
1721 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1722 QualType Ty,
1723 SourceLocation Loc,
1724 LValueBaseInfo BaseInfo,
1725 TBAAAccessInfo TBAAInfo,
1726 bool isNontemporal) {
1727 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
1728 if (GV->isThreadLocal())
1729 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1730 NotKnownNonNull);
1732 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
1733 // Boolean vectors use `iN` as storage type.
1734 if (ClangVecTy->isExtVectorBoolType()) {
1735 llvm::Type *ValTy = ConvertType(Ty);
1736 unsigned ValNumElems =
1737 cast<llvm::FixedVectorType>(ValTy)->getNumElements();
1738 // Load the `iP` storage object (P is the padded vector size).
1739 auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
1740 const auto *RawIntTy = RawIntV->getType();
1741 assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
1742 // Bitcast iP --> <P x i1>.
1743 auto *PaddedVecTy = llvm::FixedVectorType::get(
1744 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
1745 llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
1746 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
1747 V = emitBoolVecConversion(V, ValNumElems, "extractvec");
1749 return EmitFromMemory(V, Ty);
1752 // Handle vectors of size 3 like size 4 for better performance.
1753 const llvm::Type *EltTy = Addr.getElementType();
1754 const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
1756 if (!CGM.getCodeGenOpts().PreserveVec3Type && VTy->getNumElements() == 3) {
1758 // Bitcast to vec4 type.
1759 llvm::VectorType *vec4Ty =
1760 llvm::FixedVectorType::get(VTy->getElementType(), 4);
1761 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1762 // Now load value.
1763 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1765 // Shuffle vector to get vec3.
1766 V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2}, "extractVec");
1767 return EmitFromMemory(V, Ty);
1771 // Atomic operations have to be done on integral types.
1772 LValue AtomicLValue =
1773 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1774 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1775 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1778 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1779 if (isNontemporal) {
1780 llvm::MDNode *Node = llvm::MDNode::get(
1781 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1782 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
1785 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1787 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1788 // In order to prevent the optimizer from throwing away the check, don't
1789 // attach range metadata to the load.
1790 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1791 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
1792 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1793 Load->setMetadata(llvm::LLVMContext::MD_noundef,
1794 llvm::MDNode::get(getLLVMContext(), std::nullopt));
1797 return EmitFromMemory(Load, Ty);
1800 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1801 // Bool has a different representation in memory than in registers.
1802 if (hasBooleanRepresentation(Ty)) {
1803 // This should really always be an i1, but sometimes it's already
1804 // an i8, and it's awkward to track those cases down.
1805 if (Value->getType()->isIntegerTy(1))
1806 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1807 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1808 "wrong value rep of bool");
1811 return Value;
1814 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1815 // Bool has a different representation in memory than in registers.
1816 if (hasBooleanRepresentation(Ty)) {
1817 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1818 "wrong value rep of bool");
1819 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1821 if (Ty->isExtVectorBoolType()) {
1822 const auto *RawIntTy = Value->getType();
1823 // Bitcast iP --> <P x i1>.
1824 auto *PaddedVecTy = llvm::FixedVectorType::get(
1825 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
1826 auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
1827 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
1828 llvm::Type *ValTy = ConvertType(Ty);
1829 unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
1830 return emitBoolVecConversion(V, ValNumElems, "extractvec");
1833 return Value;
1836 // Convert the pointer of \p Addr to a pointer to a vector (the value type of
1837 // MatrixType), if it points to a array (the memory type of MatrixType).
1838 static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
1839 bool IsVector = true) {
1840 auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
1841 if (ArrayTy && IsVector) {
1842 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1843 ArrayTy->getNumElements());
1845 return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy));
1847 auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
1848 if (VectorTy && !IsVector) {
1849 auto *ArrayTy = llvm::ArrayType::get(
1850 VectorTy->getElementType(),
1851 cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
1853 return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy));
1856 return Addr;
1859 // Emit a store of a matrix LValue. This may require casting the original
1860 // pointer to memory address (ArrayType) to a pointer to the value type
1861 // (VectorType).
1862 static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
1863 bool isInit, CodeGenFunction &CGF) {
1864 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
1865 value->getType()->isVectorTy());
1866 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
1867 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
1868 lvalue.isNontemporal());
1871 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1872 bool Volatile, QualType Ty,
1873 LValueBaseInfo BaseInfo,
1874 TBAAAccessInfo TBAAInfo,
1875 bool isInit, bool isNontemporal) {
1876 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getPointer()))
1877 if (GV->isThreadLocal())
1878 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1879 NotKnownNonNull);
1881 llvm::Type *SrcTy = Value->getType();
1882 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
1883 auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy);
1884 if (VecTy && ClangVecTy->isExtVectorBoolType()) {
1885 auto *MemIntTy = cast<llvm::IntegerType>(Addr.getElementType());
1886 // Expand to the memory bit width.
1887 unsigned MemNumElems = MemIntTy->getPrimitiveSizeInBits();
1888 // <N x i1> --> <P x i1>.
1889 Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
1890 // <P x i1> --> iP.
1891 Value = Builder.CreateBitCast(Value, MemIntTy);
1892 } else if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1893 // Handle vec3 special.
1894 if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
1895 // Our source is a vec3, do a shuffle vector to make it a vec4.
1896 Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
1897 "extractVec");
1898 SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
1900 if (Addr.getElementType() != SrcTy) {
1901 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1906 Value = EmitToMemory(Value, Ty);
1908 LValue AtomicLValue =
1909 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1910 if (Ty->isAtomicType() ||
1911 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1912 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1913 return;
1916 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1917 if (isNontemporal) {
1918 llvm::MDNode *Node =
1919 llvm::MDNode::get(Store->getContext(),
1920 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1921 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
1924 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1927 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1928 bool isInit) {
1929 if (lvalue.getType()->isConstantMatrixType()) {
1930 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
1931 return;
1934 EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
1935 lvalue.getType(), lvalue.getBaseInfo(),
1936 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1939 // Emit a load of a LValue of matrix type. This may require casting the pointer
1940 // to memory address (ArrayType) to a pointer to the value type (VectorType).
1941 static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
1942 CodeGenFunction &CGF) {
1943 assert(LV.getType()->isConstantMatrixType());
1944 Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
1945 LV.setAddress(Addr);
1946 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
1949 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1950 /// method emits the address of the lvalue, then loads the result as an rvalue,
1951 /// returning the rvalue.
1952 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1953 if (LV.isObjCWeak()) {
1954 // load of a __weak object.
1955 Address AddrWeakObj = LV.getAddress(*this);
1956 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1957 AddrWeakObj));
1959 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1960 // In MRC mode, we do a load+autorelease.
1961 if (!getLangOpts().ObjCAutoRefCount) {
1962 return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
1965 // In ARC mode, we load retained and then consume the value.
1966 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
1967 Object = EmitObjCConsumeObject(LV.getType(), Object);
1968 return RValue::get(Object);
1971 if (LV.isSimple()) {
1972 assert(!LV.getType()->isFunctionType());
1974 if (LV.getType()->isConstantMatrixType())
1975 return EmitLoadOfMatrixLValue(LV, Loc, *this);
1977 // Everything needs a load.
1978 return RValue::get(EmitLoadOfScalar(LV, Loc));
1981 if (LV.isVectorElt()) {
1982 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1983 LV.isVolatileQualified());
1984 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1985 "vecext"));
1988 // If this is a reference to a subset of the elements of a vector, either
1989 // shuffle the input or extract/insert them as appropriate.
1990 if (LV.isExtVectorElt()) {
1991 return EmitLoadOfExtVectorElementLValue(LV);
1994 // Global Register variables always invoke intrinsics
1995 if (LV.isGlobalReg())
1996 return EmitLoadOfGlobalRegLValue(LV);
1998 if (LV.isMatrixElt()) {
1999 llvm::Value *Idx = LV.getMatrixIdx();
2000 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2001 const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
2002 llvm::MatrixBuilder MB(Builder);
2003 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2005 llvm::LoadInst *Load =
2006 Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2007 return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
2010 assert(LV.isBitField() && "Unknown LValue type!");
2011 return EmitLoadOfBitfieldLValue(LV, Loc);
2014 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
2015 SourceLocation Loc) {
2016 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2018 // Get the output type.
2019 llvm::Type *ResLTy = ConvertType(LV.getType());
2021 Address Ptr = LV.getBitFieldAddress();
2022 llvm::Value *Val =
2023 Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2025 bool UseVolatile = LV.isVolatileQualified() &&
2026 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2027 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2028 const unsigned StorageSize =
2029 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2030 if (Info.IsSigned) {
2031 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2032 unsigned HighBits = StorageSize - Offset - Info.Size;
2033 if (HighBits)
2034 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2035 if (Offset + HighBits)
2036 Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2037 } else {
2038 if (Offset)
2039 Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2040 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2041 Val = Builder.CreateAnd(
2042 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2044 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2045 EmitScalarRangeCheck(Val, LV.getType(), Loc);
2046 return RValue::get(Val);
2049 // If this is a reference to a subset of the elements of a vector, create an
2050 // appropriate shufflevector.
2051 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
2052 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2053 LV.isVolatileQualified());
2055 const llvm::Constant *Elts = LV.getExtVectorElts();
2057 // If the result of the expression is a non-vector type, we must be extracting
2058 // a single element. Just codegen as an extractelement.
2059 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2060 if (!ExprVT) {
2061 unsigned InIdx = getAccessedFieldNo(0, Elts);
2062 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2063 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
2066 // Always use shuffle vector to try to retain the original program structure
2067 unsigned NumResultElts = ExprVT->getNumElements();
2069 SmallVector<int, 4> Mask;
2070 for (unsigned i = 0; i != NumResultElts; ++i)
2071 Mask.push_back(getAccessedFieldNo(i, Elts));
2073 Vec = Builder.CreateShuffleVector(Vec, Mask);
2074 return RValue::get(Vec);
2077 /// Generates lvalue for partial ext_vector access.
2078 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
2079 Address VectorAddress = LV.getExtVectorAddress();
2080 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2081 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2083 Address CastToPointerElement =
2084 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
2085 "conv.ptr.element");
2087 const llvm::Constant *Elts = LV.getExtVectorElts();
2088 unsigned ix = getAccessedFieldNo(0, Elts);
2090 Address VectorBasePtrPlusIx =
2091 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2092 "vector.elt");
2094 return VectorBasePtrPlusIx;
2097 /// Load of global gamed gegisters are always calls to intrinsics.
2098 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
2099 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2100 "Bad type for register variable");
2101 llvm::MDNode *RegName = cast<llvm::MDNode>(
2102 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2104 // We accept integer and pointer types only
2105 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2106 llvm::Type *Ty = OrigTy;
2107 if (OrigTy->isPointerTy())
2108 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2109 llvm::Type *Types[] = { Ty };
2111 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2112 llvm::Value *Call = Builder.CreateCall(
2113 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2114 if (OrigTy->isPointerTy())
2115 Call = Builder.CreateIntToPtr(Call, OrigTy);
2116 return RValue::get(Call);
2119 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2120 /// lvalue, where both are guaranteed to the have the same type, and that type
2121 /// is 'Ty'.
2122 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
2123 bool isInit) {
2124 if (!Dst.isSimple()) {
2125 if (Dst.isVectorElt()) {
2126 // Read/modify/write the vector, inserting the new element.
2127 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2128 Dst.isVolatileQualified());
2129 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2130 if (IRStoreTy) {
2131 auto *IRVecTy = llvm::FixedVectorType::get(
2132 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2133 Vec = Builder.CreateBitCast(Vec, IRVecTy);
2134 // iN --> <N x i1>.
2136 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2137 Dst.getVectorIdx(), "vecins");
2138 if (IRStoreTy) {
2139 // <N x i1> --> <iN>.
2140 Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2142 Builder.CreateStore(Vec, Dst.getVectorAddress(),
2143 Dst.isVolatileQualified());
2144 return;
2147 // If this is an update of extended vector elements, insert them as
2148 // appropriate.
2149 if (Dst.isExtVectorElt())
2150 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
2152 if (Dst.isGlobalReg())
2153 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2155 if (Dst.isMatrixElt()) {
2156 llvm::Value *Idx = Dst.getMatrixIdx();
2157 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2158 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2159 llvm::MatrixBuilder MB(Builder);
2160 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2162 llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2163 llvm::Value *Vec =
2164 Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
2165 Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2166 Dst.isVolatileQualified());
2167 return;
2170 assert(Dst.isBitField() && "Unknown LValue type");
2171 return EmitStoreThroughBitfieldLValue(Src, Dst);
2174 // There's special magic for assigning into an ARC-qualified l-value.
2175 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2176 switch (Lifetime) {
2177 case Qualifiers::OCL_None:
2178 llvm_unreachable("present but none");
2180 case Qualifiers::OCL_ExplicitNone:
2181 // nothing special
2182 break;
2184 case Qualifiers::OCL_Strong:
2185 if (isInit) {
2186 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2187 break;
2189 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2190 return;
2192 case Qualifiers::OCL_Weak:
2193 if (isInit)
2194 // Initialize and then skip the primitive store.
2195 EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
2196 else
2197 EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2198 /*ignore*/ true);
2199 return;
2201 case Qualifiers::OCL_Autoreleasing:
2202 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
2203 Src.getScalarVal()));
2204 // fall into the normal path
2205 break;
2209 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2210 // load of a __weak object.
2211 Address LvalueDst = Dst.getAddress(*this);
2212 llvm::Value *src = Src.getScalarVal();
2213 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2214 return;
2217 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2218 // load of a __strong object.
2219 Address LvalueDst = Dst.getAddress(*this);
2220 llvm::Value *src = Src.getScalarVal();
2221 if (Dst.isObjCIvar()) {
2222 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2223 llvm::Type *ResultType = IntPtrTy;
2224 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
2225 llvm::Value *RHS = dst.getPointer();
2226 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2227 llvm::Value *LHS =
2228 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
2229 "sub.ptr.lhs.cast");
2230 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2231 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
2232 BytesBetween);
2233 } else if (Dst.isGlobalObjCRef()) {
2234 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2235 Dst.isThreadLocalRef());
2237 else
2238 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2239 return;
2242 assert(Src.isScalar() && "Can't emit an agg store with this method");
2243 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2246 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2247 llvm::Value **Result) {
2248 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2249 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
2250 Address Ptr = Dst.getBitFieldAddress();
2252 // Get the source value, truncated to the width of the bit-field.
2253 llvm::Value *SrcVal = Src.getScalarVal();
2255 // Cast the source to the storage type and shift it into place.
2256 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2257 /*isSigned=*/false);
2258 llvm::Value *MaskedVal = SrcVal;
2260 const bool UseVolatile =
2261 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2262 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2263 const unsigned StorageSize =
2264 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2265 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2266 // See if there are other bits in the bitfield's storage we'll need to load
2267 // and mask together with source before storing.
2268 if (StorageSize != Info.Size) {
2269 assert(StorageSize > Info.Size && "Invalid bitfield size.");
2270 llvm::Value *Val =
2271 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2273 // Mask the source value as needed.
2274 if (!hasBooleanRepresentation(Dst.getType()))
2275 SrcVal = Builder.CreateAnd(
2276 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
2277 "bf.value");
2278 MaskedVal = SrcVal;
2279 if (Offset)
2280 SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
2282 // Mask out the original value.
2283 Val = Builder.CreateAnd(
2284 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
2285 "bf.clear");
2287 // Or together the unchanged values and the source value.
2288 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2289 } else {
2290 assert(Offset == 0);
2291 // According to the AACPS:
2292 // When a volatile bit-field is written, and its container does not overlap
2293 // with any non-bit-field member, its container must be read exactly once
2294 // and written exactly once using the access width appropriate to the type
2295 // of the container. The two accesses are not atomic.
2296 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
2297 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
2298 Builder.CreateLoad(Ptr, true, "bf.load");
2301 // Write the new value back out.
2302 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2304 // Return the new value of the bit-field, if requested.
2305 if (Result) {
2306 llvm::Value *ResultVal = MaskedVal;
2308 // Sign extend the value if needed.
2309 if (Info.IsSigned) {
2310 assert(Info.Size <= StorageSize);
2311 unsigned HighBits = StorageSize - Info.Size;
2312 if (HighBits) {
2313 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2314 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2318 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2319 "bf.result.cast");
2320 *Result = EmitFromMemory(ResultVal, Dst.getType());
2324 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2325 LValue Dst) {
2326 // This access turns into a read/modify/write of the vector. Load the input
2327 // value now.
2328 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2329 Dst.isVolatileQualified());
2330 const llvm::Constant *Elts = Dst.getExtVectorElts();
2332 llvm::Value *SrcVal = Src.getScalarVal();
2334 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2335 unsigned NumSrcElts = VTy->getNumElements();
2336 unsigned NumDstElts =
2337 cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
2338 if (NumDstElts == NumSrcElts) {
2339 // Use shuffle vector is the src and destination are the same number of
2340 // elements and restore the vector mask since it is on the side it will be
2341 // stored.
2342 SmallVector<int, 4> Mask(NumDstElts);
2343 for (unsigned i = 0; i != NumSrcElts; ++i)
2344 Mask[getAccessedFieldNo(i, Elts)] = i;
2346 Vec = Builder.CreateShuffleVector(SrcVal, Mask);
2347 } else if (NumDstElts > NumSrcElts) {
2348 // Extended the source vector to the same length and then shuffle it
2349 // into the destination.
2350 // FIXME: since we're shuffling with undef, can we just use the indices
2351 // into that? This could be simpler.
2352 SmallVector<int, 4> ExtMask;
2353 for (unsigned i = 0; i != NumSrcElts; ++i)
2354 ExtMask.push_back(i);
2355 ExtMask.resize(NumDstElts, -1);
2356 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
2357 // build identity
2358 SmallVector<int, 4> Mask;
2359 for (unsigned i = 0; i != NumDstElts; ++i)
2360 Mask.push_back(i);
2362 // When the vector size is odd and .odd or .hi is used, the last element
2363 // of the Elts constant array will be one past the size of the vector.
2364 // Ignore the last element here, if it is greater than the mask size.
2365 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2366 NumSrcElts--;
2368 // modify when what gets shuffled in
2369 for (unsigned i = 0; i != NumSrcElts; ++i)
2370 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
2371 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2372 } else {
2373 // We should never shorten the vector
2374 llvm_unreachable("unexpected shorten vector length");
2376 } else {
2377 // If the Src is a scalar (not a vector) it must be updating one element.
2378 unsigned InIdx = getAccessedFieldNo(0, Elts);
2379 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2380 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2383 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2384 Dst.isVolatileQualified());
2387 /// Store of global named registers are always calls to intrinsics.
2388 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2389 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2390 "Bad type for register variable");
2391 llvm::MDNode *RegName = cast<llvm::MDNode>(
2392 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2393 assert(RegName && "Register LValue is not metadata");
2395 // We accept integer and pointer types only
2396 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2397 llvm::Type *Ty = OrigTy;
2398 if (OrigTy->isPointerTy())
2399 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2400 llvm::Type *Types[] = { Ty };
2402 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2403 llvm::Value *Value = Src.getScalarVal();
2404 if (OrigTy->isPointerTy())
2405 Value = Builder.CreatePtrToInt(Value, Ty);
2406 Builder.CreateCall(
2407 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2410 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2411 // generating write-barries API. It is currently a global, ivar,
2412 // or neither.
2413 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2414 LValue &LV,
2415 bool IsMemberAccess=false) {
2416 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2417 return;
2419 if (isa<ObjCIvarRefExpr>(E)) {
2420 QualType ExpTy = E->getType();
2421 if (IsMemberAccess && ExpTy->isPointerType()) {
2422 // If ivar is a structure pointer, assigning to field of
2423 // this struct follows gcc's behavior and makes it a non-ivar
2424 // writer-barrier conservatively.
2425 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2426 if (ExpTy->isRecordType()) {
2427 LV.setObjCIvar(false);
2428 return;
2431 LV.setObjCIvar(true);
2432 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2433 LV.setBaseIvarExp(Exp->getBase());
2434 LV.setObjCArray(E->getType()->isArrayType());
2435 return;
2438 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2439 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2440 if (VD->hasGlobalStorage()) {
2441 LV.setGlobalObjCRef(true);
2442 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2445 LV.setObjCArray(E->getType()->isArrayType());
2446 return;
2449 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2450 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2451 return;
2454 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2455 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2456 if (LV.isObjCIvar()) {
2457 // If cast is to a structure pointer, follow gcc's behavior and make it
2458 // a non-ivar write-barrier.
2459 QualType ExpTy = E->getType();
2460 if (ExpTy->isPointerType())
2461 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2462 if (ExpTy->isRecordType())
2463 LV.setObjCIvar(false);
2465 return;
2468 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2469 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2470 return;
2473 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2474 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2475 return;
2478 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2479 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2480 return;
2483 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2484 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2485 return;
2488 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2489 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2490 if (LV.isObjCIvar() && !LV.isObjCArray())
2491 // Using array syntax to assigning to what an ivar points to is not
2492 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2493 LV.setObjCIvar(false);
2494 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2495 // Using array syntax to assigning to what global points to is not
2496 // same as assigning to the global itself. {id *G;} G[i] = 0;
2497 LV.setGlobalObjCRef(false);
2498 return;
2501 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2502 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2503 // We don't know if member is an 'ivar', but this flag is looked at
2504 // only in the context of LV.isObjCIvar().
2505 LV.setObjCArray(E->getType()->isArrayType());
2506 return;
2510 static llvm::Value *
2511 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2512 llvm::Value *V, llvm::Type *IRType,
2513 StringRef Name = StringRef()) {
2514 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2515 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2518 static LValue EmitThreadPrivateVarDeclLValue(
2519 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2520 llvm::Type *RealVarTy, SourceLocation Loc) {
2521 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
2522 Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
2523 CGF, VD, Addr, Loc);
2524 else
2525 Addr =
2526 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2528 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2529 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2532 static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
2533 const VarDecl *VD, QualType T) {
2534 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2535 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2536 // Return an invalid address if variable is MT_To (or MT_Enter starting with
2537 // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link
2538 // and MT_To (or MT_Enter) with unified memory, return a valid address.
2539 if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2540 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
2541 !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
2542 return Address::invalid();
2543 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2544 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2545 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
2546 CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
2547 "Expected link clause OR to clause with unified memory enabled.");
2548 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2549 Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2550 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
2553 Address
2554 CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2555 LValueBaseInfo *PointeeBaseInfo,
2556 TBAAAccessInfo *PointeeTBAAInfo) {
2557 llvm::LoadInst *Load =
2558 Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
2559 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2561 QualType PointeeType = RefLVal.getType()->getPointeeType();
2562 CharUnits Align = CGM.getNaturalTypeAlignment(
2563 PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
2564 /* forPointeeType= */ true);
2565 return Address(Load, ConvertTypeForMem(PointeeType), Align);
2568 LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2569 LValueBaseInfo PointeeBaseInfo;
2570 TBAAAccessInfo PointeeTBAAInfo;
2571 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2572 &PointeeTBAAInfo);
2573 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2574 PointeeBaseInfo, PointeeTBAAInfo);
2577 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2578 const PointerType *PtrTy,
2579 LValueBaseInfo *BaseInfo,
2580 TBAAAccessInfo *TBAAInfo) {
2581 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2582 return Address(Addr, ConvertTypeForMem(PtrTy->getPointeeType()),
2583 CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), BaseInfo,
2584 TBAAInfo,
2585 /*forPointeeType=*/true));
2588 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2589 const PointerType *PtrTy) {
2590 LValueBaseInfo BaseInfo;
2591 TBAAAccessInfo TBAAInfo;
2592 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2593 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2596 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2597 const Expr *E, const VarDecl *VD) {
2598 QualType T = E->getType();
2600 // If it's thread_local, emit a call to its wrapper function instead.
2601 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2602 CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
2603 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2604 // Check if the variable is marked as declare target with link clause in
2605 // device codegen.
2606 if (CGF.getLangOpts().OpenMPIsDevice) {
2607 Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
2608 if (Addr.isValid())
2609 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2612 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2614 if (VD->getTLSKind() != VarDecl::TLS_None)
2615 V = CGF.Builder.CreateThreadLocalAddress(V);
2617 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2618 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2619 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2620 Address Addr(V, RealVarTy, Alignment);
2621 // Emit reference to the private copy of the variable if it is an OpenMP
2622 // threadprivate variable.
2623 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2624 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2625 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2626 E->getExprLoc());
2628 LValue LV = VD->getType()->isReferenceType() ?
2629 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2630 AlignmentSource::Decl) :
2631 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2632 setObjCGCLValueClass(CGF.getContext(), E, LV);
2633 return LV;
2636 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2637 GlobalDecl GD) {
2638 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2639 if (FD->hasAttr<WeakRefAttr>()) {
2640 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2641 return aliasee.getPointer();
2644 llvm::Constant *V = CGM.GetAddrOfFunction(GD);
2645 if (!FD->hasPrototype()) {
2646 if (const FunctionProtoType *Proto =
2647 FD->getType()->getAs<FunctionProtoType>()) {
2648 // Ugly case: for a K&R-style definition, the type of the definition
2649 // isn't the same as the type of a use. Correct for this with a
2650 // bitcast.
2651 QualType NoProtoType =
2652 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2653 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2654 V = llvm::ConstantExpr::getBitCast(V,
2655 CGM.getTypes().ConvertType(NoProtoType));
2658 return V;
2661 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
2662 GlobalDecl GD) {
2663 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2664 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
2665 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2666 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2667 AlignmentSource::Decl);
2670 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2671 llvm::Value *ThisValue) {
2672 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2673 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2674 return CGF.EmitLValueForField(LV, FD);
2677 /// Named Registers are named metadata pointing to the register name
2678 /// which will be read from/written to as an argument to the intrinsic
2679 /// @llvm.read/write_register.
2680 /// So far, only the name is being passed down, but other options such as
2681 /// register type, allocation type or even optimization options could be
2682 /// passed down via the metadata node.
2683 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2684 SmallString<64> Name("llvm.named.register.");
2685 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2686 assert(Asm->getLabel().size() < 64-Name.size() &&
2687 "Register name too big");
2688 Name.append(Asm->getLabel());
2689 llvm::NamedMDNode *M =
2690 CGM.getModule().getOrInsertNamedMetadata(Name);
2691 if (M->getNumOperands() == 0) {
2692 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2693 Asm->getLabel());
2694 llvm::Metadata *Ops[] = {Str};
2695 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2698 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2700 llvm::Value *Ptr =
2701 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2702 return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
2705 /// Determine whether we can emit a reference to \p VD from the current
2706 /// context, despite not necessarily having seen an odr-use of the variable in
2707 /// this context.
2708 static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
2709 const DeclRefExpr *E,
2710 const VarDecl *VD,
2711 bool IsConstant) {
2712 // For a variable declared in an enclosing scope, do not emit a spurious
2713 // reference even if we have a capture, as that will emit an unwarranted
2714 // reference to our capture state, and will likely generate worse code than
2715 // emitting a local copy.
2716 if (E->refersToEnclosingVariableOrCapture())
2717 return false;
2719 // For a local declaration declared in this function, we can always reference
2720 // it even if we don't have an odr-use.
2721 if (VD->hasLocalStorage()) {
2722 return VD->getDeclContext() ==
2723 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2726 // For a global declaration, we can emit a reference to it if we know
2727 // for sure that we are able to emit a definition of it.
2728 VD = VD->getDefinition(CGF.getContext());
2729 if (!VD)
2730 return false;
2732 // Don't emit a spurious reference if it might be to a variable that only
2733 // exists on a different device / target.
2734 // FIXME: This is unnecessarily broad. Check whether this would actually be a
2735 // cross-target reference.
2736 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
2737 CGF.getLangOpts().OpenCL) {
2738 return false;
2741 // We can emit a spurious reference only if the linkage implies that we'll
2742 // be emitting a non-interposable symbol that will be retained until link
2743 // time.
2744 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
2745 case llvm::GlobalValue::ExternalLinkage:
2746 case llvm::GlobalValue::LinkOnceODRLinkage:
2747 case llvm::GlobalValue::WeakODRLinkage:
2748 case llvm::GlobalValue::InternalLinkage:
2749 case llvm::GlobalValue::PrivateLinkage:
2750 return true;
2751 default:
2752 return false;
2756 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2757 const NamedDecl *ND = E->getDecl();
2758 QualType T = E->getType();
2760 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
2761 "should not emit an unevaluated operand");
2763 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2764 // Global Named registers access via intrinsics only
2765 if (VD->getStorageClass() == SC_Register &&
2766 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2767 return EmitGlobalNamedRegister(VD, CGM);
2769 // If this DeclRefExpr does not constitute an odr-use of the variable,
2770 // we're not permitted to emit a reference to it in general, and it might
2771 // not be captured if capture would be necessary for a use. Emit the
2772 // constant value directly instead.
2773 if (E->isNonOdrUse() == NOUR_Constant &&
2774 (VD->getType()->isReferenceType() ||
2775 !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
2776 VD->getAnyInitializer(VD);
2777 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
2778 E->getLocation(), *VD->evaluateValue(), VD->getType());
2779 assert(Val && "failed to emit constant expression");
2781 Address Addr = Address::invalid();
2782 if (!VD->getType()->isReferenceType()) {
2783 // Spill the constant value to a global.
2784 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
2785 getContext().getDeclAlign(VD));
2786 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2787 auto *PTy = llvm::PointerType::get(
2788 VarTy, getTypes().getTargetAddressSpace(VD->getType()));
2789 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
2790 } else {
2791 // Should we be using the alignment of the constant pointer we emitted?
2792 CharUnits Alignment =
2793 CGM.getNaturalTypeAlignment(E->getType(),
2794 /* BaseInfo= */ nullptr,
2795 /* TBAAInfo= */ nullptr,
2796 /* forPointeeType= */ true);
2797 Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
2799 return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2802 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
2804 // Check for captured variables.
2805 if (E->refersToEnclosingVariableOrCapture()) {
2806 VD = VD->getCanonicalDecl();
2807 if (auto *FD = LambdaCaptureFields.lookup(VD))
2808 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2809 if (CapturedStmtInfo) {
2810 auto I = LocalDeclMap.find(VD);
2811 if (I != LocalDeclMap.end()) {
2812 LValue CapLVal;
2813 if (VD->getType()->isReferenceType())
2814 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
2815 AlignmentSource::Decl);
2816 else
2817 CapLVal = MakeAddrLValue(I->second, T);
2818 // Mark lvalue as nontemporal if the variable is marked as nontemporal
2819 // in simd context.
2820 if (getLangOpts().OpenMP &&
2821 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2822 CapLVal.setNontemporal(/*Value=*/true);
2823 return CapLVal;
2825 LValue CapLVal =
2826 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2827 CapturedStmtInfo->getContextValue());
2828 Address LValueAddress = CapLVal.getAddress(*this);
2829 CapLVal = MakeAddrLValue(
2830 Address(LValueAddress.getPointer(), LValueAddress.getElementType(),
2831 getContext().getDeclAlign(VD)),
2832 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2833 CapLVal.getTBAAInfo());
2834 // Mark lvalue as nontemporal if the variable is marked as nontemporal
2835 // in simd context.
2836 if (getLangOpts().OpenMP &&
2837 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2838 CapLVal.setNontemporal(/*Value=*/true);
2839 return CapLVal;
2842 assert(isa<BlockDecl>(CurCodeDecl));
2843 Address addr = GetAddrOfBlockDecl(VD);
2844 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2848 // FIXME: We should be able to assert this for FunctionDecls as well!
2849 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2850 // those with a valid source location.
2851 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
2852 !E->getLocation().isValid()) &&
2853 "Should not use decl without marking it used!");
2855 if (ND->hasAttr<WeakRefAttr>()) {
2856 const auto *VD = cast<ValueDecl>(ND);
2857 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2858 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2861 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2862 // Check if this is a global variable.
2863 if (VD->hasLinkage() || VD->isStaticDataMember())
2864 return EmitGlobalVarDeclLValue(*this, E, VD);
2866 Address addr = Address::invalid();
2868 // The variable should generally be present in the local decl map.
2869 auto iter = LocalDeclMap.find(VD);
2870 if (iter != LocalDeclMap.end()) {
2871 addr = iter->second;
2873 // Otherwise, it might be static local we haven't emitted yet for
2874 // some reason; most likely, because it's in an outer function.
2875 } else if (VD->isStaticLocal()) {
2876 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
2877 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
2878 addr = Address(
2879 var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
2881 // No other cases for now.
2882 } else {
2883 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2886 // Handle threadlocal function locals.
2887 if (VD->getTLSKind() != VarDecl::TLS_None)
2888 addr = addr.withPointer(
2889 Builder.CreateThreadLocalAddress(addr.getPointer()), NotKnownNonNull);
2891 // Check for OpenMP threadprivate variables.
2892 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2893 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2894 return EmitThreadPrivateVarDeclLValue(
2895 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2896 E->getExprLoc());
2899 // Drill into block byref variables.
2900 bool isBlockByref = VD->isEscapingByref();
2901 if (isBlockByref) {
2902 addr = emitBlockByrefAddress(addr, VD);
2905 // Drill into reference types.
2906 LValue LV = VD->getType()->isReferenceType() ?
2907 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2908 MakeAddrLValue(addr, T, AlignmentSource::Decl);
2910 bool isLocalStorage = VD->hasLocalStorage();
2912 bool NonGCable = isLocalStorage &&
2913 !VD->getType()->isReferenceType() &&
2914 !isBlockByref;
2915 if (NonGCable) {
2916 LV.getQuals().removeObjCGCAttr();
2917 LV.setNonGC(true);
2920 bool isImpreciseLifetime =
2921 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2922 if (isImpreciseLifetime)
2923 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2924 setObjCGCLValueClass(getContext(), E, LV);
2925 return LV;
2928 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2929 LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2931 // Emit debuginfo for the function declaration if the target wants to.
2932 if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2933 if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2934 auto *Fn =
2935 cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2936 if (!Fn->getSubprogram())
2937 DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2941 return LV;
2944 // FIXME: While we're emitting a binding from an enclosing scope, all other
2945 // DeclRefExprs we see should be implicitly treated as if they also refer to
2946 // an enclosing scope.
2947 if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
2948 if (E->refersToEnclosingVariableOrCapture()) {
2949 auto *FD = LambdaCaptureFields.lookup(BD);
2950 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2952 return EmitLValue(BD->getBinding());
2955 // We can form DeclRefExprs naming GUID declarations when reconstituting
2956 // non-type template parameters into expressions.
2957 if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
2958 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
2959 AlignmentSource::Decl);
2961 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2962 return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2963 AlignmentSource::Decl);
2965 llvm_unreachable("Unhandled DeclRefExpr");
2968 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2969 // __extension__ doesn't affect lvalue-ness.
2970 if (E->getOpcode() == UO_Extension)
2971 return EmitLValue(E->getSubExpr());
2973 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2974 switch (E->getOpcode()) {
2975 default: llvm_unreachable("Unknown unary operator lvalue!");
2976 case UO_Deref: {
2977 QualType T = E->getSubExpr()->getType()->getPointeeType();
2978 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2980 LValueBaseInfo BaseInfo;
2981 TBAAAccessInfo TBAAInfo;
2982 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2983 &TBAAInfo);
2984 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2985 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2987 // We should not generate __weak write barrier on indirect reference
2988 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2989 // But, we continue to generate __strong write barrier on indirect write
2990 // into a pointer to object.
2991 if (getLangOpts().ObjC &&
2992 getLangOpts().getGC() != LangOptions::NonGC &&
2993 LV.isObjCWeak())
2994 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2995 return LV;
2997 case UO_Real:
2998 case UO_Imag: {
2999 LValue LV = EmitLValue(E->getSubExpr());
3000 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3002 // __real is valid on scalars. This is a faster way of testing that.
3003 // __imag can only produce an rvalue on scalars.
3004 if (E->getOpcode() == UO_Real &&
3005 !LV.getAddress(*this).getElementType()->isStructTy()) {
3006 assert(E->getSubExpr()->getType()->isArithmeticType());
3007 return LV;
3010 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3012 Address Component =
3013 (E->getOpcode() == UO_Real
3014 ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
3015 : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
3016 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
3017 CGM.getTBAAInfoForSubobject(LV, T));
3018 ElemLV.getQuals().addQualifiers(LV.getQuals());
3019 return ElemLV;
3021 case UO_PreInc:
3022 case UO_PreDec: {
3023 LValue LV = EmitLValue(E->getSubExpr());
3024 bool isInc = E->getOpcode() == UO_PreInc;
3026 if (E->getType()->isAnyComplexType())
3027 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3028 else
3029 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3030 return LV;
3035 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
3036 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
3037 E->getType(), AlignmentSource::Decl);
3040 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
3041 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
3042 E->getType(), AlignmentSource::Decl);
3045 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
3046 auto SL = E->getFunctionName();
3047 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3048 StringRef FnName = CurFn->getName();
3049 if (FnName.startswith("\01"))
3050 FnName = FnName.substr(1);
3051 StringRef NameItems[] = {
3052 PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
3053 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3054 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3055 std::string Name = std::string(SL->getString());
3056 if (!Name.empty()) {
3057 unsigned Discriminator =
3058 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
3059 if (Discriminator)
3060 Name += "_" + Twine(Discriminator + 1).str();
3061 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
3062 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3063 } else {
3064 auto C =
3065 CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
3066 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3069 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3070 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3073 /// Emit a type description suitable for use by a runtime sanitizer library. The
3074 /// format of a type descriptor is
3076 /// \code
3077 /// { i16 TypeKind, i16 TypeInfo }
3078 /// \endcode
3080 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
3081 /// integer, 1 for a floating point value, and -1 for anything else.
3082 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
3083 // Only emit each type's descriptor once.
3084 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3085 return C;
3087 uint16_t TypeKind = -1;
3088 uint16_t TypeInfo = 0;
3090 if (T->isIntegerType()) {
3091 TypeKind = 0;
3092 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3093 (T->isSignedIntegerType() ? 1 : 0);
3094 } else if (T->isFloatingType()) {
3095 TypeKind = 1;
3096 TypeInfo = getContext().getTypeSize(T);
3099 // Format the type name as if for a diagnostic, including quotes and
3100 // optionally an 'aka'.
3101 SmallString<32> Buffer;
3102 CGM.getDiags().ConvertArgToString(
3103 DiagnosticsEngine::ak_qualtype, (intptr_t)T.getAsOpaquePtr(), StringRef(),
3104 StringRef(), std::nullopt, Buffer, std::nullopt);
3106 llvm::Constant *Components[] = {
3107 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3108 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3110 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3112 auto *GV = new llvm::GlobalVariable(
3113 CGM.getModule(), Descriptor->getType(),
3114 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3115 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3116 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3118 // Remember the descriptor for this type.
3119 CGM.setTypeDescriptorInMap(T, GV);
3121 return GV;
3124 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3125 llvm::Type *TargetTy = IntPtrTy;
3127 if (V->getType() == TargetTy)
3128 return V;
3130 // Floating-point types which fit into intptr_t are bitcast to integers
3131 // and then passed directly (after zero-extension, if necessary).
3132 if (V->getType()->isFloatingPointTy()) {
3133 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
3134 if (Bits <= TargetTy->getIntegerBitWidth())
3135 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
3136 Bits));
3139 // Integers which fit in intptr_t are zero-extended and passed directly.
3140 if (V->getType()->isIntegerTy() &&
3141 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
3142 return Builder.CreateZExt(V, TargetTy);
3144 // Pointers are passed directly, everything else is passed by address.
3145 if (!V->getType()->isPointerTy()) {
3146 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
3147 Builder.CreateStore(V, Ptr);
3148 V = Ptr.getPointer();
3150 return Builder.CreatePtrToInt(V, TargetTy);
3153 /// Emit a representation of a SourceLocation for passing to a handler
3154 /// in a sanitizer runtime library. The format for this data is:
3155 /// \code
3156 /// struct SourceLocation {
3157 /// const char *Filename;
3158 /// int32_t Line, Column;
3159 /// };
3160 /// \endcode
3161 /// For an invalid SourceLocation, the Filename pointer is null.
3162 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
3163 llvm::Constant *Filename;
3164 int Line, Column;
3166 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
3167 if (PLoc.isValid()) {
3168 StringRef FilenameString = PLoc.getFilename();
3170 int PathComponentsToStrip =
3171 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3172 if (PathComponentsToStrip < 0) {
3173 assert(PathComponentsToStrip != INT_MIN);
3174 int PathComponentsToKeep = -PathComponentsToStrip;
3175 auto I = llvm::sys::path::rbegin(FilenameString);
3176 auto E = llvm::sys::path::rend(FilenameString);
3177 while (I != E && --PathComponentsToKeep)
3178 ++I;
3180 FilenameString = FilenameString.substr(I - E);
3181 } else if (PathComponentsToStrip > 0) {
3182 auto I = llvm::sys::path::begin(FilenameString);
3183 auto E = llvm::sys::path::end(FilenameString);
3184 while (I != E && PathComponentsToStrip--)
3185 ++I;
3187 if (I != E)
3188 FilenameString =
3189 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3190 else
3191 FilenameString = llvm::sys::path::filename(FilenameString);
3194 auto FilenameGV =
3195 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3196 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3197 cast<llvm::GlobalVariable>(
3198 FilenameGV.getPointer()->stripPointerCasts()));
3199 Filename = FilenameGV.getPointer();
3200 Line = PLoc.getLine();
3201 Column = PLoc.getColumn();
3202 } else {
3203 Filename = llvm::Constant::getNullValue(Int8PtrTy);
3204 Line = Column = 0;
3207 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3208 Builder.getInt32(Column)};
3210 return llvm::ConstantStruct::getAnon(Data);
3213 namespace {
3214 /// Specify under what conditions this check can be recovered
3215 enum class CheckRecoverableKind {
3216 /// Always terminate program execution if this check fails.
3217 Unrecoverable,
3218 /// Check supports recovering, runtime has both fatal (noreturn) and
3219 /// non-fatal handlers for this check.
3220 Recoverable,
3221 /// Runtime conditionally aborts, always need to support recovery.
3222 AlwaysRecoverable
3226 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
3227 assert(Kind.countPopulation() == 1);
3228 if (Kind == SanitizerKind::Vptr)
3229 return CheckRecoverableKind::AlwaysRecoverable;
3230 else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
3231 return CheckRecoverableKind::Unrecoverable;
3232 else
3233 return CheckRecoverableKind::Recoverable;
3236 namespace {
3237 struct SanitizerHandlerInfo {
3238 char const *const Name;
3239 unsigned Version;
3243 const SanitizerHandlerInfo SanitizerHandlers[] = {
3244 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
3245 LIST_SANITIZER_CHECKS
3246 #undef SANITIZER_CHECK
3249 static void emitCheckHandlerCall(CodeGenFunction &CGF,
3250 llvm::FunctionType *FnType,
3251 ArrayRef<llvm::Value *> FnArgs,
3252 SanitizerHandler CheckHandler,
3253 CheckRecoverableKind RecoverKind, bool IsFatal,
3254 llvm::BasicBlock *ContBB) {
3255 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3256 std::optional<ApplyDebugLocation> DL;
3257 if (!CGF.Builder.getCurrentDebugLocation()) {
3258 // Ensure that the call has at least an artificial debug location.
3259 DL.emplace(CGF, SourceLocation());
3261 bool NeedsAbortSuffix =
3262 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
3263 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3264 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3265 const StringRef CheckName = CheckInfo.Name;
3266 std::string FnName = "__ubsan_handle_" + CheckName.str();
3267 if (CheckInfo.Version && !MinimalRuntime)
3268 FnName += "_v" + llvm::utostr(CheckInfo.Version);
3269 if (MinimalRuntime)
3270 FnName += "_minimal";
3271 if (NeedsAbortSuffix)
3272 FnName += "_abort";
3273 bool MayReturn =
3274 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3276 llvm::AttrBuilder B(CGF.getLLVMContext());
3277 if (!MayReturn) {
3278 B.addAttribute(llvm::Attribute::NoReturn)
3279 .addAttribute(llvm::Attribute::NoUnwind);
3281 B.addUWTableAttr(llvm::UWTableKind::Default);
3283 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3284 FnType, FnName,
3285 llvm::AttributeList::get(CGF.getLLVMContext(),
3286 llvm::AttributeList::FunctionIndex, B),
3287 /*Local=*/true);
3288 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3289 if (!MayReturn) {
3290 HandlerCall->setDoesNotReturn();
3291 CGF.Builder.CreateUnreachable();
3292 } else {
3293 CGF.Builder.CreateBr(ContBB);
3297 void CodeGenFunction::EmitCheck(
3298 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3299 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3300 ArrayRef<llvm::Value *> DynamicArgs) {
3301 assert(IsSanitizerScope);
3302 assert(Checked.size() > 0);
3303 assert(CheckHandler >= 0 &&
3304 size_t(CheckHandler) < std::size(SanitizerHandlers));
3305 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3307 llvm::Value *FatalCond = nullptr;
3308 llvm::Value *RecoverableCond = nullptr;
3309 llvm::Value *TrapCond = nullptr;
3310 for (int i = 0, n = Checked.size(); i < n; ++i) {
3311 llvm::Value *Check = Checked[i].first;
3312 // -fsanitize-trap= overrides -fsanitize-recover=.
3313 llvm::Value *&Cond =
3314 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3315 ? TrapCond
3316 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
3317 ? RecoverableCond
3318 : FatalCond;
3319 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
3322 if (TrapCond)
3323 EmitTrapCheck(TrapCond, CheckHandler);
3324 if (!FatalCond && !RecoverableCond)
3325 return;
3327 llvm::Value *JointCond;
3328 if (FatalCond && RecoverableCond)
3329 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3330 else
3331 JointCond = FatalCond ? FatalCond : RecoverableCond;
3332 assert(JointCond);
3334 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3335 assert(SanOpts.has(Checked[0].second));
3336 #ifndef NDEBUG
3337 for (int i = 1, n = Checked.size(); i < n; ++i) {
3338 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3339 "All recoverable kinds in a single check must be same!");
3340 assert(SanOpts.has(Checked[i].second));
3342 #endif
3344 llvm::BasicBlock *Cont = createBasicBlock("cont");
3345 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3346 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3347 // Give hint that we very much don't expect to execute the handler
3348 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
3349 llvm::MDBuilder MDHelper(getLLVMContext());
3350 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3351 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3352 EmitBlock(Handlers);
3354 // Handler functions take an i8* pointing to the (handler-specific) static
3355 // information block, followed by a sequence of intptr_t arguments
3356 // representing operand values.
3357 SmallVector<llvm::Value *, 4> Args;
3358 SmallVector<llvm::Type *, 4> ArgTypes;
3359 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3360 Args.reserve(DynamicArgs.size() + 1);
3361 ArgTypes.reserve(DynamicArgs.size() + 1);
3363 // Emit handler arguments and create handler function type.
3364 if (!StaticArgs.empty()) {
3365 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3366 auto *InfoPtr = new llvm::GlobalVariable(
3367 CGM.getModule(), Info->getType(), false,
3368 llvm::GlobalVariable::PrivateLinkage, Info, "", nullptr,
3369 llvm::GlobalVariable::NotThreadLocal,
3370 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
3371 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3372 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3373 Args.push_back(EmitCastToVoidPtr(InfoPtr));
3374 ArgTypes.push_back(Args.back()->getType());
3377 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3378 Args.push_back(EmitCheckValue(DynamicArgs[i]));
3379 ArgTypes.push_back(IntPtrTy);
3383 llvm::FunctionType *FnType =
3384 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
3386 if (!FatalCond || !RecoverableCond) {
3387 // Simple case: we need to generate a single handler call, either
3388 // fatal, or non-fatal.
3389 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
3390 (FatalCond != nullptr), Cont);
3391 } else {
3392 // Emit two handler calls: first one for set of unrecoverable checks,
3393 // another one for recoverable.
3394 llvm::BasicBlock *NonFatalHandlerBB =
3395 createBasicBlock("non_fatal." + CheckName);
3396 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3397 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3398 EmitBlock(FatalHandlerBB);
3399 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
3400 NonFatalHandlerBB);
3401 EmitBlock(NonFatalHandlerBB);
3402 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
3403 Cont);
3406 EmitBlock(Cont);
3409 void CodeGenFunction::EmitCfiSlowPathCheck(
3410 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3411 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
3412 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3414 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3415 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3417 llvm::MDBuilder MDHelper(getLLVMContext());
3418 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3419 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3421 EmitBlock(CheckBB);
3423 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3425 llvm::CallInst *CheckCall;
3426 llvm::FunctionCallee SlowPathFn;
3427 if (WithDiag) {
3428 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3429 auto *InfoPtr =
3430 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3431 llvm::GlobalVariable::PrivateLinkage, Info);
3432 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3433 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3435 SlowPathFn = CGM.getModule().getOrInsertFunction(
3436 "__cfi_slowpath_diag",
3437 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3438 false));
3439 CheckCall = Builder.CreateCall(
3440 SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
3441 } else {
3442 SlowPathFn = CGM.getModule().getOrInsertFunction(
3443 "__cfi_slowpath",
3444 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3445 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3448 CGM.setDSOLocal(
3449 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
3450 CheckCall->setDoesNotThrow();
3452 EmitBlock(Cont);
3455 // Emit a stub for __cfi_check function so that the linker knows about this
3456 // symbol in LTO mode.
3457 void CodeGenFunction::EmitCfiCheckStub() {
3458 llvm::Module *M = &CGM.getModule();
3459 auto &Ctx = M->getContext();
3460 llvm::Function *F = llvm::Function::Create(
3461 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3462 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3463 CGM.setDSOLocal(F);
3464 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3465 // FIXME: consider emitting an intrinsic call like
3466 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
3467 // which can be lowered in CrossDSOCFI pass to the actual contents of
3468 // __cfi_check. This would allow inlining of __cfi_check calls.
3469 llvm::CallInst::Create(
3470 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
3471 llvm::ReturnInst::Create(Ctx, nullptr, BB);
3474 // This function is basically a switch over the CFI failure kind, which is
3475 // extracted from CFICheckFailData (1st function argument). Each case is either
3476 // llvm.trap or a call to one of the two runtime handlers, based on
3477 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
3478 // failure kind) traps, but this should really never happen. CFICheckFailData
3479 // can be nullptr if the calling module has -fsanitize-trap behavior for this
3480 // check kind; in this case __cfi_check_fail traps as well.
3481 void CodeGenFunction::EmitCfiCheckFail() {
3482 SanitizerScope SanScope(this);
3483 FunctionArgList Args;
3484 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3485 ImplicitParamDecl::Other);
3486 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3487 ImplicitParamDecl::Other);
3488 Args.push_back(&ArgData);
3489 Args.push_back(&ArgAddr);
3491 const CGFunctionInfo &FI =
3492 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3494 llvm::Function *F = llvm::Function::Create(
3495 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3496 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3498 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3499 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
3500 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3502 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3503 SourceLocation());
3505 // This function is not affected by NoSanitizeList. This function does
3506 // not have a source location, but "src:*" would still apply. Revert any
3507 // changes to SanOpts made in StartFunction.
3508 SanOpts = CGM.getLangOpts().Sanitize;
3510 llvm::Value *Data =
3511 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3512 CGM.getContext().VoidPtrTy, ArgData.getLocation());
3513 llvm::Value *Addr =
3514 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3515 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3517 // Data == nullptr means the calling module has trap behaviour for this check.
3518 llvm::Value *DataIsNotNullPtr =
3519 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3520 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
3522 llvm::StructType *SourceLocationTy =
3523 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3524 llvm::StructType *CfiCheckFailDataTy =
3525 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3527 llvm::Value *V = Builder.CreateConstGEP2_32(
3528 CfiCheckFailDataTy,
3529 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3532 Address CheckKindAddr(V, Int8Ty, getIntAlign());
3533 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3535 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3536 CGM.getLLVMContext(),
3537 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3538 llvm::Value *ValidVtable = Builder.CreateZExt(
3539 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3540 {Addr, AllVtables}),
3541 IntPtrTy);
3543 const std::pair<int, SanitizerMask> CheckKinds[] = {
3544 {CFITCK_VCall, SanitizerKind::CFIVCall},
3545 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3546 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3547 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3548 {CFITCK_ICall, SanitizerKind::CFIICall}};
3550 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3551 for (auto CheckKindMaskPair : CheckKinds) {
3552 int Kind = CheckKindMaskPair.first;
3553 SanitizerMask Mask = CheckKindMaskPair.second;
3554 llvm::Value *Cond =
3555 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3556 if (CGM.getLangOpts().Sanitize.has(Mask))
3557 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3558 {Data, Addr, ValidVtable});
3559 else
3560 EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
3563 FinishFunction();
3564 // The only reference to this function will be created during LTO link.
3565 // Make sure it survives until then.
3566 CGM.addUsedGlobal(F);
3569 void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3570 if (SanOpts.has(SanitizerKind::Unreachable)) {
3571 SanitizerScope SanScope(this);
3572 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3573 SanitizerKind::Unreachable),
3574 SanitizerHandler::BuiltinUnreachable,
3575 EmitCheckSourceLocation(Loc), std::nullopt);
3577 Builder.CreateUnreachable();
3580 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3581 SanitizerHandler CheckHandlerID) {
3582 llvm::BasicBlock *Cont = createBasicBlock("cont");
3584 // If we're optimizing, collapse all calls to trap down to just one per
3585 // check-type per function to save on code size.
3586 if (TrapBBs.size() <= CheckHandlerID)
3587 TrapBBs.resize(CheckHandlerID + 1);
3588 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3590 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB ||
3591 (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>())) {
3592 TrapBB = createBasicBlock("trap");
3593 Builder.CreateCondBr(Checked, Cont, TrapBB);
3594 EmitBlock(TrapBB);
3596 llvm::CallInst *TrapCall =
3597 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3598 llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3600 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3601 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3602 CGM.getCodeGenOpts().TrapFuncName);
3603 TrapCall->addFnAttr(A);
3605 TrapCall->setDoesNotReturn();
3606 TrapCall->setDoesNotThrow();
3607 Builder.CreateUnreachable();
3608 } else {
3609 auto Call = TrapBB->begin();
3610 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3612 Call->applyMergedLocation(Call->getDebugLoc(),
3613 Builder.getCurrentDebugLocation());
3614 Builder.CreateCondBr(Checked, Cont, TrapBB);
3617 EmitBlock(Cont);
3620 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3621 llvm::CallInst *TrapCall =
3622 Builder.CreateCall(CGM.getIntrinsic(IntrID));
3624 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3625 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3626 CGM.getCodeGenOpts().TrapFuncName);
3627 TrapCall->addFnAttr(A);
3630 return TrapCall;
3633 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3634 LValueBaseInfo *BaseInfo,
3635 TBAAAccessInfo *TBAAInfo) {
3636 assert(E->getType()->isArrayType() &&
3637 "Array to pointer decay must have array source type!");
3639 // Expressions of array type can't be bitfields or vector elements.
3640 LValue LV = EmitLValue(E);
3641 Address Addr = LV.getAddress(*this);
3643 // If the array type was an incomplete type, we need to make sure
3644 // the decay ends up being the right type.
3645 llvm::Type *NewTy = ConvertType(E->getType());
3646 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3648 // Note that VLA pointers are always decayed, so we don't need to do
3649 // anything here.
3650 if (!E->getType()->isVariableArrayType()) {
3651 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3652 "Expected pointer to array");
3653 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3656 // The result of this decay conversion points to an array element within the
3657 // base lvalue. However, since TBAA currently does not support representing
3658 // accesses to elements of member arrays, we conservatively represent accesses
3659 // to the pointee object as if it had no any base lvalue specified.
3660 // TODO: Support TBAA for member arrays.
3661 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3662 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3663 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3665 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3668 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3669 /// array to pointer, return the array subexpression.
3670 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3671 // If this isn't just an array->pointer decay, bail out.
3672 const auto *CE = dyn_cast<CastExpr>(E);
3673 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3674 return nullptr;
3676 // If this is a decay from variable width array, bail out.
3677 const Expr *SubExpr = CE->getSubExpr();
3678 if (SubExpr->getType()->isVariableArrayType())
3679 return nullptr;
3681 return SubExpr;
3684 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3685 llvm::Type *elemType,
3686 llvm::Value *ptr,
3687 ArrayRef<llvm::Value*> indices,
3688 bool inbounds,
3689 bool signedIndices,
3690 SourceLocation loc,
3691 const llvm::Twine &name = "arrayidx") {
3692 if (inbounds) {
3693 return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
3694 CodeGenFunction::NotSubtraction, loc,
3695 name);
3696 } else {
3697 return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
3701 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3702 llvm::Value *idx,
3703 CharUnits eltSize) {
3704 // If we have a constant index, we can use the exact offset of the
3705 // element we're accessing.
3706 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3707 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3708 return arrayAlign.alignmentAtOffset(offset);
3710 // Otherwise, use the worst-case alignment for any element.
3711 } else {
3712 return arrayAlign.alignmentOfArrayElement(eltSize);
3716 static QualType getFixedSizeElementType(const ASTContext &ctx,
3717 const VariableArrayType *vla) {
3718 QualType eltType;
3719 do {
3720 eltType = vla->getElementType();
3721 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3722 return eltType;
3725 /// Given an array base, check whether its member access belongs to a record
3726 /// with preserve_access_index attribute or not.
3727 static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3728 if (!ArrayBase || !CGF.getDebugInfo())
3729 return false;
3731 // Only support base as either a MemberExpr or DeclRefExpr.
3732 // DeclRefExpr to cover cases like:
3733 // struct s { int a; int b[10]; };
3734 // struct s *p;
3735 // p[1].a
3736 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3737 // p->b[5] is a MemberExpr example.
3738 const Expr *E = ArrayBase->IgnoreImpCasts();
3739 if (const auto *ME = dyn_cast<MemberExpr>(E))
3740 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3742 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3743 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3744 if (!VarDef)
3745 return false;
3747 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3748 if (!PtrT)
3749 return false;
3751 const auto *PointeeT = PtrT->getPointeeType()
3752 ->getUnqualifiedDesugaredType();
3753 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3754 return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3755 return false;
3758 return false;
3761 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3762 ArrayRef<llvm::Value *> indices,
3763 QualType eltType, bool inbounds,
3764 bool signedIndices, SourceLocation loc,
3765 QualType *arrayType = nullptr,
3766 const Expr *Base = nullptr,
3767 const llvm::Twine &name = "arrayidx") {
3768 // All the indices except that last must be zero.
3769 #ifndef NDEBUG
3770 for (auto *idx : indices.drop_back())
3771 assert(isa<llvm::ConstantInt>(idx) &&
3772 cast<llvm::ConstantInt>(idx)->isZero());
3773 #endif
3775 // Determine the element size of the statically-sized base. This is
3776 // the thing that the indices are expressed in terms of.
3777 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3778 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3781 // We can use that to compute the best alignment of the element.
3782 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3783 CharUnits eltAlign =
3784 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3786 llvm::Value *eltPtr;
3787 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3788 if (!LastIndex ||
3789 (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
3790 eltPtr = emitArraySubscriptGEP(
3791 CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3792 signedIndices, loc, name);
3793 } else {
3794 // Remember the original array subscript for bpf target
3795 unsigned idx = LastIndex->getZExtValue();
3796 llvm::DIType *DbgInfo = nullptr;
3797 if (arrayType)
3798 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3799 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3800 addr.getPointer(),
3801 indices.size() - 1,
3802 idx, DbgInfo);
3805 return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
3808 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3809 bool Accessed) {
3810 // The index must always be an integer, which is not an aggregate. Emit it
3811 // in lexical order (this complexity is, sadly, required by C++17).
3812 llvm::Value *IdxPre =
3813 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3814 bool SignedIndices = false;
3815 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3816 auto *Idx = IdxPre;
3817 if (E->getLHS() != E->getIdx()) {
3818 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3819 Idx = EmitScalarExpr(E->getIdx());
3822 QualType IdxTy = E->getIdx()->getType();
3823 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3824 SignedIndices |= IdxSigned;
3826 if (SanOpts.has(SanitizerKind::ArrayBounds))
3827 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3829 // Extend or truncate the index type to 32 or 64-bits.
3830 if (Promote && Idx->getType() != IntPtrTy)
3831 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3833 return Idx;
3835 IdxPre = nullptr;
3837 // If the base is a vector type, then we are forming a vector element lvalue
3838 // with this subscript.
3839 if (E->getBase()->getType()->isVectorType() &&
3840 !isa<ExtVectorElementExpr>(E->getBase())) {
3841 // Emit the vector as an lvalue to get its address.
3842 LValue LHS = EmitLValue(E->getBase());
3843 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3844 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3845 return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3846 E->getBase()->getType(), LHS.getBaseInfo(),
3847 TBAAAccessInfo());
3850 // All the other cases basically behave like simple offsetting.
3852 // Handle the extvector case we ignored above.
3853 if (isa<ExtVectorElementExpr>(E->getBase())) {
3854 LValue LV = EmitLValue(E->getBase());
3855 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3856 Address Addr = EmitExtVectorElementLValue(LV);
3858 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3859 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3860 SignedIndices, E->getExprLoc());
3861 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3862 CGM.getTBAAInfoForSubobject(LV, EltType));
3865 LValueBaseInfo EltBaseInfo;
3866 TBAAAccessInfo EltTBAAInfo;
3867 Address Addr = Address::invalid();
3868 if (const VariableArrayType *vla =
3869 getContext().getAsVariableArrayType(E->getType())) {
3870 // The base must be a pointer, which is not an aggregate. Emit
3871 // it. It needs to be emitted first in case it's what captures
3872 // the VLA bounds.
3873 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3874 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3876 // The element count here is the total number of non-VLA elements.
3877 llvm::Value *numElements = getVLASize(vla).NumElts;
3879 // Effectively, the multiply by the VLA size is part of the GEP.
3880 // GEP indexes are signed, and scaling an index isn't permitted to
3881 // signed-overflow, so we use the same semantics for our explicit
3882 // multiply. We suppress this if overflow is not undefined behavior.
3883 if (getLangOpts().isSignedOverflowDefined()) {
3884 Idx = Builder.CreateMul(Idx, numElements);
3885 } else {
3886 Idx = Builder.CreateNSWMul(Idx, numElements);
3889 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3890 !getLangOpts().isSignedOverflowDefined(),
3891 SignedIndices, E->getExprLoc());
3893 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3894 // Indexing over an interface, as in "NSString *P; P[4];"
3896 // Emit the base pointer.
3897 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3898 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3900 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3901 llvm::Value *InterfaceSizeVal =
3902 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3904 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3906 // We don't necessarily build correct LLVM struct types for ObjC
3907 // interfaces, so we can't rely on GEP to do this scaling
3908 // correctly, so we need to cast to i8*. FIXME: is this actually
3909 // true? A lot of other things in the fragile ABI would break...
3910 llvm::Type *OrigBaseElemTy = Addr.getElementType();
3911 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3913 // Do the GEP.
3914 CharUnits EltAlign =
3915 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3916 llvm::Value *EltPtr =
3917 emitArraySubscriptGEP(*this, Addr.getElementType(), Addr.getPointer(),
3918 ScaledIdx, false, SignedIndices, E->getExprLoc());
3919 Addr = Address(EltPtr, Addr.getElementType(), EltAlign);
3921 // Cast back.
3922 Addr = Builder.CreateElementBitCast(Addr, OrigBaseElemTy);
3923 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3924 // If this is A[i] where A is an array, the frontend will have decayed the
3925 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3926 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3927 // "gep x, i" here. Emit one "gep A, 0, i".
3928 assert(Array->getType()->isArrayType() &&
3929 "Array to pointer decay must have array source type!");
3930 LValue ArrayLV;
3931 // For simple multidimensional array indexing, set the 'accessed' flag for
3932 // better bounds-checking of the base expression.
3933 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3934 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3935 else
3936 ArrayLV = EmitLValue(Array);
3937 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3939 // Propagate the alignment from the array itself to the result.
3940 QualType arrayType = Array->getType();
3941 Addr = emitArraySubscriptGEP(
3942 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
3943 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3944 E->getExprLoc(), &arrayType, E->getBase());
3945 EltBaseInfo = ArrayLV.getBaseInfo();
3946 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3947 } else {
3948 // The base must be a pointer; emit it with an estimate of its alignment.
3949 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3950 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3951 QualType ptrType = E->getBase()->getType();
3952 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3953 !getLangOpts().isSignedOverflowDefined(),
3954 SignedIndices, E->getExprLoc(), &ptrType,
3955 E->getBase());
3958 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3960 if (getLangOpts().ObjC &&
3961 getLangOpts().getGC() != LangOptions::NonGC) {
3962 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3963 setObjCGCLValueClass(getContext(), E, LV);
3965 return LV;
3968 LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
3969 assert(
3970 !E->isIncomplete() &&
3971 "incomplete matrix subscript expressions should be rejected during Sema");
3972 LValue Base = EmitLValue(E->getBase());
3973 llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
3974 llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
3975 llvm::Value *NumRows = Builder.getIntN(
3976 RowIdx->getType()->getScalarSizeInBits(),
3977 E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
3978 llvm::Value *FinalIdx =
3979 Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
3980 return LValue::MakeMatrixElt(
3981 MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
3982 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
3985 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3986 LValueBaseInfo &BaseInfo,
3987 TBAAAccessInfo &TBAAInfo,
3988 QualType BaseTy, QualType ElTy,
3989 bool IsLowerBound) {
3990 LValue BaseLVal;
3991 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3992 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3993 if (BaseTy->isArrayType()) {
3994 Address Addr = BaseLVal.getAddress(CGF);
3995 BaseInfo = BaseLVal.getBaseInfo();
3997 // If the array type was an incomplete type, we need to make sure
3998 // the decay ends up being the right type.
3999 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
4000 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
4002 // Note that VLA pointers are always decayed, so we don't need to do
4003 // anything here.
4004 if (!BaseTy->isVariableArrayType()) {
4005 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4006 "Expected pointer to array");
4007 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4010 return CGF.Builder.CreateElementBitCast(Addr,
4011 CGF.ConvertTypeForMem(ElTy));
4013 LValueBaseInfo TypeBaseInfo;
4014 TBAAAccessInfo TypeTBAAInfo;
4015 CharUnits Align =
4016 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
4017 BaseInfo.mergeForCast(TypeBaseInfo);
4018 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
4019 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)),
4020 CGF.ConvertTypeForMem(ElTy), Align);
4022 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
4025 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
4026 bool IsLowerBound) {
4027 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
4028 QualType ResultExprTy;
4029 if (auto *AT = getContext().getAsArrayType(BaseTy))
4030 ResultExprTy = AT->getElementType();
4031 else
4032 ResultExprTy = BaseTy->getPointeeType();
4033 llvm::Value *Idx = nullptr;
4034 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
4035 // Requesting lower bound or upper bound, but without provided length and
4036 // without ':' symbol for the default length -> length = 1.
4037 // Idx = LowerBound ?: 0;
4038 if (auto *LowerBound = E->getLowerBound()) {
4039 Idx = Builder.CreateIntCast(
4040 EmitScalarExpr(LowerBound), IntPtrTy,
4041 LowerBound->getType()->hasSignedIntegerRepresentation());
4042 } else
4043 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
4044 } else {
4045 // Try to emit length or lower bound as constant. If this is possible, 1
4046 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
4047 // IR (LB + Len) - 1.
4048 auto &C = CGM.getContext();
4049 auto *Length = E->getLength();
4050 llvm::APSInt ConstLength;
4051 if (Length) {
4052 // Idx = LowerBound + Length - 1;
4053 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4054 ConstLength = CL->zextOrTrunc(PointerWidthInBits);
4055 Length = nullptr;
4057 auto *LowerBound = E->getLowerBound();
4058 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4059 if (LowerBound) {
4060 if (std::optional<llvm::APSInt> LB =
4061 LowerBound->getIntegerConstantExpr(C)) {
4062 ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
4063 LowerBound = nullptr;
4066 if (!Length)
4067 --ConstLength;
4068 else if (!LowerBound)
4069 --ConstLowerBound;
4071 if (Length || LowerBound) {
4072 auto *LowerBoundVal =
4073 LowerBound
4074 ? Builder.CreateIntCast(
4075 EmitScalarExpr(LowerBound), IntPtrTy,
4076 LowerBound->getType()->hasSignedIntegerRepresentation())
4077 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
4078 auto *LengthVal =
4079 Length
4080 ? Builder.CreateIntCast(
4081 EmitScalarExpr(Length), IntPtrTy,
4082 Length->getType()->hasSignedIntegerRepresentation())
4083 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
4084 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
4085 /*HasNUW=*/false,
4086 !getLangOpts().isSignedOverflowDefined());
4087 if (Length && LowerBound) {
4088 Idx = Builder.CreateSub(
4089 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
4090 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4092 } else
4093 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
4094 } else {
4095 // Idx = ArraySize - 1;
4096 QualType ArrayTy = BaseTy->isPointerType()
4097 ? E->getBase()->IgnoreParenImpCasts()->getType()
4098 : BaseTy;
4099 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
4100 Length = VAT->getSizeExpr();
4101 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4102 ConstLength = *L;
4103 Length = nullptr;
4105 } else {
4106 auto *CAT = C.getAsConstantArrayType(ArrayTy);
4107 assert(CAT && "unexpected type for array initializer");
4108 ConstLength = CAT->getSize();
4110 if (Length) {
4111 auto *LengthVal = Builder.CreateIntCast(
4112 EmitScalarExpr(Length), IntPtrTy,
4113 Length->getType()->hasSignedIntegerRepresentation());
4114 Idx = Builder.CreateSub(
4115 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
4116 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4117 } else {
4118 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
4119 --ConstLength;
4120 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
4124 assert(Idx);
4126 Address EltPtr = Address::invalid();
4127 LValueBaseInfo BaseInfo;
4128 TBAAAccessInfo TBAAInfo;
4129 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
4130 // The base must be a pointer, which is not an aggregate. Emit
4131 // it. It needs to be emitted first in case it's what captures
4132 // the VLA bounds.
4133 Address Base =
4134 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
4135 BaseTy, VLA->getElementType(), IsLowerBound);
4136 // The element count here is the total number of non-VLA elements.
4137 llvm::Value *NumElements = getVLASize(VLA).NumElts;
4139 // Effectively, the multiply by the VLA size is part of the GEP.
4140 // GEP indexes are signed, and scaling an index isn't permitted to
4141 // signed-overflow, so we use the same semantics for our explicit
4142 // multiply. We suppress this if overflow is not undefined behavior.
4143 if (getLangOpts().isSignedOverflowDefined())
4144 Idx = Builder.CreateMul(Idx, NumElements);
4145 else
4146 Idx = Builder.CreateNSWMul(Idx, NumElements);
4147 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
4148 !getLangOpts().isSignedOverflowDefined(),
4149 /*signedIndices=*/false, E->getExprLoc());
4150 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4151 // If this is A[i] where A is an array, the frontend will have decayed the
4152 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
4153 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4154 // "gep x, i" here. Emit one "gep A, 0, i".
4155 assert(Array->getType()->isArrayType() &&
4156 "Array to pointer decay must have array source type!");
4157 LValue ArrayLV;
4158 // For simple multidimensional array indexing, set the 'accessed' flag for
4159 // better bounds-checking of the base expression.
4160 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4161 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4162 else
4163 ArrayLV = EmitLValue(Array);
4165 // Propagate the alignment from the array itself to the result.
4166 EltPtr = emitArraySubscriptGEP(
4167 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
4168 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
4169 /*signedIndices=*/false, E->getExprLoc());
4170 BaseInfo = ArrayLV.getBaseInfo();
4171 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
4172 } else {
4173 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
4174 TBAAInfo, BaseTy, ResultExprTy,
4175 IsLowerBound);
4176 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
4177 !getLangOpts().isSignedOverflowDefined(),
4178 /*signedIndices=*/false, E->getExprLoc());
4181 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
4184 LValue CodeGenFunction::
4185 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
4186 // Emit the base vector as an l-value.
4187 LValue Base;
4189 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
4190 if (E->isArrow()) {
4191 // If it is a pointer to a vector, emit the address and form an lvalue with
4192 // it.
4193 LValueBaseInfo BaseInfo;
4194 TBAAAccessInfo TBAAInfo;
4195 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4196 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
4197 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
4198 Base.getQuals().removeObjCGCAttr();
4199 } else if (E->getBase()->isGLValue()) {
4200 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
4201 // emit the base as an lvalue.
4202 assert(E->getBase()->getType()->isVectorType());
4203 Base = EmitLValue(E->getBase());
4204 } else {
4205 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
4206 assert(E->getBase()->getType()->isVectorType() &&
4207 "Result must be a vector");
4208 llvm::Value *Vec = EmitScalarExpr(E->getBase());
4210 // Store the vector to memory (because LValue wants an address).
4211 Address VecMem = CreateMemTemp(E->getBase()->getType());
4212 Builder.CreateStore(Vec, VecMem);
4213 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
4214 AlignmentSource::Decl);
4217 QualType type =
4218 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
4220 // Encode the element access list into a vector of unsigned indices.
4221 SmallVector<uint32_t, 4> Indices;
4222 E->getEncodedElementAccess(Indices);
4224 if (Base.isSimple()) {
4225 llvm::Constant *CV =
4226 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4227 return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
4228 Base.getBaseInfo(), TBAAAccessInfo());
4230 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
4232 llvm::Constant *BaseElts = Base.getExtVectorElts();
4233 SmallVector<llvm::Constant *, 4> CElts;
4235 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
4236 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
4237 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
4238 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
4239 Base.getBaseInfo(), TBAAAccessInfo());
4242 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
4243 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
4244 EmitIgnoredExpr(E->getBase());
4245 return EmitDeclRefLValue(DRE);
4248 Expr *BaseExpr = E->getBase();
4249 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
4250 LValue BaseLV;
4251 if (E->isArrow()) {
4252 LValueBaseInfo BaseInfo;
4253 TBAAAccessInfo TBAAInfo;
4254 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
4255 QualType PtrTy = BaseExpr->getType()->getPointeeType();
4256 SanitizerSet SkippedChecks;
4257 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
4258 if (IsBaseCXXThis)
4259 SkippedChecks.set(SanitizerKind::Alignment, true);
4260 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
4261 SkippedChecks.set(SanitizerKind::Null, true);
4262 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
4263 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
4264 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
4265 } else
4266 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
4268 NamedDecl *ND = E->getMemberDecl();
4269 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
4270 LValue LV = EmitLValueForField(BaseLV, Field);
4271 setObjCGCLValueClass(getContext(), E, LV);
4272 if (getLangOpts().OpenMP) {
4273 // If the member was explicitly marked as nontemporal, mark it as
4274 // nontemporal. If the base lvalue is marked as nontemporal, mark access
4275 // to children as nontemporal too.
4276 if ((IsWrappedCXXThis(BaseExpr) &&
4277 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4278 BaseLV.isNontemporal())
4279 LV.setNontemporal(/*Value=*/true);
4281 return LV;
4284 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
4285 return EmitFunctionDeclLValue(*this, E, FD);
4287 llvm_unreachable("Unhandled member declaration!");
4290 /// Given that we are currently emitting a lambda, emit an l-value for
4291 /// one of its members.
4292 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4293 if (CurCodeDecl) {
4294 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
4295 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4297 QualType LambdaTagType =
4298 getContext().getTagDeclType(Field->getParent());
4299 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
4300 return EmitLValueForField(LambdaLV, Field);
4303 /// Get the field index in the debug info. The debug info structure/union
4304 /// will ignore the unnamed bitfields.
4305 unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
4306 unsigned FieldIndex) {
4307 unsigned I = 0, Skipped = 0;
4309 for (auto *F : Rec->getDefinition()->fields()) {
4310 if (I == FieldIndex)
4311 break;
4312 if (F->isUnnamedBitfield())
4313 Skipped++;
4314 I++;
4317 return FieldIndex - Skipped;
4320 /// Get the address of a zero-sized field within a record. The resulting
4321 /// address doesn't necessarily have the right type.
4322 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
4323 const FieldDecl *Field) {
4324 CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
4325 CGF.getContext().getFieldOffset(Field));
4326 if (Offset.isZero())
4327 return Base;
4328 Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
4329 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4332 /// Drill down to the storage of a field without walking into
4333 /// reference types.
4335 /// The resulting address doesn't necessarily have the right type.
4336 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
4337 const FieldDecl *field) {
4338 if (field->isZeroSize(CGF.getContext()))
4339 return emitAddrOfZeroSizeField(CGF, base, field);
4341 const RecordDecl *rec = field->getParent();
4343 unsigned idx =
4344 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4346 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
4349 static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
4350 Address addr, const FieldDecl *field) {
4351 const RecordDecl *rec = field->getParent();
4352 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
4353 base.getType(), rec->getLocation());
4355 unsigned idx =
4356 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4358 return CGF.Builder.CreatePreserveStructAccessIndex(
4359 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
4362 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4363 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4364 if (!RD)
4365 return false;
4367 if (RD->isDynamicClass())
4368 return true;
4370 for (const auto &Base : RD->bases())
4371 if (hasAnyVptr(Base.getType(), Context))
4372 return true;
4374 for (const FieldDecl *Field : RD->fields())
4375 if (hasAnyVptr(Field->getType(), Context))
4376 return true;
4378 return false;
4381 LValue CodeGenFunction::EmitLValueForField(LValue base,
4382 const FieldDecl *field) {
4383 LValueBaseInfo BaseInfo = base.getBaseInfo();
4385 if (field->isBitField()) {
4386 const CGRecordLayout &RL =
4387 CGM.getTypes().getCGRecordLayout(field->getParent());
4388 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4389 const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4390 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4391 Info.VolatileStorageSize != 0 &&
4392 field->getType()
4393 .withCVRQualifiers(base.getVRQualifiers())
4394 .isVolatileQualified();
4395 Address Addr = base.getAddress(*this);
4396 unsigned Idx = RL.getLLVMFieldNo(field);
4397 const RecordDecl *rec = field->getParent();
4398 if (!UseVolatile) {
4399 if (!IsInPreservedAIRegion &&
4400 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4401 if (Idx != 0)
4402 // For structs, we GEP to the field that the record layout suggests.
4403 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4404 } else {
4405 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4406 getContext().getRecordType(rec), rec->getLocation());
4407 Addr = Builder.CreatePreserveStructAccessIndex(
4408 Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4409 DbgInfo);
4412 const unsigned SS =
4413 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
4414 // Get the access type.
4415 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4416 if (Addr.getElementType() != FieldIntTy)
4417 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
4418 if (UseVolatile) {
4419 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4420 if (VolatileOffset)
4421 Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4424 QualType fieldType =
4425 field->getType().withCVRQualifiers(base.getVRQualifiers());
4426 // TODO: Support TBAA for bit fields.
4427 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
4428 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
4429 TBAAAccessInfo());
4432 // Fields of may-alias structures are may-alias themselves.
4433 // FIXME: this should get propagated down through anonymous structs
4434 // and unions.
4435 QualType FieldType = field->getType();
4436 const RecordDecl *rec = field->getParent();
4437 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
4438 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
4439 TBAAAccessInfo FieldTBAAInfo;
4440 if (base.getTBAAInfo().isMayAlias() ||
4441 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
4442 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4443 } else if (rec->isUnion()) {
4444 // TODO: Support TBAA for unions.
4445 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4446 } else {
4447 // If no base type been assigned for the base access, then try to generate
4448 // one for this base lvalue.
4449 FieldTBAAInfo = base.getTBAAInfo();
4450 if (!FieldTBAAInfo.BaseType) {
4451 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4452 assert(!FieldTBAAInfo.Offset &&
4453 "Nonzero offset for an access with no base type!");
4456 // Adjust offset to be relative to the base type.
4457 const ASTRecordLayout &Layout =
4458 getContext().getASTRecordLayout(field->getParent());
4459 unsigned CharWidth = getContext().getCharWidth();
4460 if (FieldTBAAInfo.BaseType)
4461 FieldTBAAInfo.Offset +=
4462 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
4464 // Update the final access type and size.
4465 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
4466 FieldTBAAInfo.Size =
4467 getContext().getTypeSizeInChars(FieldType).getQuantity();
4470 Address addr = base.getAddress(*this);
4471 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4472 if (CGM.getCodeGenOpts().StrictVTablePointers &&
4473 ClassDef->isDynamicClass()) {
4474 // Getting to any field of dynamic object requires stripping dynamic
4475 // information provided by invariant.group. This is because accessing
4476 // fields may leak the real address of dynamic object, which could result
4477 // in miscompilation when leaked pointer would be compared.
4478 auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
4479 addr = Address(stripped, addr.getElementType(), addr.getAlignment());
4483 unsigned RecordCVR = base.getVRQualifiers();
4484 if (rec->isUnion()) {
4485 // For unions, there is no pointer adjustment.
4486 if (CGM.getCodeGenOpts().StrictVTablePointers &&
4487 hasAnyVptr(FieldType, getContext()))
4488 // Because unions can easily skip invariant.barriers, we need to add
4489 // a barrier every time CXXRecord field with vptr is referenced.
4490 addr = Builder.CreateLaunderInvariantGroup(addr);
4492 if (IsInPreservedAIRegion ||
4493 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4494 // Remember the original union field index
4495 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
4496 rec->getLocation());
4497 addr = Address(
4498 Builder.CreatePreserveUnionAccessIndex(
4499 addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
4500 addr.getElementType(), addr.getAlignment());
4503 if (FieldType->isReferenceType())
4504 addr = Builder.CreateElementBitCast(
4505 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4506 } else {
4507 if (!IsInPreservedAIRegion &&
4508 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
4509 // For structs, we GEP to the field that the record layout suggests.
4510 addr = emitAddrOfFieldStorage(*this, addr, field);
4511 else
4512 // Remember the original struct field index
4513 addr = emitPreserveStructAccess(*this, base, addr, field);
4516 // If this is a reference field, load the reference right now.
4517 if (FieldType->isReferenceType()) {
4518 LValue RefLVal =
4519 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4520 if (RecordCVR & Qualifiers::Volatile)
4521 RefLVal.getQuals().addVolatile();
4522 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
4524 // Qualifiers on the struct don't apply to the referencee.
4525 RecordCVR = 0;
4526 FieldType = FieldType->getPointeeType();
4529 // Make sure that the address is pointing to the right type. This is critical
4530 // for both unions and structs. A union needs a bitcast, a struct element
4531 // will need a bitcast if the LLVM type laid out doesn't match the desired
4532 // type.
4533 addr = Builder.CreateElementBitCast(
4534 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4536 if (field->hasAttr<AnnotateAttr>())
4537 addr = EmitFieldAnnotations(field, addr);
4539 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4540 LV.getQuals().addCVRQualifiers(RecordCVR);
4542 // __weak attribute on a field is ignored.
4543 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
4544 LV.getQuals().removeObjCGCAttr();
4546 return LV;
4549 LValue
4550 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
4551 const FieldDecl *Field) {
4552 QualType FieldType = Field->getType();
4554 if (!FieldType->isReferenceType())
4555 return EmitLValueForField(Base, Field);
4557 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
4559 // Make sure that the address is pointing to the right type.
4560 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4561 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
4563 // TODO: Generate TBAA information that describes this access as a structure
4564 // member access and not just an access to an object of the field's type. This
4565 // should be similar to what we do in EmitLValueForField().
4566 LValueBaseInfo BaseInfo = Base.getBaseInfo();
4567 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4568 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
4569 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
4570 CGM.getTBAAInfoForSubobject(Base, FieldType));
4573 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
4574 if (E->isFileScope()) {
4575 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
4576 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
4578 if (E->getType()->isVariablyModifiedType())
4579 // make sure to emit the VLA size.
4580 EmitVariablyModifiedType(E->getType());
4582 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
4583 const Expr *InitExpr = E->getInitializer();
4584 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
4586 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4587 /*Init*/ true);
4589 // Block-scope compound literals are destroyed at the end of the enclosing
4590 // scope in C.
4591 if (!getLangOpts().CPlusPlus)
4592 if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
4593 pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
4594 E->getType(), getDestroyer(DtorKind),
4595 DtorKind & EHCleanup);
4597 return Result;
4600 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4601 if (!E->isGLValue())
4602 // Initializing an aggregate temporary in C++11: T{...}.
4603 return EmitAggExprToLValue(E);
4605 // An lvalue initializer list must be initializing a reference.
4606 assert(E->isTransparent() && "non-transparent glvalue init list");
4607 return EmitLValue(E->getInit(0));
4610 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
4611 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4612 /// LValue is returned and the current block has been terminated.
4613 static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4614 const Expr *Operand) {
4615 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4616 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4617 return std::nullopt;
4620 return CGF.EmitLValue(Operand);
4623 namespace {
4624 // Handle the case where the condition is a constant evaluatable simple integer,
4625 // which means we don't have to separately handle the true/false blocks.
4626 std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
4627 CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
4628 const Expr *condExpr = E->getCond();
4629 bool CondExprBool;
4630 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4631 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
4632 if (!CondExprBool)
4633 std::swap(Live, Dead);
4635 if (!CGF.ContainsLabel(Dead)) {
4636 // If the true case is live, we need to track its region.
4637 if (CondExprBool)
4638 CGF.incrementProfileCounter(E);
4639 // If a throw expression we emit it and return an undefined lvalue
4640 // because it can't be used.
4641 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
4642 CGF.EmitCXXThrowExpr(ThrowExpr);
4643 llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
4644 llvm::Type *Ty = llvm::PointerType::getUnqual(ElemTy);
4645 return CGF.MakeAddrLValue(
4646 Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
4647 Dead->getType());
4649 return CGF.EmitLValue(Live);
4652 return std::nullopt;
4654 struct ConditionalInfo {
4655 llvm::BasicBlock *lhsBlock, *rhsBlock;
4656 std::optional<LValue> LHS, RHS;
4659 // Create and generate the 3 blocks for a conditional operator.
4660 // Leaves the 'current block' in the continuation basic block.
4661 template<typename FuncTy>
4662 ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
4663 const AbstractConditionalOperator *E,
4664 const FuncTy &BranchGenFunc) {
4665 ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
4666 CGF.createBasicBlock("cond.false"), std::nullopt,
4667 std::nullopt};
4668 llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
4670 CodeGenFunction::ConditionalEvaluation eval(CGF);
4671 CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
4672 CGF.getProfileCount(E));
4674 // Any temporaries created here are conditional.
4675 CGF.EmitBlock(Info.lhsBlock);
4676 CGF.incrementProfileCounter(E);
4677 eval.begin(CGF);
4678 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
4679 eval.end(CGF);
4680 Info.lhsBlock = CGF.Builder.GetInsertBlock();
4682 if (Info.LHS)
4683 CGF.Builder.CreateBr(endBlock);
4685 // Any temporaries created here are conditional.
4686 CGF.EmitBlock(Info.rhsBlock);
4687 eval.begin(CGF);
4688 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
4689 eval.end(CGF);
4690 Info.rhsBlock = CGF.Builder.GetInsertBlock();
4691 CGF.EmitBlock(endBlock);
4693 return Info;
4695 } // namespace
4697 void CodeGenFunction::EmitIgnoredConditionalOperator(
4698 const AbstractConditionalOperator *E) {
4699 if (!E->isGLValue()) {
4700 // ?: here should be an aggregate.
4701 assert(hasAggregateEvaluationKind(E->getType()) &&
4702 "Unexpected conditional operator!");
4703 return (void)EmitAggExprToLValue(E);
4706 OpaqueValueMapping binding(*this, E);
4707 if (HandleConditionalOperatorLValueSimpleCase(*this, E))
4708 return;
4710 EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
4711 CGF.EmitIgnoredExpr(E);
4712 return LValue{};
4715 LValue CodeGenFunction::EmitConditionalOperatorLValue(
4716 const AbstractConditionalOperator *expr) {
4717 if (!expr->isGLValue()) {
4718 // ?: here should be an aggregate.
4719 assert(hasAggregateEvaluationKind(expr->getType()) &&
4720 "Unexpected conditional operator!");
4721 return EmitAggExprToLValue(expr);
4724 OpaqueValueMapping binding(*this, expr);
4725 if (std::optional<LValue> Res =
4726 HandleConditionalOperatorLValueSimpleCase(*this, expr))
4727 return *Res;
4729 ConditionalInfo Info = EmitConditionalBlocks(
4730 *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
4731 return EmitLValueOrThrowExpression(CGF, E);
4734 if ((Info.LHS && !Info.LHS->isSimple()) ||
4735 (Info.RHS && !Info.RHS->isSimple()))
4736 return EmitUnsupportedLValue(expr, "conditional operator");
4738 if (Info.LHS && Info.RHS) {
4739 Address lhsAddr = Info.LHS->getAddress(*this);
4740 Address rhsAddr = Info.RHS->getAddress(*this);
4741 llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
4742 phi->addIncoming(lhsAddr.getPointer(), Info.lhsBlock);
4743 phi->addIncoming(rhsAddr.getPointer(), Info.rhsBlock);
4744 Address result(phi, lhsAddr.getElementType(),
4745 std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
4746 AlignmentSource alignSource =
4747 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
4748 Info.RHS->getBaseInfo().getAlignmentSource());
4749 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4750 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
4751 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4752 TBAAInfo);
4753 } else {
4754 assert((Info.LHS || Info.RHS) &&
4755 "both operands of glvalue conditional are throw-expressions?");
4756 return Info.LHS ? *Info.LHS : *Info.RHS;
4760 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4761 /// type. If the cast is to a reference, we can have the usual lvalue result,
4762 /// otherwise if a cast is needed by the code generator in an lvalue context,
4763 /// then it must mean that we need the address of an aggregate in order to
4764 /// access one of its members. This can happen for all the reasons that casts
4765 /// are permitted with aggregate result, including noop aggregate casts, and
4766 /// cast from scalar to union.
4767 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
4768 switch (E->getCastKind()) {
4769 case CK_ToVoid:
4770 case CK_BitCast:
4771 case CK_LValueToRValueBitCast:
4772 case CK_ArrayToPointerDecay:
4773 case CK_FunctionToPointerDecay:
4774 case CK_NullToMemberPointer:
4775 case CK_NullToPointer:
4776 case CK_IntegralToPointer:
4777 case CK_PointerToIntegral:
4778 case CK_PointerToBoolean:
4779 case CK_VectorSplat:
4780 case CK_IntegralCast:
4781 case CK_BooleanToSignedIntegral:
4782 case CK_IntegralToBoolean:
4783 case CK_IntegralToFloating:
4784 case CK_FloatingToIntegral:
4785 case CK_FloatingToBoolean:
4786 case CK_FloatingCast:
4787 case CK_FloatingRealToComplex:
4788 case CK_FloatingComplexToReal:
4789 case CK_FloatingComplexToBoolean:
4790 case CK_FloatingComplexCast:
4791 case CK_FloatingComplexToIntegralComplex:
4792 case CK_IntegralRealToComplex:
4793 case CK_IntegralComplexToReal:
4794 case CK_IntegralComplexToBoolean:
4795 case CK_IntegralComplexCast:
4796 case CK_IntegralComplexToFloatingComplex:
4797 case CK_DerivedToBaseMemberPointer:
4798 case CK_BaseToDerivedMemberPointer:
4799 case CK_MemberPointerToBoolean:
4800 case CK_ReinterpretMemberPointer:
4801 case CK_AnyPointerToBlockPointerCast:
4802 case CK_ARCProduceObject:
4803 case CK_ARCConsumeObject:
4804 case CK_ARCReclaimReturnedObject:
4805 case CK_ARCExtendBlockObject:
4806 case CK_CopyAndAutoreleaseBlockObject:
4807 case CK_IntToOCLSampler:
4808 case CK_FloatingToFixedPoint:
4809 case CK_FixedPointToFloating:
4810 case CK_FixedPointCast:
4811 case CK_FixedPointToBoolean:
4812 case CK_FixedPointToIntegral:
4813 case CK_IntegralToFixedPoint:
4814 case CK_MatrixCast:
4815 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4817 case CK_Dependent:
4818 llvm_unreachable("dependent cast kind in IR gen!");
4820 case CK_BuiltinFnToFnPtr:
4821 llvm_unreachable("builtin functions are handled elsewhere");
4823 // These are never l-values; just use the aggregate emission code.
4824 case CK_NonAtomicToAtomic:
4825 case CK_AtomicToNonAtomic:
4826 return EmitAggExprToLValue(E);
4828 case CK_Dynamic: {
4829 LValue LV = EmitLValue(E->getSubExpr());
4830 Address V = LV.getAddress(*this);
4831 const auto *DCE = cast<CXXDynamicCastExpr>(E);
4832 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4835 case CK_ConstructorConversion:
4836 case CK_UserDefinedConversion:
4837 case CK_CPointerToObjCPointerCast:
4838 case CK_BlockPointerToObjCPointerCast:
4839 case CK_LValueToRValue:
4840 return EmitLValue(E->getSubExpr());
4842 case CK_NoOp: {
4843 // CK_NoOp can model a qualification conversion, which can remove an array
4844 // bound and change the IR type.
4845 // FIXME: Once pointee types are removed from IR, remove this.
4846 LValue LV = EmitLValue(E->getSubExpr());
4847 if (LV.isSimple()) {
4848 Address V = LV.getAddress(*this);
4849 if (V.isValid()) {
4850 llvm::Type *T = ConvertTypeForMem(E->getType());
4851 if (V.getElementType() != T)
4852 LV.setAddress(Builder.CreateElementBitCast(V, T));
4855 return LV;
4858 case CK_UncheckedDerivedToBase:
4859 case CK_DerivedToBase: {
4860 const auto *DerivedClassTy =
4861 E->getSubExpr()->getType()->castAs<RecordType>();
4862 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4864 LValue LV = EmitLValue(E->getSubExpr());
4865 Address This = LV.getAddress(*this);
4867 // Perform the derived-to-base conversion
4868 Address Base = GetAddressOfBaseClass(
4869 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4870 /*NullCheckValue=*/false, E->getExprLoc());
4872 // TODO: Support accesses to members of base classes in TBAA. For now, we
4873 // conservatively pretend that the complete object is of the base class
4874 // type.
4875 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4876 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4878 case CK_ToUnion:
4879 return EmitAggExprToLValue(E);
4880 case CK_BaseToDerived: {
4881 const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
4882 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4884 LValue LV = EmitLValue(E->getSubExpr());
4886 // Perform the base-to-derived conversion
4887 Address Derived = GetAddressOfDerivedClass(
4888 LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
4889 /*NullCheckValue=*/false);
4891 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4892 // performed and the object is not of the derived type.
4893 if (sanitizePerformTypeCheck())
4894 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4895 Derived.getPointer(), E->getType());
4897 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4898 EmitVTablePtrCheckForCast(E->getType(), Derived,
4899 /*MayBeNull=*/false, CFITCK_DerivedCast,
4900 E->getBeginLoc());
4902 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4903 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4905 case CK_LValueBitCast: {
4906 // This must be a reinterpret_cast (or c-style equivalent).
4907 const auto *CE = cast<ExplicitCastExpr>(E);
4909 CGM.EmitExplicitCastExprType(CE, this);
4910 LValue LV = EmitLValue(E->getSubExpr());
4911 Address V = Builder.CreateElementBitCast(
4912 LV.getAddress(*this),
4913 ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
4915 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4916 EmitVTablePtrCheckForCast(E->getType(), V,
4917 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4918 E->getBeginLoc());
4920 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4921 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4923 case CK_AddressSpaceConversion: {
4924 LValue LV = EmitLValue(E->getSubExpr());
4925 QualType DestTy = getContext().getPointerType(E->getType());
4926 llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4927 *this, LV.getPointer(*this),
4928 E->getSubExpr()->getType().getAddressSpace(),
4929 E->getType().getAddressSpace(), ConvertType(DestTy));
4930 return MakeAddrLValue(Address(V, ConvertTypeForMem(E->getType()),
4931 LV.getAddress(*this).getAlignment()),
4932 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
4934 case CK_ObjCObjectLValueCast: {
4935 LValue LV = EmitLValue(E->getSubExpr());
4936 Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
4937 ConvertType(E->getType()));
4938 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4939 CGM.getTBAAInfoForSubobject(LV, E->getType()));
4941 case CK_ZeroToOCLOpaqueType:
4942 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
4945 llvm_unreachable("Unhandled lvalue cast kind?");
4948 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4949 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4950 return getOrCreateOpaqueLValueMapping(e);
4953 LValue
4954 CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
4955 assert(OpaqueValueMapping::shouldBindAsLValue(e));
4957 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
4958 it = OpaqueLValues.find(e);
4960 if (it != OpaqueLValues.end())
4961 return it->second;
4963 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
4964 return EmitLValue(e->getSourceExpr());
4967 RValue
4968 CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
4969 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
4971 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
4972 it = OpaqueRValues.find(e);
4974 if (it != OpaqueRValues.end())
4975 return it->second;
4977 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
4978 return EmitAnyExpr(e->getSourceExpr());
4981 RValue CodeGenFunction::EmitRValueForField(LValue LV,
4982 const FieldDecl *FD,
4983 SourceLocation Loc) {
4984 QualType FT = FD->getType();
4985 LValue FieldLV = EmitLValueForField(LV, FD);
4986 switch (getEvaluationKind(FT)) {
4987 case TEK_Complex:
4988 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4989 case TEK_Aggregate:
4990 return FieldLV.asAggregateRValue(*this);
4991 case TEK_Scalar:
4992 // This routine is used to load fields one-by-one to perform a copy, so
4993 // don't load reference fields.
4994 if (FD->getType()->isReferenceType())
4995 return RValue::get(FieldLV.getPointer(*this));
4996 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4997 // primitive load.
4998 if (FieldLV.isBitField())
4999 return EmitLoadOfLValue(FieldLV, Loc);
5000 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
5002 llvm_unreachable("bad evaluation kind");
5005 //===--------------------------------------------------------------------===//
5006 // Expression Emission
5007 //===--------------------------------------------------------------------===//
5009 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
5010 ReturnValueSlot ReturnValue) {
5011 // Builtins never have block type.
5012 if (E->getCallee()->getType()->isBlockPointerType())
5013 return EmitBlockCallExpr(E, ReturnValue);
5015 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
5016 return EmitCXXMemberCallExpr(CE, ReturnValue);
5018 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
5019 return EmitCUDAKernelCallExpr(CE, ReturnValue);
5021 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
5022 if (const CXXMethodDecl *MD =
5023 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
5024 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
5026 CGCallee callee = EmitCallee(E->getCallee());
5028 if (callee.isBuiltin()) {
5029 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
5030 E, ReturnValue);
5033 if (callee.isPseudoDestructor()) {
5034 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
5037 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
5040 /// Emit a CallExpr without considering whether it might be a subclass.
5041 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
5042 ReturnValueSlot ReturnValue) {
5043 CGCallee Callee = EmitCallee(E->getCallee());
5044 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
5047 // Detect the unusual situation where an inline version is shadowed by a
5048 // non-inline version. In that case we should pick the external one
5049 // everywhere. That's GCC behavior too.
5050 static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD) {
5051 for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
5052 if (!PD->isInlineBuiltinDeclaration())
5053 return false;
5054 return true;
5057 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
5058 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
5060 if (auto builtinID = FD->getBuiltinID()) {
5061 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
5062 std::string NoBuiltins = "no-builtins";
5064 StringRef Ident = CGF.CGM.getMangledName(GD);
5065 std::string FDInlineName = (Ident + ".inline").str();
5067 bool IsPredefinedLibFunction =
5068 CGF.getContext().BuiltinInfo.isPredefinedLibFunction(builtinID);
5069 bool HasAttributeNoBuiltin =
5070 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
5071 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
5073 // When directing calling an inline builtin, call it through it's mangled
5074 // name to make it clear it's not the actual builtin.
5075 if (CGF.CurFn->getName() != FDInlineName &&
5076 OnlyHasInlineBuiltinDeclaration(FD)) {
5077 llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5078 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
5079 llvm::Module *M = Fn->getParent();
5080 llvm::Function *Clone = M->getFunction(FDInlineName);
5081 if (!Clone) {
5082 Clone = llvm::Function::Create(Fn->getFunctionType(),
5083 llvm::GlobalValue::InternalLinkage,
5084 Fn->getAddressSpace(), FDInlineName, M);
5085 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
5087 return CGCallee::forDirect(Clone, GD);
5090 // Replaceable builtins provide their own implementation of a builtin. If we
5091 // are in an inline builtin implementation, avoid trivial infinite
5092 // recursion. Honor __attribute__((no_builtin("foo"))) or
5093 // __attribute__((no_builtin)) on the current function unless foo is
5094 // not a predefined library function which means we must generate the
5095 // builtin no matter what.
5096 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
5097 return CGCallee::forBuiltin(builtinID, FD);
5100 llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
5101 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
5102 FD->hasAttr<CUDAGlobalAttr>())
5103 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
5104 cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
5106 return CGCallee::forDirect(CalleePtr, GD);
5109 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
5110 E = E->IgnoreParens();
5112 // Look through function-to-pointer decay.
5113 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
5114 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
5115 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
5116 return EmitCallee(ICE->getSubExpr());
5119 // Resolve direct calls.
5120 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
5121 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
5122 return EmitDirectCallee(*this, FD);
5124 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
5125 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
5126 EmitIgnoredExpr(ME->getBase());
5127 return EmitDirectCallee(*this, FD);
5130 // Look through template substitutions.
5131 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
5132 return EmitCallee(NTTP->getReplacement());
5134 // Treat pseudo-destructor calls differently.
5135 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
5136 return CGCallee::forPseudoDestructor(PDE);
5139 // Otherwise, we have an indirect reference.
5140 llvm::Value *calleePtr;
5141 QualType functionType;
5142 if (auto ptrType = E->getType()->getAs<PointerType>()) {
5143 calleePtr = EmitScalarExpr(E);
5144 functionType = ptrType->getPointeeType();
5145 } else {
5146 functionType = E->getType();
5147 calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
5149 assert(functionType->isFunctionType());
5151 GlobalDecl GD;
5152 if (const auto *VD =
5153 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
5154 GD = GlobalDecl(VD);
5156 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
5157 CGCallee callee(calleeInfo, calleePtr);
5158 return callee;
5161 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
5162 // Comma expressions just emit their LHS then their RHS as an l-value.
5163 if (E->getOpcode() == BO_Comma) {
5164 EmitIgnoredExpr(E->getLHS());
5165 EnsureInsertPoint();
5166 return EmitLValue(E->getRHS());
5169 if (E->getOpcode() == BO_PtrMemD ||
5170 E->getOpcode() == BO_PtrMemI)
5171 return EmitPointerToDataMemberBinaryExpr(E);
5173 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
5175 // Note that in all of these cases, __block variables need the RHS
5176 // evaluated first just in case the variable gets moved by the RHS.
5178 switch (getEvaluationKind(E->getType())) {
5179 case TEK_Scalar: {
5180 switch (E->getLHS()->getType().getObjCLifetime()) {
5181 case Qualifiers::OCL_Strong:
5182 return EmitARCStoreStrong(E, /*ignored*/ false).first;
5184 case Qualifiers::OCL_Autoreleasing:
5185 return EmitARCStoreAutoreleasing(E).first;
5187 // No reason to do any of these differently.
5188 case Qualifiers::OCL_None:
5189 case Qualifiers::OCL_ExplicitNone:
5190 case Qualifiers::OCL_Weak:
5191 break;
5194 RValue RV = EmitAnyExpr(E->getRHS());
5195 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
5196 if (RV.isScalar())
5197 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
5198 EmitStoreThroughLValue(RV, LV);
5199 if (getLangOpts().OpenMP)
5200 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
5201 E->getLHS());
5202 return LV;
5205 case TEK_Complex:
5206 return EmitComplexAssignmentLValue(E);
5208 case TEK_Aggregate:
5209 return EmitAggExprToLValue(E);
5211 llvm_unreachable("bad evaluation kind");
5214 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
5215 RValue RV = EmitCallExpr(E);
5217 if (!RV.isScalar())
5218 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5219 AlignmentSource::Decl);
5221 assert(E->getCallReturnType(getContext())->isReferenceType() &&
5222 "Can't have a scalar return unless the return type is a "
5223 "reference type!");
5225 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5228 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
5229 // FIXME: This shouldn't require another copy.
5230 return EmitAggExprToLValue(E);
5233 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
5234 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
5235 && "binding l-value to type which needs a temporary");
5236 AggValueSlot Slot = CreateAggTemp(E->getType());
5237 EmitCXXConstructExpr(E, Slot);
5238 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5241 LValue
5242 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
5243 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
5246 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
5247 return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()),
5248 ConvertType(E->getType()));
5251 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
5252 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
5253 AlignmentSource::Decl);
5256 LValue
5257 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
5258 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
5259 Slot.setExternallyDestructed();
5260 EmitAggExpr(E->getSubExpr(), Slot);
5261 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
5262 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5265 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
5266 RValue RV = EmitObjCMessageExpr(E);
5268 if (!RV.isScalar())
5269 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5270 AlignmentSource::Decl);
5272 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
5273 "Can't have a scalar return unless the return type is a "
5274 "reference type!");
5276 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5279 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
5280 Address V =
5281 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
5282 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
5285 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
5286 const ObjCIvarDecl *Ivar) {
5287 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
5290 llvm::Value *
5291 CodeGenFunction::EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface,
5292 const ObjCIvarDecl *Ivar) {
5293 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
5294 QualType PointerDiffType = getContext().getPointerDiffType();
5295 return Builder.CreateZExtOrTrunc(OffsetValue,
5296 getTypes().ConvertType(PointerDiffType));
5299 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
5300 llvm::Value *BaseValue,
5301 const ObjCIvarDecl *Ivar,
5302 unsigned CVRQualifiers) {
5303 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
5304 Ivar, CVRQualifiers);
5307 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
5308 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
5309 llvm::Value *BaseValue = nullptr;
5310 const Expr *BaseExpr = E->getBase();
5311 Qualifiers BaseQuals;
5312 QualType ObjectTy;
5313 if (E->isArrow()) {
5314 BaseValue = EmitScalarExpr(BaseExpr);
5315 ObjectTy = BaseExpr->getType()->getPointeeType();
5316 BaseQuals = ObjectTy.getQualifiers();
5317 } else {
5318 LValue BaseLV = EmitLValue(BaseExpr);
5319 BaseValue = BaseLV.getPointer(*this);
5320 ObjectTy = BaseExpr->getType();
5321 BaseQuals = ObjectTy.getQualifiers();
5324 LValue LV =
5325 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
5326 BaseQuals.getCVRQualifiers());
5327 setObjCGCLValueClass(getContext(), E, LV);
5328 return LV;
5331 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
5332 // Can only get l-value for message expression returning aggregate type
5333 RValue RV = EmitAnyExprToTemp(E);
5334 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5335 AlignmentSource::Decl);
5338 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
5339 const CallExpr *E, ReturnValueSlot ReturnValue,
5340 llvm::Value *Chain) {
5341 // Get the actual function type. The callee type will always be a pointer to
5342 // function type or a block pointer type.
5343 assert(CalleeType->isFunctionPointerType() &&
5344 "Call must have function pointer type!");
5346 const Decl *TargetDecl =
5347 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
5349 CalleeType = getContext().getCanonicalType(CalleeType);
5351 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
5353 CGCallee Callee = OrigCallee;
5355 if (SanOpts.has(SanitizerKind::Function) &&
5356 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
5357 !isa<FunctionNoProtoType>(PointeeType)) {
5358 if (llvm::Constant *PrefixSig =
5359 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
5360 SanitizerScope SanScope(this);
5361 auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
5363 llvm::Type *PrefixSigType = PrefixSig->getType();
5364 llvm::StructType *PrefixStructTy = llvm::StructType::get(
5365 CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
5367 llvm::Value *CalleePtr = Callee.getFunctionPointer();
5369 // On 32-bit Arm, the low bit of a function pointer indicates whether
5370 // it's using the Arm or Thumb instruction set. The actual first
5371 // instruction lives at the same address either way, so we must clear
5372 // that low bit before using the function address to find the prefix
5373 // structure.
5375 // This applies to both Arm and Thumb target triples, because
5376 // either one could be used in an interworking context where it
5377 // might be passed function pointers of both types.
5378 llvm::Value *AlignedCalleePtr;
5379 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
5380 llvm::Value *CalleeAddress =
5381 Builder.CreatePtrToInt(CalleePtr, IntPtrTy);
5382 llvm::Value *Mask = llvm::ConstantInt::get(IntPtrTy, ~1);
5383 llvm::Value *AlignedCalleeAddress =
5384 Builder.CreateAnd(CalleeAddress, Mask);
5385 AlignedCalleePtr =
5386 Builder.CreateIntToPtr(AlignedCalleeAddress, CalleePtr->getType());
5387 } else {
5388 AlignedCalleePtr = CalleePtr;
5391 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
5392 AlignedCalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
5393 llvm::Value *CalleeSigPtr =
5394 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
5395 llvm::Value *CalleeSig =
5396 Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
5397 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
5399 llvm::BasicBlock *Cont = createBasicBlock("cont");
5400 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
5401 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
5403 EmitBlock(TypeCheck);
5404 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
5405 Int32Ty,
5406 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
5407 getPointerAlign());
5408 llvm::Value *CalleeTypeHashMatch =
5409 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
5410 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
5411 EmitCheckTypeDescriptor(CalleeType)};
5412 EmitCheck(std::make_pair(CalleeTypeHashMatch, SanitizerKind::Function),
5413 SanitizerHandler::FunctionTypeMismatch, StaticData,
5414 {CalleePtr});
5416 Builder.CreateBr(Cont);
5417 EmitBlock(Cont);
5421 const auto *FnType = cast<FunctionType>(PointeeType);
5423 // If we are checking indirect calls and this call is indirect, check that the
5424 // function pointer is a member of the bit set for the function type.
5425 if (SanOpts.has(SanitizerKind::CFIICall) &&
5426 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5427 SanitizerScope SanScope(this);
5428 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
5430 llvm::Metadata *MD;
5431 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
5432 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
5433 else
5434 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
5436 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
5438 llvm::Value *CalleePtr = Callee.getFunctionPointer();
5439 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
5440 llvm::Value *TypeTest = Builder.CreateCall(
5441 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
5443 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
5444 llvm::Constant *StaticData[] = {
5445 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
5446 EmitCheckSourceLocation(E->getBeginLoc()),
5447 EmitCheckTypeDescriptor(QualType(FnType, 0)),
5449 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
5450 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
5451 CastedCallee, StaticData);
5452 } else {
5453 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
5454 SanitizerHandler::CFICheckFail, StaticData,
5455 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
5459 CallArgList Args;
5460 if (Chain)
5461 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
5462 CGM.getContext().VoidPtrTy);
5464 // C++17 requires that we evaluate arguments to a call using assignment syntax
5465 // right-to-left, and that we evaluate arguments to certain other operators
5466 // left-to-right. Note that we allow this to override the order dictated by
5467 // the calling convention on the MS ABI, which means that parameter
5468 // destruction order is not necessarily reverse construction order.
5469 // FIXME: Revisit this based on C++ committee response to unimplementability.
5470 EvaluationOrder Order = EvaluationOrder::Default;
5471 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
5472 if (OCE->isAssignmentOp())
5473 Order = EvaluationOrder::ForceRightToLeft;
5474 else {
5475 switch (OCE->getOperator()) {
5476 case OO_LessLess:
5477 case OO_GreaterGreater:
5478 case OO_AmpAmp:
5479 case OO_PipePipe:
5480 case OO_Comma:
5481 case OO_ArrowStar:
5482 Order = EvaluationOrder::ForceLeftToRight;
5483 break;
5484 default:
5485 break;
5490 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
5491 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
5493 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
5494 Args, FnType, /*ChainCall=*/Chain);
5496 // C99 6.5.2.2p6:
5497 // If the expression that denotes the called function has a type
5498 // that does not include a prototype, [the default argument
5499 // promotions are performed]. If the number of arguments does not
5500 // equal the number of parameters, the behavior is undefined. If
5501 // the function is defined with a type that includes a prototype,
5502 // and either the prototype ends with an ellipsis (, ...) or the
5503 // types of the arguments after promotion are not compatible with
5504 // the types of the parameters, the behavior is undefined. If the
5505 // function is defined with a type that does not include a
5506 // prototype, and the types of the arguments after promotion are
5507 // not compatible with those of the parameters after promotion,
5508 // the behavior is undefined [except in some trivial cases].
5509 // That is, in the general case, we should assume that a call
5510 // through an unprototyped function type works like a *non-variadic*
5511 // call. The way we make this work is to cast to the exact type
5512 // of the promoted arguments.
5514 // Chain calls use this same code path to add the invisible chain parameter
5515 // to the function type.
5516 if (isa<FunctionNoProtoType>(FnType) || Chain) {
5517 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
5518 int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
5519 CalleeTy = CalleeTy->getPointerTo(AS);
5521 llvm::Value *CalleePtr = Callee.getFunctionPointer();
5522 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
5523 Callee.setFunctionPointer(CalleePtr);
5526 // HIP function pointer contains kernel handle when it is used in triple
5527 // chevron. The kernel stub needs to be loaded from kernel handle and used
5528 // as callee.
5529 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5530 isa<CUDAKernelCallExpr>(E) &&
5531 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5532 llvm::Value *Handle = Callee.getFunctionPointer();
5533 auto *Cast =
5534 Builder.CreateBitCast(Handle, Handle->getType()->getPointerTo());
5535 auto *Stub = Builder.CreateLoad(
5536 Address(Cast, Handle->getType(), CGM.getPointerAlign()));
5537 Callee.setFunctionPointer(Stub);
5539 llvm::CallBase *CallOrInvoke = nullptr;
5540 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5541 E == MustTailCall, E->getExprLoc());
5543 // Generate function declaration DISuprogram in order to be used
5544 // in debug info about call sites.
5545 if (CGDebugInfo *DI = getDebugInfo()) {
5546 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5547 FunctionArgList Args;
5548 QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
5549 DI->EmitFuncDeclForCallSite(CallOrInvoke,
5550 DI->getFunctionType(CalleeDecl, ResTy, Args),
5551 CalleeDecl);
5555 return Call;
5558 LValue CodeGenFunction::
5559 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
5560 Address BaseAddr = Address::invalid();
5561 if (E->getOpcode() == BO_PtrMemI) {
5562 BaseAddr = EmitPointerWithAlignment(E->getLHS());
5563 } else {
5564 BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
5567 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5568 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
5570 LValueBaseInfo BaseInfo;
5571 TBAAAccessInfo TBAAInfo;
5572 Address MemberAddr =
5573 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
5574 &TBAAInfo);
5576 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
5579 /// Given the address of a temporary variable, produce an r-value of
5580 /// its type.
5581 RValue CodeGenFunction::convertTempToRValue(Address addr,
5582 QualType type,
5583 SourceLocation loc) {
5584 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
5585 switch (getEvaluationKind(type)) {
5586 case TEK_Complex:
5587 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
5588 case TEK_Aggregate:
5589 return lvalue.asAggregateRValue(*this);
5590 case TEK_Scalar:
5591 return RValue::get(EmitLoadOfScalar(lvalue, loc));
5593 llvm_unreachable("bad evaluation kind");
5596 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
5597 assert(Val->getType()->isFPOrFPVectorTy());
5598 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
5599 return;
5601 llvm::MDBuilder MDHelper(getLLVMContext());
5602 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
5604 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
5607 namespace {
5608 struct LValueOrRValue {
5609 LValue LV;
5610 RValue RV;
5614 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
5615 const PseudoObjectExpr *E,
5616 bool forLValue,
5617 AggValueSlot slot) {
5618 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
5620 // Find the result expression, if any.
5621 const Expr *resultExpr = E->getResultExpr();
5622 LValueOrRValue result;
5624 for (PseudoObjectExpr::const_semantics_iterator
5625 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
5626 const Expr *semantic = *i;
5628 // If this semantic expression is an opaque value, bind it
5629 // to the result of its source expression.
5630 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
5631 // Skip unique OVEs.
5632 if (ov->isUnique()) {
5633 assert(ov != resultExpr &&
5634 "A unique OVE cannot be used as the result expression");
5635 continue;
5638 // If this is the result expression, we may need to evaluate
5639 // directly into the slot.
5640 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
5641 OVMA opaqueData;
5642 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
5643 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
5644 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
5645 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
5646 AlignmentSource::Decl);
5647 opaqueData = OVMA::bind(CGF, ov, LV);
5648 result.RV = slot.asRValue();
5650 // Otherwise, emit as normal.
5651 } else {
5652 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
5654 // If this is the result, also evaluate the result now.
5655 if (ov == resultExpr) {
5656 if (forLValue)
5657 result.LV = CGF.EmitLValue(ov);
5658 else
5659 result.RV = CGF.EmitAnyExpr(ov, slot);
5663 opaques.push_back(opaqueData);
5665 // Otherwise, if the expression is the result, evaluate it
5666 // and remember the result.
5667 } else if (semantic == resultExpr) {
5668 if (forLValue)
5669 result.LV = CGF.EmitLValue(semantic);
5670 else
5671 result.RV = CGF.EmitAnyExpr(semantic, slot);
5673 // Otherwise, evaluate the expression in an ignored context.
5674 } else {
5675 CGF.EmitIgnoredExpr(semantic);
5679 // Unbind all the opaques now.
5680 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
5681 opaques[i].unbind(CGF);
5683 return result;
5686 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
5687 AggValueSlot slot) {
5688 return emitPseudoObjectExpr(*this, E, false, slot).RV;
5691 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
5692 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;