clang 23.0.0git
CGExpr.cpp
Go to the documentation of this file.
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.
10//
11//===----------------------------------------------------------------------===//
12
13#include "ABIInfoImpl.h"
14#include "CGCUDARuntime.h"
15#include "CGCXXABI.h"
16#include "CGCall.h"
17#include "CGCleanup.h"
18#include "CGDebugInfo.h"
19#include "CGHLSLRuntime.h"
20#include "CGObjCRuntime.h"
21#include "CGOpenMPRuntime.h"
22#include "CGRecordLayout.h"
23#include "CodeGenFunction.h"
24#include "CodeGenModule.h"
25#include "CodeGenPGO.h"
26#include "ConstantEmitter.h"
27#include "TargetInfo.h"
29#include "clang/AST/ASTLambda.h"
30#include "clang/AST/Attr.h"
31#include "clang/AST/DeclObjC.h"
32#include "clang/AST/Expr.h"
35#include "clang/AST/NSAPI.h"
40#include "clang/Basic/Module.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/ScopeExit.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/IR/Constants.h"
46#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/IntrinsicsWebAssembly.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/MDBuilder.h"
51#include "llvm/IR/MatrixBuilder.h"
52#include "llvm/Support/ConvertUTF.h"
53#include "llvm/Support/Endian.h"
54#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/Path.h"
56#include "llvm/Support/xxhash.h"
57#include "llvm/Transforms/Utils/SanitizerStats.h"
58
59#include <numeric>
60#include <optional>
61#include <string>
62
63using namespace clang;
64using namespace CodeGen;
65
66namespace clang {
67// TODO: consider deprecating ClSanitizeGuardChecks; functionality is subsumed
68// by -fsanitize-skip-hot-cutoff
69llvm::cl::opt<bool> ClSanitizeGuardChecks(
70 "ubsan-guard-checks", llvm::cl::Optional,
71 llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
72
73} // namespace clang
74
75//===--------------------------------------------------------------------===//
76// Defines for metadata
77//===--------------------------------------------------------------------===//
78
79// Those values are crucial to be the SAME as in ubsan runtime library.
81 /// An integer type.
82 TK_Integer = 0x0000,
83 /// A floating-point type.
84 TK_Float = 0x0001,
85 /// An _BitInt(N) type.
86 TK_BitInt = 0x0002,
87 /// Any other type. The value representation is unspecified.
88 TK_Unknown = 0xffff
89};
90
91//===--------------------------------------------------------------------===//
92// Miscellaneous Helper Methods
93//===--------------------------------------------------------------------===//
94
95static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID) {
96 switch (ID) {
97#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
98 case SanitizerHandler::Enum: \
99 return Msg;
101#undef SANITIZER_CHECK
102 }
103 llvm_unreachable("unhandled switch case");
104}
105
106/// CreateTempAlloca - This creates a alloca and inserts it into the entry
107/// block.
110 const Twine &Name,
111 llvm::Value *ArraySize) {
112 if (getLangOpts().EmitLogicalPointer) {
113 auto Alloca = Builder.CreateStructuredAlloca(Ty, Name);
114 return RawAddress(Alloca, Ty, Align, KnownNonNull);
115 }
116
117 auto *Alloca = CreateTempAlloca(Ty, Name, ArraySize);
118 Alloca->setAlignment(Align.getAsAlign());
119 return RawAddress(Alloca, Ty, Align, KnownNonNull);
120}
121
122RawAddress CodeGenFunction::MaybeCastStackAddressSpace(RawAddress Alloca,
123 LangAS DestLangAS,
124 llvm::Value *ArraySize) {
125
126 llvm::Value *V = Alloca.getPointer();
127 // Alloca always returns a pointer in alloca address space, which may
128 // be different from the type defined by the language. For example,
129 // in C++ the auto variables are in the default address space. Therefore
130 // cast alloca to the default address space when necessary.
131
132 unsigned DestAddrSpace = getContext().getTargetAddressSpace(DestLangAS);
133 if (DestAddrSpace != Alloca.getAddressSpace()) {
134 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
135 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
136 // otherwise alloca is inserted at the current insertion point of the
137 // builder.
138 if (!ArraySize)
139 Builder.SetInsertPoint(getPostAllocaInsertPoint());
140 V = performAddrSpaceCast(V, Builder.getPtrTy(DestAddrSpace));
141 }
142
143 return RawAddress(V, Alloca.getElementType(), Alloca.getAlignment(),
145}
146
148 CharUnits Align, const Twine &Name,
149 llvm::Value *ArraySize,
150 RawAddress *AllocaAddr) {
151 RawAddress Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
152 if (AllocaAddr)
153 *AllocaAddr = Alloca;
154 return MaybeCastStackAddressSpace(Alloca, DestLangAS, ArraySize);
155}
156
157/// CreateTempAlloca - This creates an alloca and inserts it into the entry
158/// block if \p ArraySize is nullptr, otherwise inserts it at the current
159/// insertion point of the builder.
160llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
161 const Twine &Name,
162 llvm::Value *ArraySize) {
163 llvm::AllocaInst *Alloca;
164 if (ArraySize)
165 Alloca = Builder.CreateAlloca(Ty, ArraySize, Name);
166 else
167 Alloca =
168 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
169 ArraySize, Name, AllocaInsertPt->getIterator());
170 if (SanOpts.Mask & SanitizerKind::Address) {
171 Alloca->addAnnotationMetadata({"alloca_name_altered", Name.str()});
172 }
173 if (Allocas) {
174 Allocas->Add(Alloca);
175 }
176 return Alloca;
177}
178
179/// CreateDefaultAlignTempAlloca - This creates an alloca with the
180/// default alignment of the corresponding LLVM type, which is *not*
181/// guaranteed to be related in any way to the expected alignment of
182/// an AST type that might have been lowered to Ty.
184 const Twine &Name) {
185 CharUnits Align =
186 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
187 return CreateTempAlloca(Ty, LangAS::Default, Align, Name);
188}
189
191 const Twine &Name) {
193 return CreateTempAllocaWithoutCast(ConvertType(Ty), Align, Name, nullptr);
194}
195
197 RawAddress *Alloca) {
198 // FIXME: Should we prefer the preferred type alignment here?
199 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
200}
201
203 const Twine &Name,
204 RawAddress *Alloca) {
207 /*ArraySize=*/nullptr, Alloca);
208
209 if (Ty->isConstantMatrixType()) {
210 auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
211 auto *ArrayElementTy = ArrayTy->getElementType();
212 auto ArrayElements = ArrayTy->getNumElements();
213 if (getContext().getLangOpts().HLSL) {
214 auto *VectorTy = cast<llvm::FixedVectorType>(ArrayElementTy);
215 ArrayElementTy = VectorTy->getElementType();
216 ArrayElements *= VectorTy->getNumElements();
217 }
218 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
219
220 Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(),
222 }
223 return Result;
224}
225
227 CharUnits Align,
228 const Twine &Name) {
229 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
230}
231
233 const Twine &Name) {
234 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
235 Name);
236}
237
238/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
239/// expression and compare the result against zero, returning an Int1Ty value.
241 PGO->setCurrentStmt(E);
242 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
243 llvm::Value *MemPtr = EmitScalarExpr(E);
244 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
245 }
246
247 QualType BoolTy = getContext().BoolTy;
248 SourceLocation Loc = E->getExprLoc();
249 CGFPOptionsRAII FPOptsRAII(*this, E);
250 if (!E->getType()->isAnyComplexType())
251 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
252
254 Loc);
255}
256
257/// EmitIgnoredExpr - Emit code to compute the specified expression,
258/// ignoring the result.
260 if (E->isPRValue())
261 return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
262
263 // if this is a bitfield-resulting conditional operator, we can special case
264 // emit this. The normal 'EmitLValue' version of this is particularly
265 // difficult to codegen for, since creating a single "LValue" for two
266 // different sized arguments here is not particularly doable.
267 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
269 if (CondOp->getObjectKind() == OK_BitField)
270 return EmitIgnoredConditionalOperator(CondOp);
271 }
272
273 // Just emit it as an l-value and drop the result.
274 EmitLValue(E);
275}
276
277/// EmitAnyExpr - Emit code to compute the specified expression which
278/// can have any type. The result is returned as an RValue struct.
279/// If this is an aggregate expression, AggSlot indicates where the
280/// result should be returned.
282 AggValueSlot aggSlot,
283 bool ignoreResult) {
284 switch (getEvaluationKind(E->getType())) {
285 case TEK_Scalar:
286 return RValue::get(EmitScalarExpr(E, ignoreResult));
287 case TEK_Complex:
288 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
289 case TEK_Aggregate:
290 if (!ignoreResult && aggSlot.isIgnored())
291 aggSlot = CreateAggTemp(E->getType().getUnqualifiedType(), "agg-temp");
292 EmitAggExpr(E, aggSlot);
293 return aggSlot.asRValue();
294 }
295 llvm_unreachable("bad evaluation kind");
296}
297
298/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
299/// always be accessible even if no aggregate location is provided.
302
304 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
305 return EmitAnyExpr(E, AggSlot);
306}
307
308/// EmitAnyExprToMem - Evaluate an expression into a given memory
309/// location.
311 Address Location,
312 Qualifiers Quals,
313 bool IsInit) {
314 // FIXME: This function should take an LValue as an argument.
315 switch (getEvaluationKind(E->getType())) {
316 case TEK_Complex:
318 /*isInit*/ false);
319 return;
320
321 case TEK_Aggregate: {
322 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
327 return;
328 }
329
330 case TEK_Scalar: {
331 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
332 LValue LV = MakeAddrLValue(Location, E->getType());
334 return;
335 }
336 }
337 llvm_unreachable("bad evaluation kind");
338}
339
341 const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed) {
342 QualType Type = LV.getType();
343 switch (getEvaluationKind(Type)) {
344 case TEK_Complex:
345 EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
346 return;
347 case TEK_Aggregate:
351 AggValueSlot::MayOverlap, IsZeroed));
352 return;
353 case TEK_Scalar:
354 if (LV.isSimple())
355 EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
356 else
358 return;
359 }
360 llvm_unreachable("bad evaluation kind");
361}
362
363static void
365 const Expr *E, Address ReferenceTemporary) {
366 // Objective-C++ ARC:
367 // If we are binding a reference to a temporary that has ownership, we
368 // need to perform retain/release operations on the temporary.
369 //
370 // FIXME: This should be looking at E, not M.
371 if (auto Lifetime = M->getType().getObjCLifetime()) {
372 switch (Lifetime) {
375 // Carry on to normal cleanup handling.
376 break;
377
379 // Nothing to do; cleaned up by an autorelease pool.
380 return;
381
384 switch (StorageDuration Duration = M->getStorageDuration()) {
385 case SD_Static:
386 // Note: we intentionally do not register a cleanup to release
387 // the object on program termination.
388 return;
389
390 case SD_Thread:
391 // FIXME: We should probably register a cleanup in this case.
392 return;
393
394 case SD_Automatic:
398 if (Lifetime == Qualifiers::OCL_Strong) {
399 const ValueDecl *VD = M->getExtendingDecl();
400 bool Precise = isa_and_nonnull<VarDecl>(VD) &&
401 VD->hasAttr<ObjCPreciseLifetimeAttr>();
405 } else {
406 // __weak objects always get EH cleanups; otherwise, exceptions
407 // could cause really nasty crashes instead of mere leaks.
410 }
411 if (Duration == SD_FullExpression)
412 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
413 M->getType(), *Destroy,
415 else
416 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
417 M->getType(),
418 *Destroy, CleanupKind & EHCleanup);
419 return;
420
421 case SD_Dynamic:
422 llvm_unreachable("temporary cannot have dynamic storage duration");
423 }
424 llvm_unreachable("unknown storage duration");
425 }
426 }
427
429 if (DK != QualType::DK_none) {
430 switch (M->getStorageDuration()) {
431 case SD_Static:
432 case SD_Thread: {
433 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
434 if (const auto *ClassDecl =
436 ClassDecl && !ClassDecl->hasTrivialDestructor())
437 // Get the destructor for the reference temporary.
438 ReferenceTemporaryDtor = ClassDecl->getDestructor();
439
440 if (!ReferenceTemporaryDtor)
441 return;
442
443 llvm::FunctionCallee CleanupFn;
444 llvm::Constant *CleanupArg;
445 if (E->getType()->isArrayType()) {
447 ReferenceTemporary, E->getType(), CodeGenFunction::destroyCXXObject,
448 CGF.getLangOpts().Exceptions,
449 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
450 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
451 } else {
452 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
453 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
454 CleanupArg =
455 cast<llvm::Constant>(ReferenceTemporary.emitRawPointer(CGF));
456 }
458 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
459 } break;
461 CGF.pushDestroy(DK, ReferenceTemporary, E->getType());
462 break;
463 case SD_Automatic:
464 CGF.pushLifetimeExtendedDestroy(DK, ReferenceTemporary, E->getType());
465 break;
466 case SD_Dynamic:
467 llvm_unreachable("temporary cannot have dynamic storage duration");
468 }
469 }
470}
471
474 const Expr *Inner,
475 RawAddress *Alloca = nullptr) {
476 switch (M->getStorageDuration()) {
478 case SD_Automatic: {
479 // If we have a constant temporary array or record try to promote it into a
480 // constant global under the same rules a normal constant would've been
481 // promoted. This is easier on the optimizer and generally emits fewer
482 // instructions.
483 QualType Ty = Inner->getType();
484 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
485 (Ty->isArrayType() || Ty->isRecordType()) &&
486 Ty.isConstantStorage(CGF.getContext(), true, false))
487 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
488 auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
489 auto *GV = new llvm::GlobalVariable(
490 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
491 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
492 llvm::GlobalValue::NotThreadLocal,
494 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
495 GV->setAlignment(alignment.getAsAlign());
496 llvm::Constant *C = GV;
497 if (AS != Ty.getAddressSpace())
499 GV, llvm::PointerType::get(CGF.getLLVMContext(),
501 Ty.getAddressSpace())));
502 // FIXME: Should we put the new global into a COMDAT?
503 return RawAddress(C, GV->getValueType(), alignment);
504 }
505 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
506 }
507 case SD_Thread:
508 case SD_Static:
509 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
510
511 case SD_Dynamic:
512 llvm_unreachable("temporary can't have dynamic storage duration");
513 }
514 llvm_unreachable("unknown storage duration");
515}
516
517/// Helper method to check if the underlying ABI is AAPCS
518static bool isAAPCS(const TargetInfo &TargetInfo) {
519 return TargetInfo.getABI().starts_with("aapcs");
520}
521
524 const Expr *E = M->getSubExpr();
525
526 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
527 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
528 "Reference should never be pseudo-strong!");
529
530 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
531 // as that will cause the lifetime adjustment to be lost for ARC
532 auto ownership = M->getType().getObjCLifetime();
533 if (ownership != Qualifiers::OCL_None &&
534 ownership != Qualifiers::OCL_ExplicitNone) {
536 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
537 llvm::Type *Ty = ConvertTypeForMem(E->getType());
538 Object = Object.withElementType(Ty);
539
540 // createReferenceTemporary will promote the temporary to a global with a
541 // constant initializer if it can. It can only do this to a value of
542 // ARC-manageable type if the value is global and therefore "immune" to
543 // ref-counting operations. Therefore we have no need to emit either a
544 // dynamic initialization or a cleanup and we can just return the address
545 // of the temporary.
546 if (Var->hasInitializer())
548
549 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
550 }
551 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
553
554 switch (getEvaluationKind(E->getType())) {
555 default: llvm_unreachable("expected scalar or aggregate expression");
556 case TEK_Scalar:
557 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
558 break;
559 case TEK_Aggregate: {
561 E->getType().getQualifiers(),
566 break;
567 }
568 }
569
570 pushTemporaryCleanup(*this, M, E, Object);
571 return RefTempDst;
572 }
573
576 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
577
578 for (const auto &Ignored : CommaLHSs)
579 EmitIgnoredExpr(Ignored);
580
581 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
582 if (opaque->getType()->isRecordType()) {
583 assert(Adjustments.empty());
584 return EmitOpaqueValueLValue(opaque);
585 }
586 }
587
588 // Create and initialize the reference temporary.
589 RawAddress Alloca = Address::invalid();
590 RawAddress Object = createReferenceTemporary(*this, M, E, &Alloca);
591 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
592 Object.getPointer()->stripPointerCasts())) {
593 llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
594 Object = Object.withElementType(TemporaryType);
595 // If the temporary is a global and has a constant initializer or is a
596 // constant temporary that we promoted to a global, we may have already
597 // initialized it.
598 if (!Var->hasInitializer()) {
599 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
601 if (RefType.getPointerAuth()) {
602 // Use the qualifier of the reference temporary to sign the pointer.
603 LValue LV = MakeRawAddrLValue(Object.getPointer(), RefType,
604 Object.getAlignment());
605 EmitScalarInit(E, M->getExtendingDecl(), LV, false);
606 } else {
607 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/ true);
608 }
609 }
610 } else {
611 switch (M->getStorageDuration()) {
612 case SD_Automatic:
613 if (EmitLifetimeStart(Alloca.getPointer())) {
615 Alloca);
616 }
617 break;
618
619 case SD_FullExpression: {
620 if (!ShouldEmitLifetimeMarkers)
621 break;
622
623 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
624 // marker. Instead, start the lifetime of a conditional temporary earlier
625 // so that it's unconditional. Don't do this with sanitizers which need
626 // more precise lifetime marks. However when inside an "await.suspend"
627 // block, we should always avoid conditional cleanup because it creates
628 // boolean marker that lives across await_suspend, which can destroy coro
629 // frame.
630 ConditionalEvaluation *OldConditional = nullptr;
631 CGBuilderTy::InsertPoint OldIP;
633 ((!SanOpts.has(SanitizerKind::HWAddress) &&
634 !SanOpts.has(SanitizerKind::Memory) &&
635 !SanOpts.has(SanitizerKind::MemtagStack) &&
636 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
637 inSuspendBlock())) {
638 OldConditional = OutermostConditional;
639 OutermostConditional = nullptr;
640
641 OldIP = Builder.saveIP();
642 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
643 Builder.restoreIP(CGBuilderTy::InsertPoint(
644 Block, llvm::BasicBlock::iterator(Block->back())));
645 }
646
647 if (EmitLifetimeStart(Alloca.getPointer())) {
649 }
650
651 if (OldConditional) {
652 OutermostConditional = OldConditional;
653 Builder.restoreIP(OldIP);
654 }
655 break;
656 }
657
658 default:
659 break;
660 }
661 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
662 }
663 pushTemporaryCleanup(*this, M, E, Object);
664
665 // Perform derived-to-base casts and/or field accesses, to get from the
666 // temporary object we created (and, potentially, for which we extended
667 // the lifetime) to the subobject we're binding the reference to.
668 for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
669 switch (Adjustment.Kind) {
671 Object =
672 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
673 Adjustment.DerivedToBase.BasePath->path_begin(),
674 Adjustment.DerivedToBase.BasePath->path_end(),
675 /*NullCheckValue=*/ false, E->getExprLoc());
676 break;
677
680 LV = EmitLValueForField(LV, Adjustment.Field);
681 assert(LV.isSimple() &&
682 "materialized temporary field is not a simple lvalue");
683 Object = LV.getAddress();
684 break;
685 }
686
688 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
690 E, Object, Ptr, Adjustment.Ptr.MPT, /*IsInBounds=*/true);
691 break;
692 }
693 }
694 }
695
697}
698
699RValue
701 // Emit the expression as an lvalue.
702 LValue LV = EmitLValue(E);
703 assert(LV.isSimple());
704 llvm::Value *Value = LV.getPointer(*this);
705
707 // C++11 [dcl.ref]p5 (as amended by core issue 453):
708 // If a glvalue to which a reference is directly bound designates neither
709 // an existing object or function of an appropriate type nor a region of
710 // storage of suitable size and alignment to contain an object of the
711 // reference's type, the behavior is undefined.
712 QualType Ty = E->getType();
714 }
715
716 return RValue::get(Value);
717}
718
719
720/// getAccessedFieldNo - Given an encoded value and a result number, return the
721/// input field number being accessed.
723 const llvm::Constant *Elts) {
724 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
725 ->getZExtValue();
726}
727
728static llvm::Value *emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc,
729 llvm::Value *Ptr) {
730 llvm::Value *A0 =
731 Builder.CreateMul(Ptr, Builder.getInt64(0xbf58476d1ce4e5b9u));
732 llvm::Value *A1 =
733 Builder.CreateXor(A0, Builder.CreateLShr(A0, Builder.getInt64(31)));
734 return Builder.CreateXor(Acc, A1);
735}
736
741
744 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
745 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
748}
749
751 return SanOpts.has(SanitizerKind::Null) ||
752 SanOpts.has(SanitizerKind::Alignment) ||
753 SanOpts.has(SanitizerKind::ObjectSize) ||
754 SanOpts.has(SanitizerKind::Vptr);
755}
756
758 llvm::Value *Ptr, QualType Ty,
759 CharUnits Alignment,
760 SanitizerSet SkippedChecks,
761 llvm::Value *ArraySize) {
763 return;
764
765 // Don't check pointers outside the default address space. The null check
766 // isn't correct, the object-size check isn't supported by LLVM, and we can't
767 // communicate the addresses to the runtime handler for the vptr check.
768 if (Ptr->getType()->getPointerAddressSpace())
769 return;
770
771 // Don't check pointers to volatile data. The behavior here is implementation-
772 // defined.
773 if (Ty.isVolatileQualified())
774 return;
775
776 // Quickly determine whether we have a pointer to an alloca. It's possible
777 // to skip null checks, and some alignment checks, for these pointers. This
778 // can reduce compile-time significantly.
779 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
780
781 llvm::Value *IsNonNull = nullptr;
782 bool IsGuaranteedNonNull =
783 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
784
785 llvm::BasicBlock *Done = nullptr;
786 bool DoneViaNullSanitize = false;
787
788 {
789 auto CheckHandler = SanitizerHandler::TypeMismatch;
790 SanitizerDebugLocation SanScope(this,
791 {SanitizerKind::SO_Null,
792 SanitizerKind::SO_ObjectSize,
793 SanitizerKind::SO_Alignment},
794 CheckHandler);
795
797 Checks;
798
799 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
800 bool AllowNullPointers = isNullPointerAllowed(TCK);
801 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
802 !IsGuaranteedNonNull) {
803 // The glvalue must not be an empty glvalue.
804 IsNonNull = Builder.CreateIsNotNull(Ptr);
805
806 // The IR builder can constant-fold the null check if the pointer points
807 // to a constant.
808 IsGuaranteedNonNull = IsNonNull == True;
809
810 // Skip the null check if the pointer is known to be non-null.
811 if (!IsGuaranteedNonNull) {
812 if (AllowNullPointers) {
813 // When performing pointer casts, it's OK if the value is null.
814 // Skip the remaining checks in that case.
815 Done = createBasicBlock("null");
816 DoneViaNullSanitize = true;
817 llvm::BasicBlock *Rest = createBasicBlock("not.null");
818 Builder.CreateCondBr(IsNonNull, Rest, Done);
819 EmitBlock(Rest);
820 } else {
821 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::SO_Null));
822 }
823 }
824 }
825
826 if (SanOpts.has(SanitizerKind::ObjectSize) &&
827 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
828 !Ty->isIncompleteType()) {
829 uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
830 llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
831 if (ArraySize)
832 Size = Builder.CreateMul(Size, ArraySize);
833
834 // Degenerate case: new X[0] does not need an objectsize check.
835 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
836 if (!ConstantSize || !ConstantSize->isNullValue()) {
837 // The glvalue must refer to a large enough storage region.
838 // FIXME: If Address Sanitizer is enabled, insert dynamic
839 // instrumentation
840 // to check this.
841 // FIXME: Get object address space
842 llvm::Type *Tys[2] = {IntPtrTy, Int8PtrTy};
843 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
844 llvm::Value *Min = Builder.getFalse();
845 llvm::Value *NullIsUnknown = Builder.getFalse();
846 llvm::Value *Dynamic = Builder.getFalse();
847 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
848 Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
849 Checks.push_back(
850 std::make_pair(LargeEnough, SanitizerKind::SO_ObjectSize));
851 }
852 }
853
854 llvm::MaybeAlign AlignVal;
855 llvm::Value *PtrAsInt = nullptr;
856
857 if (SanOpts.has(SanitizerKind::Alignment) &&
858 !SkippedChecks.has(SanitizerKind::Alignment)) {
859 AlignVal = Alignment.getAsMaybeAlign();
860 if (!Ty->isIncompleteType() && !AlignVal)
861 AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
862 /*ForPointeeType=*/true)
863 .getAsMaybeAlign();
864
865 // The glvalue must be suitably aligned.
866 if (AlignVal && *AlignVal > llvm::Align(1) &&
867 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
868 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
869 llvm::Value *Align = Builder.CreateAnd(
870 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
871 llvm::Value *Aligned =
872 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
873 if (Aligned != True)
874 Checks.push_back(
875 std::make_pair(Aligned, SanitizerKind::SO_Alignment));
876 }
877 }
878
879 if (Checks.size() > 0) {
880 llvm::Constant *StaticData[] = {
882 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
883 llvm::ConstantInt::get(Int8Ty, TCK)};
884 EmitCheck(Checks, CheckHandler, StaticData, PtrAsInt ? PtrAsInt : Ptr);
885 }
886 }
887
888 // If possible, check that the vptr indicates that there is a subobject of
889 // type Ty at offset zero within this object.
890 //
891 // C++11 [basic.life]p5,6:
892 // [For storage which does not refer to an object within its lifetime]
893 // The program has undefined behavior if:
894 // -- the [pointer or glvalue] is used to access a non-static data member
895 // or call a non-static member function
896 if (SanOpts.has(SanitizerKind::Vptr) &&
897 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
898 SanitizerDebugLocation SanScope(this, {SanitizerKind::SO_Vptr},
899 SanitizerHandler::DynamicTypeCacheMiss);
900
901 // Ensure that the pointer is non-null before loading it. If there is no
902 // compile-time guarantee, reuse the run-time null check or emit a new one.
903 if (!IsGuaranteedNonNull) {
904 if (!IsNonNull)
905 IsNonNull = Builder.CreateIsNotNull(Ptr);
906 if (!Done)
907 Done = createBasicBlock("vptr.null");
908 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
909 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
910 EmitBlock(VptrNotNull);
911 }
912
913 // Compute a deterministic hash of the mangled name of the type.
914 SmallString<64> MangledName;
915 llvm::raw_svector_ostream Out(MangledName);
916 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
917 Out);
918
919 // Contained in NoSanitizeList based on the mangled type.
920 if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
921 Out.str())) {
922 // Load the vptr, and mix it with TypeHash.
923 llvm::Value *TypeHash =
924 llvm::ConstantInt::get(Int64Ty, xxh3_64bits(Out.str()));
925
926 llvm::Type *VPtrTy = llvm::PointerType::get(getLLVMContext(), 0);
927 Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign());
928 llvm::Value *VPtrVal = GetVTablePtr(VPtrAddr, VPtrTy,
929 Ty->getAsCXXRecordDecl(),
931 VPtrVal = Builder.CreateBitOrPointerCast(VPtrVal, IntPtrTy);
932
933 llvm::Value *Hash =
934 emitHashMix(Builder, TypeHash, Builder.CreateZExt(VPtrVal, Int64Ty));
935 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
936
937 // Look the hash up in our cache.
938 const int CacheSize = 128;
939 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
940 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
941 "__ubsan_vptr_type_cache");
942 llvm::Value *Slot = Builder.CreateAnd(Hash,
943 llvm::ConstantInt::get(IntPtrTy,
944 CacheSize-1));
945 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
946 llvm::Value *CacheVal = Builder.CreateAlignedLoad(
947 IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
949
950 // If the hash isn't in the cache, call a runtime handler to perform the
951 // hard work of checking whether the vptr is for an object of the right
952 // type. This will either fill in the cache and return, or produce a
953 // diagnostic.
954 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
955 llvm::Constant *StaticData[] = {
958 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
959 llvm::ConstantInt::get(Int8Ty, TCK)
960 };
961 llvm::Value *DynamicData[] = { Ptr, Hash };
962 EmitCheck(std::make_pair(EqualHash, SanitizerKind::SO_Vptr),
963 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
964 DynamicData);
965 }
966 }
967
968 if (Done) {
969 SanitizerDebugLocation SanScope(
970 this,
971 {DoneViaNullSanitize ? SanitizerKind::SO_Null : SanitizerKind::SO_Vptr},
972 DoneViaNullSanitize ? SanitizerHandler::TypeMismatch
973 : SanitizerHandler::DynamicTypeCacheMiss);
974 Builder.CreateBr(Done);
975 EmitBlock(Done);
976 }
977}
978
980 QualType EltTy) {
982 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
983 if (!EltSize)
984 return nullptr;
985
986 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
987 if (!ArrayDeclRef)
988 return nullptr;
989
990 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
991 if (!ParamDecl)
992 return nullptr;
993
994 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
995 if (!POSAttr)
996 return nullptr;
997
998 // Don't load the size if it's a lower bound.
999 int POSType = POSAttr->getType();
1000 if (POSType != 0 && POSType != 1)
1001 return nullptr;
1002
1003 // Find the implicit size parameter.
1004 auto PassedSizeIt = SizeArguments.find(ParamDecl);
1005 if (PassedSizeIt == SizeArguments.end())
1006 return nullptr;
1007
1008 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
1009 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
1010 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
1011 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
1012 C.getSizeType(), E->getExprLoc());
1013 llvm::Value *SizeOfElement =
1014 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
1015 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
1016}
1017
1018/// If Base is known to point to the start of an array, return the length of
1019/// that array. Return 0 if the length cannot be determined.
1021 const Expr *Base,
1022 QualType &IndexedType,
1024 StrictFlexArraysLevel) {
1025 // For the vector indexing extension, the bound is the number of elements.
1026 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
1027 IndexedType = Base->getType();
1028 return CGF.Builder.getInt32(VT->getNumElements());
1029 }
1030
1031 Base = Base->IgnoreParens();
1032
1033 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1034 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
1035 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
1036 StrictFlexArraysLevel)) {
1037 CodeGenFunction::SanitizerScope SanScope(&CGF);
1038
1039 IndexedType = CE->getSubExpr()->getType();
1040 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
1041 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
1042 return CGF.Builder.getInt(CAT->getSize());
1043
1044 if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
1045 return CGF.getVLASize(VAT).NumElts;
1046 // Ignore pass_object_size here. It's not applicable on decayed pointers.
1047 }
1048 }
1049
1050 CodeGenFunction::SanitizerScope SanScope(&CGF);
1051
1052 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
1053 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
1054 IndexedType = Base->getType();
1055 return POS;
1056 }
1057
1058 return nullptr;
1059}
1060
1061/// Returns true if \p Field is reachable from \p RD either as a direct field or
1062/// through a chain of nested record fields (including anonymous
1063/// structs/unions). This mirrors the GEP path that getGEPIndicesToField builds,
1064/// and is used to identify the right anchor expression in Base.
1065static bool RecordContainsField(const RecordDecl *RD, const FieldDecl *Field) {
1066 for (const FieldDecl *FD : RD->fields()) {
1067 if (FD == Field)
1068 return true;
1069 QualType Ty = FD->getType();
1070 if (Ty->isRecordType())
1071 if (RecordContainsField(Ty->getAsRecordDecl(), Field))
1072 return true;
1073 }
1074 return false;
1075}
1076
1077namespace {
1078
1079/// \p StructAccessBase returns the base \p Expr of a field access. It returns
1080/// either a \p DeclRefExpr, representing the base pointer to the struct, i.e.:
1081///
1082/// p in p-> a.b.c
1083///
1084/// or a \p MemberExpr, if the \p MemberExpr has the \p RecordDecl we're
1085/// looking for:
1086///
1087/// struct s {
1088/// struct s *ptr;
1089/// int count;
1090/// char array[] __attribute__((counted_by(count)));
1091/// };
1092///
1093/// If we have an expression like \p p->ptr->array[index], we want the
1094/// \p MemberExpr for \p p->ptr instead of \p p.
1095class StructAccessBase
1096 : public ConstStmtVisitor<StructAccessBase, const Expr *> {
1097 /// The count field we're navigating to. We stop at the innermost expression
1098 /// whose struct type transitively contains this field, so that
1099 /// getGEPIndicesToField can navigate from that struct down to it.
1100 const FieldDecl *CountDecl;
1101
1102 /// Returns true if E's record type (or pointee record type) transitively
1103 /// contains CountDecl. Handles both direct containment and nested structs,
1104 /// so we don't need a pre-computed RD from the caller.
1105 bool IsExpectedRecordDecl(const Expr *E) const {
1106 QualType Ty = E->getType();
1107 if (Ty->isPointerType())
1108 Ty = Ty->getPointeeType();
1109 const RecordDecl *RD = Ty->getAsRecordDecl();
1110 return RD && RecordContainsField(RD, CountDecl);
1111 }
1112
1113public:
1114 StructAccessBase(const FieldDecl *CountDecl) : CountDecl(CountDecl) {}
1115
1116 //===--------------------------------------------------------------------===//
1117 // Visitor Methods
1118 //===--------------------------------------------------------------------===//
1119
1120 // NOTE: If we build C++ support for counted_by, then we'll have to handle
1121 // horrors like this:
1122 //
1123 // struct S {
1124 // int x, y;
1125 // int blah[] __attribute__((counted_by(x)));
1126 // } s;
1127 //
1128 // int foo(int index, int val) {
1129 // int (S::*IHatePMDs)[] = &S::blah;
1130 // (s.*IHatePMDs)[index] = val;
1131 // }
1132
1133 const Expr *Visit(const Expr *E) {
1134 return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(E);
1135 }
1136
1137 const Expr *VisitStmt(const Stmt *S) { return nullptr; }
1138
1139 // These are the types we expect to return (in order of most to least
1140 // likely):
1141 //
1142 // 1. DeclRefExpr - This is the expression for the base of the structure.
1143 // It's exactly what we want to build an access to the \p counted_by
1144 // field.
1145 // 2. MemberExpr - This is the expression that has the same \p RecordDecl
1146 // as the flexble array member's lexical enclosing \p RecordDecl. This
1147 // allows us to catch things like: "p->p->array"
1148 // 3. CompoundLiteralExpr - This is for people who create something
1149 // heretical like (struct foo has a flexible array member):
1150 //
1151 // (struct foo){ 1, 2 }.blah[idx];
1152 const Expr *VisitDeclRefExpr(const DeclRefExpr *E) {
1153 return IsExpectedRecordDecl(E) ? E : nullptr;
1154 }
1155 const Expr *VisitMemberExpr(const MemberExpr *E) {
1156 if (IsExpectedRecordDecl(E) && E->isArrow())
1157 return E;
1158 const Expr *Res = Visit(E->getBase());
1159 return !Res && IsExpectedRecordDecl(E) ? E : Res;
1160 }
1161 const Expr *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1162 return IsExpectedRecordDecl(E) ? E : nullptr;
1163 }
1164 const Expr *VisitCallExpr(const CallExpr *E) {
1165 return IsExpectedRecordDecl(E) ? E : nullptr;
1166 }
1167
1168 const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1169 if (IsExpectedRecordDecl(E))
1170 return E;
1171 return Visit(E->getBase());
1172 }
1173 const Expr *VisitCastExpr(const CastExpr *E) {
1174 if (E->getCastKind() == CK_LValueToRValue)
1175 return IsExpectedRecordDecl(E) ? E : nullptr;
1176 return Visit(E->getSubExpr());
1177 }
1178 const Expr *VisitParenExpr(const ParenExpr *E) {
1179 return Visit(E->getSubExpr());
1180 }
1181 const Expr *VisitUnaryAddrOf(const UnaryOperator *E) {
1182 return Visit(E->getSubExpr());
1183 }
1184 const Expr *VisitUnaryDeref(const UnaryOperator *E) {
1185 return Visit(E->getSubExpr());
1186 }
1187};
1188
1189} // end anonymous namespace
1190
1192
1194 const FieldDecl *Field,
1195 RecIndicesTy &Indices) {
1196 const CGRecordLayout &Layout = CGF.CGM.getTypes().getCGRecordLayout(RD);
1197 int64_t FieldNo = -1;
1198 for (const FieldDecl *FD : RD->fields()) {
1199 if (!Layout.containsFieldDecl(FD))
1200 // This could happen if the field has a struct type that's empty. I don't
1201 // know why either.
1202 continue;
1203
1204 FieldNo = Layout.getLLVMFieldNo(FD);
1205 if (FD == Field) {
1206 Indices.emplace_back(CGF.Builder.getInt32(FieldNo));
1207 return true;
1208 }
1209
1210 QualType Ty = FD->getType();
1211 if (Ty->isRecordType()) {
1212 if (getGEPIndicesToField(CGF, Ty->getAsRecordDecl(), Field, Indices)) {
1213 if (RD->isUnion())
1214 FieldNo = 0;
1215 Indices.emplace_back(CGF.Builder.getInt32(FieldNo));
1216 return true;
1217 }
1218 }
1219 }
1220
1221 return false;
1222}
1223
1225 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1226 // Walk Base to find the deepest sub-expression whose struct type transitively
1227 // contains CountDecl. This is our GEP anchor — getGEPIndicesToField then
1228 // builds the field indices from that struct down to CountDecl, handling any
1229 // intermediate nesting without requiring us to pre-compute a RecordDecl from
1230 // Base's type or from CountDecl's parent chain.
1231 const Expr *StructBase = StructAccessBase(CountDecl).Visit(Base);
1232 if (!StructBase || StructBase->HasSideEffects(getContext()))
1233 return nullptr;
1234
1235 // Derive the record type from the anchor expression itself.
1236 QualType StructTy = StructBase->getType();
1237 if (StructTy->isPointerType())
1238 StructTy = StructTy->getPointeeType();
1239 const RecordDecl *RD = StructTy->getAsRecordDecl();
1240 if (!RD)
1241 return nullptr;
1242
1243 llvm::Value *Res = nullptr;
1244 if (StructBase->getType()->isPointerType()) {
1245 LValueBaseInfo BaseInfo;
1246 TBAAAccessInfo TBAAInfo;
1247 Address Addr = EmitPointerWithAlignment(StructBase, &BaseInfo, &TBAAInfo);
1248 Res = Addr.emitRawPointer(*this);
1249 } else if (StructBase->isLValue()) {
1250 LValue LV = EmitLValue(StructBase);
1251 Address Addr = LV.getAddress();
1252 Res = Addr.emitRawPointer(*this);
1253 } else {
1254 return nullptr;
1255 }
1256
1257 RecIndicesTy Indices;
1258 getGEPIndicesToField(*this, RD, CountDecl, Indices);
1259 if (Indices.empty())
1260 return nullptr;
1261
1262 Indices.push_back(Builder.getInt32(0));
1263 CanQualType T = CGM.getContext().getCanonicalTagType(RD);
1264 return Builder.CreateInBoundsGEP(ConvertType(T), Res,
1265 RecIndicesTy(llvm::reverse(Indices)),
1266 "counted_by.gep");
1267}
1268
1269/// This method is typically called in contexts where we can't generate
1270/// side-effects, like in __builtin_dynamic_object_size. When finding
1271/// expressions, only choose those that have either already been emitted or can
1272/// be loaded without side-effects.
1273///
1274/// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
1275/// within the top-level struct.
1276/// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
1278 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1279 if (llvm::Value *GEP = GetCountedByFieldExprGEP(Base, FAMDecl, CountDecl))
1280 return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), GEP,
1281 getIntAlign(), "counted_by.load");
1282 return nullptr;
1283}
1284
1286 const Expr *ArrayExprBase,
1287 llvm::Value *IndexVal, QualType IndexType,
1288 bool Accessed) {
1289 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
1290 "should not be called unless adding bounds checks");
1291 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
1292 getLangOpts().getStrictFlexArraysLevel();
1293 QualType ArrayExprBaseType;
1294 llvm::Value *BoundsVal = getArrayIndexingBound(
1295 *this, ArrayExprBase, ArrayExprBaseType, StrictFlexArraysLevel);
1296
1297 EmitBoundsCheckImpl(ArrayExpr, ArrayExprBaseType, IndexVal, IndexType,
1298 BoundsVal, getContext().getSizeType(), Accessed);
1299}
1300
1302 QualType ArrayBaseType,
1303 llvm::Value *IndexVal,
1304 QualType IndexType,
1305 llvm::Value *BoundsVal,
1306 QualType BoundsType, bool Accessed) {
1307 if (!BoundsVal)
1308 return;
1309
1310 auto CheckKind = SanitizerKind::SO_ArrayBounds;
1311 auto CheckHandler = SanitizerHandler::OutOfBounds;
1312 SanitizerDebugLocation SanScope(this, {CheckKind}, CheckHandler);
1313
1314 // All hail the C implicit type conversion rules!!!
1315 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
1316 bool BoundsSigned = BoundsType->isSignedIntegerOrEnumerationType();
1317
1318 const ASTContext &Ctx = getContext();
1319 llvm::Type *Ty = ConvertType(
1320 Ctx.getTypeSize(IndexType) >= Ctx.getTypeSize(BoundsType) ? IndexType
1321 : BoundsType);
1322
1323 llvm::Value *IndexInst = Builder.CreateIntCast(IndexVal, Ty, IndexSigned);
1324 llvm::Value *BoundsInst = Builder.CreateIntCast(BoundsVal, Ty, false);
1325
1326 llvm::Constant *StaticData[] = {
1327 EmitCheckSourceLocation(ArrayExpr->getExprLoc()),
1328 EmitCheckTypeDescriptor(ArrayBaseType),
1329 EmitCheckTypeDescriptor(IndexType),
1330 };
1331
1332 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexInst, BoundsInst)
1333 : Builder.CreateICmpULE(IndexInst, BoundsInst);
1334
1335 if (BoundsSigned) {
1336 // Don't allow a negative bounds.
1337 llvm::Value *Cmp = Builder.CreateICmpSGT(
1338 BoundsVal, llvm::ConstantInt::get(BoundsVal->getType(), 0));
1339 Check = Builder.CreateAnd(Cmp, Check);
1340 }
1341
1342 EmitCheck(std::make_pair(Check, CheckKind), CheckHandler, StaticData,
1343 IndexInst);
1344}
1345
1347 auto ATMD = infer_alloc::getAllocTokenMetadata(AllocType, getContext());
1348 if (!ATMD)
1349 return nullptr;
1350
1351 llvm::MDBuilder MDB(getLLVMContext());
1352 auto *TypeNameMD = MDB.createString(ATMD->TypeName);
1353 auto *ContainsPtrC = Builder.getInt1(ATMD->ContainsPointer);
1354 auto *ContainsPtrMD = MDB.createConstant(ContainsPtrC);
1355
1356 // Format: !{<type-name>, <contains-pointer>}
1357 return llvm::MDNode::get(CGM.getLLVMContext(), {TypeNameMD, ContainsPtrMD});
1358}
1359
1360void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
1361 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1362 "Only needed with -fsanitize=alloc-token");
1363 CB->setMetadata(llvm::LLVMContext::MD_alloc_token,
1364 buildAllocToken(AllocType));
1365}
1366
1369 if (!AllocType.isNull())
1370 return buildAllocToken(AllocType);
1371 return nullptr;
1372}
1373
1374void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
1375 assert(SanOpts.has(SanitizerKind::AllocToken) &&
1376 "Only needed with -fsanitize=alloc-token");
1377 if (llvm::MDNode *MDN = buildAllocToken(E))
1378 CB->setMetadata(llvm::LLVMContext::MD_alloc_token, MDN);
1379}
1380
1383 bool isInc, bool isPre) {
1384 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1385
1386 llvm::Value *NextVal;
1387 if (isa<llvm::IntegerType>(InVal.first->getType())) {
1388 uint64_t AmountVal = isInc ? 1 : -1;
1389 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1390
1391 // Add the inc/dec to the real part.
1392 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1393 } else {
1394 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1395 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1396 if (!isInc)
1397 FVal.changeSign();
1398 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1399
1400 // Add the inc/dec to the real part.
1401 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1402 }
1403
1404 ComplexPairTy IncVal(NextVal, InVal.second);
1405
1406 // Store the updated result through the lvalue.
1407 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1408 if (getLangOpts().OpenMP)
1409 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1410 E->getSubExpr());
1411
1412 // If this is a postinc, return the value read from memory, otherwise use the
1413 // updated value.
1414 return isPre ? IncVal : InVal;
1415}
1416
1418 CodeGenFunction *CGF) {
1419 // Bind VLAs in the cast type.
1420 if (CGF && E->getType()->isVariablyModifiedType())
1422
1423 if (CGDebugInfo *DI = getModuleDebugInfo())
1424 DI->EmitExplicitCastType(E->getType());
1425}
1426
1427//===----------------------------------------------------------------------===//
1428// LValue Expression Emission
1429//===----------------------------------------------------------------------===//
1430
1431static CharUnits getArrayElementAlign(CharUnits arrayAlign, llvm::Value *idx,
1432 CharUnits eltSize) {
1433 // If we have a constant index, we can use the exact offset of the
1434 // element we're accessing.
1435 if (auto *constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
1436 CharUnits offset = constantIdx->getZExtValue() * eltSize;
1437 return arrayAlign.alignmentAtOffset(offset);
1438 }
1439
1440 // Otherwise, use the worst-case alignment for any element.
1441 return arrayAlign.alignmentOfArrayElement(eltSize);
1442}
1443
1444/// Emit pointer + index arithmetic.
1446 const BinaryOperator *BO,
1447 LValueBaseInfo *BaseInfo,
1448 TBAAAccessInfo *TBAAInfo,
1449 KnownNonNull_t IsKnownNonNull) {
1450 assert(BO->isAdditiveOp() && "Expect an addition or subtraction.");
1451 Expr *pointerOperand = BO->getLHS();
1452 Expr *indexOperand = BO->getRHS();
1453 bool isSubtraction = BO->getOpcode() == BO_Sub;
1454
1455 Address BaseAddr = Address::invalid();
1456 llvm::Value *index = nullptr;
1457 // In a subtraction, the LHS is always the pointer.
1458 // Note: do not change the evaluation order.
1459 if (!isSubtraction && !pointerOperand->getType()->isAnyPointerType()) {
1460 std::swap(pointerOperand, indexOperand);
1461 index = CGF.EmitScalarExpr(indexOperand);
1462 BaseAddr = CGF.EmitPointerWithAlignment(pointerOperand, BaseInfo, TBAAInfo,
1464 } else {
1465 BaseAddr = CGF.EmitPointerWithAlignment(pointerOperand, BaseInfo, TBAAInfo,
1467 index = CGF.EmitScalarExpr(indexOperand);
1468 }
1469
1470 llvm::Value *pointer = BaseAddr.getBasePointer();
1471 llvm::Value *Res = CGF.EmitPointerArithmetic(
1472 BO, pointerOperand, pointer, indexOperand, index, isSubtraction);
1473 QualType PointeeTy = BO->getType()->getPointeeType();
1474 CharUnits Align =
1476 CGF.getContext().getTypeSizeInChars(PointeeTy));
1477 return Address(Res, CGF.ConvertTypeForMem(PointeeTy), Align,
1479 /*Offset=*/nullptr, IsKnownNonNull);
1480}
1481
1483 TBAAAccessInfo *TBAAInfo,
1484 KnownNonNull_t IsKnownNonNull,
1485 CodeGenFunction &CGF) {
1486 // We allow this with ObjC object pointers because of fragile ABIs.
1487 assert(E->getType()->isPointerType() ||
1489 E = E->IgnoreParens();
1490
1491 // Casts:
1492 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1493 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1494 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
1495
1496 switch (CE->getCastKind()) {
1497 // Non-converting casts (but not C's implicit conversion from void*).
1498 case CK_BitCast:
1499 case CK_NoOp:
1500 case CK_AddressSpaceConversion:
1501 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1502 if (PtrTy->getPointeeType()->isVoidType())
1503 break;
1504
1505 LValueBaseInfo InnerBaseInfo;
1506 TBAAAccessInfo InnerTBAAInfo;
1508 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1509 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1510 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1511
1512 if (isa<ExplicitCastExpr>(CE)) {
1513 LValueBaseInfo TargetTypeBaseInfo;
1514 TBAAAccessInfo TargetTypeTBAAInfo;
1516 E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1517 if (TBAAInfo)
1518 *TBAAInfo =
1519 CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
1520 // If the source l-value is opaque, honor the alignment of the
1521 // casted-to type.
1522 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1523 if (BaseInfo)
1524 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1525 Addr.setAlignment(Align);
1526 }
1527 }
1528
1529 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1530 CE->getCastKind() == CK_BitCast) {
1531 if (auto PT = E->getType()->getAs<PointerType>())
1532 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
1533 /*MayBeNull=*/true,
1535 CE->getBeginLoc());
1536 }
1537
1538 llvm::Type *ElemTy =
1540 Addr = Addr.withElementType(ElemTy);
1541 if (CE->getCastKind() == CK_AddressSpaceConversion)
1543 Addr, CGF.ConvertType(E->getType()), ElemTy);
1544
1545 return CGF.authPointerToPointerCast(Addr, CE->getSubExpr()->getType(),
1546 CE->getType());
1547 }
1548 break;
1549
1550 // Array-to-pointer decay.
1551 case CK_ArrayToPointerDecay:
1552 return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1553
1554 // Derived-to-base conversions.
1555 case CK_UncheckedDerivedToBase:
1556 case CK_DerivedToBase: {
1557 // TODO: Support accesses to members of base classes in TBAA. For now, we
1558 // conservatively pretend that the complete object is of the base class
1559 // type.
1560 if (TBAAInfo)
1561 *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1563 CE->getSubExpr(), BaseInfo, nullptr,
1564 (KnownNonNull_t)(IsKnownNonNull ||
1565 CE->getCastKind() == CK_UncheckedDerivedToBase));
1566 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1567 return CGF.GetAddressOfBaseClass(
1568 Addr, Derived, CE->path_begin(), CE->path_end(),
1569 CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1570 }
1571
1572 // TODO: Is there any reason to treat base-to-derived conversions
1573 // specially?
1574 default:
1575 break;
1576 }
1577 }
1578
1579 // Unary &.
1580 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1581 if (UO->getOpcode() == UO_AddrOf) {
1582 LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1583 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1584 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1585 return LV.getAddress();
1586 }
1587 }
1588
1589 // std::addressof and variants.
1590 if (auto *Call = dyn_cast<CallExpr>(E)) {
1591 switch (Call->getBuiltinCallee()) {
1592 default:
1593 break;
1594 case Builtin::BIaddressof:
1595 case Builtin::BI__addressof:
1596 case Builtin::BI__builtin_addressof: {
1597 LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
1598 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1599 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1600 return LV.getAddress();
1601 }
1602 }
1603 }
1604
1605 // Pointer arithmetic: pointer +/- index.
1606 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
1607 if (BO->isAdditiveOp())
1608 return emitPointerArithmetic(CGF, BO, BaseInfo, TBAAInfo, IsKnownNonNull);
1609 }
1610
1611 // TODO: conditional operators, comma.
1612
1613 // Otherwise, use the alignment of the type.
1616 /*ForPointeeType=*/true, BaseInfo, TBAAInfo, IsKnownNonNull);
1617}
1618
1619/// EmitPointerWithAlignment - Given an expression of pointer type, try to
1620/// derive a more accurate bound on the alignment of the pointer.
1622 const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1623 KnownNonNull_t IsKnownNonNull) {
1624 Address Addr =
1625 ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1626 if (IsKnownNonNull && !Addr.isKnownNonNull())
1627 Addr.setKnownNonNull();
1628 return Addr;
1629}
1630
1632 llvm::Value *V = RV.getScalarVal();
1633 if (auto MPT = T->getAs<MemberPointerType>())
1634 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1635 return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1636}
1637
1639 if (Ty->isVoidType())
1640 return RValue::get(nullptr);
1641
1642 switch (getEvaluationKind(Ty)) {
1643 case TEK_Complex: {
1644 llvm::Type *EltTy =
1646 llvm::Value *U = llvm::UndefValue::get(EltTy);
1647 return RValue::getComplex(std::make_pair(U, U));
1648 }
1649
1650 // If this is a use of an undefined aggregate type, the aggregate must have an
1651 // identifiable address. Just because the contents of the value are undefined
1652 // doesn't mean that the address can't be taken and compared.
1653 case TEK_Aggregate: {
1654 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1655 return RValue::getAggregate(DestPtr);
1656 }
1657
1658 case TEK_Scalar:
1659 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1660 }
1661 llvm_unreachable("bad evaluation kind");
1662}
1663
1665 const char *Name) {
1666 ErrorUnsupported(E, Name);
1667 return GetUndefRValue(E->getType());
1668}
1669
1671 const char *Name) {
1672 ErrorUnsupported(E, Name);
1673 llvm::Type *ElTy = ConvertType(E->getType());
1674 llvm::Type *Ty = DefaultPtrTy;
1675 return MakeAddrLValue(
1676 Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
1677}
1678
1680 const Expr *Base = Obj;
1681 while (!isa<CXXThisExpr>(Base)) {
1682 // The result of a dynamic_cast can be null.
1684 return false;
1685
1686 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1687 Base = CE->getSubExpr();
1688 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1689 Base = PE->getSubExpr();
1690 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1691 if (UO->getOpcode() == UO_Extension)
1692 Base = UO->getSubExpr();
1693 else
1694 return false;
1695 } else {
1696 return false;
1697 }
1698 }
1699 return true;
1700}
1701
1703 LValue LV;
1704 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1705 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1706 else
1707 LV = EmitLValue(E);
1708 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1709 SanitizerSet SkippedChecks;
1710 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1711 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1712 if (IsBaseCXXThis)
1713 SkippedChecks.set(SanitizerKind::Alignment, true);
1714 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1715 SkippedChecks.set(SanitizerKind::Null, true);
1716 }
1717 EmitTypeCheck(TCK, E->getExprLoc(), LV, E->getType(), SkippedChecks);
1718 }
1719 return LV;
1720}
1721
1722/// EmitLValue - Emit code to compute a designator that specifies the location
1723/// of the expression.
1724///
1725/// This can return one of two things: a simple address or a bitfield reference.
1726/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1727/// an LLVM pointer type.
1728///
1729/// If this returns a bitfield reference, nothing about the pointee type of the
1730/// LLVM value is known: For example, it may not be a pointer to an integer.
1731///
1732/// If this returns a normal address, and if the lvalue's C type is fixed size,
1733/// this method guarantees that the returned pointer type will point to an LLVM
1734/// type of the same size of the lvalue's type. If the lvalue has a variable
1735/// length type, this is not possible.
1736///
1738 KnownNonNull_t IsKnownNonNull) {
1739 // Running with sufficient stack space to avoid deeply nested expressions
1740 // cause a stack overflow.
1741 LValue LV;
1742 CGM.runWithSufficientStackSpace(
1743 E->getExprLoc(), [&] { LV = EmitLValueHelper(E, IsKnownNonNull); });
1744
1745 if (IsKnownNonNull && !LV.isKnownNonNull())
1746 LV.setKnownNonNull();
1747 return LV;
1748}
1749
1750LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1751 KnownNonNull_t IsKnownNonNull) {
1752 ApplyDebugLocation DL(*this, E);
1753 switch (E->getStmtClass()) {
1754 default: return EmitUnsupportedLValue(E, "l-value expression");
1755
1756 case Expr::ObjCPropertyRefExprClass:
1757 llvm_unreachable("cannot emit a property reference directly");
1758
1759 case Expr::ObjCSelectorExprClass:
1761 case Expr::ObjCIsaExprClass:
1763 case Expr::BinaryOperatorClass:
1765 case Expr::CompoundAssignOperatorClass: {
1766 QualType Ty = E->getType();
1767 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1768 Ty = AT->getValueType();
1769 if (!Ty->isAnyComplexType())
1772 }
1773 case Expr::CallExprClass:
1774 case Expr::CXXMemberCallExprClass:
1775 case Expr::CXXOperatorCallExprClass:
1776 case Expr::UserDefinedLiteralClass:
1778 case Expr::CXXRewrittenBinaryOperatorClass:
1779 return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1780 IsKnownNonNull);
1781 case Expr::VAArgExprClass:
1783 case Expr::DeclRefExprClass:
1785 case Expr::ConstantExprClass: {
1786 const ConstantExpr *CE = cast<ConstantExpr>(E);
1787 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE))
1789 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
1790 }
1791 case Expr::ParenExprClass:
1792 return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
1793 case Expr::GenericSelectionExprClass:
1794 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1795 IsKnownNonNull);
1796 case Expr::PredefinedExprClass:
1798 case Expr::StringLiteralClass:
1800 case Expr::ObjCEncodeExprClass:
1802 case Expr::PseudoObjectExprClass:
1804 case Expr::InitListExprClass:
1806 case Expr::CXXTemporaryObjectExprClass:
1807 case Expr::CXXConstructExprClass:
1809 case Expr::CXXBindTemporaryExprClass:
1811 case Expr::CXXUuidofExprClass:
1813 case Expr::LambdaExprClass:
1814 return EmitAggExprToLValue(E);
1815
1816 case Expr::ExprWithCleanupsClass: {
1817 const auto *cleanups = cast<ExprWithCleanups>(E);
1818 RunCleanupsScope Scope(*this);
1819 LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1820 if (LV.isSimple()) {
1821 // Defend against branches out of gnu statement expressions surrounded by
1822 // cleanups.
1823 Address Addr = LV.getAddress();
1824 llvm::Value *V = Addr.getBasePointer();
1825 Scope.ForceCleanup({&V});
1826 Addr.replaceBasePointer(V);
1827 return LValue::MakeAddr(Addr, LV.getType(), getContext(),
1828 LV.getBaseInfo(), LV.getTBAAInfo());
1829 }
1830 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1831 // bitfield lvalue or some other non-simple lvalue?
1832 return LV;
1833 }
1834
1835 case Expr::CXXDefaultArgExprClass: {
1836 auto *DAE = cast<CXXDefaultArgExpr>(E);
1837 CXXDefaultArgExprScope Scope(*this, DAE);
1838 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1839 }
1840 case Expr::CXXDefaultInitExprClass: {
1841 auto *DIE = cast<CXXDefaultInitExpr>(E);
1842 CXXDefaultInitExprScope Scope(*this, DIE);
1843 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1844 }
1845 case Expr::CXXTypeidExprClass:
1847
1848 case Expr::ObjCMessageExprClass:
1850 case Expr::ObjCIvarRefExprClass:
1852 case Expr::StmtExprClass:
1854 case Expr::UnaryOperatorClass:
1856 case Expr::ArraySubscriptExprClass:
1858 case Expr::MatrixSingleSubscriptExprClass:
1860 case Expr::MatrixSubscriptExprClass:
1862 case Expr::ArraySectionExprClass:
1864 case Expr::ExtVectorElementExprClass:
1866 case Expr::MatrixElementExprClass:
1868 case Expr::CXXThisExprClass:
1870 case Expr::MemberExprClass:
1872 case Expr::CompoundLiteralExprClass:
1874 case Expr::ConditionalOperatorClass:
1876 case Expr::BinaryConditionalOperatorClass:
1878 case Expr::ChooseExprClass:
1879 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
1880 case Expr::OpaqueValueExprClass:
1882 case Expr::SubstNonTypeTemplateParmExprClass:
1883 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1884 IsKnownNonNull);
1885 case Expr::ImplicitCastExprClass:
1886 case Expr::CStyleCastExprClass:
1887 case Expr::CXXFunctionalCastExprClass:
1888 case Expr::CXXStaticCastExprClass:
1889 case Expr::CXXDynamicCastExprClass:
1890 case Expr::CXXReinterpretCastExprClass:
1891 case Expr::CXXConstCastExprClass:
1892 case Expr::CXXAddrspaceCastExprClass:
1893 case Expr::ObjCBridgedCastExprClass:
1894 return EmitCastLValue(cast<CastExpr>(E));
1895
1896 case Expr::MaterializeTemporaryExprClass:
1898
1899 case Expr::CoawaitExprClass:
1901 case Expr::CoyieldExprClass:
1903 case Expr::PackIndexingExprClass:
1904 return EmitLValue(cast<PackIndexingExpr>(E)->getSelectedExpr());
1905 case Expr::HLSLOutArgExprClass:
1906 llvm_unreachable("cannot emit a HLSL out argument directly");
1907 }
1908}
1909
1910/// Given an object of the given canonical type, can we safely copy a
1911/// value out of it based on its initializer?
1913 assert(type.isCanonical());
1914 assert(!type->isReferenceType());
1915
1916 // Must be const-qualified but non-volatile.
1917 Qualifiers qs = type.getLocalQualifiers();
1918 if (!qs.hasConst() || qs.hasVolatile()) return false;
1919
1920 // Otherwise, all object types satisfy this except C++ classes with
1921 // mutable subobjects or non-trivial copy/destroy behavior.
1922 if (const auto *RT = dyn_cast<RecordType>(type))
1923 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1924 RD = RD->getDefinitionOrSelf();
1925 if (RD->hasMutableFields() || !RD->isTrivial())
1926 return false;
1927 }
1928
1929 return true;
1930}
1931
1932/// Can we constant-emit a load of a reference to a variable of the
1933/// given type? This is different from predicates like
1934/// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1935/// in situations that don't necessarily satisfy the language's rules
1936/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1937/// to do this with const float variables even if those variables
1938/// aren't marked 'constexpr'.
1946 type = type.getCanonicalType();
1947 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1948 if (isConstantEmittableObjectType(ref->getPointeeType()))
1950 return CEK_AsReferenceOnly;
1951 }
1953 return CEK_AsValueOnly;
1954 return CEK_None;
1955}
1956
1957/// Try to emit a reference to the given value without producing it as
1958/// an l-value. This is just an optimization, but it avoids us needing
1959/// to emit global copies of variables if they're named without triggering
1960/// a formal use in a context where we can't emit a direct reference to them,
1961/// for instance if a block or lambda or a member of a local class uses a
1962/// const int variable or constexpr variable from an enclosing function.
1965 const ValueDecl *Value = RefExpr->getDecl();
1966
1967 // The value needs to be an enum constant or a constant variable.
1969 if (isa<ParmVarDecl>(Value)) {
1970 CEK = CEK_None;
1971 } else if (const auto *var = dyn_cast<VarDecl>(Value)) {
1972 CEK = checkVarTypeForConstantEmission(var->getType());
1973 } else if (isa<EnumConstantDecl>(Value)) {
1974 CEK = CEK_AsValueOnly;
1975 } else {
1976 CEK = CEK_None;
1977 }
1978 if (CEK == CEK_None) return ConstantEmission();
1979
1980 Expr::EvalResult result;
1981 bool resultIsReference;
1982 QualType resultType;
1983
1984 // It's best to evaluate all the way as an r-value if that's permitted.
1985 if (CEK != CEK_AsReferenceOnly &&
1986 RefExpr->EvaluateAsRValue(result, getContext())) {
1987 resultIsReference = false;
1988 resultType = RefExpr->getType().getUnqualifiedType();
1989
1990 // Otherwise, try to evaluate as an l-value.
1991 } else if (CEK != CEK_AsValueOnly &&
1992 RefExpr->EvaluateAsLValue(result, getContext())) {
1993 resultIsReference = true;
1994 resultType = Value->getType();
1995
1996 // Failure.
1997 } else {
1998 return ConstantEmission();
1999 }
2000
2001 // In any case, if the initializer has side-effects, abandon ship.
2002 if (result.HasSideEffects)
2003 return ConstantEmission();
2004
2005 // In CUDA/HIP device compilation, a lambda may capture a reference variable
2006 // referencing a global host variable by copy. In this case the lambda should
2007 // make a copy of the value of the global host variable. The DRE of the
2008 // captured reference variable cannot be emitted as load from the host
2009 // global variable as compile time constant, since the host variable is not
2010 // accessible on device. The DRE of the captured reference variable has to be
2011 // loaded from captures.
2012 if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
2014 auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
2015 if (isLambdaMethod(MD) && MD->getOverloadedOperator() == OO_Call) {
2016 const APValue::LValueBase &base = result.Val.getLValueBase();
2017 if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
2018 if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
2019 if (!VD->hasAttr<CUDADeviceAttr>()) {
2020 return ConstantEmission();
2021 }
2022 }
2023 }
2024 }
2025 }
2026
2027 // Emit as a constant.
2028 llvm::Constant *C = ConstantEmitter(*this).emitAbstract(
2029 RefExpr->getLocation(), result.Val, resultType);
2030
2031 // Make sure we emit a debug reference to the global variable.
2032 // This should probably fire even for
2033 if (isa<VarDecl>(Value)) {
2034 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(Value)))
2035 EmitDeclRefExprDbgValue(RefExpr, result.Val);
2036 } else {
2038 EmitDeclRefExprDbgValue(RefExpr, result.Val);
2039 }
2040
2041 // If we emitted a reference constant, we need to dereference that.
2042 if (resultIsReference)
2044
2046}
2047
2049 const MemberExpr *ME) {
2050 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
2051 // Try to emit static variable member expressions as DREs.
2052 return DeclRefExpr::Create(
2054 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
2055 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
2056 }
2057 return nullptr;
2058}
2059
2063 return tryEmitAsConstant(DRE);
2064 return ConstantEmission();
2065}
2066
2069 assert(Constant && "not a constant");
2070 if (Constant.isReference())
2071 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
2072 E->getExprLoc())
2073 .getScalarVal();
2074 return Constant.getValue();
2075}
2076
2078 SourceLocation Loc) {
2079 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
2080 lvalue.getType(), Loc, lvalue.getBaseInfo(),
2081 lvalue.getTBAAInfo(), lvalue.isNontemporal());
2082}
2083
2084// This method SHOULD NOT be extended to support additional types, like BitInt
2085// types, without an opt-in bool controlled by a CodeGenOptions setting (like
2086// -fstrict-bool) and a new UBSan check (like SanitizerKind::Bool) as breaking
2087// that assumption would lead to memory corruption. See link for examples of how
2088// having a bool that has a value different from 0 or 1 in memory can lead to
2089// memory corruption.
2090// https://discourse.llvm.org/t/defining-what-happens-when-a-bool-isn-t-0-or-1/86778
2091static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min,
2092 llvm::APInt &End, bool StrictEnums, bool StrictBool,
2093 bool IsBool) {
2094 const auto *ED = Ty->getAsEnumDecl();
2095 bool IsRegularCPlusPlusEnum =
2096 CGF.getLangOpts().CPlusPlus && StrictEnums && ED && !ED->isFixed();
2097 if (!IsBool && !IsRegularCPlusPlusEnum)
2098 return false;
2099
2100 if (IsBool) {
2101 if (!StrictBool)
2102 return false;
2103 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
2104 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
2105 } else {
2106 ED->getValueRange(End, Min);
2107 }
2108 return true;
2109}
2110
2111llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
2112 llvm::APInt Min, End;
2113 bool IsBool = Ty->hasBooleanRepresentation() && !Ty->isVectorType();
2114 bool StrictBoolEnabled = CGM.getCodeGenOpts().getLoadBoolFromMem() ==
2116 if (!getRangeForType(*this, Ty, Min, End,
2117 /*StrictEnums=*/CGM.getCodeGenOpts().StrictEnums,
2118 /*StrictBool=*/StrictBoolEnabled, /*IsBool=*/IsBool))
2119 return nullptr;
2120
2121 llvm::MDBuilder MDHelper(getLLVMContext());
2122 return MDHelper.createRange(Min, End);
2123}
2124
2126 SourceLocation Loc) {
2127 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
2128 // In order to prevent the optimizer from throwing away the check, don't
2129 // attach range metadata to the load.
2130 } else if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2131 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
2132 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
2133 Load->setMetadata(llvm::LLVMContext::MD_noundef,
2134 llvm::MDNode::get(CGM.getLLVMContext(), {}));
2135 }
2136 }
2137}
2138
2140 SourceLocation Loc) {
2141 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
2142 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
2143 if (!HasBoolCheck && !HasEnumCheck)
2144 return false;
2145
2146 bool IsBool = (Ty->hasBooleanRepresentation() && !Ty->isVectorType()) ||
2147 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
2148 bool NeedsBoolCheck = HasBoolCheck && IsBool;
2149 bool NeedsEnumCheck = HasEnumCheck && Ty->isEnumeralType();
2150 if (!NeedsBoolCheck && !NeedsEnumCheck)
2151 return false;
2152
2153 // Single-bit booleans don't need to be checked. Special-case this to avoid
2154 // a bit width mismatch when handling bitfield values. This is handled by
2155 // EmitFromMemory for the non-bitfield case.
2156 if (IsBool &&
2157 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
2158 return false;
2159
2160 if (NeedsEnumCheck &&
2161 getContext().isTypeIgnoredBySanitizer(SanitizerKind::Enum, Ty))
2162 return false;
2163
2164 llvm::APInt Min, End;
2165 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true,
2166 /*StrictBool=*/true, IsBool))
2167 return true;
2168
2170 NeedsEnumCheck ? SanitizerKind::SO_Enum : SanitizerKind::SO_Bool;
2171
2172 auto &Ctx = getLLVMContext();
2173 auto CheckHandler = SanitizerHandler::LoadInvalidValue;
2174 SanitizerDebugLocation SanScope(this, {Kind}, CheckHandler);
2175 llvm::Value *Check;
2176 --End;
2177 if (!Min) {
2178 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
2179 } else {
2180 llvm::Value *Upper =
2181 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
2182 llvm::Value *Lower =
2183 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
2184 Check = Builder.CreateAnd(Upper, Lower);
2185 }
2186 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
2188 EmitCheck(std::make_pair(Check, Kind), CheckHandler, StaticArgs, Value);
2189 return true;
2190}
2191
2193 QualType Ty,
2194 SourceLocation Loc,
2195 LValueBaseInfo BaseInfo,
2196 TBAAAccessInfo TBAAInfo,
2197 bool isNontemporal) {
2198 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2199 if (GV->isThreadLocal())
2200 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2202
2203 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2204 // Boolean vectors use `iN` as storage type.
2205 if (ClangVecTy->isPackedVectorBoolType(getContext())) {
2206 llvm::Type *ValTy = ConvertType(Ty);
2207 unsigned ValNumElems =
2208 cast<llvm::FixedVectorType>(ValTy)->getNumElements();
2209 // Load the `iP` storage object (P is the padded vector size).
2210 auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
2211 const auto *RawIntTy = RawIntV->getType();
2212 assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
2213 // Bitcast iP --> <P x i1>.
2214 auto *PaddedVecTy = llvm::FixedVectorType::get(
2215 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2216 llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
2217 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2218 V = emitBoolVecConversion(V, ValNumElems, "extractvec");
2219
2220 return EmitFromMemory(V, Ty);
2221 }
2222
2223 // Handles vectors of sizes that are likely to be expanded to a larger size
2224 // to optimize performance.
2225 auto *VTy = cast<llvm::FixedVectorType>(Addr.getElementType());
2226 auto *NewVecTy =
2227 CGM.getABIInfo().getOptimalVectorMemoryType(VTy, getLangOpts());
2228
2229 if (VTy != NewVecTy) {
2230 Address Cast = Addr.withElementType(NewVecTy);
2231 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVecN");
2232 unsigned OldNumElements = VTy->getNumElements();
2233 SmallVector<int, 16> Mask(OldNumElements);
2234 std::iota(Mask.begin(), Mask.end(), 0);
2235 V = Builder.CreateShuffleVector(V, Mask, "extractVec");
2236 return EmitFromMemory(V, Ty);
2237 }
2238 }
2239
2240 // Atomic operations have to be done on integral types.
2241 LValue AtomicLValue =
2242 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2243 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
2244 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
2245 }
2246
2247 Addr =
2248 Addr.withElementType(convertTypeForLoadStore(Ty, Addr.getElementType()));
2249
2250 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
2251 if (isNontemporal) {
2252 llvm::MDNode *Node = llvm::MDNode::get(
2253 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2254 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2255 }
2256
2257 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
2258
2259 maybeAttachRangeForLoad(Load, Ty, Loc);
2260
2261 return EmitFromMemory(Load, Ty);
2262}
2263
2264/// Converts a scalar value from its primary IR type (as returned
2265/// by ConvertType) to its load/store type (as returned by
2266/// convertTypeForLoadStore).
2267llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
2268 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2269 Ty = AtomicTy->getValueType();
2270
2271 if (Ty->isExtVectorBoolType() || Ty->isConstantMatrixBoolType()) {
2272 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2273
2274 if (Value->getType() == StoreTy)
2275 return Value;
2276
2277 if (StoreTy->isVectorTy() && StoreTy->getScalarSizeInBits() >
2278 Value->getType()->getScalarSizeInBits())
2279 return Builder.CreateZExt(Value, StoreTy);
2280
2281 // Expand to the memory bit width.
2282 unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits();
2283 // <N x i1> --> <P x i1>.
2284 Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
2285 // <P x i1> --> iP.
2286 Value = Builder.CreateBitCast(Value, StoreTy);
2287 }
2288
2289 if (Ty->hasBooleanRepresentation() || Ty->isBitIntType()) {
2290 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2292 return Builder.CreateIntCast(Value, StoreTy, Signed, "storedv");
2293 }
2294
2295 return Value;
2296}
2297
2298/// Converts a scalar value from its load/store type (as returned
2299/// by convertTypeForLoadStore) to its primary IR type (as returned
2300/// by ConvertType).
2301llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
2302 if (auto *AtomicTy = Ty->getAs<AtomicType>())
2303 Ty = AtomicTy->getValueType();
2304
2306 const auto *RawIntTy = Value->getType();
2307
2308 // Bitcast iP --> <P x i1>.
2309 auto *PaddedVecTy = llvm::FixedVectorType::get(
2310 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2311 auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
2312 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2313 llvm::Type *ValTy = ConvertType(Ty);
2314 unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
2315 return emitBoolVecConversion(V, ValNumElems, "extractvec");
2316 }
2317
2318 llvm::Type *ResTy = ConvertType(Ty);
2319 bool HasBoolRep = Ty->hasBooleanRepresentation() || Ty->isExtVectorBoolType();
2320 if (HasBoolRep && CGM.getCodeGenOpts().isConvertingBoolWithCmp0()) {
2321 return Builder.CreateICmpNE(
2322 Value, llvm::Constant::getNullValue(Value->getType()), "loadedv");
2323 }
2324 if (HasBoolRep || Ty->isBitIntType())
2325 return Builder.CreateTrunc(Value, ResTy, "loadedv");
2326
2327 return Value;
2328}
2329
2330// Convert the pointer of \p Addr to a pointer to a vector (the value type of
2331// MatrixType), if it points to a array (the memory type of MatrixType).
2333 CodeGenFunction &CGF,
2334 bool IsVector = true) {
2335 auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
2336 if (ArrayTy && IsVector) {
2337 auto ArrayElements = ArrayTy->getNumElements();
2338 auto *ArrayElementTy = ArrayTy->getElementType();
2339 if (CGF.getContext().getLangOpts().HLSL) {
2340 auto *VectorTy = cast<llvm::FixedVectorType>(ArrayElementTy);
2341 ArrayElementTy = VectorTy->getElementType();
2342 ArrayElements *= VectorTy->getNumElements();
2343 }
2344 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
2345
2346 return Addr.withElementType(VectorTy);
2347 }
2348 auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
2349 if (VectorTy && !IsVector) {
2350 auto *ArrayTy = llvm::ArrayType::get(
2351 VectorTy->getElementType(),
2352 cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
2353
2354 return Addr.withElementType(ArrayTy);
2355 }
2356
2357 return Addr;
2358}
2359
2361 LValue Base;
2362 if (E->getBase()->isGLValue())
2363 Base = EmitLValue(E->getBase());
2364 else {
2365 assert(E->getBase()->getType()->isConstantMatrixType() &&
2366 "Result must be a Constant Matrix");
2367 llvm::Value *Mat = EmitScalarExpr(E->getBase());
2368 Address MatMem = CreateMemTemp(E->getBase()->getType());
2369 QualType Ty = E->getBase()->getType();
2370 llvm::Type *LTy = convertTypeForLoadStore(Ty, Mat->getType());
2371 if (LTy->getScalarSizeInBits() > Mat->getType()->getScalarSizeInBits())
2372 Mat = Builder.CreateZExt(Mat, LTy);
2373 Builder.CreateStore(Mat, MatMem);
2375 }
2376 QualType ResultType =
2377 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
2378
2379 // Encode the element access list into a vector of unsigned indices.
2380 // getEncodedElementAccess returns row-major linearized indices.
2382 E->getEncodedElementAccess(Indices);
2383
2384 // getEncodedElementAccess returns row-major linearized indices
2385 // If the matrix memory layout is column-major, convert indices
2386 // to column-major indices.
2387 bool IsRowMajor = isMatrixRowMajor(getLangOpts(), E->getBase()->getType());
2388 if (!IsRowMajor) {
2389 const auto *MT = E->getBase()->getType()->castAs<ConstantMatrixType>();
2390 unsigned NumCols = MT->getNumColumns();
2391 for (uint32_t &Idx : Indices) {
2392 // Decompose row-major index: Row = Idx / NumCols, Col = Idx % NumCols
2393 unsigned Row = Idx / NumCols;
2394 unsigned Col = Idx % NumCols;
2395 // Re-linearize as column-major
2396 Idx = MT->getColumnMajorFlattenedIndex(Row, Col);
2397 }
2398 }
2399
2400 if (Base.isSimple()) {
2401 RawAddress MatAddr = Base.getAddress();
2402 if (getLangOpts().HLSL &&
2404 MatAddr = CGM.getHLSLRuntime().createBufferMatrixTempAddress(Base, *this);
2405
2406 llvm::Constant *CV =
2407 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
2409 CV, ResultType, Base.getBaseInfo(),
2410 TBAAAccessInfo());
2411 }
2412 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2413
2414 llvm::Constant *BaseElts = Base.getExtVectorElts();
2416
2417 for (unsigned Index : Indices)
2418 CElts.push_back(BaseElts->getAggregateElement(Index));
2419 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2420
2422 MaybeConvertMatrixAddress(Base.getExtVectorAddress(), *this), CV,
2423 ResultType, Base.getBaseInfo(), TBAAAccessInfo());
2424}
2425
2426// Emit a store of a matrix LValue. This may require casting the original
2427// pointer to memory address (ArrayType) to a pointer to the value type
2428// (VectorType).
2429static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
2430 bool isInit, CodeGenFunction &CGF) {
2431 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(), CGF,
2432 value->getType()->isVectorTy());
2433 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
2434 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
2435 lvalue.isNontemporal());
2436}
2437
2439 bool Volatile, QualType Ty,
2440 LValueBaseInfo BaseInfo,
2441 TBAAAccessInfo TBAAInfo,
2442 bool isInit, bool isNontemporal) {
2443 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2444 if (GV->isThreadLocal())
2445 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2447
2448 // Handles vectors of sizes that are likely to be expanded to a larger size
2449 // to optimize performance.
2450 llvm::Type *SrcTy = Value->getType();
2451 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2452 if (auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2453 auto *NewVecTy =
2454 CGM.getABIInfo().getOptimalVectorMemoryType(VecTy, getLangOpts());
2455 if (!ClangVecTy->isPackedVectorBoolType(getContext()) &&
2456 VecTy != NewVecTy) {
2457 SmallVector<int, 16> Mask(NewVecTy->getNumElements(),
2458 VecTy->getNumElements());
2459 std::iota(Mask.begin(), Mask.begin() + VecTy->getNumElements(), 0);
2460 // Use undef instead of poison for the padding lanes, to make sure no
2461 // padding bits are poisoned, which may break coercion.
2462 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
2463 Mask, "extractVec");
2464 SrcTy = NewVecTy;
2465 }
2466 if (Addr.getElementType() != SrcTy)
2467 Addr = Addr.withElementType(SrcTy);
2468 }
2469 }
2470
2471 Value = EmitToMemory(Value, Ty);
2472
2473 LValue AtomicLValue =
2474 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2475 if (Ty->isAtomicType() ||
2476 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
2477 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
2478 return;
2479 }
2480
2481 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
2483
2484 if (isNontemporal) {
2485 llvm::MDNode *Node =
2486 llvm::MDNode::get(Store->getContext(),
2487 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2488 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2489 }
2490
2491 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2492}
2493
2494void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
2495 bool isInit) {
2496 if (lvalue.getType()->isConstantMatrixType()) {
2497 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
2498 return;
2499 }
2500
2501 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
2502 lvalue.getType(), lvalue.getBaseInfo(),
2503 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
2504}
2505
2506// Emit a load of a LValue of matrix type. This may require casting the pointer
2507// to memory address (ArrayType) to a pointer to the value type (VectorType).
2509 CodeGenFunction &CGF) {
2510 assert(LV.getType()->isConstantMatrixType());
2511 RawAddress DestAddr = LV.getAddress();
2512
2513 // HLSL constant buffers may pad matrix layouts, so copy elements into a
2514 // non-padded local alloca before loading.
2515 if (CGF.getLangOpts().HLSL &&
2516 LV.getType().getAddressSpace() == LangAS::hlsl_constant)
2517 DestAddr = CGF.CGM.getHLSLRuntime().createBufferMatrixTempAddress(LV, CGF);
2518
2519 Address Addr = MaybeConvertMatrixAddress(DestAddr, CGF);
2520 LV.setAddress(Addr);
2521 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
2522}
2523
2525 SourceLocation Loc) {
2526 QualType Ty = LV.getType();
2527 switch (getEvaluationKind(Ty)) {
2528 case TEK_Scalar:
2529 return EmitLoadOfLValue(LV, Loc);
2530 case TEK_Complex:
2531 return RValue::getComplex(EmitLoadOfComplex(LV, Loc));
2532 case TEK_Aggregate:
2533 EmitAggFinalDestCopy(Ty, Slot, LV, EVK_NonRValue);
2534 return Slot.asRValue();
2535 }
2536 llvm_unreachable("bad evaluation kind");
2537}
2538
2539/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
2540/// method emits the address of the lvalue, then loads the result as an rvalue,
2541/// returning the rvalue.
2543 // Load from __ptrauth.
2544 if (PointerAuthQualifier PtrAuth = LV.getQuals().getPointerAuth()) {
2546 llvm::Value *Value = EmitLoadOfLValue(LV, Loc).getScalarVal();
2547 return RValue::get(EmitPointerAuthUnqualify(PtrAuth, Value, LV.getType(),
2548 LV.getAddress(),
2549 /*known nonnull*/ false));
2550 }
2551
2552 if (LV.isObjCWeak()) {
2553 // load of a __weak object.
2554 Address AddrWeakObj = LV.getAddress();
2555 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
2556 AddrWeakObj));
2557 }
2559 // In MRC mode, we do a load+autorelease.
2560 if (!getLangOpts().ObjCAutoRefCount) {
2562 }
2563
2564 // In ARC mode, we load retained and then consume the value.
2565 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
2567 return RValue::get(Object);
2568 }
2569
2570 if (LV.isSimple()) {
2571 assert(!LV.getType()->isFunctionType());
2572
2573 if (LV.getType()->isConstantMatrixType())
2574 return EmitLoadOfMatrixLValue(LV, Loc, *this);
2575
2576 // Everything needs a load.
2577 return RValue::get(EmitLoadOfScalar(LV, Loc));
2578 }
2579
2580 if (LV.isVectorElt()) {
2581 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
2582 LV.isVolatileQualified());
2583 llvm::Value *Elt =
2584 Builder.CreateExtractElement(Load, LV.getVectorIdx(), "vecext");
2585 return RValue::get(EmitFromMemory(Elt, LV.getType()));
2586 }
2587
2588 // If this is a reference to a subset of the elements of a vector, either
2589 // shuffle the input or extract/insert them as appropriate.
2590 if (LV.isExtVectorElt()) {
2592 }
2593
2594 // Global Register variables always invoke intrinsics
2595 if (LV.isGlobalReg())
2596 return EmitLoadOfGlobalRegLValue(LV);
2597
2598 if (LV.isMatrixElt()) {
2599 llvm::Value *Idx = LV.getMatrixIdx();
2600 QualType EltTy = LV.getType();
2601 if (const auto *MatTy = EltTy->getAs<ConstantMatrixType>()) {
2602 EltTy = MatTy->getElementType();
2603 if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2604 llvm::MatrixBuilder MB(Builder);
2605 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2606 }
2607 }
2608 llvm::LoadInst *Load =
2609 Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
2610 llvm::Value *Elt = Builder.CreateExtractElement(Load, Idx, "matrixext");
2611 return RValue::get(EmitFromMemory(Elt, EltTy));
2612 }
2613 if (LV.isMatrixRow()) {
2614 QualType MatTy = LV.getType();
2615 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2616
2617 unsigned NumRows = MT->getNumRows();
2618 unsigned NumCols = MT->getNumColumns();
2619 unsigned NumLanes = NumCols;
2620 llvm::Value *MatrixVec = EmitLoadOfScalar(LV, Loc);
2621 llvm::Value *Row = LV.getMatrixRowIdx();
2622 llvm::Type *ElemTy = ConvertType(MT->getElementType());
2623 llvm::Constant *ColConstsIndices = nullptr;
2624 llvm::MatrixBuilder MB(Builder);
2625
2626 if (LV.isMatrixRowSwizzle()) {
2627 ColConstsIndices = LV.getMatrixRowElts();
2628 NumLanes = llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2629 ->getNumElements();
2630 }
2631
2632 llvm::Type *RowTy = llvm::FixedVectorType::get(ElemTy, NumLanes);
2633 llvm::Value *Result = llvm::PoisonValue::get(RowTy); // <NumLanes x T>
2634
2635 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2636 llvm::Value *ColIdx;
2637 if (ColConstsIndices)
2638 ColIdx = ColConstsIndices->getAggregateElement(Col);
2639 else
2640 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2641 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), MatTy);
2642 llvm::Value *EltIndex =
2643 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2644 llvm::Value *Elt = Builder.CreateExtractElement(MatrixVec, EltIndex);
2645 llvm::Value *Lane = llvm::ConstantInt::get(Builder.getInt32Ty(), Col);
2646 Result = Builder.CreateInsertElement(Result, Elt, Lane);
2647 }
2648
2649 return RValue::get(Result);
2650 }
2651
2652 assert(LV.isBitField() && "Unknown LValue type!");
2653 return EmitLoadOfBitfieldLValue(LV, Loc);
2654}
2655
2657 SourceLocation Loc) {
2658 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2659
2660 // Get the output type.
2661 llvm::Type *ResLTy = ConvertType(LV.getType());
2662
2663 Address Ptr = LV.getBitFieldAddress();
2664 llvm::Value *Val =
2665 Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2666
2667 bool UseVolatile = LV.isVolatileQualified() &&
2668 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2669 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2670 const unsigned StorageSize =
2671 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2672 if (Info.IsSigned) {
2673 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2674 unsigned HighBits = StorageSize - Offset - Info.Size;
2675 if (HighBits)
2676 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2677 if (Offset + HighBits)
2678 Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2679 } else {
2680 if (Offset)
2681 Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2682 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2683 Val = Builder.CreateAnd(
2684 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2685 }
2686 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2687 EmitScalarRangeCheck(Val, LV.getType(), Loc);
2688 return RValue::get(Val);
2689}
2690
2691// If this is a reference to a subset of the elements of a vector, create an
2692// appropriate shufflevector.
2694 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2695 LV.isVolatileQualified());
2696
2697 // HLSL allows treating scalars as one-element vectors. Converting the scalar
2698 // IR value to a vector here allows the rest of codegen to behave as normal.
2699 if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) {
2700 llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2701 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2702 Vec = Builder.CreateInsertElement(DstTy, Vec, Zero, "cast.splat");
2703 }
2704
2705 const llvm::Constant *Elts = LV.getExtVectorElts();
2706
2707 // If the result of the expression is a non-vector type, we must be extracting
2708 // a single element. Just codegen as an extractelement.
2709 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2710 if (!ExprVT) {
2711 unsigned InIdx = getAccessedFieldNo(0, Elts);
2712 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2713
2714 llvm::Value *Element = Builder.CreateExtractElement(Vec, Elt);
2715
2716 llvm::Type *LVTy = ConvertType(LV.getType());
2717 if (Element->getType()->getPrimitiveSizeInBits() >
2718 LVTy->getPrimitiveSizeInBits()) {
2719 if (LV.getType()->hasBooleanRepresentation() &&
2720 CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2721 Element = Builder.CreateICmpNE(
2722 Element, llvm::Constant::getNullValue(Element->getType()));
2723 else
2724 Element = Builder.CreateTrunc(Element, LVTy);
2725 }
2726
2727 return RValue::get(Element);
2728 }
2729
2730 // Always use shuffle vector to try to retain the original program structure
2731 unsigned NumResultElts = ExprVT->getNumElements();
2732
2734 for (unsigned i = 0; i != NumResultElts; ++i)
2735 Mask.push_back(getAccessedFieldNo(i, Elts));
2736
2737 Vec = Builder.CreateShuffleVector(Vec, Mask);
2738
2739 if (LV.getType()->isExtVectorBoolType()) {
2740 if (CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2741 Vec = Builder.CreateICmpNE(Vec,
2742 llvm::Constant::getNullValue(Vec->getType()));
2743 else
2744 Vec = Builder.CreateTrunc(Vec, ConvertType(LV.getType()), "truncv");
2745 }
2746
2747 return RValue::get(Vec);
2748}
2749
2750/// Generates lvalue for partial ext_vector access.
2752 Address VectorAddress = LV.getExtVectorAddress();
2753 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2754 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2755
2756 Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
2757
2758 const llvm::Constant *Elts = LV.getExtVectorElts();
2759 unsigned ix = getAccessedFieldNo(0, Elts);
2760
2761 Address VectorBasePtrPlusIx =
2762 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2763 "vector.elt");
2764
2765 return VectorBasePtrPlusIx;
2766}
2767
2768/// Load of global named registers are always calls to intrinsics.
2770 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2771 "Bad type for register variable");
2772 llvm::MDNode *RegName = cast<llvm::MDNode>(
2773 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2774
2775 // We accept integer and pointer types only
2776 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2777 llvm::Type *Ty = OrigTy;
2778 if (OrigTy->isPointerTy())
2779 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2780 llvm::Type *Types[] = { Ty };
2781
2782 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2783 llvm::Value *Call = Builder.CreateCall(
2784 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2785 if (OrigTy->isPointerTy())
2786 Call = Builder.CreateIntToPtr(Call, OrigTy);
2787 return RValue::get(Call);
2788}
2789
2790/// EmitStoreThroughLValue - Store the specified rvalue into the specified
2791/// lvalue, where both are guaranteed to the have the same type, and that type
2792/// is 'Ty'.
2794 bool isInit) {
2795 if (!Dst.isSimple()) {
2796 if (Dst.isVectorElt()) {
2797 if (getLangOpts().HLSL) {
2798 // HLSL allows direct access to vector elements, so storing to
2799 // individual elements of a vector through VectorElt is handled as
2800 // separate store instructions.
2801 Address DstAddr = Dst.getVectorAddress();
2802 llvm::Type *DestAddrTy = DstAddr.getElementType();
2803 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2805 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2806
2807 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2808 "vector element type must be at least byte-sized");
2809
2810 llvm::Value *Val = Src.getScalarVal();
2811 if (Val->getType()->getPrimitiveSizeInBits() <
2812 ElemTy->getScalarSizeInBits())
2813 Val = Builder.CreateZExt(Val, ElemTy->getScalarType());
2814
2815 llvm::Value *Idx = Dst.getVectorIdx();
2816 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2817 Address DstElemAddr =
2818 Builder.CreateGEP(DstAddr, {Zero, Idx}, DestAddrTy, ElemAlign);
2819 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2820 return;
2821 }
2822
2823 // Read/modify/write the vector, inserting the new element.
2824 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2825 Dst.isVolatileQualified());
2826 llvm::Type *VecTy = Vec->getType();
2827 llvm::Value *SrcVal = Src.getScalarVal();
2828
2829 if (VecTy->isVectorTy() && SrcVal->getType()->getPrimitiveSizeInBits() <
2830 VecTy->getScalarSizeInBits())
2831 SrcVal = Builder.CreateZExt(SrcVal, VecTy->getScalarType());
2832
2833 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2834 if (IRStoreTy) {
2835 auto *IRVecTy = llvm::FixedVectorType::get(
2836 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2837 Vec = Builder.CreateBitCast(Vec, IRVecTy);
2838 // iN --> <N x i1>.
2839 }
2840
2841 // Allow inserting `<1 x T>` into an `<N x T>`. It can happen with scalar
2842 // types which are mapped to vector LLVM IR types (e.g. for implementing
2843 // an ABI).
2844 if (auto *EltTy = dyn_cast<llvm::FixedVectorType>(SrcVal->getType());
2845 EltTy && EltTy->getNumElements() == 1)
2846 SrcVal = Builder.CreateBitCast(SrcVal, EltTy->getElementType());
2847
2848 Vec = Builder.CreateInsertElement(Vec, SrcVal, Dst.getVectorIdx(),
2849 "vecins");
2850 if (IRStoreTy) {
2851 // <N x i1> --> <iN>.
2852 Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2853 }
2854
2855 auto *I = Builder.CreateStore(Vec, Dst.getVectorAddress(),
2856 Dst.isVolatileQualified());
2858 return;
2859 }
2860
2861 // If this is an update of extended vector elements, insert them as
2862 // appropriate.
2863 if (Dst.isExtVectorElt())
2865
2866 if (Dst.isGlobalReg())
2867 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2868
2869 if (Dst.isMatrixElt()) {
2870 if (getLangOpts().HLSL) {
2871 // HLSL allows direct access to matrix elements, so storing to
2872 // individual elements of a matrix through MatrixElt is handled as
2873 // separate store instructions.
2874 Address DstAddr = Dst.getMatrixAddress();
2875 llvm::Type *DestAddrTy = DstAddr.getElementType();
2876 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2878 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2879
2880 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2881 "matrix element type must be at least byte-sized");
2882
2883 llvm::Value *Val = Src.getScalarVal();
2884 if (Val->getType()->getPrimitiveSizeInBits() <
2885 ElemTy->getScalarSizeInBits())
2886 Val = Builder.CreateZExt(Val, ElemTy->getScalarType());
2887
2888 llvm::Value *Idx = Dst.getMatrixIdx();
2889 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2890 Address DstElemAddr =
2891 Builder.CreateGEP(DstAddr, {Zero, Idx}, DestAddrTy, ElemAlign);
2892 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
2893 return;
2894 }
2895
2896 llvm::Value *Idx = Dst.getMatrixIdx();
2897 if (CGM.getCodeGenOpts().isOptimizedBuild()) {
2898 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2899 llvm::MatrixBuilder MB(Builder);
2900 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2901 }
2902 llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2903 llvm::Value *InsertVal = Src.getScalarVal();
2904 llvm::Value *Vec =
2905 Builder.CreateInsertElement(Load, InsertVal, Idx, "matins");
2906 auto *I = Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2907 Dst.isVolatileQualified());
2909 return;
2910 }
2911 if (Dst.isMatrixRow()) {
2912 // NOTE: Since there are no other languages that implement matrix single
2913 // subscripting, the logic here is specific to HLSL which allows
2914 // per-element stores to rows of matrices.
2915 assert(getLangOpts().HLSL &&
2916 "Store through matrix row LValues is only implemented for HLSL!");
2917 QualType MatTy = Dst.getType();
2918 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
2919
2920 unsigned NumRows = MT->getNumRows();
2921 unsigned NumCols = MT->getNumColumns();
2922 unsigned NumLanes = NumCols;
2923
2924 Address DstAddr = Dst.getMatrixAddress();
2925 llvm::Type *DestAddrTy = DstAddr.getElementType();
2926 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2927 CharUnits ElemAlign =
2928 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2929
2930 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2931 "matrix element type must be at least byte-sized");
2932
2933 llvm::Value *RowVal = Src.getScalarVal();
2934 if (RowVal->getType()->getScalarType()->getPrimitiveSizeInBits() <
2935 ElemTy->getScalarSizeInBits()) {
2936 auto *RowValVecTy = cast<llvm::FixedVectorType>(RowVal->getType());
2937 llvm::Type *StorageElmTy = llvm::FixedVectorType::get(
2938 ElemTy->getScalarType(), RowValVecTy->getNumElements());
2939 RowVal = Builder.CreateZExt(RowVal, StorageElmTy);
2940 }
2941
2942 llvm::MatrixBuilder MB(Builder);
2943
2944 llvm::Constant *ColConstsIndices = nullptr;
2945 if (Dst.isMatrixRowSwizzle()) {
2946 ColConstsIndices = Dst.getMatrixRowElts();
2947 NumLanes =
2948 llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2949 ->getNumElements();
2950 }
2951
2952 llvm::Value *Row = Dst.getMatrixRowIdx();
2953 for (unsigned Col = 0; Col < NumLanes; ++Col) {
2954 llvm::Value *ColIdx;
2955 if (ColConstsIndices)
2956 ColIdx = ColConstsIndices->getAggregateElement(Col);
2957 else
2958 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2959 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), Dst.getType());
2960 llvm::Value *EltIndex =
2961 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2962 llvm::Value *Lane = llvm::ConstantInt::get(Builder.getInt32Ty(), Col);
2963 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2964 llvm::Value *NewElt = Builder.CreateExtractElement(RowVal, Lane);
2965 Address DstElemAddr =
2966 Builder.CreateGEP(DstAddr, {Zero, EltIndex}, DestAddrTy, ElemAlign);
2967 Builder.CreateStore(NewElt, DstElemAddr, Dst.isVolatileQualified());
2968 }
2969
2970 return;
2971 }
2972
2973 assert(Dst.isBitField() && "Unknown LValue type");
2974 return EmitStoreThroughBitfieldLValue(Src, Dst);
2975 }
2976
2977 // Handle __ptrauth qualification by re-signing the value.
2978 if (PointerAuthQualifier PointerAuth = Dst.getQuals().getPointerAuth()) {
2979 Src = RValue::get(EmitPointerAuthQualify(PointerAuth, Src.getScalarVal(),
2980 Dst.getType(), Dst.getAddress(),
2981 /*known nonnull*/ false));
2982 }
2983
2984 // There's special magic for assigning into an ARC-qualified l-value.
2985 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2986 switch (Lifetime) {
2988 llvm_unreachable("present but none");
2989
2991 // nothing special
2992 break;
2993
2995 if (isInit) {
2996 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2997 break;
2998 }
2999 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
3000 return;
3001
3003 if (isInit)
3004 // Initialize and then skip the primitive store.
3006 else
3008 /*ignore*/ true);
3009 return;
3010
3013 Src.getScalarVal()));
3014 // fall into the normal path
3015 break;
3016 }
3017 }
3018
3019 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
3020 // load of a __weak object.
3021 Address LvalueDst = Dst.getAddress();
3022 llvm::Value *src = Src.getScalarVal();
3023 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
3024 return;
3025 }
3026
3027 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
3028 // load of a __strong object.
3029 Address LvalueDst = Dst.getAddress();
3030 llvm::Value *src = Src.getScalarVal();
3031 if (Dst.isObjCIvar()) {
3032 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
3033 llvm::Type *ResultType = IntPtrTy;
3035 llvm::Value *RHS = dst.emitRawPointer(*this);
3036 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
3037 llvm::Value *LHS = Builder.CreatePtrToInt(LvalueDst.emitRawPointer(*this),
3038 ResultType, "sub.ptr.lhs.cast");
3039 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
3040 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, BytesBetween);
3041 } else if (Dst.isGlobalObjCRef()) {
3042 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
3043 Dst.isThreadLocalRef());
3044 }
3045 else
3046 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
3047 return;
3048 }
3049
3050 assert(Src.isScalar() && "Can't emit an agg store with this method");
3051 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
3052}
3053
3055 llvm::Value **Result) {
3056 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
3057 llvm::Type *ResLTy = convertTypeForLoadStore(Dst.getType());
3058 Address Ptr = Dst.getBitFieldAddress();
3059
3060 // Get the source value, truncated to the width of the bit-field.
3061 llvm::Value *SrcVal = Src.getScalarVal();
3062
3063 // Cast the source to the storage type and shift it into place.
3064 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
3065 /*isSigned=*/false);
3066 llvm::Value *MaskedVal = SrcVal;
3067
3068 const bool UseVolatile =
3069 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
3070 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
3071 const unsigned StorageSize =
3072 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
3073 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
3074 // See if there are other bits in the bitfield's storage we'll need to load
3075 // and mask together with source before storing.
3076 if (StorageSize != Info.Size) {
3077 assert(StorageSize > Info.Size && "Invalid bitfield size.");
3078 llvm::Value *Val =
3079 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
3080
3081 // Mask the source value as needed.
3082 if (!Dst.getType()->hasBooleanRepresentation())
3083 SrcVal = Builder.CreateAnd(
3084 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
3085 "bf.value");
3086 MaskedVal = SrcVal;
3087 if (Offset)
3088 SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
3089
3090 // Mask out the original value.
3091 Val = Builder.CreateAnd(
3092 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
3093 "bf.clear");
3094
3095 // Or together the unchanged values and the source value.
3096 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
3097 } else {
3098 assert(Offset == 0);
3099 // According to the AACPS:
3100 // When a volatile bit-field is written, and its container does not overlap
3101 // with any non-bit-field member, its container must be read exactly once
3102 // and written exactly once using the access width appropriate to the type
3103 // of the container. The two accesses are not atomic.
3104 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
3105 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
3106 Builder.CreateLoad(Ptr, true, "bf.load");
3107 }
3108
3109 // Write the new value back out.
3110 auto *I = Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
3111 addInstToCurrentSourceAtom(I, SrcVal);
3112
3113 // Return the new value of the bit-field, if requested.
3114 if (Result) {
3115 llvm::Value *ResultVal = MaskedVal;
3116
3117 // Sign extend the value if needed.
3118 if (Info.IsSigned) {
3119 assert(Info.Size <= StorageSize);
3120 unsigned HighBits = StorageSize - Info.Size;
3121 if (HighBits) {
3122 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
3123 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
3124 }
3125 }
3126
3127 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
3128 "bf.result.cast");
3129 *Result = EmitFromMemory(ResultVal, Dst.getType());
3130 }
3131}
3132
3134 LValue Dst) {
3135 llvm::Value *SrcVal = Src.getScalarVal();
3136 Address DstAddr = Dst.getExtVectorAddress();
3137 const llvm::Constant *Elts = Dst.getExtVectorElts();
3138 if (DstAddr.getElementType()->getScalarSizeInBits() >
3139 SrcVal->getType()->getScalarSizeInBits())
3140 SrcVal = Builder.CreateZExt(
3141 SrcVal, convertTypeForLoadStore(Dst.getType(), SrcVal->getType()));
3142
3143 if (getLangOpts().HLSL) {
3144 llvm::Type *DestAddrTy = DstAddr.getElementType();
3145 // HLSL allows storing to scalar values through ExtVector component LValues.
3146 // To support this we need to handle the case where the destination address
3147 // is a scalar.
3148 if (!DestAddrTy->isVectorTy()) {
3149 assert(!Dst.getType()->isVectorType() &&
3150 "this should only occur for non-vector l-values");
3151 Builder.CreateStore(SrcVal, DstAddr, Dst.isVolatileQualified());
3152 return;
3153 }
3154
3155 // HLSL allows direct access to vector elements, so storing to individual
3156 // elements of a vector through ExtVector is handled as separate store
3157 // instructions.
3158 // If we are updating multiple elements, Dst and Src are vectors; for
3159 // a single element update they are scalars.
3160 const VectorType *VTy = Dst.getType()->getAs<VectorType>();
3161 unsigned NumSrcElts = VTy ? VTy->getNumElements() : 1;
3163 CGM.getDataLayout().getPrefTypeAlign(DestAddrTy->getScalarType()));
3164 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
3165
3166 for (unsigned I = 0; I != NumSrcElts; ++I) {
3167 llvm::Value *Val = VTy ? Builder.CreateExtractElement(
3168 SrcVal, llvm::ConstantInt::get(Int32Ty, I))
3169 : SrcVal;
3170 unsigned FieldNo = getAccessedFieldNo(I, Elts);
3171 Address DstElemAddr = Address::invalid();
3172 if (FieldNo == 0)
3173 DstElemAddr = DstAddr.withAlignment(ElemAlign);
3174 else
3175 DstElemAddr = Builder.CreateGEP(
3176 DstAddr, {Zero, llvm::ConstantInt::get(Int32Ty, FieldNo)},
3177 DestAddrTy, ElemAlign);
3178 Builder.CreateStore(Val, DstElemAddr, Dst.isVolatileQualified());
3179 }
3180 return;
3181 }
3182
3183 // This access turns into a read/modify/write of the vector. Load the input
3184 // value now.
3185 llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
3186 llvm::Type *VecTy = Vec->getType();
3187
3188 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
3189 unsigned NumSrcElts = VTy->getNumElements();
3190 unsigned NumDstElts = cast<llvm::FixedVectorType>(VecTy)->getNumElements();
3191 if (NumDstElts == NumSrcElts) {
3192 // Use shuffle vector is the src and destination are the same number of
3193 // elements and restore the vector mask since it is on the side it will be
3194 // stored.
3195 SmallVector<int, 4> Mask(NumDstElts);
3196 for (unsigned i = 0; i != NumSrcElts; ++i)
3197 Mask[getAccessedFieldNo(i, Elts)] = i;
3198
3199 Vec = Builder.CreateShuffleVector(SrcVal, Mask);
3200 } else if (NumDstElts > NumSrcElts) {
3201 // Extended the source vector to the same length and then shuffle it
3202 // into the destination.
3203 // FIXME: since we're shuffling with undef, can we just use the indices
3204 // into that? This could be simpler.
3205 SmallVector<int, 4> ExtMask;
3206 for (unsigned i = 0; i != NumSrcElts; ++i)
3207 ExtMask.push_back(i);
3208 ExtMask.resize(NumDstElts, -1);
3209 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
3210 // build identity
3212 for (unsigned i = 0; i != NumDstElts; ++i)
3213 Mask.push_back(i);
3214
3215 // When the vector size is odd and .odd or .hi is used, the last element
3216 // of the Elts constant array will be one past the size of the vector.
3217 // Ignore the last element here, if it is greater than the mask size.
3218 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
3219 NumSrcElts--;
3220
3221 // modify when what gets shuffled in
3222 for (unsigned i = 0; i != NumSrcElts; ++i)
3223 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
3224 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
3225 } else {
3226 // We should never shorten the vector
3227 llvm_unreachable("unexpected shorten vector length");
3228 }
3229 } else {
3230 // If the Src is a scalar (not a vector), and the target is a vector it must
3231 // be updating one element.
3232 unsigned InIdx = getAccessedFieldNo(0, Elts);
3233 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
3234
3235 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
3236 }
3237
3238 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
3239 Dst.isVolatileQualified());
3240}
3241
3242/// Store of global named registers are always calls to intrinsics.
3244 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
3245 "Bad type for register variable");
3246 llvm::MDNode *RegName = cast<llvm::MDNode>(
3247 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
3248 assert(RegName && "Register LValue is not metadata");
3249
3250 // We accept integer and pointer types only
3251 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
3252 llvm::Type *Ty = OrigTy;
3253 if (OrigTy->isPointerTy())
3254 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
3255 llvm::Type *Types[] = { Ty };
3256
3257 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
3258 llvm::Value *Value = Src.getScalarVal();
3259 if (OrigTy->isPointerTy())
3260 Value = Builder.CreatePtrToInt(Value, Ty);
3261 Builder.CreateCall(
3262 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
3263}
3264
3265// setObjCGCLValueClass - sets class of the lvalue for the purpose of
3266// generating write-barries API. It is currently a global, ivar,
3267// or neither.
3268static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
3269 LValue &LV,
3270 bool IsMemberAccess=false) {
3271 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
3272 return;
3273
3274 if (isa<ObjCIvarRefExpr>(E)) {
3275 QualType ExpTy = E->getType();
3276 if (IsMemberAccess && ExpTy->isPointerType()) {
3277 // If ivar is a structure pointer, assigning to field of
3278 // this struct follows gcc's behavior and makes it a non-ivar
3279 // writer-barrier conservatively.
3280 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3281 if (ExpTy->isRecordType()) {
3282 LV.setObjCIvar(false);
3283 return;
3284 }
3285 }
3286 LV.setObjCIvar(true);
3287 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
3288 LV.setBaseIvarExp(Exp->getBase());
3289 LV.setObjCArray(E->getType()->isArrayType());
3290 return;
3291 }
3292
3293 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
3294 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
3295 if (VD->hasGlobalStorage()) {
3296 LV.setGlobalObjCRef(true);
3297 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
3298 }
3299 }
3300 LV.setObjCArray(E->getType()->isArrayType());
3301 return;
3302 }
3303
3304 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
3305 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3306 return;
3307 }
3308
3309 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
3310 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3311 if (LV.isObjCIvar()) {
3312 // If cast is to a structure pointer, follow gcc's behavior and make it
3313 // a non-ivar write-barrier.
3314 QualType ExpTy = E->getType();
3315 if (ExpTy->isPointerType())
3316 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
3317 if (ExpTy->isRecordType())
3318 LV.setObjCIvar(false);
3319 }
3320 return;
3321 }
3322
3323 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
3324 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
3325 return;
3326 }
3327
3328 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
3329 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3330 return;
3331 }
3332
3333 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
3334 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3335 return;
3336 }
3337
3338 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
3339 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
3340 return;
3341 }
3342
3343 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
3344 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
3345 if (LV.isObjCIvar() && !LV.isObjCArray())
3346 // Using array syntax to assigning to what an ivar points to is not
3347 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
3348 LV.setObjCIvar(false);
3349 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
3350 // Using array syntax to assigning to what global points to is not
3351 // same as assigning to the global itself. {id *G;} G[i] = 0;
3352 LV.setGlobalObjCRef(false);
3353 return;
3354 }
3355
3356 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
3357 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
3358 // We don't know if member is an 'ivar', but this flag is looked at
3359 // only in the context of LV.isObjCIvar().
3360 LV.setObjCArray(E->getType()->isArrayType());
3361 return;
3362 }
3363}
3364
3366 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
3367 llvm::Type *RealVarTy, SourceLocation Loc) {
3368 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
3370 CGF, VD, Addr, Loc);
3371 else
3372 Addr =
3373 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
3374
3375 Addr = Addr.withElementType(RealVarTy);
3377}
3378
3380 const VarDecl *VD, QualType T) {
3381 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3382 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3383 // Always return an invalid address for MT_Local, and also for
3384 // MT_To/MT_Enter when unified memory is not enabled. These use direct
3385 // access (global exists in device image). Otherwise, return a valid
3386 // address.
3387 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Local ||
3388 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3389 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3391 return Address::invalid();
3392 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3393 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3394 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3396 "Expected link clause OR to clause with unified memory enabled.");
3397 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
3399 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
3400}
3401
3402Address
3404 LValueBaseInfo *PointeeBaseInfo,
3405 TBAAAccessInfo *PointeeTBAAInfo) {
3406 llvm::LoadInst *Load =
3407 Builder.CreateLoad(RefLVal.getAddress(), RefLVal.isVolatile());
3408 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
3409 QualType PTy = RefLVal.getType()->getPointeeType();
3410 CharUnits Align = CGM.getNaturalTypeAlignment(
3411 PTy, PointeeBaseInfo, PointeeTBAAInfo, /*ForPointeeType=*/true);
3412 if (!PTy->isIncompleteType()) {
3413 llvm::LLVMContext &Ctx = getLLVMContext();
3414 llvm::MDBuilder MDB(Ctx);
3415 // Emit !nonnull metadata
3416 if (CGM.getTypes().getTargetAddressSpace(PTy) == 0 &&
3417 !CGM.getCodeGenOpts().NullPointerIsValid)
3418 Load->setMetadata(llvm::LLVMContext::MD_nonnull,
3419 llvm::MDNode::get(Ctx, {}));
3420 // Emit !align metadata
3421 if (PTy->isObjectType()) {
3422 auto AlignVal = Align.getQuantity();
3423 if (AlignVal > 1) {
3424 Load->setMetadata(
3425 llvm::LLVMContext::MD_align,
3426 llvm::MDNode::get(Ctx, MDB.createConstant(llvm::ConstantInt::get(
3427 Builder.getInt64Ty(), AlignVal))));
3428 }
3429 }
3430 }
3431 return makeNaturalAddressForPointer(Load, PTy, Align,
3432 /*ForPointeeType=*/true, PointeeBaseInfo,
3433 PointeeTBAAInfo);
3434}
3435
3437 LValueBaseInfo PointeeBaseInfo;
3438 TBAAAccessInfo PointeeTBAAInfo;
3439 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
3440 &PointeeTBAAInfo);
3441 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
3442 PointeeBaseInfo, PointeeTBAAInfo);
3443}
3444
3446 const PointerType *PtrTy,
3447 LValueBaseInfo *BaseInfo,
3448 TBAAAccessInfo *TBAAInfo) {
3449 llvm::Value *Addr = Builder.CreateLoad(Ptr);
3450 return makeNaturalAddressForPointer(Addr, PtrTy->getPointeeType(),
3451 CharUnits(), /*ForPointeeType=*/true,
3452 BaseInfo, TBAAInfo);
3453}
3454
3456 const PointerType *PtrTy) {
3457 LValueBaseInfo BaseInfo;
3458 TBAAAccessInfo TBAAInfo;
3459 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
3460 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
3461}
3462
3464 const Expr *E, const VarDecl *VD) {
3465 QualType T = E->getType();
3466
3467 // If it's thread_local, emit a call to its wrapper function instead.
3468 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
3470 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
3471 // Check if the variable is marked as declare target with link clause in
3472 // device codegen.
3473 if (CGF.getLangOpts().OpenMPIsTargetDevice) {
3475 if (Addr.isValid())
3477 }
3478
3479 // Global HLSL resource arrays initialized on access; create a temporary with
3480 // the initialized global resource array.
3481 if (CGF.getLangOpts().HLSL && VD->getType()->isHLSLResourceRecordArray()) {
3482 std::optional<LValue> LV =
3484 if (LV.has_value())
3485 return LV.value();
3486 }
3487
3488 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
3489
3490 if (VD->getTLSKind() != VarDecl::TLS_None)
3491 V = CGF.Builder.CreateThreadLocalAddress(V);
3492
3493 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
3494 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
3495 Address Addr(V, RealVarTy, Alignment);
3496 // Emit reference to the private copy of the variable if it is an OpenMP
3497 // threadprivate variable.
3498 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
3499 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3500 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
3501 E->getExprLoc());
3502 }
3503 LValue LV = VD->getType()->isReferenceType() ?
3507 setObjCGCLValueClass(CGF.getContext(), E, LV);
3508 return LV;
3509}
3510
3512 llvm::Type *Ty) {
3513 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3514 if (FD->hasAttr<WeakRefAttr>()) {
3516 return aliasee.getPointer();
3517 }
3518
3519 llvm::Constant *V = GetAddrOfFunction(GD, Ty);
3520 return V;
3521}
3522
3523static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
3524 GlobalDecl GD) {
3525 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3526 llvm::Constant *V = CGF.CGM.getFunctionPointer(GD);
3527 QualType ETy = E->getType();
3529 if (auto *GV = dyn_cast<llvm::GlobalValue>(V))
3530 V = llvm::NoCFIValue::get(GV);
3531 }
3532 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
3533 return CGF.MakeAddrLValue(V, ETy, Alignment, AlignmentSource::Decl);
3534}
3535
3537 llvm::Value *ThisValue) {
3538
3539 return CGF.EmitLValueForLambdaField(FD, ThisValue);
3540}
3541
3542/// Named Registers are named metadata pointing to the register name
3543/// which will be read from/written to as an argument to the intrinsic
3544/// @llvm.read/write_register.
3545/// So far, only the name is being passed down, but other options such as
3546/// register type, allocation type or even optimization options could be
3547/// passed down via the metadata node.
3548static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
3549 SmallString<64> Name("llvm.named.register.");
3550 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
3551 assert(Asm->getLabel().size() < 64-Name.size() &&
3552 "Register name too big");
3553 Name.append(Asm->getLabel());
3554 llvm::NamedMDNode *M =
3555 CGM.getModule().getOrInsertNamedMetadata(Name);
3556 if (M->getNumOperands() == 0) {
3557 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
3558 Asm->getLabel());
3559 llvm::Metadata *Ops[] = {Str};
3560 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3561 }
3562
3563 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
3564
3565 llvm::Value *Ptr =
3566 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
3567 return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
3568}
3569
3570/// Determine whether we can emit a reference to \p VD from the current
3571/// context, despite not necessarily having seen an odr-use of the variable in
3572/// this context.
3574 const DeclRefExpr *E,
3575 const VarDecl *VD) {
3576 // For a variable declared in an enclosing scope, do not emit a spurious
3577 // reference even if we have a capture, as that will emit an unwarranted
3578 // reference to our capture state, and will likely generate worse code than
3579 // emitting a local copy.
3581 return false;
3582
3583 // For a local declaration declared in this function, we can always reference
3584 // it even if we don't have an odr-use.
3585 if (VD->hasLocalStorage()) {
3586 return VD->getDeclContext() ==
3587 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
3588 }
3589
3590 // For a global declaration, we can emit a reference to it if we know
3591 // for sure that we are able to emit a definition of it.
3592 VD = VD->getDefinition(CGF.getContext());
3593 if (!VD)
3594 return false;
3595
3596 // Don't emit a spurious reference if it might be to a variable that only
3597 // exists on a different device / target.
3598 // FIXME: This is unnecessarily broad. Check whether this would actually be a
3599 // cross-target reference.
3600 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
3601 CGF.getLangOpts().OpenCL) {
3602 return false;
3603 }
3604
3605 // We can emit a spurious reference only if the linkage implies that we'll
3606 // be emitting a non-interposable symbol that will be retained until link
3607 // time.
3608 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
3609 case llvm::GlobalValue::ExternalLinkage:
3610 case llvm::GlobalValue::LinkOnceODRLinkage:
3611 case llvm::GlobalValue::WeakODRLinkage:
3612 case llvm::GlobalValue::InternalLinkage:
3613 case llvm::GlobalValue::PrivateLinkage:
3614 return true;
3615 default:
3616 return false;
3617 }
3618}
3619
3621 const NamedDecl *ND = E->getDecl();
3622 QualType T = E->getType();
3623
3624 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
3625 "should not emit an unevaluated operand");
3626
3627 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3628 // Global Named registers access via intrinsics only
3629 if (VD->getStorageClass() == SC_Register &&
3630 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3631 return EmitGlobalNamedRegister(VD, CGM);
3632
3633 // If this DeclRefExpr does not constitute an odr-use of the variable,
3634 // we're not permitted to emit a reference to it in general, and it might
3635 // not be captured if capture would be necessary for a use. Emit the
3636 // constant value directly instead.
3637 if (E->isNonOdrUse() == NOUR_Constant &&
3638 (VD->getType()->isReferenceType() ||
3639 !canEmitSpuriousReferenceToVariable(*this, E, VD))) {
3640 VD->getAnyInitializer(VD);
3641 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
3642 E->getLocation(), *VD->evaluateValue(), VD->getType());
3643 assert(Val && "failed to emit constant expression");
3644
3646 if (!VD->getType()->isReferenceType()) {
3647 // Spill the constant value to a global.
3648 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
3649 getContext().getDeclAlign(VD));
3650 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
3651 auto *PTy = llvm::PointerType::get(
3652 getLLVMContext(), getTypes().getTargetAddressSpace(VD->getType()));
3653 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
3654 } else {
3655 // Should we be using the alignment of the constant pointer we emitted?
3656 CharUnits Alignment =
3657 CGM.getNaturalTypeAlignment(E->getType(),
3658 /* BaseInfo= */ nullptr,
3659 /* TBAAInfo= */ nullptr,
3660 /* forPointeeType= */ true);
3661 Addr = makeNaturalAddressForPointer(Val, T, Alignment);
3662 }
3664 }
3665
3666 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
3667
3668 // Check for captured variables.
3670 VD = VD->getCanonicalDecl();
3671 if (auto *FD = LambdaCaptureFields.lookup(VD))
3672 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3673 if (CapturedStmtInfo) {
3674 auto I = LocalDeclMap.find(VD);
3675 if (I != LocalDeclMap.end()) {
3676 LValue CapLVal;
3677 if (VD->getType()->isReferenceType())
3678 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
3680 else
3681 CapLVal = MakeAddrLValue(I->second, T);
3682 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3683 // in simd context.
3684 if (getLangOpts().OpenMP &&
3685 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3686 CapLVal.setNontemporal(/*Value=*/true);
3687 return CapLVal;
3688 }
3689 LValue CapLVal =
3690 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
3691 CapturedStmtInfo->getContextValue());
3692 Address LValueAddress = CapLVal.getAddress();
3693 CapLVal = MakeAddrLValue(Address(LValueAddress.emitRawPointer(*this),
3694 LValueAddress.getElementType(),
3695 getContext().getDeclAlign(VD)),
3696 CapLVal.getType(),
3698 CapLVal.getTBAAInfo());
3699 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3700 // in simd context.
3701 if (getLangOpts().OpenMP &&
3702 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3703 CapLVal.setNontemporal(/*Value=*/true);
3704 return CapLVal;
3705 }
3706
3707 assert(isa<BlockDecl>(CurCodeDecl));
3708 Address addr = GetAddrOfBlockDecl(VD);
3709 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
3710 }
3711 }
3712
3713 // FIXME: We should be able to assert this for FunctionDecls as well!
3714 // FIXME: We should be able to assert this for all DeclRefExprs, not just
3715 // those with a valid source location.
3716 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
3717 !E->getLocation().isValid()) &&
3718 "Should not use decl without marking it used!");
3719
3720 if (ND->hasAttr<WeakRefAttr>()) {
3721 const auto *VD = cast<ValueDecl>(ND);
3722 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
3723 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
3724 }
3725
3726 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3727 // Check if this is a global variable.
3728 if (VD->hasLinkage() || VD->isStaticDataMember())
3729 return EmitGlobalVarDeclLValue(*this, E, VD);
3730
3731 Address addr = Address::invalid();
3732
3733 // The variable should generally be present in the local decl map.
3734 auto iter = LocalDeclMap.find(VD);
3735 if (iter != LocalDeclMap.end()) {
3736 addr = iter->second;
3737
3738 // Otherwise, it might be static local we haven't emitted yet for
3739 // some reason; most likely, because it's in an outer function.
3740 } else if (VD->isStaticLocal()) {
3741 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
3742 *VD, CGM.getLLVMLinkageVarDefinition(VD));
3743 addr = Address(
3744 var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
3745
3746 // No other cases for now.
3747 } else {
3748 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
3749 }
3750
3751 // Handle threadlocal function locals.
3752 if (VD->getTLSKind() != VarDecl::TLS_None)
3753 addr = addr.withPointer(
3754 Builder.CreateThreadLocalAddress(addr.getBasePointer()),
3756
3757 // Check for OpenMP threadprivate variables.
3758 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
3759 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3761 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
3762 E->getExprLoc());
3763 }
3764
3765 // Drill into block byref variables.
3766 bool isBlockByref = VD->isEscapingByref();
3767 if (isBlockByref) {
3768 addr = emitBlockByrefAddress(addr, VD);
3769 }
3770
3771 // Drill into reference types.
3772 LValue LV = VD->getType()->isReferenceType() ?
3775
3776 bool isLocalStorage = VD->hasLocalStorage();
3777
3778 bool NonGCable = isLocalStorage &&
3779 !VD->getType()->isReferenceType() &&
3780 !isBlockByref;
3781 if (NonGCable) {
3783 LV.setNonGC(true);
3784 }
3785
3786 bool isImpreciseLifetime =
3787 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3788 if (isImpreciseLifetime)
3791 return LV;
3792 }
3793
3794 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3795 return EmitFunctionDeclLValue(*this, E, FD);
3796
3797 // FIXME: While we're emitting a binding from an enclosing scope, all other
3798 // DeclRefExprs we see should be implicitly treated as if they also refer to
3799 // an enclosing scope.
3800 if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
3802 auto *FD = LambdaCaptureFields.lookup(BD);
3803 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3804 }
3805 // Suppress debug location updates when visiting the binding, since the
3806 // binding may emit instructions that would otherwise be associated with the
3807 // binding itself, rather than the expression referencing the binding. (this
3808 // leads to jumpy debug stepping behavior where the location/debugger jump
3809 // back to the binding declaration, then back to the expression referencing
3810 // the binding)
3812 return EmitLValue(BD->getBinding(), NotKnownNonNull);
3813 }
3814
3815 // We can form DeclRefExprs naming GUID declarations when reconstituting
3816 // non-type template parameters into expressions.
3817 if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
3818 return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
3820
3821 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3822 ConstantAddress ATPO = CGM.GetAddrOfTemplateParamObject(TPO);
3823 auto AS = getLangASFromTargetAS(ATPO.getAddressSpace());
3824
3825 if (AS != T.getAddressSpace()) {
3826 auto TargetAS = getContext().getTargetAddressSpace(T.getAddressSpace());
3827 llvm::Type *PtrTy =
3828 llvm::PointerType::get(CGM.getLLVMContext(), TargetAS);
3829 llvm::Constant *ASC = CGM.performAddrSpaceCast(ATPO.getPointer(), PtrTy);
3830 ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment());
3831 }
3832
3833 return MakeAddrLValue(ATPO, T, AlignmentSource::Decl);
3834 }
3835
3836 llvm_unreachable("Unhandled DeclRefExpr");
3837}
3838
3840 // __extension__ doesn't affect lvalue-ness.
3841 if (E->getOpcode() == UO_Extension)
3842 return EmitLValue(E->getSubExpr());
3843
3845 switch (E->getOpcode()) {
3846 default: llvm_unreachable("Unknown unary operator lvalue!");
3847 case UO_Deref: {
3849 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3850
3851 LValueBaseInfo BaseInfo;
3852 TBAAAccessInfo TBAAInfo;
3854 &TBAAInfo);
3855 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
3857
3858 // We should not generate __weak write barrier on indirect reference
3859 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
3860 // But, we continue to generate __strong write barrier on indirect write
3861 // into a pointer to object.
3862 if (getLangOpts().ObjC &&
3863 getLangOpts().getGC() != LangOptions::NonGC &&
3864 LV.isObjCWeak())
3866 return LV;
3867 }
3868 case UO_Real:
3869 case UO_Imag: {
3870 LValue LV = EmitLValue(E->getSubExpr());
3871 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3872
3873 // __real is valid on scalars. This is a faster way of testing that.
3874 // __imag can only produce an rvalue on scalars.
3875 if (E->getOpcode() == UO_Real &&
3876 !LV.getAddress().getElementType()->isStructTy()) {
3877 assert(E->getSubExpr()->getType()->isArithmeticType());
3878 return LV;
3879 }
3880
3881 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3882
3883 Address Component =
3884 (E->getOpcode() == UO_Real
3887 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
3888 CGM.getTBAAInfoForSubobject(LV, T));
3889 ElemLV.getQuals().addQualifiers(LV.getQuals());
3890 return ElemLV;
3891 }
3892 case UO_PreInc:
3893 case UO_PreDec: {
3894 LValue LV = EmitLValue(E->getSubExpr());
3895 bool isInc = E->getOpcode() == UO_PreInc;
3896
3897 if (E->getType()->isAnyComplexType())
3898 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3899 else
3900 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3901 return LV;
3902 }
3903 }
3904}
3905
3907 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
3909}
3910
3912 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
3914}
3915
3917 auto SL = E->getFunctionName();
3918 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3919 StringRef FnName = CurFn->getName();
3920 FnName.consume_front("\01");
3921 StringRef NameItems[] = {
3923 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3924 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3925 std::string Name = std::string(SL->getString());
3926 if (!Name.empty()) {
3927 unsigned Discriminator =
3928 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
3929 if (Discriminator)
3930 Name += "_" + Twine(Discriminator + 1).str();
3931 auto C = CGM.GetAddrOfConstantCString(Name, GVName);
3933 } else {
3934 auto C = CGM.GetAddrOfConstantCString(std::string(FnName), GVName);
3936 }
3937 }
3938 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3940}
3941
3942/// Emit a type description suitable for use by a runtime sanitizer library. The
3943/// format of a type descriptor is
3944///
3945/// \code
3946/// { i16 TypeKind, i16 TypeInfo }
3947/// \endcode
3948///
3949/// followed by an array of i8 containing the type name with extra information
3950/// for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
3951/// floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0xFFFF) for
3952/// anything else.
3954 // Only emit each type's descriptor once.
3955 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3956 return C;
3957
3958 uint16_t TypeKind = TK_Unknown;
3959 uint16_t TypeInfo = 0;
3960 bool IsBitInt = false;
3961
3962 if (T->isIntegerType()) {
3963 TypeKind = TK_Integer;
3964 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3965 (T->isSignedIntegerType() ? 1 : 0);
3966 // Follow suggestion from discussion of issue 64100.
3967 // So we can write the exact amount of bits in TypeName after '\0'
3968 // making it <diagnostic-like type name>.'\0'.<32-bit width>.
3969 if (T->isSignedIntegerType() && T->getAs<BitIntType>()) {
3970 // Do a sanity checks as we are using 32-bit type to store bit length.
3971 assert(getContext().getTypeSize(T) > 0 &&
3972 " non positive amount of bits in __BitInt type");
3973 assert(getContext().getTypeSize(T) <= 0xFFFFFFFF &&
3974 " too many bits in __BitInt type");
3975
3976 // Redefine TypeKind with the actual __BitInt type if we have signed
3977 // BitInt.
3978 TypeKind = TK_BitInt;
3979 IsBitInt = true;
3980 }
3981 } else if (T->isFloatingType()) {
3982 TypeKind = TK_Float;
3984 }
3985
3986 // Format the type name as if for a diagnostic, including quotes and
3987 // optionally an 'aka'.
3988 SmallString<32> Buffer;
3989 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
3990 (intptr_t)T.getAsOpaquePtr(), StringRef(),
3991 StringRef(), {}, Buffer, {});
3992
3993 if (IsBitInt) {
3994 // The Structure is: 0 to end the string, 32 bit unsigned integer in target
3995 // endianness, zero.
3996 char S[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};
3997 const auto *EIT = T->castAs<BitIntType>();
3998 uint32_t Bits = EIT->getNumBits();
3999 llvm::support::endian::write32(S + 1, Bits,
4000 getTarget().isBigEndian()
4001 ? llvm::endianness::big
4002 : llvm::endianness::little);
4003 StringRef Str = StringRef(S, sizeof(S) / sizeof(decltype(S[0])));
4004 Buffer.append(Str);
4005 }
4006
4007 llvm::Constant *Components[] = {
4008 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
4009 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
4010 };
4011 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
4012
4013 auto *GV = new llvm::GlobalVariable(
4014 CGM.getModule(), Descriptor->getType(),
4015 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
4016 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4017 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
4018
4019 // Remember the descriptor for this type.
4020 CGM.setTypeDescriptorInMap(T, GV);
4021
4022 return GV;
4023}
4024
4025llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
4026 llvm::Type *TargetTy = IntPtrTy;
4027
4028 if (V->getType() == TargetTy)
4029 return V;
4030
4031 // Floating-point types which fit into intptr_t are bitcast to integers
4032 // and then passed directly (after zero-extension, if necessary).
4033 if (V->getType()->isFloatingPointTy()) {
4034 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
4035 if (Bits <= TargetTy->getIntegerBitWidth())
4036 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
4037 Bits));
4038 }
4039
4040 // Integers which fit in intptr_t are zero-extended and passed directly.
4041 if (V->getType()->isIntegerTy() &&
4042 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
4043 return Builder.CreateZExt(V, TargetTy);
4044
4045 // Pointers are passed directly, everything else is passed by address.
4046 if (!V->getType()->isPointerTy()) {
4047 RawAddress Ptr = CreateDefaultAlignTempAlloca(V->getType());
4048 Builder.CreateStore(V, Ptr);
4049 V = Ptr.getPointer();
4050 }
4051 return Builder.CreatePtrToInt(V, TargetTy);
4052}
4053
4054/// Emit a representation of a SourceLocation for passing to a handler
4055/// in a sanitizer runtime library. The format for this data is:
4056/// \code
4057/// struct SourceLocation {
4058/// const char *Filename;
4059/// int32_t Line, Column;
4060/// };
4061/// \endcode
4062/// For an invalid SourceLocation, the Filename pointer is null.
4064 llvm::Constant *Filename;
4065 int Line, Column;
4066
4068 if (PLoc.isValid()) {
4069 StringRef FilenameString = PLoc.getFilename();
4070
4071 int PathComponentsToStrip =
4072 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
4073 if (PathComponentsToStrip < 0) {
4074 assert(PathComponentsToStrip != INT_MIN);
4075 int PathComponentsToKeep = -PathComponentsToStrip;
4076 auto I = llvm::sys::path::rbegin(FilenameString);
4077 auto E = llvm::sys::path::rend(FilenameString);
4078 while (I != E && --PathComponentsToKeep)
4079 ++I;
4080
4081 FilenameString = FilenameString.substr(I - E);
4082 } else if (PathComponentsToStrip > 0) {
4083 auto I = llvm::sys::path::begin(FilenameString);
4084 auto E = llvm::sys::path::end(FilenameString);
4085 while (I != E && PathComponentsToStrip--)
4086 ++I;
4087
4088 if (I != E)
4089 FilenameString =
4090 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
4091 else
4092 FilenameString = llvm::sys::path::filename(FilenameString);
4093 }
4094
4095 auto FilenameGV =
4096 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
4097 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
4099 FilenameGV.getPointer()->stripPointerCasts()));
4100 Filename = FilenameGV.getPointer();
4101 Line = PLoc.getLine();
4102 Column = PLoc.getColumn();
4103 } else {
4104 Filename = llvm::Constant::getNullValue(Int8PtrTy);
4105 Line = Column = 0;
4106 }
4107
4108 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
4109 Builder.getInt32(Column)};
4110
4111 return llvm::ConstantStruct::getAnon(Data);
4112}
4113
4114namespace {
4115/// Specify under what conditions this check can be recovered
4116enum class CheckRecoverableKind {
4117 /// Always terminate program execution if this check fails.
4119 /// Check supports recovering, runtime has both fatal (noreturn) and
4120 /// non-fatal handlers for this check.
4121 Recoverable,
4122 /// Runtime conditionally aborts, always need to support recovery.
4124};
4125}
4126
4127static CheckRecoverableKind
4129 if (Ordinal == SanitizerKind::SO_Vptr)
4130 return CheckRecoverableKind::AlwaysRecoverable;
4131 else if (Ordinal == SanitizerKind::SO_Return ||
4132 Ordinal == SanitizerKind::SO_Unreachable)
4133 return CheckRecoverableKind::Unrecoverable;
4134 else
4135 return CheckRecoverableKind::Recoverable;
4136}
4137
4138namespace {
4139struct SanitizerHandlerInfo {
4140 char const *const Name;
4141 unsigned Version;
4142};
4143}
4144
4145const SanitizerHandlerInfo SanitizerHandlers[] = {
4146#define SANITIZER_CHECK(Enum, Name, Version, Msg) {#Name, Version},
4148#undef SANITIZER_CHECK
4149};
4150
4152 llvm::FunctionType *FnType,
4154 SanitizerHandler CheckHandler,
4155 CheckRecoverableKind RecoverKind, bool IsFatal,
4156 llvm::BasicBlock *ContBB, bool NoMerge) {
4157 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
4158 std::optional<ApplyDebugLocation> DL;
4159 if (!CGF.Builder.getCurrentDebugLocation()) {
4160 // Ensure that the call has at least an artificial debug location.
4161 DL.emplace(CGF, SourceLocation());
4162 }
4163 bool NeedsAbortSuffix =
4164 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
4165 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
4166 bool HandlerPreserveAllRegs =
4167 CGF.CGM.getCodeGenOpts().SanitizeHandlerPreserveAllRegs;
4168 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
4169 const StringRef CheckName = CheckInfo.Name;
4170 std::string FnName = "__ubsan_handle_" + CheckName.str();
4171 if (CheckInfo.Version && !MinimalRuntime)
4172 FnName += "_v" + llvm::utostr(CheckInfo.Version);
4173 if (MinimalRuntime)
4174 FnName += "_minimal";
4175 if (NeedsAbortSuffix)
4176 FnName += "_abort";
4177 if (HandlerPreserveAllRegs && !NeedsAbortSuffix)
4178 FnName += "_preserve";
4179 bool MayReturn =
4180 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
4181
4182 llvm::AttrBuilder B(CGF.getLLVMContext());
4183 if (!MayReturn) {
4184 B.addAttribute(llvm::Attribute::NoReturn)
4185 .addAttribute(llvm::Attribute::NoUnwind);
4186 }
4187 B.addUWTableAttr(llvm::UWTableKind::Default);
4188
4189 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
4190 FnType, FnName,
4191 llvm::AttributeList::get(CGF.getLLVMContext(),
4192 llvm::AttributeList::FunctionIndex, B),
4193 /*Local=*/true);
4194 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
4195 NoMerge = NoMerge || !CGF.CGM.getCodeGenOpts().isOptimizedBuild() ||
4196 (CGF.CurCodeDecl && CGF.CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4197 if (NoMerge)
4198 HandlerCall->addFnAttr(llvm::Attribute::NoMerge);
4199 if (HandlerPreserveAllRegs && !NeedsAbortSuffix) {
4200 // N.B. there is also a clang::CallingConv which is not what we want here.
4201 HandlerCall->setCallingConv(llvm::CallingConv::PreserveAll);
4202 }
4203 if (!MayReturn) {
4204 HandlerCall->setDoesNotReturn();
4205 CGF.Builder.CreateUnreachable();
4206 } else {
4207 CGF.Builder.CreateBr(ContBB);
4208 }
4209}
4210
4212 ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> Checked,
4213 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
4214 ArrayRef<llvm::Value *> DynamicArgs, const TrapReason *TR) {
4215 assert(IsSanitizerScope);
4216 assert(Checked.size() > 0);
4217 assert(CheckHandler >= 0 &&
4218 size_t(CheckHandler) < std::size(SanitizerHandlers));
4219 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
4220
4221 llvm::Value *FatalCond = nullptr;
4222 llvm::Value *RecoverableCond = nullptr;
4223 llvm::Value *TrapCond = nullptr;
4224 bool NoMerge = false;
4225 // Expand checks into:
4226 // (Check1 || !allow_ubsan_check) && (Check2 || !allow_ubsan_check) ...
4227 // We need separate allow_ubsan_check intrinsics because they have separately
4228 // specified cutoffs.
4229 // This expression looks expensive but will be simplified after
4230 // LowerAllowCheckPass.
4231 for (auto &[Check, Ord] : Checked) {
4232 llvm::Value *GuardedCheck = Check;
4234 (CGM.getCodeGenOpts().SanitizeSkipHotCutoffs[Ord] > 0)) {
4235 llvm::Value *Allow = Builder.CreateCall(
4236 CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check),
4237 llvm::ConstantInt::get(CGM.Int8Ty, Ord));
4238 GuardedCheck = Builder.CreateOr(Check, Builder.CreateNot(Allow));
4239 }
4240
4241 // -fsanitize-trap= overrides -fsanitize-recover=.
4242 llvm::Value *&Cond = CGM.getCodeGenOpts().SanitizeTrap.has(Ord) ? TrapCond
4243 : CGM.getCodeGenOpts().SanitizeRecover.has(Ord)
4244 ? RecoverableCond
4245 : FatalCond;
4246 Cond = Cond ? Builder.CreateAnd(Cond, GuardedCheck) : GuardedCheck;
4247
4248 if (!CGM.getCodeGenOpts().SanitizeMergeHandlers.has(Ord))
4249 NoMerge = true;
4250 }
4251
4252 if (TrapCond)
4253 EmitTrapCheck(TrapCond, CheckHandler, NoMerge, TR);
4254 if (!FatalCond && !RecoverableCond)
4255 return;
4256
4257 llvm::Value *JointCond;
4258 if (FatalCond && RecoverableCond)
4259 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
4260 else
4261 JointCond = FatalCond ? FatalCond : RecoverableCond;
4262 assert(JointCond);
4263
4264 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
4265 assert(SanOpts.has(Checked[0].second));
4266#ifndef NDEBUG
4267 for (int i = 1, n = Checked.size(); i < n; ++i) {
4268 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
4269 "All recoverable kinds in a single check must be same!");
4270 assert(SanOpts.has(Checked[i].second));
4271 }
4272#endif
4273
4274 llvm::BasicBlock *Cont = createBasicBlock("cont");
4275 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
4276 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
4277 // Give hint that we very much don't expect to execute the handler
4278 llvm::MDBuilder MDHelper(getLLVMContext());
4279 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4280 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
4281 EmitBlock(Handlers);
4282
4283 // Clear arguments for the MinimalRuntime handler.
4284 if (CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
4285 StaticArgs = {};
4286 DynamicArgs = {};
4287 }
4288
4289 // Handler functions take an i8* pointing to the (handler-specific) static
4290 // information block, followed by a sequence of intptr_t arguments
4291 // representing operand values.
4294
4295 Args.reserve(DynamicArgs.size() + 1);
4296 ArgTypes.reserve(DynamicArgs.size() + 1);
4297
4298 // Emit handler arguments and create handler function type.
4299 if (!StaticArgs.empty()) {
4300 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4301 auto *InfoPtr = new llvm::GlobalVariable(
4302 CGM.getModule(), Info->getType(),
4303 // Non-constant global is used in a handler to deduplicate reports.
4304 // TODO: change deduplication logic and make it constant.
4305 /*isConstant=*/false, llvm::GlobalVariable::PrivateLinkage, Info, "",
4306 nullptr, llvm::GlobalVariable::NotThreadLocal,
4307 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
4308 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4309 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4310 Args.push_back(InfoPtr);
4311 ArgTypes.push_back(Args.back()->getType());
4312 }
4313
4314 for (llvm::Value *DynamicArg : DynamicArgs) {
4315 Args.push_back(EmitCheckValue(DynamicArg));
4316 ArgTypes.push_back(IntPtrTy);
4317 }
4318
4319 llvm::FunctionType *FnType =
4320 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
4321
4322 if (!FatalCond || !RecoverableCond) {
4323 // Simple case: we need to generate a single handler call, either
4324 // fatal, or non-fatal.
4325 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
4326 (FatalCond != nullptr), Cont, NoMerge);
4327 } else {
4328 // Emit two handler calls: first one for set of unrecoverable checks,
4329 // another one for recoverable.
4330 llvm::BasicBlock *NonFatalHandlerBB =
4331 createBasicBlock("non_fatal." + CheckName);
4332 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
4333 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
4334 EmitBlock(FatalHandlerBB);
4335 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
4336 NonFatalHandlerBB, NoMerge);
4337 EmitBlock(NonFatalHandlerBB);
4338 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
4339 Cont, NoMerge);
4340 }
4341
4342 EmitBlock(Cont);
4343}
4344
4346 SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond,
4347 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4348 ArrayRef<llvm::Constant *> StaticArgs) {
4349 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
4350
4351 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
4352 llvm::CondBrInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
4353
4354 llvm::MDBuilder MDHelper(getLLVMContext());
4355 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4356 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
4357
4358 EmitBlock(CheckBB);
4359
4360 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Ordinal);
4361
4362 llvm::CallInst *CheckCall;
4363 llvm::FunctionCallee SlowPathFn;
4364 if (WithDiag) {
4365 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4366 auto *InfoPtr =
4367 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
4368 llvm::GlobalVariable::PrivateLinkage, Info);
4369 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4370 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4371
4372 SlowPathFn = CGM.getModule().getOrInsertFunction(
4373 "__cfi_slowpath_diag",
4374 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
4375 false));
4376 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
4377 } else {
4378 SlowPathFn = CGM.getModule().getOrInsertFunction(
4379 "__cfi_slowpath",
4380 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
4381 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
4382 }
4383
4384 CGM.setDSOLocal(
4385 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
4386 CheckCall->setDoesNotThrow();
4387
4388 EmitBlock(Cont);
4389}
4390
4391// Emit a stub for __cfi_check function so that the linker knows about this
4392// symbol in LTO mode.
4394 llvm::Module *M = &CGM.getModule();
4395 ASTContext &C = getContext();
4396 QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
4397
4398 auto *ArgCallsiteTypeId =
4400 auto *ArgAddr =
4402 auto *ArgCFICheckFailData =
4404 FunctionArgList FnArgs{ArgCallsiteTypeId, ArgAddr, ArgCFICheckFailData};
4405 const CGFunctionInfo &FI =
4406 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs);
4407
4408 llvm::Function *F = llvm::Function::Create(
4409 llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false),
4410 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
4411 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4412 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4413 F->setAlignment(llvm::Align(4096));
4414 CGM.setDSOLocal(F);
4415
4416 llvm::LLVMContext &Ctx = M->getContext();
4417 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
4418 // CrossDSOCFI pass is not executed if there is no executable code.
4419 SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)};
4420 llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB);
4421 llvm::ReturnInst::Create(Ctx, nullptr, BB);
4422}
4423
4424// This function is basically a switch over the CFI failure kind, which is
4425// extracted from CFICheckFailData (1st function argument). Each case is either
4426// llvm.trap or a call to one of the two runtime handlers, based on
4427// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
4428// failure kind) traps, but this should really never happen. CFICheckFailData
4429// can be nullptr if the calling module has -fsanitize-trap behavior for this
4430// check kind; in this case __cfi_check_fail traps as well.
4432 auto CheckHandler = SanitizerHandler::CFICheckFail;
4433 // TODO: the SanitizerKind is not yet determined for this check (and might
4434 // not even be available, if Data == nullptr). However, we still want to
4435 // annotate the instrumentation. We approximate this by using all the CFI
4436 // kinds.
4437 SanitizerDebugLocation SanScope(
4438 this,
4439 {SanitizerKind::SO_CFIVCall, SanitizerKind::SO_CFINVCall,
4440 SanitizerKind::SO_CFIDerivedCast, SanitizerKind::SO_CFIUnrelatedCast,
4441 SanitizerKind::SO_CFIICall},
4442 CheckHandler);
4443 auto *ArgData = ImplicitParamDecl::Create(
4445 auto *ArgAddr = ImplicitParamDecl::Create(
4447
4448 FunctionArgList Args{ArgData, ArgAddr};
4449 const CGFunctionInfo &FI =
4450 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
4451
4452 llvm::Function *F = llvm::Function::Create(
4453 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
4454 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
4455
4456 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
4457 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
4458 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
4459
4460 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
4461 SourceLocation());
4462
4464
4465 // This function is not affected by NoSanitizeList. This function does
4466 // not have a source location, but "src:*" would still apply. Revert any
4467 // changes to SanOpts made in StartFunction.
4468 SanOpts = CGM.getLangOpts().Sanitize;
4469
4470 llvm::Value *Data =
4471 EmitLoadOfScalar(GetAddrOfLocalVar(ArgData), /*Volatile=*/false,
4472 CGM.getContext().VoidPtrTy, ArgData->getLocation());
4473 llvm::Value *Addr =
4474 EmitLoadOfScalar(GetAddrOfLocalVar(ArgAddr), /*Volatile=*/false,
4475 CGM.getContext().VoidPtrTy, ArgAddr->getLocation());
4476
4477 // Data == nullptr means the calling module has trap behaviour for this check.
4478 llvm::Value *DataIsNotNullPtr =
4479 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
4480 // TODO: since there is no data, we don't know the CheckKind, and therefore
4481 // cannot inspect CGM.getCodeGenOpts().SanitizeMergeHandlers. We default to
4482 // NoMerge = false. Users can disable merging by disabling optimization.
4483 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail,
4484 /*NoMerge=*/false);
4485
4486 llvm::StructType *SourceLocationTy =
4487 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
4488 llvm::StructType *CfiCheckFailDataTy =
4489 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
4490
4491 llvm::Value *V = Builder.CreateConstGEP2_32(
4492 CfiCheckFailDataTy, Builder.CreatePointerCast(Data, DefaultPtrTy), 0, 0);
4493
4494 Address CheckKindAddr(V, Int8Ty, getIntAlign());
4495 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
4496
4497 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
4498 CGM.getLLVMContext(),
4499 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
4500 llvm::Value *ValidVtable = Builder.CreateZExt(
4501 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
4502 {Addr, AllVtables}),
4503 IntPtrTy);
4504
4505 const std::pair<int, SanitizerKind::SanitizerOrdinal> CheckKinds[] = {
4506 {CFITCK_VCall, SanitizerKind::SO_CFIVCall},
4507 {CFITCK_NVCall, SanitizerKind::SO_CFINVCall},
4508 {CFITCK_DerivedCast, SanitizerKind::SO_CFIDerivedCast},
4509 {CFITCK_UnrelatedCast, SanitizerKind::SO_CFIUnrelatedCast},
4510 {CFITCK_ICall, SanitizerKind::SO_CFIICall}};
4511
4512 for (auto CheckKindOrdinalPair : CheckKinds) {
4513 int Kind = CheckKindOrdinalPair.first;
4514 SanitizerKind::SanitizerOrdinal Ordinal = CheckKindOrdinalPair.second;
4515
4516 // TODO: we could apply SanitizerAnnotateDebugInfo(Ordinal) instead of
4517 // relying on the SanitizerScope with all CFI ordinals
4518
4519 llvm::Value *Cond =
4520 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
4521 if (CGM.getLangOpts().Sanitize.has(Ordinal))
4522 EmitCheck(std::make_pair(Cond, Ordinal), SanitizerHandler::CFICheckFail,
4523 {}, {Data, Addr, ValidVtable});
4524 else
4525 // TODO: we can't rely on CGM.getCodeGenOpts().SanitizeMergeHandlers.
4526 // Although the compiler allows SanitizeMergeHandlers to be set
4527 // independently of CGM.getLangOpts().Sanitize, Driver/SanitizerArgs.cpp
4528 // requires that SanitizeMergeHandlers is a subset of Sanitize.
4529 EmitTrapCheck(Cond, CheckHandler, /*NoMerge=*/false);
4530 }
4531
4533 // The only reference to this function will be created during LTO link.
4534 // Make sure it survives until then.
4535 CGM.addUsedGlobal(F);
4536}
4537
4539 if (SanOpts.has(SanitizerKind::Unreachable)) {
4540 auto CheckOrdinal = SanitizerKind::SO_Unreachable;
4541 auto CheckHandler = SanitizerHandler::BuiltinUnreachable;
4542 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4543 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
4544 CheckOrdinal),
4545 CheckHandler, EmitCheckSourceLocation(Loc), {});
4546 }
4547 Builder.CreateUnreachable();
4548}
4549
4550void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
4551 SanitizerHandler CheckHandlerID,
4552 bool NoMerge, const TrapReason *TR) {
4553 llvm::BasicBlock *Cont = createBasicBlock("cont");
4554
4555 // If we're optimizing, collapse all calls to trap down to just one per
4556 // check-type per function to save on code size.
4557 if ((int)TrapBBs.size() <= CheckHandlerID)
4558 TrapBBs.resize(CheckHandlerID + 1);
4559
4560 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
4561
4562 llvm::DILocation *TrapLocation = Builder.getCurrentDebugLocation();
4563 llvm::StringRef TrapMessage;
4564 llvm::StringRef TrapCategory;
4565 auto DebugTrapReasonKind = CGM.getCodeGenOpts().getSanitizeDebugTrapReasons();
4566 if (TR && !TR->isEmpty() &&
4567 DebugTrapReasonKind ==
4569 TrapMessage = TR->getMessage();
4570 TrapCategory = TR->getCategory();
4571 } else {
4572 TrapMessage = GetUBSanTrapForHandler(CheckHandlerID);
4573 TrapCategory = "Undefined Behavior Sanitizer";
4574 }
4575
4576 if (getDebugInfo() && !TrapMessage.empty() &&
4577 DebugTrapReasonKind !=
4579 TrapLocation) {
4580 TrapLocation = getDebugInfo()->CreateTrapFailureMessageFor(
4581 TrapLocation, TrapCategory, TrapMessage);
4582 }
4583
4584 NoMerge = NoMerge || !CGM.getCodeGenOpts().isOptimizedBuild() ||
4585 (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>());
4586
4587 llvm::MDBuilder MDHelper(getLLVMContext());
4588 if (TrapBB && !NoMerge) {
4589 auto Call = TrapBB->begin();
4590 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
4591
4592 Call->applyMergedLocation(Call->getDebugLoc(), TrapLocation);
4593
4594 Builder.CreateCondBr(Checked, Cont, TrapBB,
4595 MDHelper.createLikelyBranchWeights());
4596 } else {
4597 TrapBB = createBasicBlock("trap");
4598 Builder.CreateCondBr(Checked, Cont, TrapBB,
4599 MDHelper.createLikelyBranchWeights());
4600 EmitBlock(TrapBB);
4601
4602 ApplyDebugLocation applyTrapDI(*this, TrapLocation);
4603
4604 llvm::CallInst *TrapCall;
4605 if (CGM.getCodeGenOpts().SanitizeTrapLoop)
4606 TrapCall =
4607 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::looptrap));
4608 else
4609 TrapCall = Builder.CreateCall(
4610 CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
4611 llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
4612
4613 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4614 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4615 CGM.getCodeGenOpts().TrapFuncName);
4616 TrapCall->addFnAttr(A);
4617 }
4618 if (NoMerge)
4619 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4620 TrapCall->setDoesNotReturn();
4621 TrapCall->setDoesNotThrow();
4622 Builder.CreateUnreachable();
4623 }
4624
4625 EmitBlock(Cont);
4626}
4627
4628llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
4629 llvm::CallInst *TrapCall =
4630 Builder.CreateCall(CGM.getIntrinsic(IntrID));
4631
4632 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
4633 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
4634 CGM.getCodeGenOpts().TrapFuncName);
4635 TrapCall->addFnAttr(A);
4636 }
4637
4639 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4640 return TrapCall;
4641}
4642
4644 LValueBaseInfo *BaseInfo,
4645 TBAAAccessInfo *TBAAInfo) {
4646 assert(E->getType()->isArrayType() &&
4647 "Array to pointer decay must have array source type!");
4648
4649 // Expressions of array type can't be bitfields or vector elements.
4650 LValue LV = EmitLValue(E);
4651 Address Addr = LV.getAddress();
4652
4653 // If the array type was an incomplete type, we need to make sure
4654 // the decay ends up being the right type.
4655 llvm::Type *NewTy = ConvertType(E->getType());
4656 Addr = Addr.withElementType(NewTy);
4657
4658 // Note that VLA pointers are always decayed, so we don't need to do
4659 // anything here.
4660 if (!E->getType()->isVariableArrayType()) {
4661 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4662 "Expected pointer to array");
4663
4664 if (getLangOpts().EmitLogicalPointer) {
4665 // Array-to-pointer decay for an SGEP is a no-op as we don't do any
4666 // logical indexing. See #179951 for some additional context.
4667 auto *SGEP =
4668 Builder.CreateStructuredGEP(NewTy, Addr.emitRawPointer(*this), {});
4669 Addr = Address(SGEP, NewTy, Addr.getAlignment(), Addr.isKnownNonNull());
4670 } else {
4671 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4672 }
4673 }
4674
4675 // The result of this decay conversion points to an array element within the
4676 // base lvalue. However, since TBAA currently does not support representing
4677 // accesses to elements of member arrays, we conservatively represent accesses
4678 // to the pointee object as if it had no any base lvalue specified.
4679 // TODO: Support TBAA for member arrays.
4681 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
4682 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
4683
4684 return Addr.withElementType(ConvertTypeForMem(EltType));
4685}
4686
4687/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
4688/// array to pointer, return the array subexpression.
4689static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
4690 // If this isn't just an array->pointer decay, bail out.
4691 const auto *CE = dyn_cast<CastExpr>(E);
4692 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4693 return nullptr;
4694
4695 // If this is a decay from variable width array, bail out.
4696 const Expr *SubExpr = CE->getSubExpr();
4697 if (SubExpr->getType()->isVariableArrayType())
4698 return nullptr;
4699
4700 return SubExpr;
4701}
4702
4704 llvm::Type *elemType,
4705 llvm::Value *ptr,
4706 ArrayRef<llvm::Value*> indices,
4707 bool inbounds,
4708 bool signedIndices,
4709 SourceLocation loc,
4710 const llvm::Twine &name = "arrayidx") {
4711 if (inbounds && CGF.getLangOpts().EmitLogicalPointer)
4712 return CGF.Builder.CreateStructuredGEP(elemType, ptr, indices);
4713
4714 if (inbounds) {
4715 return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
4717 name);
4718 } else {
4719 return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
4720 }
4721}
4722
4725 llvm::Type *arrayType,
4726 llvm::Type *elementType, bool inbounds,
4727 bool signedIndices, SourceLocation loc,
4728 CharUnits align,
4729 const llvm::Twine &name = "arrayidx") {
4730 if (inbounds && CGF.getLangOpts().EmitLogicalPointer)
4731 return RawAddress(CGF.Builder.CreateStructuredGEP(arrayType,
4732 addr.emitRawPointer(CGF),
4733 indices.drop_front()),
4734 elementType, align);
4735
4736 if (inbounds) {
4737 return CGF.EmitCheckedInBoundsGEP(addr, indices, elementType, signedIndices,
4739 align, name);
4740 } else {
4741 return CGF.Builder.CreateGEP(addr, indices, elementType, align, name);
4742 }
4743}
4744
4746 const VariableArrayType *vla) {
4747 QualType eltType;
4748 do {
4749 eltType = vla->getElementType();
4750 } while ((vla = ctx.getAsVariableArrayType(eltType)));
4751 return eltType;
4752}
4753
4755 return D && D->hasAttr<BPFPreserveStaticOffsetAttr>();
4756}
4757
4758static bool hasBPFPreserveStaticOffset(const Expr *E) {
4759 if (!E)
4760 return false;
4761 QualType PointeeType = E->getType()->getPointeeType();
4762 if (PointeeType.isNull())
4763 return false;
4764 if (const auto *BaseDecl = PointeeType->getAsRecordDecl())
4765 return hasBPFPreserveStaticOffset(BaseDecl);
4766 return false;
4767}
4768
4769// Wraps Addr with a call to llvm.preserve.static.offset intrinsic.
4771 Address &Addr) {
4772 if (!CGF.getTarget().getTriple().isBPF())
4773 return Addr;
4774
4775 llvm::Function *Fn =
4776 CGF.CGM.getIntrinsic(llvm::Intrinsic::preserve_static_offset);
4777 llvm::CallInst *Call = CGF.Builder.CreateCall(Fn, {Addr.emitRawPointer(CGF)});
4778 return Address(Call, Addr.getElementType(), Addr.getAlignment());
4779}
4780
4781/// Given an array base, check whether its member access belongs to a record
4782/// with preserve_access_index attribute or not.
4783static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
4784 if (!ArrayBase || !CGF.getDebugInfo())
4785 return false;
4786
4787 // Only support base as either a MemberExpr or DeclRefExpr.
4788 // DeclRefExpr to cover cases like:
4789 // struct s { int a; int b[10]; };
4790 // struct s *p;
4791 // p[1].a
4792 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
4793 // p->b[5] is a MemberExpr example.
4794 const Expr *E = ArrayBase->IgnoreImpCasts();
4795 if (const auto *ME = dyn_cast<MemberExpr>(E))
4796 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4797
4798 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
4799 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
4800 if (!VarDef)
4801 return false;
4802
4803 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
4804 if (!PtrT)
4805 return false;
4806
4807 const auto *PointeeT = PtrT->getPointeeType()
4809 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
4810 return RecT->getDecl()
4811 ->getMostRecentDecl()
4812 ->hasAttr<BPFPreserveAccessIndexAttr>();
4813 return false;
4814 }
4815
4816 return false;
4817}
4818
4821 QualType eltType, bool inbounds,
4822 bool signedIndices, SourceLocation loc,
4823 QualType *arrayType = nullptr,
4824 const Expr *Base = nullptr,
4825 const llvm::Twine &name = "arrayidx") {
4826 // All the indices except that last must be zero.
4827#ifndef NDEBUG
4828 for (auto *idx : indices.drop_back())
4829 assert(isa<llvm::ConstantInt>(idx) &&
4830 cast<llvm::ConstantInt>(idx)->isZero());
4831#endif
4832
4833 // Determine the element size of the statically-sized base. This is
4834 // the thing that the indices are expressed in terms of.
4835 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
4836 eltType = getFixedSizeElementType(CGF.getContext(), vla);
4837 }
4838
4839 // We can use that to compute the best alignment of the element.
4840 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
4841 CharUnits eltAlign =
4842 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
4843
4845 addr = wrapWithBPFPreserveStaticOffset(CGF, addr);
4846
4847 llvm::Value *eltPtr;
4848 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4849 if (!LastIndex ||
4851 addr = emitArraySubscriptGEP(CGF, addr, indices,
4853 : nullptr,
4854 CGF.ConvertTypeForMem(eltType), inbounds,
4855 signedIndices, loc, eltAlign, name);
4856 return addr;
4857 } else {
4858 // Remember the original array subscript for bpf target
4859 unsigned idx = LastIndex->getZExtValue();
4860 llvm::DIType *DbgInfo = nullptr;
4861 if (arrayType)
4862 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
4863 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(
4864 addr.getElementType(), addr.emitRawPointer(CGF), indices.size() - 1,
4865 idx, DbgInfo);
4866 }
4867
4868 return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
4869}
4870
4871namespace {
4872
4873/// StructFieldAccess is a simple visitor class to grab the first l-value to
4874/// r-value cast Expr.
4875struct StructFieldAccess
4876 : public ConstStmtVisitor<StructFieldAccess, const Expr *> {
4877 const Expr *VisitCastExpr(const CastExpr *E) {
4878 if (E->getCastKind() == CK_LValueToRValue)
4879 return E;
4880 return Visit(E->getSubExpr());
4881 }
4882 const Expr *VisitParenExpr(const ParenExpr *E) {
4883 return Visit(E->getSubExpr());
4884 }
4885};
4886
4887} // end anonymous namespace
4888
4889/// The offset of a field from the beginning of the record.
4891 const FieldDecl *Field, int64_t &Offset) {
4892 ASTContext &Ctx = CGF.getContext();
4893 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
4894 unsigned FieldNo = 0;
4895
4896 for (const FieldDecl *FD : RD->fields()) {
4897 if (FD == Field) {
4898 Offset += Layout.getFieldOffset(FieldNo);
4899 return true;
4900 }
4901
4902 QualType Ty = FD->getType();
4903 if (Ty->isRecordType())
4904 if (getFieldOffsetInBits(CGF, Ty->getAsRecordDecl(), Field, Offset)) {
4905 Offset += Layout.getFieldOffset(FieldNo);
4906 return true;
4907 }
4908
4909 if (!RD->isUnion())
4910 ++FieldNo;
4911 }
4912
4913 return false;
4914}
4915
4916/// Returns the relative offset difference between \p FD1 and \p FD2.
4917/// \code
4918/// offsetof(struct foo, FD1) - offsetof(struct foo, FD2)
4919/// \endcode
4920/// Both fields must be within the same struct.
4921static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF,
4922 const FieldDecl *FD1,
4923 const FieldDecl *FD2) {
4924 const RecordDecl *FD1OuterRec =
4926 const RecordDecl *FD2OuterRec =
4928
4929 if (FD1OuterRec != FD2OuterRec)
4930 // Fields must be within the same RecordDecl.
4931 return std::optional<int64_t>();
4932
4933 int64_t FD1Offset = 0;
4934 if (!getFieldOffsetInBits(CGF, FD1OuterRec, FD1, FD1Offset))
4935 return std::optional<int64_t>();
4936
4937 int64_t FD2Offset = 0;
4938 if (!getFieldOffsetInBits(CGF, FD2OuterRec, FD2, FD2Offset))
4939 return std::optional<int64_t>();
4940
4941 return std::make_optional<int64_t>(FD1Offset - FD2Offset);
4942}
4943
4944/// EmitCountedByBoundsChecking - If the array being accessed has a "counted_by"
4945/// attribute, generate bounds checking code. The "count" field is at the top
4946/// level of the struct or in an anonymous struct, that's also at the top level.
4947/// Future expansions may allow the "count" to reside at any place in the
4948/// struct, but the value of "counted_by" will be a "simple" path to the count,
4949/// i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or
4950/// similar to emit the correct GEP.
4952 const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst,
4953 QualType IndexType, llvm::Value *IndexVal, bool Accessed,
4954 bool FlexibleArray) {
4955 const auto *ME = dyn_cast<MemberExpr>(ArrayExpr->IgnoreImpCasts());
4956 if (!ME || !ME->getMemberDecl()->getType()->isCountAttributedType())
4957 return;
4958
4959 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
4960 getLangOpts().getStrictFlexArraysLevel();
4961 if (FlexibleArray &&
4962 !ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel))
4963 return;
4964
4965 const FieldDecl *FD = cast<FieldDecl>(ME->getMemberDecl());
4966 const FieldDecl *CountFD = FD->findCountedByField();
4967 if (!CountFD)
4968 return;
4969
4970 if (std::optional<int64_t> Diff =
4971 getOffsetDifferenceInBits(*this, CountFD, FD)) {
4972 if (!ArrayInst.isValid()) {
4973 // An invalid Address indicates we're checking a pointer array access.
4974 // Emit the checked L-Value here.
4975 LValue LV = EmitCheckedLValue(ArrayExpr, TCK_MemberAccess);
4976 ArrayInst = LV.getAddress();
4977 }
4978
4979 // FIXME: The 'static_cast' is necessary, otherwise the result turns into a
4980 // uint64_t, which messes things up if we have a negative offset difference.
4981 Diff = *Diff / static_cast<int64_t>(CGM.getContext().getCharWidth());
4982
4983 // Create a GEP with the byte offset between the counted object and the
4984 // count and use that to load the count value.
4985 ArrayInst = Builder.CreatePointerBitCastOrAddrSpaceCast(ArrayInst,
4986 Int8PtrTy, Int8Ty);
4987
4988 llvm::Type *BoundsType = ConvertType(CountFD->getType());
4989 llvm::Value *BoundsVal =
4990 Builder.CreateInBoundsGEP(Int8Ty, ArrayInst.emitRawPointer(*this),
4991 Builder.getInt32(*Diff), ".counted_by.gep");
4992 BoundsVal = Builder.CreateAlignedLoad(BoundsType, BoundsVal, getIntAlign(),
4993 ".counted_by.load");
4994
4995 // Now emit the bounds checking.
4996 EmitBoundsCheckImpl(ArrayExpr, ArrayType, IndexVal, IndexType, BoundsVal,
4997 CountFD->getType(), Accessed);
4998 }
4999}
5000
5002 bool Accessed) {
5003 // The index must always be an integer, which is not an aggregate. Emit it
5004 // in lexical order (this complexity is, sadly, required by C++17).
5005 llvm::Value *IdxPre =
5006 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
5007 bool SignedIndices = false;
5008 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
5009 auto *Idx = IdxPre;
5010 if (E->getLHS() != E->getIdx()) {
5011 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
5012 Idx = EmitScalarExpr(E->getIdx());
5013 }
5014
5015 QualType IdxTy = E->getIdx()->getType();
5016 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
5017 SignedIndices |= IdxSigned;
5018
5019 if (SanOpts.has(SanitizerKind::ArrayBounds))
5020 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
5021
5022 // Extend or truncate the index type to 32 or 64-bits.
5023 if (Promote && Idx->getType() != IntPtrTy)
5024 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
5025
5026 return Idx;
5027 };
5028 IdxPre = nullptr;
5029
5030 // If the base is a vector type, then we are forming a vector element lvalue
5031 // with this subscript.
5032 if (E->getBase()->getType()->isSubscriptableVectorType() &&
5034 // Emit the vector as an lvalue to get its address.
5035 LValue LHS = EmitLValue(E->getBase());
5036 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
5037 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
5038 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
5039 LHS.getBaseInfo(), TBAAAccessInfo());
5040 }
5041
5042 // The HLSL runtime handles subscript expressions on global resource arrays
5043 // and objects with HLSL buffer layouts.
5044 if (getLangOpts().HLSL) {
5045 std::optional<LValue> LV;
5046 if (E->getType()->isHLSLResourceRecord() ||
5048 LV = CGM.getHLSLRuntime().emitResourceArraySubscriptExpr(E, *this);
5049 } else if (E->getType().getAddressSpace() == LangAS::hlsl_constant) {
5050 LV = CGM.getHLSLRuntime().emitBufferArraySubscriptExpr(E, *this,
5051 EmitIdxAfterBase);
5052 }
5053 if (LV.has_value())
5054 return *LV;
5055 }
5056
5057 // All the other cases basically behave like simple offsetting.
5058
5059 // Handle the extvector case we ignored above.
5061 LValue LV = EmitLValue(E->getBase());
5062 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5064
5065 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
5066 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
5067 SignedIndices, E->getExprLoc());
5068 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
5069 CGM.getTBAAInfoForSubobject(LV, EltType));
5070 }
5071
5072 LValueBaseInfo EltBaseInfo;
5073 TBAAAccessInfo EltTBAAInfo;
5075 if (const VariableArrayType *vla =
5076 getContext().getAsVariableArrayType(E->getType())) {
5077 // The base must be a pointer, which is not an aggregate. Emit
5078 // it. It needs to be emitted first in case it's what captures
5079 // the VLA bounds.
5080 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5081 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5082
5083 // The element count here is the total number of non-VLA elements.
5084 llvm::Value *numElements = getVLASize(vla).NumElts;
5085
5086 // Effectively, the multiply by the VLA size is part of the GEP.
5087 // GEP indexes are signed, and scaling an index isn't permitted to
5088 // signed-overflow, so we use the same semantics for our explicit
5089 // multiply. We suppress this if overflow is not undefined behavior.
5090 if (getLangOpts().PointerOverflowDefined) {
5091 Idx = Builder.CreateMul(Idx, numElements);
5092 } else {
5093 Idx = Builder.CreateNSWMul(Idx, numElements);
5094 }
5095
5096 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
5097 !getLangOpts().PointerOverflowDefined,
5098 SignedIndices, E->getExprLoc());
5099
5100 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
5101 // Indexing over an interface, as in "NSString *P; P[4];"
5102
5103 // Emit the base pointer.
5104 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5105 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5106
5107 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
5108 llvm::Value *InterfaceSizeVal =
5109 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
5110
5111 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
5112
5113 // We don't necessarily build correct LLVM struct types for ObjC
5114 // interfaces, so we can't rely on GEP to do this scaling
5115 // correctly, so we need to cast to i8*. FIXME: is this actually
5116 // true? A lot of other things in the fragile ABI would break...
5117 llvm::Type *OrigBaseElemTy = Addr.getElementType();
5118
5119 // Do the GEP.
5120 CharUnits EltAlign =
5121 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
5122 llvm::Value *EltPtr =
5123 emitArraySubscriptGEP(*this, Int8Ty, Addr.emitRawPointer(*this),
5124 ScaledIdx, false, SignedIndices, E->getExprLoc());
5125 Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
5126 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
5127 // If this is A[i] where A is an array, the frontend will have decayed the
5128 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5129 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5130 // "gep x, i" here. Emit one "gep A, 0, i".
5131 assert(Array->getType()->isArrayType() &&
5132 "Array to pointer decay must have array source type!");
5133 LValue ArrayLV;
5134 // For simple multidimensional array indexing, set the 'accessed' flag for
5135 // better bounds-checking of the base expression.
5136 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5137 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
5138 else
5139 ArrayLV = EmitLValue(Array);
5140 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5141
5142 if (SanOpts.has(SanitizerKind::ArrayBounds))
5143 EmitCountedByBoundsChecking(Array, Array->getType(), ArrayLV.getAddress(),
5144 E->getIdx()->getType(), Idx, Accessed,
5145 /*FlexibleArray=*/true);
5146
5147 // Propagate the alignment from the array itself to the result.
5148 QualType arrayType = Array->getType();
5150 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5151 E->getType(), !getLangOpts().PointerOverflowDefined, SignedIndices,
5152 E->getExprLoc(), &arrayType, E->getBase());
5153 EltBaseInfo = ArrayLV.getBaseInfo();
5154 if (!CGM.getCodeGenOpts().NewStructPathTBAA) {
5155 // Since CodeGenTBAA::getTypeInfoHelper only handles array types for
5156 // new struct path TBAA, we must a use a plain access.
5157 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
5158 } else if (ArrayLV.getTBAAInfo().isMayAlias()) {
5159 EltTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5160 } else if (ArrayLV.getTBAAInfo().isIncomplete()) {
5161 // The array element is complete, even if the array is not.
5162 EltTBAAInfo = CGM.getTBAAAccessInfo(E->getType());
5163 } else {
5164 // The TBAA access info from the array (base) lvalue is ordinary. We will
5165 // adapt it to create access info for the element.
5166 EltTBAAInfo = ArrayLV.getTBAAInfo();
5167
5168 // We retain the TBAA struct path (BaseType and Offset members) from the
5169 // array. In the TBAA representation, we map any array access to the
5170 // element at index 0, as the index is generally a runtime value. This
5171 // element has the same offset in the base type as the array itself.
5172 // If the array lvalue had no base type, there is no point trying to
5173 // generate one, since an array itself is not a valid base type.
5174
5175 // We also retain the access type from the base lvalue, but the access
5176 // size must be updated to the size of an individual element.
5177 EltTBAAInfo.Size =
5179 }
5180 } else {
5181 // The base must be a pointer; emit it with an estimate of its alignment.
5182 Address BaseAddr =
5183 EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
5184 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
5185 QualType ptrType = E->getBase()->getType();
5186 Addr = emitArraySubscriptGEP(*this, BaseAddr, Idx, E->getType(),
5187 !getLangOpts().PointerOverflowDefined,
5188 SignedIndices, E->getExprLoc(), &ptrType,
5189 E->getBase());
5190
5191 if (SanOpts.has(SanitizerKind::ArrayBounds)) {
5192 StructFieldAccess Visitor;
5193 const Expr *Base = Visitor.Visit(E->getBase());
5194
5195 if (const auto *CE = dyn_cast_if_present<CastExpr>(Base);
5196 CE && CE->getCastKind() == CK_LValueToRValue)
5198 E->getIdx()->getType(), Idx, Accessed,
5199 /*FlexibleArray=*/false);
5200 }
5201 }
5202
5203 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
5204
5205 if (getLangOpts().ObjC &&
5206 getLangOpts().getGC() != LangOptions::NonGC) {
5209 }
5210 return LV;
5211}
5212
5214 llvm::Value *Idx = EmitScalarExpr(E);
5215 if (Idx->getType() == IntPtrTy)
5216 return Idx;
5217 bool IsSigned = E->getType()->isSignedIntegerOrEnumerationType();
5218 return Builder.CreateIntCast(Idx, IntPtrTy, IsSigned);
5219}
5220
5222 const MatrixSingleSubscriptExpr *E) {
5223 LValue Base = EmitLValue(E->getBase());
5224 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
5225
5226 RawAddress MatAddr = Base.getAddress();
5227 if (getLangOpts().HLSL &&
5229 MatAddr = CGM.getHLSLRuntime().createBufferMatrixTempAddress(Base, *this);
5230
5231 return LValue::MakeMatrixRow(MaybeConvertMatrixAddress(MatAddr, *this),
5232 RowIdx, E->getBase()->getType(),
5233 Base.getBaseInfo(), TBAAAccessInfo());
5234}
5235
5237 assert(
5238 !E->isIncomplete() &&
5239 "incomplete matrix subscript expressions should be rejected during Sema");
5240 LValue Base = EmitLValue(E->getBase());
5241
5242 // Extend or truncate the index type to 32 or 64-bits if needed.
5243 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
5244 llvm::Value *ColIdx = EmitMatrixIndexExpr(E->getColumnIdx());
5245 llvm::MatrixBuilder MB(Builder);
5246 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
5247 unsigned NumCols = MatrixTy->getNumColumns();
5248 unsigned NumRows = MatrixTy->getNumRows();
5249 bool IsMatrixRowMajor =
5251 llvm::Value *FinalIdx =
5252 MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
5253
5254 return LValue::MakeMatrixElt(
5255 MaybeConvertMatrixAddress(Base.getAddress(), *this), FinalIdx,
5256 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
5257}
5258
5260 LValueBaseInfo &BaseInfo,
5261 TBAAAccessInfo &TBAAInfo,
5262 QualType BaseTy, QualType ElTy,
5263 bool IsLowerBound) {
5264 LValue BaseLVal;
5265 if (auto *ASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParenImpCasts())) {
5266 BaseLVal = CGF.EmitArraySectionExpr(ASE, IsLowerBound);
5267 if (BaseTy->isArrayType()) {
5268 Address Addr = BaseLVal.getAddress();
5269 BaseInfo = BaseLVal.getBaseInfo();
5270
5271 // If the array type was an incomplete type, we need to make sure
5272 // the decay ends up being the right type.
5273 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
5274 Addr = Addr.withElementType(NewTy);
5275
5276 // Note that VLA pointers are always decayed, so we don't need to do
5277 // anything here.
5278 if (!BaseTy->isVariableArrayType()) {
5279 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
5280 "Expected pointer to array");
5281 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
5282 }
5283
5284 return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
5285 }
5286 LValueBaseInfo TypeBaseInfo;
5287 TBAAAccessInfo TypeTBAAInfo;
5288 CharUnits Align =
5289 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
5290 BaseInfo.mergeForCast(TypeBaseInfo);
5291 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
5292 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()),
5293 CGF.ConvertTypeForMem(ElTy), Align);
5294 }
5295 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
5296}
5297
5299 bool IsLowerBound) {
5300
5301 assert(!E->isOpenACCArraySection() &&
5302 "OpenACC Array section codegen not implemented");
5303
5305 QualType ResultExprTy;
5306 if (auto *AT = getContext().getAsArrayType(BaseTy))
5307 ResultExprTy = AT->getElementType();
5308 else
5309 ResultExprTy = BaseTy->getPointeeType();
5310 llvm::Value *Idx = nullptr;
5311 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
5312 // Requesting lower bound or upper bound, but without provided length and
5313 // without ':' symbol for the default length -> length = 1.
5314 // Idx = LowerBound ?: 0;
5315 if (auto *LowerBound = E->getLowerBound()) {
5316 Idx = Builder.CreateIntCast(
5317 EmitScalarExpr(LowerBound), IntPtrTy,
5318 LowerBound->getType()->hasSignedIntegerRepresentation());
5319 } else
5320 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
5321 } else {
5322 // Try to emit length or lower bound as constant. If this is possible, 1
5323 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
5324 // IR (LB + Len) - 1.
5325 auto &C = CGM.getContext();
5326 auto *Length = E->getLength();
5327 llvm::APSInt ConstLength;
5328 if (Length) {
5329 // Idx = LowerBound + Length - 1;
5330 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
5331 ConstLength = CL->zextOrTrunc(PointerWidthInBits);
5332 Length = nullptr;
5333 }
5334 auto *LowerBound = E->getLowerBound();
5335 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
5336 if (LowerBound) {
5337 if (std::optional<llvm::APSInt> LB =
5338 LowerBound->getIntegerConstantExpr(C)) {
5339 ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
5340 LowerBound = nullptr;
5341 }
5342 }
5343 if (!Length)
5344 --ConstLength;
5345 else if (!LowerBound)
5346 --ConstLowerBound;
5347
5348 if (Length || LowerBound) {
5349 auto *LowerBoundVal =
5350 LowerBound
5351 ? Builder.CreateIntCast(
5352 EmitScalarExpr(LowerBound), IntPtrTy,
5353 LowerBound->getType()->hasSignedIntegerRepresentation())
5354 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
5355 auto *LengthVal =
5356 Length
5357 ? Builder.CreateIntCast(
5358 EmitScalarExpr(Length), IntPtrTy,
5359 Length->getType()->hasSignedIntegerRepresentation())
5360 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
5361 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
5362 /*HasNUW=*/false,
5363 !getLangOpts().PointerOverflowDefined);
5364 if (Length && LowerBound) {
5365 Idx = Builder.CreateSub(
5366 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
5367 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5368 }
5369 } else
5370 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
5371 } else {
5372 // Idx = ArraySize - 1;
5373 QualType ArrayTy = BaseTy->isPointerType()
5375 : BaseTy;
5376 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
5377 Length = VAT->getSizeExpr();
5378 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
5379 ConstLength = *L;
5380 Length = nullptr;
5381 }
5382 } else {
5383 auto *CAT = C.getAsConstantArrayType(ArrayTy);
5384 assert(CAT && "unexpected type for array initializer");
5385 ConstLength = CAT->getSize();
5386 }
5387 if (Length) {
5388 auto *LengthVal = Builder.CreateIntCast(
5389 EmitScalarExpr(Length), IntPtrTy,
5390 Length->getType()->hasSignedIntegerRepresentation());
5391 Idx = Builder.CreateSub(
5392 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
5393 /*HasNUW=*/false, !getLangOpts().PointerOverflowDefined);
5394 } else {
5395 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
5396 --ConstLength;
5397 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
5398 }
5399 }
5400 }
5401 assert(Idx);
5402
5403 Address EltPtr = Address::invalid();
5404 LValueBaseInfo BaseInfo;
5405 TBAAAccessInfo TBAAInfo;
5406 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
5407 // The base must be a pointer, which is not an aggregate. Emit
5408 // it. It needs to be emitted first in case it's what captures
5409 // the VLA bounds.
5410 Address Base =
5411 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
5412 BaseTy, VLA->getElementType(), IsLowerBound);
5413 // The element count here is the total number of non-VLA elements.
5414 llvm::Value *NumElements = getVLASize(VLA).NumElts;
5415
5416 // Effectively, the multiply by the VLA size is part of the GEP.
5417 // GEP indexes are signed, and scaling an index isn't permitted to
5418 // signed-overflow, so we use the same semantics for our explicit
5419 // multiply. We suppress this if overflow is not undefined behavior.
5420 if (getLangOpts().PointerOverflowDefined)
5421 Idx = Builder.CreateMul(Idx, NumElements);
5422 else
5423 Idx = Builder.CreateNSWMul(Idx, NumElements);
5424 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
5425 !getLangOpts().PointerOverflowDefined,
5426 /*signedIndices=*/false, E->getExprLoc());
5427 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
5428 // If this is A[i] where A is an array, the frontend will have decayed the
5429 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
5430 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
5431 // "gep x, i" here. Emit one "gep A, 0, i".
5432 assert(Array->getType()->isArrayType() &&
5433 "Array to pointer decay must have array source type!");
5434 LValue ArrayLV;
5435 // For simple multidimensional array indexing, set the 'accessed' flag for
5436 // better bounds-checking of the base expression.
5437 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5438 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
5439 else
5440 ArrayLV = EmitLValue(Array);
5441
5442 // Propagate the alignment from the array itself to the result.
5443 EltPtr = emitArraySubscriptGEP(
5444 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5445 ResultExprTy, !getLangOpts().PointerOverflowDefined,
5446 /*signedIndices=*/false, E->getExprLoc());
5447 BaseInfo = ArrayLV.getBaseInfo();
5448 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
5449 } else {
5450 Address Base =
5451 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, BaseTy,
5452 ResultExprTy, IsLowerBound);
5453 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
5454 !getLangOpts().PointerOverflowDefined,
5455 /*signedIndices=*/false, E->getExprLoc());
5456 }
5457
5458 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
5459}
5460
5463 // Emit the base vector as an l-value.
5464 LValue Base;
5465
5466 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
5467 if (E->isArrow()) {
5468 // If it is a pointer to a vector, emit the address and form an lvalue with
5469 // it.
5470 LValueBaseInfo BaseInfo;
5471 TBAAAccessInfo TBAAInfo;
5472 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
5473 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
5474 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
5475 Base.getQuals().removeObjCGCAttr();
5476 } else if (E->getBase()->isGLValue()) {
5477 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
5478 // emit the base as an lvalue.
5479 assert(E->getBase()->getType()->isVectorType());
5480 Base = EmitLValue(E->getBase());
5481 } else {
5482 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
5483 assert(E->getBase()->getType()->isVectorType() &&
5484 "Result must be a vector");
5485 llvm::Value *Vec = EmitScalarExpr(E->getBase());
5486
5487 // Store the vector to memory (because LValue wants an address).
5488 Address VecMem = CreateMemTemp(E->getBase()->getType());
5489 // need to zero extend an hlsl boolean vector to store it back to memory
5490 QualType Ty = E->getBase()->getType();
5491 llvm::Type *LTy = convertTypeForLoadStore(Ty, Vec->getType());
5492 if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
5493 Vec = Builder.CreateZExt(Vec, LTy);
5494 Builder.CreateStore(Vec, VecMem);
5496 }
5497
5498 QualType type =
5499 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
5500
5501 // Encode the element access list into a vector of unsigned indices.
5503 E->getEncodedElementAccess(Indices);
5504
5505 if (Base.isSimple()) {
5506 llvm::Constant *CV =
5507 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
5508 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
5509 Base.getBaseInfo(), TBAAAccessInfo());
5510 }
5511
5512 if (Base.isMatrixRow()) {
5513 if (auto *RowIdx =
5514 llvm::dyn_cast<llvm::ConstantInt>(Base.getMatrixRowIdx())) {
5516 QualType MatTy = Base.getType();
5517 const ConstantMatrixType *MT = MatTy->castAs<ConstantMatrixType>();
5518 unsigned NumCols = Indices.size();
5519 unsigned NumRows = MT->getNumRows();
5520 unsigned Row = RowIdx->getZExtValue();
5521 QualType VecQT = E->getBase()->getType();
5522 if (NumCols != MT->getNumColumns()) {
5523 const auto *EVT = VecQT->getAs<ExtVectorType>();
5524 QualType ElemQT = EVT->getElementType();
5525 VecQT = getContext().getExtVectorType(ElemQT, NumCols);
5526 }
5527 for (unsigned C = 0; C < NumCols; ++C) {
5528 unsigned Col = Indices[C];
5529 unsigned Linear = Col * NumRows + Row;
5530 MatIndices.push_back(llvm::ConstantInt::get(Int32Ty, Linear));
5531 }
5532
5533 llvm::Constant *ConstIdxs = llvm::ConstantVector::get(MatIndices);
5534 return LValue::MakeExtVectorElt(Base.getMatrixAddress(), ConstIdxs, VecQT,
5535 Base.getBaseInfo(), TBAAAccessInfo());
5536 }
5537 llvm::Constant *Cols =
5538 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
5539 // Note: intentionally not using E.getType() so we can reuse isMatrixRow()
5540 // implementations in EmitLoadOfLValue & EmitStoreThroughLValue and don't
5541 // need the LValue to have its own number of rows and columns when the
5542 // type is a vector.
5544 Base.getMatrixAddress(), Base.getMatrixRowIdx(), Cols, Base.getType(),
5545 Base.getBaseInfo(), TBAAAccessInfo());
5546 }
5547
5548 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
5549
5550 llvm::Constant *BaseElts = Base.getExtVectorElts();
5552
5553 for (unsigned Index : Indices)
5554 CElts.push_back(BaseElts->getAggregateElement(Index));
5555 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
5556 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
5557 Base.getBaseInfo(), TBAAAccessInfo());
5558}
5559
5561 const Expr *UnderlyingBaseExpr = E->IgnoreParens();
5562 while (auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
5563 UnderlyingBaseExpr = BaseMemberExpr->getBase()->IgnoreParens();
5564 return getContext().isSentinelNullExpr(UnderlyingBaseExpr);
5565}
5566
5568 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
5570 return EmitDeclRefLValue(DRE);
5571 }
5572
5573 if (getLangOpts().HLSL) {
5574 QualType QT = E->getType();
5576 return CGM.getHLSLRuntime().emitBufferMemberExpr(*this, E);
5577
5579 std::optional<LValue> LV;
5580 LV = CGM.getHLSLRuntime().emitResourceMemberExpr(*this, E);
5581 if (LV.has_value())
5582 return *LV;
5583 }
5584 }
5585
5586 Expr *BaseExpr = E->getBase();
5587 // Check whether the underlying base pointer is a constant null.
5588 // If so, we do not set inbounds flag for GEP to avoid breaking some
5589 // old-style offsetof idioms.
5590 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
5592 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
5593 LValue BaseLV;
5594 if (E->isArrow()) {
5595 LValueBaseInfo BaseInfo;
5596 TBAAAccessInfo TBAAInfo;
5597 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
5598 QualType PtrTy = BaseExpr->getType()->getPointeeType();
5599 SanitizerSet SkippedChecks;
5600 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
5601 if (IsBaseCXXThis)
5602 SkippedChecks.set(SanitizerKind::Alignment, true);
5603 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
5604 SkippedChecks.set(SanitizerKind::Null, true);
5606 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
5607 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
5608 } else
5609 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
5610
5611 NamedDecl *ND = E->getMemberDecl();
5612 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
5613 LValue LV = EmitLValueForField(BaseLV, Field, IsInBounds);
5615 if (getLangOpts().OpenMP) {
5616 // If the member was explicitly marked as nontemporal, mark it as
5617 // nontemporal. If the base lvalue is marked as nontemporal, mark access
5618 // to children as nontemporal too.
5619 if ((IsWrappedCXXThis(BaseExpr) &&
5620 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
5621 BaseLV.isNontemporal())
5622 LV.setNontemporal(/*Value=*/true);
5623 }
5624 return LV;
5625 }
5626
5627 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
5628 return EmitFunctionDeclLValue(*this, E, FD);
5629
5630 llvm_unreachable("Unhandled member declaration!");
5631}
5632
5633/// Given that we are currently emitting a lambda, emit an l-value for
5634/// one of its members.
5635///
5637 llvm::Value *ThisValue) {
5638 bool HasExplicitObjectParameter = false;
5639 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl);
5640 if (MD) {
5641 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
5642 assert(MD->getParent()->isLambda());
5643 assert(MD->getParent() == Field->getParent());
5644 }
5645 LValue LambdaLV;
5646 if (HasExplicitObjectParameter) {
5647 const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0);
5648 auto It = LocalDeclMap.find(D);
5649 assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
5650 Address AddrOfExplicitObject = It->getSecond();
5651 if (D->getType()->isReferenceType())
5652 LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(),
5654 else
5655 LambdaLV = MakeAddrLValue(AddrOfExplicitObject,
5657
5658 // Make sure we have an lvalue to the lambda itself and not a derived class.
5659 auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl();
5660 auto *LambdaTy = cast<CXXRecordDecl>(Field->getParent());
5661 if (ThisTy != LambdaTy) {
5662 const CXXCastPath &BasePathArray = getContext().LambdaCastPaths.at(MD);
5664 LambdaLV.getAddress(), ThisTy, BasePathArray.begin(),
5665 BasePathArray.end(), /*NullCheckValue=*/false, SourceLocation());
5667 LambdaLV = MakeAddrLValue(Base, T);
5668 }
5669 } else {
5670 CanQualType LambdaTagType =
5671 getContext().getCanonicalTagType(Field->getParent());
5672 LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
5673 }
5674 return EmitLValueForField(LambdaLV, Field);
5675}
5676
5678 return EmitLValueForLambdaField(Field, CXXABIThisValue);
5679}
5680
5681/// Get the field index in the debug info. The debug info structure/union
5682/// will ignore the unnamed bitfields.
5684 unsigned FieldIndex) {
5685 unsigned I = 0, Skipped = 0;
5686
5687 for (auto *F : Rec->getDefinition()->fields()) {
5688 if (I == FieldIndex)
5689 break;
5690 if (F->isUnnamedBitField())
5691 Skipped++;
5692 I++;
5693 }
5694
5695 return FieldIndex - Skipped;
5696}
5697
5698/// Get the address of a zero-sized field within a record. The resulting
5699/// address doesn't necessarily have the right type.
5701 const FieldDecl *Field,
5702 bool IsInBounds) {
5704 CGF.getContext().getFieldOffset(Field));
5705 if (Offset.isZero())
5706 return Base;
5707 Base = Base.withElementType(CGF.Int8Ty);
5708 if (!IsInBounds)
5709 return CGF.Builder.CreateConstByteGEP(Base, Offset);
5710 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
5711}
5712
5713/// Drill down to the storage of a field without walking into reference types,
5714/// and without respect for pointer field protection.
5715///
5716/// The resulting address doesn't necessarily have the right type.
5718 const FieldDecl *field,
5719 bool IsInBounds) {
5720 if (isEmptyFieldForLayout(CGF.getContext(), field))
5721 return emitAddrOfZeroSizeField(CGF, base, field, IsInBounds);
5722
5723 const RecordDecl *rec = field->getParent();
5724
5725 unsigned idx =
5726 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5727 llvm::Type *StructType =
5729
5730 if (CGF.getLangOpts().EmitLogicalPointer)
5731 return RawAddress(
5732 CGF.Builder.CreateStructuredGEP(StructType, base.emitRawPointer(CGF),
5733 {CGF.Builder.getSize(idx)}),
5734 base.getElementType(), base.getAlignment());
5735
5736 if (!IsInBounds)
5737 return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
5738
5739 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
5740}
5741
5742/// Drill down to the storage of a field without walking into reference types,
5743/// wrapping the address in an llvm.protected.field.ptr intrinsic for the
5744/// pointer field protection feature if necessary.
5745///
5746/// The resulting address doesn't necessarily have the right type.
5748 const FieldDecl *field, bool IsInBounds) {
5749 Address Addr = emitRawAddrOfFieldStorage(CGF, base, field, IsInBounds);
5750
5751 if (!CGF.getContext().isPFPField(field))
5752 return Addr;
5753
5754 return CGF.EmitAddressOfPFPField(base, Addr, field);
5755}
5756
5758 Address addr, const FieldDecl *field) {
5759 const RecordDecl *rec = field->getParent();
5760 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
5761 base.getType(), rec->getLocation());
5762
5763 unsigned idx =
5764 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
5765
5767 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
5768}
5769
5770static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
5771 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
5772 if (!RD)
5773 return false;
5774
5775 if (RD->isDynamicClass())
5776 return true;
5777
5778 for (const auto &Base : RD->bases())
5779 if (hasAnyVptr(Base.getType(), Context))
5780 return true;
5781
5782 for (const FieldDecl *Field : RD->fields())
5783 if (hasAnyVptr(Field->getType(), Context))
5784 return true;
5785
5786 return false;
5787}
5788
5790 bool IsInBounds) {
5791 LValueBaseInfo BaseInfo = base.getBaseInfo();
5792
5793 if (field->isBitField()) {
5794 const CGRecordLayout &RL =
5795 CGM.getTypes().getCGRecordLayout(field->getParent());
5796 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
5797 const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
5798 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
5799 Info.VolatileStorageSize != 0 &&
5800 field->getType()
5803 Address Addr = base.getAddress();
5804 unsigned Idx = RL.getLLVMFieldNo(field);
5805 const RecordDecl *rec = field->getParent();
5808 if (!UseVolatile) {
5809 if (!IsInPreservedAIRegion &&
5810 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5811 if (Idx != 0) {
5812 // For structs, we GEP to the field that the record layout suggests.
5813 if (!IsInBounds)
5814 Addr = Builder.CreateConstGEP2_32(Addr, 0, Idx, field->getName());
5815 else
5816 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
5817 }
5818 } else {
5819 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
5820 getContext().getCanonicalTagType(rec), rec->getLocation());
5821 Addr = Builder.CreatePreserveStructAccessIndex(
5822 Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
5823 DbgInfo);
5824 }
5825 }
5826 const unsigned SS =
5827 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
5828 // Get the access type.
5829 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
5830 Addr = Addr.withElementType(FieldIntTy);
5831 if (UseVolatile) {
5832 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
5833 if (VolatileOffset)
5834 Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
5835 }
5836
5837 QualType fieldType =
5838 field->getType().withCVRQualifiers(base.getVRQualifiers());
5839 // TODO: Support TBAA for bit fields.
5840 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
5841 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
5842 TBAAAccessInfo());
5843 }
5844
5845 // Fields of may-alias structures are may-alias themselves.
5846 // FIXME: this should get propagated down through anonymous structs
5847 // and unions.
5848 QualType FieldType = field->getType();
5849 const RecordDecl *rec = field->getParent();
5850 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
5851 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
5852 TBAAAccessInfo FieldTBAAInfo;
5853 if (base.getTBAAInfo().isMayAlias() ||
5854 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
5855 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5856 } else if (rec->isUnion()) {
5857 // TODO: Support TBAA for unions.
5858 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
5859 } else {
5860 // If no base type been assigned for the base access, then try to generate
5861 // one for this base lvalue.
5862 FieldTBAAInfo = base.getTBAAInfo();
5863 if (!FieldTBAAInfo.BaseType) {
5864 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
5865 assert(!FieldTBAAInfo.Offset &&
5866 "Nonzero offset for an access with no base type!");
5867 }
5868
5869 // Adjust offset to be relative to the base type.
5870 const ASTRecordLayout &Layout =
5872 unsigned CharWidth = getContext().getCharWidth();
5873 if (FieldTBAAInfo.BaseType)
5874 FieldTBAAInfo.Offset +=
5875 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
5876
5877 // Update the final access type and size.
5878 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
5879 FieldTBAAInfo.Size =
5881 }
5882
5883 Address addr = base.getAddress();
5885 addr = wrapWithBPFPreserveStaticOffset(*this, addr);
5886 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
5887 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5888 ClassDef->isDynamicClass()) {
5889 // Getting to any field of dynamic object requires stripping dynamic
5890 // information provided by invariant.group. This is because accessing
5891 // fields may leak the real address of dynamic object, which could result
5892 // in miscompilation when leaked pointer would be compared.
5893 auto *stripped =
5894 Builder.CreateStripInvariantGroup(addr.emitRawPointer(*this));
5895 addr = Address(stripped, addr.getElementType(), addr.getAlignment());
5896 }
5897 }
5898
5899 unsigned RecordCVR = base.getVRQualifiers();
5900 if (rec->isUnion()) {
5901 // For unions, there is no pointer adjustment.
5902 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5903 hasAnyVptr(FieldType, getContext()))
5904 // Because unions can easily skip invariant.barriers, we need to add
5905 // a barrier every time CXXRecord field with vptr is referenced.
5906 addr = Builder.CreateLaunderInvariantGroup(addr);
5907
5909 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5910 // Remember the original union field index
5911 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
5912 rec->getLocation());
5913 addr =
5914 Address(Builder.CreatePreserveUnionAccessIndex(
5915 addr.emitRawPointer(*this),
5916 getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
5917 addr.getElementType(), addr.getAlignment());
5918 }
5919
5920 if (FieldType->isReferenceType())
5921 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5922 } else {
5923 if (!IsInPreservedAIRegion &&
5924 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
5925 // For structs, we GEP to the field that the record layout suggests.
5926 addr = emitAddrOfFieldStorage(*this, addr, field, IsInBounds);
5927 else
5928 // Remember the original struct field index
5929 addr = emitPreserveStructAccess(*this, base, addr, field);
5930 }
5931
5932 // If this is a reference field, load the reference right now.
5933 if (FieldType->isReferenceType()) {
5934 LValue RefLVal =
5935 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5936 if (RecordCVR & Qualifiers::Volatile)
5937 RefLVal.getQuals().addVolatile();
5938 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
5939
5940 // Qualifiers on the struct don't apply to the referencee.
5941 RecordCVR = 0;
5942 FieldType = FieldType->getPointeeType();
5943 }
5944
5945 // Make sure that the address is pointing to the right type. This is critical
5946 // for both unions and structs.
5947 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5948
5949 if (field->hasAttr<AnnotateAttr>())
5950 addr = EmitFieldAnnotations(field, addr);
5951
5952 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5953 LV.getQuals().addCVRQualifiers(RecordCVR);
5954
5955 // __weak attribute on a field is ignored.
5958
5959 return LV;
5960}
5961
5962LValue
5964 const FieldDecl *Field) {
5965 QualType FieldType = Field->getType();
5966
5967 if (!FieldType->isReferenceType())
5968 return EmitLValueForField(Base, Field);
5969
5971 *this, Base.getAddress(), Field,
5972 /*IsInBounds=*/!getLangOpts().PointerOverflowDefined);
5973
5974 // Make sure that the address is pointing to the right type.
5975 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
5976 V = V.withElementType(llvmType);
5977
5978 // TODO: Generate TBAA information that describes this access as a structure
5979 // member access and not just an access to an object of the field's type. This
5980 // should be similar to what we do in EmitLValueForField().
5981 LValueBaseInfo BaseInfo = Base.getBaseInfo();
5982 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
5983 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
5984 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
5985 CGM.getTBAAInfoForSubobject(Base, FieldType));
5986}
5987
5989 if (E->isFileScope()) {
5990 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
5991 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
5992 }
5993 if (E->getType()->isVariablyModifiedType())
5994 // make sure to emit the VLA size.
5996
5997 Address DeclPtr = CreateMemTempWithoutCast(E->getType(), ".compoundliteral");
5998 const Expr *InitExpr = E->getInitializer();
6000
6001 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
6002 /*Init*/ true);
6003
6004 // Block-scope compound literals are destroyed at the end of the enclosing
6005 // scope in C.
6006 if (!getLangOpts().CPlusPlus)
6009 E->getType(), getDestroyer(DtorKind),
6010 DtorKind & EHCleanup);
6011
6012 return Result;
6013}
6014
6016 if (!E->isGLValue())
6017 // Initializing an aggregate temporary in C++11: T{...}.
6018 return EmitAggExprToLValue(E);
6019
6020 // An lvalue initializer list must be initializing a reference.
6021 assert(E->isTransparent() && "non-transparent glvalue init list");
6022 return EmitLValue(E->getInit(0));
6023}
6024
6025/// Emit the operand of a glvalue conditional operator. This is either a glvalue
6026/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
6027/// LValue is returned and the current block has been terminated.
6028static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
6029 const Expr *Operand) {
6030 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
6031 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
6032 return std::nullopt;
6033 }
6034
6035 return CGF.EmitLValue(Operand);
6036}
6037
6038namespace {
6039// Handle the case where the condition is a constant evaluatable simple integer,
6040// which means we don't have to separately handle the true/false blocks.
6041std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
6042 CodeGenFunction &CGF, const AbstractConditionalOperator *E) {
6043 const Expr *condExpr = E->getCond();
6044 bool CondExprBool;
6045 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
6046 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
6047 if (!CondExprBool)
6048 std::swap(Live, Dead);
6049
6050 if (!CGF.ContainsLabel(Dead)) {
6051 // If the true case is live, we need to track its region.
6052 CGF.incrementProfileCounter(CondExprBool ? CGF.UseExecPath
6053 : CGF.UseSkipPath,
6054 E, /*UseBoth=*/true);
6055 CGF.markStmtMaybeUsed(Dead);
6056 // If a throw expression we emit it and return an undefined lvalue
6057 // because it can't be used.
6058 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
6059 CGF.EmitCXXThrowExpr(ThrowExpr);
6060 llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
6061 llvm::Type *Ty = CGF.DefaultPtrTy;
6062 return CGF.MakeAddrLValue(
6063 Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
6064 Dead->getType());
6065 }
6066 return CGF.EmitLValue(Live);
6067 }
6068 }
6069 return std::nullopt;
6070}
6071struct ConditionalInfo {
6072 llvm::BasicBlock *lhsBlock, *rhsBlock;
6073 std::optional<LValue> LHS, RHS;
6074};
6075
6076// Create and generate the 3 blocks for a conditional operator.
6077// Leaves the 'current block' in the continuation basic block.
6078template<typename FuncTy>
6079ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
6080 const AbstractConditionalOperator *E,
6081 const FuncTy &BranchGenFunc) {
6082 ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
6083 CGF.createBasicBlock("cond.false"), std::nullopt,
6084 std::nullopt};
6085 llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
6086
6088 CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
6089 CGF.getProfileCount(E));
6090
6091 // Any temporaries created here are conditional.
6092 CGF.EmitBlock(Info.lhsBlock);
6094 eval.begin(CGF);
6095 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
6096 eval.end(CGF);
6097 Info.lhsBlock = CGF.Builder.GetInsertBlock();
6098
6099 if (Info.LHS)
6100 CGF.Builder.CreateBr(endBlock);
6101
6102 // Any temporaries created here are conditional.
6103 CGF.EmitBlock(Info.rhsBlock);
6105 eval.begin(CGF);
6106 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
6107 eval.end(CGF);
6108 Info.rhsBlock = CGF.Builder.GetInsertBlock();
6109 CGF.EmitBlock(endBlock);
6110
6111 return Info;
6112}
6113} // namespace
6114
6116 const AbstractConditionalOperator *E) {
6117 if (!E->isGLValue()) {
6118 // ?: here should be an aggregate.
6119 assert(hasAggregateEvaluationKind(E->getType()) &&
6120 "Unexpected conditional operator!");
6121 return (void)EmitAggExprToLValue(E);
6122 }
6123
6124 OpaqueValueMapping binding(*this, E);
6125 if (HandleConditionalOperatorLValueSimpleCase(*this, E))
6126 return;
6127
6128 EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
6129 CGF.EmitIgnoredExpr(E);
6130 return LValue{};
6131 });
6132}
6135 if (!expr->isGLValue()) {
6136 // ?: here should be an aggregate.
6137 assert(hasAggregateEvaluationKind(expr->getType()) &&
6138 "Unexpected conditional operator!");
6139 return EmitAggExprToLValue(expr);
6140 }
6141
6142 OpaqueValueMapping binding(*this, expr);
6143 if (std::optional<LValue> Res =
6144 HandleConditionalOperatorLValueSimpleCase(*this, expr))
6145 return *Res;
6146
6147 ConditionalInfo Info = EmitConditionalBlocks(
6148 *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
6149 return EmitLValueOrThrowExpression(CGF, E);
6150 });
6151
6152 if ((Info.LHS && !Info.LHS->isSimple()) ||
6153 (Info.RHS && !Info.RHS->isSimple()))
6154 return EmitUnsupportedLValue(expr, "conditional operator");
6155
6156 if (Info.LHS && Info.RHS) {
6157 Address lhsAddr = Info.LHS->getAddress();
6158 Address rhsAddr = Info.RHS->getAddress();
6160 lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock,
6161 Builder.GetInsertBlock(), expr->getType());
6162 AlignmentSource alignSource =
6163 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
6164 Info.RHS->getBaseInfo().getAlignmentSource());
6165 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
6166 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
6167 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
6168 TBAAInfo);
6169 } else {
6170 assert((Info.LHS || Info.RHS) &&
6171 "both operands of glvalue conditional are throw-expressions?");
6172 return Info.LHS ? *Info.LHS : *Info.RHS;
6173 }
6174}
6175
6176/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
6177/// type. If the cast is to a reference, we can have the usual lvalue result,
6178/// otherwise if a cast is needed by the code generator in an lvalue context,
6179/// then it must mean that we need the address of an aggregate in order to
6180/// access one of its members. This can happen for all the reasons that casts
6181/// are permitted with aggregate result, including noop aggregate casts, and
6182/// cast from scalar to union.
6184 llvm::scope_exit RestoreCurCast([this, Prev = CurCast] { CurCast = Prev; });
6185 CurCast = E;
6186 switch (E->getCastKind()) {
6187 case CK_ToVoid:
6188 case CK_BitCast:
6189 case CK_LValueToRValueBitCast:
6190 case CK_ArrayToPointerDecay:
6191 case CK_FunctionToPointerDecay:
6192 case CK_NullToMemberPointer:
6193 case CK_NullToPointer:
6194 case CK_IntegralToPointer:
6195 case CK_PointerToIntegral:
6196 case CK_PointerToBoolean:
6197 case CK_IntegralCast:
6198 case CK_BooleanToSignedIntegral:
6199 case CK_IntegralToBoolean:
6200 case CK_IntegralToFloating:
6201 case CK_FloatingToIntegral:
6202 case CK_FloatingToBoolean:
6203 case CK_FloatingCast:
6204 case CK_FloatingRealToComplex:
6205 case CK_FloatingComplexToReal:
6206 case CK_FloatingComplexToBoolean:
6207 case CK_FloatingComplexCast:
6208 case CK_FloatingComplexToIntegralComplex:
6209 case CK_IntegralRealToComplex:
6210 case CK_IntegralComplexToReal:
6211 case CK_IntegralComplexToBoolean:
6212 case CK_IntegralComplexCast:
6213 case CK_IntegralComplexToFloatingComplex:
6214 case CK_DerivedToBaseMemberPointer:
6215 case CK_BaseToDerivedMemberPointer:
6216 case CK_MemberPointerToBoolean:
6217 case CK_ReinterpretMemberPointer:
6218 case CK_AnyPointerToBlockPointerCast:
6219 case CK_ARCProduceObject:
6220 case CK_ARCConsumeObject:
6221 case CK_ARCReclaimReturnedObject:
6222 case CK_ARCExtendBlockObject:
6223 case CK_CopyAndAutoreleaseBlockObject:
6224 case CK_IntToOCLSampler:
6225 case CK_FloatingToFixedPoint:
6226 case CK_FixedPointToFloating:
6227 case CK_FixedPointCast:
6228 case CK_FixedPointToBoolean:
6229 case CK_FixedPointToIntegral:
6230 case CK_IntegralToFixedPoint:
6231 case CK_MatrixCast:
6232 case CK_HLSLVectorTruncation:
6233 case CK_HLSLMatrixTruncation:
6234 case CK_HLSLArrayRValue:
6235 case CK_HLSLElementwiseCast:
6236 case CK_HLSLAggregateSplatCast:
6237 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
6238
6239 case CK_Dependent:
6240 llvm_unreachable("dependent cast kind in IR gen!");
6241
6242 case CK_BuiltinFnToFnPtr:
6243 llvm_unreachable("builtin functions are handled elsewhere");
6244
6245 // These are never l-values; just use the aggregate emission code.
6246 case CK_NonAtomicToAtomic:
6247 case CK_AtomicToNonAtomic:
6248 return EmitAggExprToLValue(E);
6249
6250 case CK_Dynamic: {
6251 LValue LV = EmitLValue(E->getSubExpr());
6252 Address V = LV.getAddress();
6253 const auto *DCE = cast<CXXDynamicCastExpr>(E);
6255 }
6256
6257 case CK_ConstructorConversion:
6258 case CK_UserDefinedConversion:
6259 case CK_CPointerToObjCPointerCast:
6260 case CK_BlockPointerToObjCPointerCast:
6261 case CK_LValueToRValue:
6262 return EmitLValue(E->getSubExpr());
6263
6264 case CK_NoOp: {
6265 // CK_NoOp can model a qualification conversion, which can remove an array
6266 // bound and change the IR type.
6267 // FIXME: Once pointee types are removed from IR, remove this.
6268 LValue LV = EmitLValue(E->getSubExpr());
6269 // Propagate the volatile qualifer to LValue, if exist in E.
6271 LV.getQuals() = E->getType().getQualifiers();
6272 if (LV.isSimple()) {
6273 Address V = LV.getAddress();
6274 if (V.isValid()) {
6275 llvm::Type *T = ConvertTypeForMem(E->getType());
6276 if (V.getElementType() != T)
6277 LV.setAddress(V.withElementType(T));
6278 }
6279 }
6280 return LV;
6281 }
6282
6283 case CK_UncheckedDerivedToBase:
6284 case CK_DerivedToBase: {
6285 auto *DerivedClassDecl = E->getSubExpr()->getType()->castAsCXXRecordDecl();
6286 LValue LV = EmitLValue(E->getSubExpr());
6287 Address This = LV.getAddress();
6288
6289 // Perform the derived-to-base conversion
6291 This, DerivedClassDecl, E->path_begin(), E->path_end(),
6292 /*NullCheckValue=*/false, E->getExprLoc());
6293
6294 // TODO: Support accesses to members of base classes in TBAA. For now, we
6295 // conservatively pretend that the complete object is of the base class
6296 // type.
6297 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
6298 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6299 }
6300 case CK_ToUnion:
6301 return EmitAggExprToLValue(E);
6302 case CK_BaseToDerived: {
6303 auto *DerivedClassDecl = E->getType()->castAsCXXRecordDecl();
6304 LValue LV = EmitLValue(E->getSubExpr());
6305
6306 // Perform the base-to-derived conversion
6308 LV.getAddress(), DerivedClassDecl, E->path_begin(), E->path_end(),
6309 /*NullCheckValue=*/false);
6310
6311 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
6312 // performed and the object is not of the derived type.
6315 E->getType());
6316
6317 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
6318 EmitVTablePtrCheckForCast(E->getType(), Derived,
6319 /*MayBeNull=*/false, CFITCK_DerivedCast,
6320 E->getBeginLoc());
6321
6322 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
6323 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6324 }
6325 case CK_LValueBitCast: {
6326 // This must be a reinterpret_cast (or c-style equivalent).
6327 const auto *CE = cast<ExplicitCastExpr>(E);
6328
6329 CGM.EmitExplicitCastExprType(CE, this);
6330 LValue LV = EmitLValue(E->getSubExpr());
6332 ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
6333
6334 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
6336 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
6337 E->getBeginLoc());
6338
6339 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
6340 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6341 }
6342 case CK_AddressSpaceConversion: {
6343 LValue LV = EmitLValue(E->getSubExpr());
6344 QualType DestTy = getContext().getPointerType(E->getType());
6345 llvm::Value *V =
6346 performAddrSpaceCast(LV.getPointer(*this), ConvertType(DestTy));
6348 LV.getAddress().getAlignment()),
6349 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
6350 }
6351 case CK_ObjCObjectLValueCast: {
6352 LValue LV = EmitLValue(E->getSubExpr());
6354 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
6355 CGM.getTBAAInfoForSubobject(LV, E->getType()));
6356 }
6357 case CK_ZeroToOCLOpaqueType:
6358 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
6359
6360 case CK_VectorSplat: {
6361 // LValue results of vector splats are only supported in HLSL.
6362 if (!getLangOpts().HLSL)
6363 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
6364 return EmitLValue(E->getSubExpr());
6365 }
6366 }
6367
6368 llvm_unreachable("Unhandled lvalue cast kind?");
6369}
6370
6375
6376std::pair<LValue, LValue>
6378 // Emitting the casted temporary through an opaque value.
6379 LValue BaseLV = EmitLValue(E->getArgLValue());
6381
6382 QualType ExprTy = E->getType();
6383 Address OutTemp = CreateIRTempWithoutCast(ExprTy);
6384 LValue TempLV = MakeAddrLValue(OutTemp, ExprTy);
6385
6386 // Start the lifetime before the copy-in so that the temporary is live when
6387 // the initial value is written. This ensures the store is within the
6388 // lifetime and is not killed by a store undef inserted at lifetime.start.
6390
6391 if (E->isInOut())
6393 TempLV);
6394
6396 return std::make_pair(BaseLV, TempLV);
6397}
6398
6400 CallArgList &Args, QualType Ty) {
6401
6402 auto [BaseLV, TempLV] = EmitHLSLOutArgLValues(E, Ty);
6403
6404 llvm::Value *Addr = TempLV.getAddress().getBasePointer();
6405 llvm::Type *ElTy = ConvertTypeForMem(TempLV.getType());
6406
6407 Address TmpAddr(Addr, ElTy, TempLV.getAlignment());
6408 Args.addWriteback(BaseLV, TmpAddr, nullptr, E->getWritebackCast());
6409 Args.add(RValue::get(TmpAddr, *this), Ty);
6410 return TempLV;
6411}
6412
6413LValue
6416
6417 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
6418 it = OpaqueLValues.find(e);
6419
6420 if (it != OpaqueLValues.end())
6421 return it->second;
6422
6423 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
6424 return EmitLValue(e->getSourceExpr());
6425}
6426
6427RValue
6430
6431 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
6432 it = OpaqueRValues.find(e);
6433
6434 if (it != OpaqueRValues.end())
6435 return it->second;
6436
6437 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
6438 return EmitAnyExpr(e->getSourceExpr());
6439}
6440
6443 return OpaqueLValues.contains(E);
6444 return OpaqueRValues.contains(E);
6445}
6446
6448 const FieldDecl *FD,
6449 SourceLocation Loc) {
6450 QualType FT = FD->getType();
6451 LValue FieldLV = EmitLValueForField(LV, FD);
6452 switch (getEvaluationKind(FT)) {
6453 case TEK_Complex:
6454 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
6455 case TEK_Aggregate:
6456 return FieldLV.asAggregateRValue();
6457 case TEK_Scalar:
6458 // This routine is used to load fields one-by-one to perform a copy, so
6459 // don't load reference fields.
6460 if (FD->getType()->isReferenceType())
6461 return RValue::get(FieldLV.getPointer(*this));
6462 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
6463 // primitive load.
6464 if (FieldLV.isBitField())
6465 return EmitLoadOfLValue(FieldLV, Loc);
6466 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
6467 }
6468 llvm_unreachable("bad evaluation kind");
6469}
6470
6471//===--------------------------------------------------------------------===//
6472// Expression Emission
6473//===--------------------------------------------------------------------===//
6474
6477 llvm::CallBase **CallOrInvoke) {
6478 llvm::CallBase *CallOrInvokeStorage;
6479 if (!CallOrInvoke) {
6480 CallOrInvoke = &CallOrInvokeStorage;
6481 }
6482
6483 llvm::scope_exit AddCoroElideSafeOnExit([&] {
6484 if (E->isCoroElideSafe()) {
6485 auto *I = *CallOrInvoke;
6486 if (I)
6487 I->addFnAttr(llvm::Attribute::CoroElideSafe);
6488 }
6489 });
6490
6491 // Builtins never have block type.
6492 if (E->getCallee()->getType()->isBlockPointerType())
6493 return EmitBlockCallExpr(E, ReturnValue, CallOrInvoke);
6494
6495 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
6496 return EmitCXXMemberCallExpr(CE, ReturnValue, CallOrInvoke);
6497
6498 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
6499 return EmitCUDAKernelCallExpr(CE, ReturnValue, CallOrInvoke);
6500
6501 // A CXXOperatorCallExpr is created even for explicit object methods, but
6502 // these should be treated like static function call.
6503 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
6504 if (const auto *MD =
6505 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
6506 MD && MD->isImplicitObjectMemberFunction())
6507 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue, CallOrInvoke);
6508
6509 CGCallee callee = EmitCallee(E->getCallee());
6510
6511 if (callee.isBuiltin()) {
6512 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
6513 E, ReturnValue);
6514 }
6515
6516 if (callee.isPseudoDestructor()) {
6518 }
6519
6520 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue,
6521 /*Chain=*/nullptr, CallOrInvoke);
6522}
6523
6524/// Emit a CallExpr without considering whether it might be a subclass.
6527 llvm::CallBase **CallOrInvoke) {
6528 CGCallee Callee = EmitCallee(E->getCallee());
6529 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
6530 /*Chain=*/nullptr, CallOrInvoke);
6531}
6532
6533// Detect the unusual situation where an inline version is shadowed by a
6534// non-inline version. In that case we should pick the external one
6535// everywhere. That's GCC behavior too.
6537 for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
6538 if (!PD->isInlineBuiltinDeclaration())
6539 return false;
6540 return true;
6541}
6542
6544 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
6545
6546 if (auto builtinID = FD->getBuiltinID()) {
6547 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
6548 std::string NoBuiltins = "no-builtins";
6549
6550 StringRef Ident = CGF.CGM.getMangledName(GD);
6551 std::string FDInlineName = (Ident + ".inline").str();
6552
6553 bool IsPredefinedLibFunction =
6555 bool HasAttributeNoBuiltin =
6556 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
6557 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
6558
6559 // When directing calling an inline builtin, call it through it's mangled
6560 // name to make it clear it's not the actual builtin.
6561 if (CGF.CurFn->getName() != FDInlineName &&
6563 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6564 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
6565 llvm::Module *M = Fn->getParent();
6566 llvm::Function *Clone = M->getFunction(FDInlineName);
6567 if (!Clone) {
6568 Clone = llvm::Function::Create(Fn->getFunctionType(),
6569 llvm::GlobalValue::InternalLinkage,
6570 Fn->getAddressSpace(), FDInlineName, M);
6571 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
6572 }
6573 return CGCallee::forDirect(Clone, GD);
6574 }
6575
6576 // Replaceable builtins provide their own implementation of a builtin. If we
6577 // are in an inline builtin implementation, avoid trivial infinite
6578 // recursion. Honor __attribute__((no_builtin("foo"))) or
6579 // __attribute__((no_builtin)) on the current function unless foo is
6580 // not a predefined library function which means we must generate the
6581 // builtin no matter what.
6582 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
6583 return CGCallee::forBuiltin(builtinID, FD);
6584 }
6585
6586 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
6587 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
6588 FD->hasAttr<CUDAGlobalAttr>())
6589 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
6590 cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
6591
6592 return CGCallee::forDirect(CalleePtr, GD);
6593}
6594
6596 if (DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
6598 return GlobalDecl(FD);
6599}
6600
6602 E = E->IgnoreParens();
6603
6604 // A WebAssembly funcref is an opaque reference type and llvm only accepts
6605 // function pointers as the call target. To make an indirect call through a
6606 // reference type, first use the llvm.wasm.funcref.to_ptr intrinsic to make a
6607 // fake function pointer to it. The backend lowers the resulting indirect call
6608 // to a table.set into a single element dummy table + call_indirect 0.
6609 auto ConvertFuncrefToPtr = [&](llvm::Value *CalleePtr) -> llvm::Value * {
6610 if (auto *TET = dyn_cast<llvm::TargetExtType>(CalleePtr->getType());
6611 TET && TET->getName() == "wasm.funcref") {
6612 llvm::Function *ToPtr =
6613 CGM.getIntrinsic(llvm::Intrinsic::wasm_funcref_to_ptr);
6614 return Builder.CreateCall(ToPtr, {CalleePtr});
6615 }
6616 return CalleePtr;
6617 };
6618
6619 // Look through function-to-pointer decay.
6620 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
6621 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
6622 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
6623 return EmitCallee(ICE->getSubExpr());
6624 }
6625
6626 // Try to remember the original __ptrauth qualifier for loads of
6627 // function pointers.
6628 if (ICE->getCastKind() == CK_LValueToRValue) {
6629 const Expr *SubExpr = ICE->getSubExpr();
6630 if (const auto *PtrType = SubExpr->getType()->getAs<PointerType>()) {
6631 std::pair<llvm::Value *, CGPointerAuthInfo> Result =
6633
6635 assert(FunctionType->isFunctionType());
6636
6637 GlobalDecl GD;
6638 if (const auto *VD =
6639 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee())) {
6640 GD = GlobalDecl(VD);
6641 }
6643 CGCallee Callee(CalleeInfo, ConvertFuncrefToPtr(Result.first),
6644 Result.second);
6645 return Callee;
6646 }
6647 }
6648
6649 // Resolve direct calls.
6650 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
6651 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6653 }
6654 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
6655 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
6656 EmitIgnoredExpr(ME->getBase());
6657 return EmitDirectCallee(*this, FD);
6658 }
6659
6660 // Look through template substitutions.
6661 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
6662 return EmitCallee(NTTP->getReplacement());
6663
6664 // Treat pseudo-destructor calls differently.
6665 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
6667 }
6668
6669 // Otherwise, we have an indirect reference.
6670 llvm::Value *calleePtr;
6672 if (auto ptrType = E->getType()->getAs<PointerType>()) {
6673 calleePtr = EmitScalarExpr(E);
6674 functionType = ptrType->getPointeeType();
6675 } else {
6676 functionType = E->getType();
6677 calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
6678 }
6679 assert(functionType->isFunctionType());
6680
6681 GlobalDecl GD;
6682 if (const auto *VD =
6683 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
6684 GD = GlobalDecl(VD);
6685
6686 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
6687 CGPointerAuthInfo pointerAuth = CGM.getFunctionPointerAuthInfo(functionType);
6688 CGCallee callee(calleeInfo, ConvertFuncrefToPtr(calleePtr), pointerAuth);
6689 return callee;
6690}
6691
6693 // Comma expressions just emit their LHS then their RHS as an l-value.
6694 if (E->getOpcode() == BO_Comma) {
6695 EmitIgnoredExpr(E->getLHS());
6697 return EmitLValue(E->getRHS());
6698 }
6699
6700 if (E->getOpcode() == BO_PtrMemD ||
6701 E->getOpcode() == BO_PtrMemI)
6703
6704 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
6705
6706 // Create a Key Instructions source location atom group that covers both
6707 // LHS and RHS expressions. Nested RHS expressions may get subsequently
6708 // separately grouped (1 below):
6709 //
6710 // 1. `a = b = c` -> Two atoms.
6711 // 2. `x = new(1)` -> One atom (for both addr store and value store).
6712 // 3. Complex and agg assignment -> One atom.
6714
6715 // Note that in all of these cases, __block variables need the RHS
6716 // evaluated first just in case the variable gets moved by the RHS.
6717
6718 switch (getEvaluationKind(E->getType())) {
6719 case TEK_Scalar: {
6720 if (PointerAuthQualifier PtrAuth =
6721 E->getLHS()->getType().getPointerAuth()) {
6723 LValue CopiedLV = LV;
6724 CopiedLV.getQuals().removePointerAuth();
6725 llvm::Value *RV =
6726 EmitPointerAuthQualify(PtrAuth, E->getRHS(), CopiedLV.getAddress());
6727 EmitNullabilityCheck(CopiedLV, RV, E->getExprLoc());
6728 EmitStoreThroughLValue(RValue::get(RV), CopiedLV);
6729 return LV;
6730 }
6731
6732 switch (E->getLHS()->getType().getObjCLifetime()) {
6734 return EmitARCStoreStrong(E, /*ignored*/ false).first;
6735
6737 return EmitARCStoreAutoreleasing(E).first;
6738
6739 // No reason to do any of these differently.
6743 break;
6744 }
6745
6746 // TODO: Can we de-duplicate this code with the corresponding code in
6747 // CGExprScalar, similar to the way EmitCompoundAssignmentLValue works?
6748 RValue RV;
6749 llvm::Value *Previous = nullptr;
6750 QualType SrcType = E->getRHS()->getType();
6751 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
6752 // we want to extract that value and potentially (if the bitfield sanitizer
6753 // is enabled) use it to check for an implicit conversion.
6754 if (E->getLHS()->refersToBitField()) {
6755 llvm::Value *RHS =
6757 RV = RValue::get(RHS);
6758 } else
6759 RV = EmitAnyExpr(E->getRHS());
6760
6762
6763 if (RV.isScalar())
6765
6766 if (LV.isBitField()) {
6767 llvm::Value *Result = nullptr;
6768 // If bitfield sanitizers are enabled we want to use the result
6769 // to check whether a truncation or sign change has occurred.
6770 if (SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
6772 else
6774
6775 // If the expression contained an implicit conversion, make sure
6776 // to use the value before the scalar conversion.
6777 llvm::Value *Src = Previous ? Previous : RV.getScalarVal();
6778 QualType DstType = E->getLHS()->getType();
6779 EmitBitfieldConversionCheck(Src, SrcType, Result, DstType,
6780 LV.getBitFieldInfo(), E->getExprLoc());
6781 } else
6782 EmitStoreThroughLValue(RV, LV);
6783
6784 if (getLangOpts().OpenMP)
6785 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
6786 E->getLHS());
6787 return LV;
6788 }
6789
6790 case TEK_Complex:
6792
6793 case TEK_Aggregate:
6794 // If the lang opt is HLSL and the LHS is a constant array
6795 // then we are performing a copy assignment and call a special
6796 // function because EmitAggExprToLValue emits to a temporary LValue
6798 return EmitHLSLArrayAssignLValue(E);
6799
6800 return EmitAggExprToLValue(E);
6801 }
6802 llvm_unreachable("bad evaluation kind");
6803}
6804
6805// This function implements trivial copy assignment for HLSL's
6806// assignable constant arrays.
6808 // Don't emit an LValue for the RHS because it might not be an LValue
6809 LValue LHS = EmitLValue(E->getLHS());
6810
6811 // If the RHS is a global resource array, copy all individual resources
6812 // into LHS.
6813 if (E->getRHS()->getType()->isHLSLResourceRecordArray()) {
6818 if (CGM.getHLSLRuntime().emitGlobalResourceArray(*this, E->getRHS(), Slot))
6819 return LHS;
6820 }
6821
6822 // In C the RHS of an assignment operator is an RValue.
6823 // EmitAggregateAssign takes an LValue for the RHS. Instead we can call
6824 // EmitInitializationToLValue to emit an RValue into an LValue.
6826 return LHS;
6827}
6828
6830 llvm::CallBase **CallOrInvoke) {
6831 RValue RV = EmitCallExpr(E, ReturnValueSlot(), CallOrInvoke);
6832
6833 if (!RV.isScalar())
6834 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6836
6837 assert(E->getCallReturnType(getContext())->isReferenceType() &&
6838 "Can't have a scalar return unless the return type is a "
6839 "reference type!");
6840
6842}
6843
6845 // FIXME: This shouldn't require another copy.
6846 return EmitAggExprToLValue(E);
6847}
6848
6851 && "binding l-value to type which needs a temporary");
6852 AggValueSlot Slot = CreateAggTemp(E->getType());
6853 EmitCXXConstructExpr(E, Slot);
6855}
6856
6857LValue
6861
6863 return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
6864 .withElementType(ConvertType(E->getType()));
6865}
6866
6871
6872LValue
6880
6883
6884 if (!RV.isScalar())
6885 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6887
6888 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
6889 "Can't have a scalar return unless the return type is a "
6890 "reference type!");
6891
6893}
6894
6896 Address V =
6897 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
6899}
6900
6902 const ObjCIvarDecl *Ivar) {
6903 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
6904}
6905
6906llvm::Value *
6908 const ObjCIvarDecl *Ivar) {
6909 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
6910 QualType PointerDiffType = getContext().getPointerDiffType();
6911 return Builder.CreateZExtOrTrunc(OffsetValue,
6912 getTypes().ConvertType(PointerDiffType));
6913}
6914
6916 llvm::Value *BaseValue,
6917 const ObjCIvarDecl *Ivar,
6918 unsigned CVRQualifiers) {
6919 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
6920 Ivar, CVRQualifiers);
6921}
6922
6924 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
6925 llvm::Value *BaseValue = nullptr;
6926 const Expr *BaseExpr = E->getBase();
6927 Qualifiers BaseQuals;
6928 QualType ObjectTy;
6929 if (E->isArrow()) {
6930 BaseValue = EmitScalarExpr(BaseExpr);
6931 ObjectTy = BaseExpr->getType()->getPointeeType();
6932 BaseQuals = ObjectTy.getQualifiers();
6933 } else {
6934 LValue BaseLV = EmitLValue(BaseExpr);
6935 BaseValue = BaseLV.getPointer(*this);
6936 ObjectTy = BaseExpr->getType();
6937 BaseQuals = ObjectTy.getQualifiers();
6938 }
6939
6940 LValue LV =
6941 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
6942 BaseQuals.getCVRQualifiers());
6944 return LV;
6945}
6946
6948 // Can only get l-value for message expression returning aggregate type
6949 RValue RV = EmitAnyExprToTemp(E);
6950 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
6952}
6953
6955 const CGCallee &OrigCallee, const CallExpr *E,
6957 llvm::Value *Chain,
6958 llvm::CallBase **CallOrInvoke,
6959 CGFunctionInfo const **ResolvedFnInfo) {
6960 // Get the actual function type. The callee type will always be a pointer to
6961 // function type or a block pointer type.
6962 assert(CalleeType->isFunctionPointerType() &&
6963 "Call must have function pointer type!");
6964
6965 const Decl *TargetDecl =
6966 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
6967
6968 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
6969 !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
6970 "trying to emit a call to an immediate function");
6971
6972 CalleeType = getContext().getCanonicalType(CalleeType);
6973
6974 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
6975
6976 CGCallee Callee = OrigCallee;
6977
6978 bool CFIUnchecked = CalleeType->hasPointeeToCFIUncheckedCalleeFunctionType();
6979
6980 if (SanOpts.has(SanitizerKind::Function) &&
6981 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
6982 !isa<FunctionNoProtoType>(PointeeType) && !CFIUnchecked) {
6983 if (llvm::Constant *PrefixSig =
6984 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
6985 auto CheckOrdinal = SanitizerKind::SO_Function;
6986 auto CheckHandler = SanitizerHandler::FunctionTypeMismatch;
6987 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6988 auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
6989
6990 llvm::Type *PrefixSigType = PrefixSig->getType();
6991 llvm::StructType *PrefixStructTy = llvm::StructType::get(
6992 CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
6993
6994 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6995 if (CGM.getCodeGenOpts().PointerAuth.FunctionPointers) {
6996 // Use raw pointer since we are using the callee pointer as data here.
6997 Address Addr =
6998 Address(CalleePtr, CalleePtr->getType(),
7000 CalleePtr->getPointerAlignment(CGM.getDataLayout())),
7001 Callee.getPointerAuthInfo(), nullptr);
7002 CalleePtr = Addr.emitRawPointer(*this);
7003 }
7004
7005 // On 32-bit Arm, the low bit of a function pointer indicates whether
7006 // it's using the Arm or Thumb instruction set. The actual first
7007 // instruction lives at the same address either way, so we must clear
7008 // that low bit before using the function address to find the prefix
7009 // structure.
7010 //
7011 // This applies to both Arm and Thumb target triples, because
7012 // either one could be used in an interworking context where it
7013 // might be passed function pointers of both types.
7014 llvm::Value *AlignedCalleePtr;
7015 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
7016 AlignedCalleePtr = Builder.CreateIntrinsic(
7017 CalleePtr->getType(), llvm::Intrinsic::ptrmask,
7018 {CalleePtr, llvm::ConstantInt::getSigned(IntPtrTy, ~1)});
7019 } else {
7020 AlignedCalleePtr = CalleePtr;
7021 }
7022
7023 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
7024 llvm::Value *CalleeSigPtr =
7025 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
7026 llvm::Value *CalleeSig =
7027 Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
7028 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
7029
7030 llvm::BasicBlock *Cont = createBasicBlock("cont");
7031 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
7032 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
7033
7034 EmitBlock(TypeCheck);
7035 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
7036 Int32Ty,
7037 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
7038 getPointerAlign());
7039 llvm::Value *CalleeTypeHashMatch =
7040 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
7041 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
7042 EmitCheckTypeDescriptor(CalleeType)};
7043 EmitCheck(std::make_pair(CalleeTypeHashMatch, CheckOrdinal), CheckHandler,
7044 StaticData, {CalleePtr});
7045
7046 Builder.CreateBr(Cont);
7047 EmitBlock(Cont);
7048 }
7049 }
7050
7051 const auto *FnType = cast<FunctionType>(PointeeType);
7052
7053 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
7054 FD && DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
7055 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FnType);
7056
7057 // If we are checking indirect calls and this call is indirect, check that the
7058 // function pointer is a member of the bit set for the function type.
7059 if (SanOpts.has(SanitizerKind::CFIICall) &&
7060 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) && !CFIUnchecked) {
7061 auto CheckOrdinal = SanitizerKind::SO_CFIICall;
7062 auto CheckHandler = SanitizerHandler::CFICheckFail;
7063 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
7064 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
7065
7066 llvm::Metadata *MD =
7067 CGM.CreateMetadataIdentifierForFnType(QualType(FnType, 0));
7068
7069 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
7070
7071 llvm::Value *CalleePtr = Callee.getFunctionPointer();
7072 llvm::Value *TypeTest = Builder.CreateCall(
7073 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
7074
7075 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
7076 llvm::Constant *StaticData[] = {
7077 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
7080 };
7081 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
7082 EmitCfiSlowPathCheck(CheckOrdinal, TypeTest, CrossDsoTypeId, CalleePtr,
7083 StaticData);
7084 } else {
7085 EmitCheck(std::make_pair(TypeTest, CheckOrdinal), CheckHandler,
7086 StaticData, {CalleePtr, llvm::UndefValue::get(IntPtrTy)});
7087 }
7088 }
7089
7090 CallArgList Args;
7091 if (Chain)
7092 Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy);
7093
7094 // C++17 requires that we evaluate arguments to a call using assignment syntax
7095 // right-to-left, and that we evaluate arguments to certain other operators
7096 // left-to-right. Note that we allow this to override the order dictated by
7097 // the calling convention on the MS ABI, which means that parameter
7098 // destruction order is not necessarily reverse construction order.
7099 // FIXME: Revisit this based on C++ committee response to unimplementability.
7101 bool StaticOperator = false;
7102 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7103 if (OCE->isAssignmentOp())
7105 else {
7106 switch (OCE->getOperator()) {
7107 case OO_LessLess:
7108 case OO_GreaterGreater:
7109 case OO_AmpAmp:
7110 case OO_PipePipe:
7111 case OO_Comma:
7112 case OO_ArrowStar:
7114 break;
7115 default:
7116 break;
7117 }
7118 }
7119
7120 if (const auto *MD =
7121 dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
7122 MD && MD->isStatic())
7123 StaticOperator = true;
7124 }
7125
7126 auto Arguments = E->arguments();
7127 if (StaticOperator) {
7128 // If we're calling a static operator, we need to emit the object argument
7129 // and ignore it.
7130 EmitIgnoredExpr(E->getArg(0));
7131 Arguments = drop_begin(Arguments, 1);
7132 }
7133 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
7134 E->getDirectCallee(), /*ParamsToSkip=*/0, Order);
7135
7136 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
7137 Args, FnType, /*ChainCall=*/Chain);
7138
7139 if (ResolvedFnInfo)
7140 *ResolvedFnInfo = &FnInfo;
7141
7142 // HIP function pointer contains kernel handle when it is used in triple
7143 // chevron. The kernel stub needs to be loaded from kernel handle and used
7144 // as callee.
7145 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
7147 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
7148 llvm::Value *Handle = Callee.getFunctionPointer();
7149 auto *Stub = Builder.CreateLoad(
7150 Address(Handle, Handle->getType(), CGM.getPointerAlign()));
7151 Callee.setFunctionPointer(Stub);
7152 }
7153
7154 // Insert function pointer lookup if this is a target call
7155 //
7156 // This is used for the indirect function case, virtual function case is
7157 // handled in ItaniumCXXABI.cpp
7158 if (getLangOpts().OpenMPIsTargetDevice && CGM.getTriple().isGPU() &&
7159 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
7160 const Expr *CalleeExpr = E->getCallee()->IgnoreParenImpCasts();
7161 const DeclRefExpr *DRE = nullptr;
7162 while (CalleeExpr) {
7163 if ((DRE = dyn_cast<DeclRefExpr>(CalleeExpr)))
7164 break;
7165 if (const auto *ME = dyn_cast<MemberExpr>(CalleeExpr))
7166 CalleeExpr = ME->getBase()->IgnoreParenImpCasts();
7167 else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(CalleeExpr))
7168 CalleeExpr = ASE->getBase()->IgnoreParenImpCasts();
7169 else
7170 break;
7171 }
7172
7173 const auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7174 if (VD && VD->hasAttr<OMPTargetIndirectCallAttr>()) {
7175 auto *FuncPtrTy = llvm::PointerType::get(
7176 CGM.getLLVMContext(), CGM.getDataLayout().getProgramAddressSpace());
7177 llvm::Type *RtlFnArgs[] = {FuncPtrTy};
7178 llvm::FunctionCallee DeviceRtlFn = CGM.CreateRuntimeFunction(
7179 llvm::FunctionType::get(FuncPtrTy, RtlFnArgs, false),
7180 "__llvm_omp_indirect_call_lookup");
7181 llvm::Value *Func = Callee.getFunctionPointer();
7182 llvm::Type *BackupTy = Func->getType();
7183 Func = Builder.CreatePointerBitCastOrAddrSpaceCast(Func, FuncPtrTy);
7184 Func = EmitRuntimeCall(DeviceRtlFn, {Func});
7185 Func = Builder.CreatePointerBitCastOrAddrSpaceCast(Func, BackupTy);
7186 Callee.setFunctionPointer(Func);
7187 }
7188 }
7189
7190 llvm::CallBase *LocalCallOrInvoke = nullptr;
7191 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &LocalCallOrInvoke,
7192 E == MustTailCall, E->getExprLoc());
7193
7194 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
7195 if (CalleeDecl->hasAttr<RestrictAttr>() ||
7196 CalleeDecl->hasAttr<MallocSpanAttr>() ||
7197 CalleeDecl->hasAttr<AllocSizeAttr>()) {
7198 // Function has 'malloc' (aka. 'restrict') or 'alloc_size' attribute.
7199 if (SanOpts.has(SanitizerKind::AllocToken)) {
7200 // Set !alloc_token metadata.
7201 EmitAllocToken(LocalCallOrInvoke, E);
7202 }
7203 }
7204 }
7205 if (CallOrInvoke)
7206 *CallOrInvoke = LocalCallOrInvoke;
7207
7208 return Call;
7209}
7210
7213 Address BaseAddr = Address::invalid();
7214 if (E->getOpcode() == BO_PtrMemI) {
7215 BaseAddr = EmitPointerWithAlignment(E->getLHS());
7216 } else {
7217 BaseAddr = EmitLValue(E->getLHS()).getAddress();
7218 }
7219
7220 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
7221 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
7222
7223 LValueBaseInfo BaseInfo;
7224 TBAAAccessInfo TBAAInfo;
7225 bool IsInBounds = !getLangOpts().PointerOverflowDefined &&
7228 E, BaseAddr, OffsetV, MPT, IsInBounds, &BaseInfo, &TBAAInfo);
7229
7230 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
7231}
7232
7233/// Given the address of a temporary variable, produce an r-value of
7234/// its type.
7236 QualType type,
7237 SourceLocation loc) {
7239 switch (getEvaluationKind(type)) {
7240 case TEK_Complex:
7241 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
7242 case TEK_Aggregate:
7243 return lvalue.asAggregateRValue();
7244 case TEK_Scalar:
7245 return RValue::get(EmitLoadOfScalar(lvalue, loc));
7246 }
7247 llvm_unreachable("bad evaluation kind");
7248}
7249
7250void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
7251 assert(Val->getType()->isFPOrFPVectorTy());
7252 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
7253 return;
7254
7255 llvm::MDBuilder MDHelper(getLLVMContext());
7256 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
7257
7258 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
7259}
7260
7262 llvm::Type *EltTy = Val->getType()->getScalarType();
7263 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7264 return;
7265
7266 if ((getLangOpts().OpenCL &&
7267 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7268 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7269 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7270 // OpenCL v1.1 s7.4: minimum accuracy of single precision sqrt is 3 ulp.
7271 // OpenCL v3.0 s7.4: minimum accuracy of half precision sqrt is 1.5 ulp.
7272 //
7273 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7274 // build option allows an application to specify that single precision
7275 // floating-point divide (x/y and 1/x) and sqrt used in the program
7276 // source are correctly rounded.
7277 //
7278 // TODO: CUDA has a prec-sqrt flag
7279 SetFPAccuracy(Val, EltTy->isFloatTy() ? 3.0f : 1.5f);
7280 }
7281}
7282
7284 llvm::Type *EltTy = Val->getType()->getScalarType();
7285 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7286 return;
7287
7288 if ((getLangOpts().OpenCL &&
7289 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7290 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
7291 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7292 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5 ulp.
7293 // OpenCL v3.0 s7.4: minimum accuracy of half precision / is 1 ulp.
7294 //
7295 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
7296 // build option allows an application to specify that single precision
7297 // floating-point divide (x/y and 1/x) and sqrt used in the program
7298 // source are correctly rounded.
7299 //
7300 // TODO: CUDA has a prec-div flag
7301 SetFPAccuracy(Val, EltTy->isFloatTy() ? 2.5f : 1.f);
7302 }
7303}
7304
7305namespace {
7306 struct LValueOrRValue {
7307 LValue LV;
7308 RValue RV;
7309 };
7310}
7311
7312static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
7313 const PseudoObjectExpr *E,
7314 bool forLValue,
7315 AggValueSlot slot) {
7317
7318 // Find the result expression, if any.
7319 const Expr *resultExpr = E->getResultExpr();
7320 LValueOrRValue result;
7321
7323 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
7324 const Expr *semantic = *i;
7325
7326 // If this semantic expression is an opaque value, bind it
7327 // to the result of its source expression.
7328 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
7329 // Skip unique OVEs.
7330 if (ov->isUnique()) {
7331 assert(ov != resultExpr &&
7332 "A unique OVE cannot be used as the result expression");
7333 continue;
7334 }
7335
7336 // If this is the result expression, we may need to evaluate
7337 // directly into the slot.
7339 OVMA opaqueData;
7340 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
7342 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
7343 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
7345 opaqueData = OVMA::bind(CGF, ov, LV);
7346 result.RV = slot.asRValue();
7347
7348 // Otherwise, emit as normal.
7349 } else {
7350 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
7351
7352 // If this is the result, also evaluate the result now.
7353 if (ov == resultExpr) {
7354 if (forLValue)
7355 result.LV = CGF.EmitLValue(ov);
7356 else
7357 result.RV = CGF.EmitAnyExpr(ov, slot);
7358 }
7359 }
7360
7361 opaques.push_back(opaqueData);
7362
7363 // Otherwise, if the expression is the result, evaluate it
7364 // and remember the result.
7365 } else if (semantic == resultExpr) {
7366 if (forLValue)
7367 result.LV = CGF.EmitLValue(semantic);
7368 else
7369 result.RV = CGF.EmitAnyExpr(semantic, slot);
7370
7371 // Otherwise, evaluate the expression in an ignored context.
7372 } else {
7373 CGF.EmitIgnoredExpr(semantic);
7374 }
7375 }
7376
7377 // Unbind all the opaques now.
7378 for (CodeGenFunction::OpaqueValueMappingData &opaque : opaques)
7379 opaque.unbind(CGF);
7380
7381 return result;
7382}
7383
7385 AggValueSlot slot) {
7386 return emitPseudoObjectExpr(*this, E, false, slot).RV;
7387}
7388
7392
7394 LValue Val, SmallVectorImpl<LValue> &AccessList) {
7395
7397 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7398 WorkList;
7399 llvm::IntegerType *IdxTy = llvm::IntegerType::get(getLLVMContext(), 32);
7400 WorkList.push_back({Val, Val.getType(), {llvm::ConstantInt::get(IdxTy, 0)}});
7401
7402 while (!WorkList.empty()) {
7403 auto [LVal, T, IdxList] = WorkList.pop_back_val();
7404 T = T.getCanonicalType().getUnqualifiedType();
7405 if (const auto *CAT = dyn_cast<ConstantArrayType>(T)) {
7406 uint64_t Size = CAT->getZExtSize();
7407 for (int64_t I = Size - 1; I > -1; I--) {
7408 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7409 IdxListCopy.push_back(llvm::ConstantInt::get(IdxTy, I));
7410 WorkList.emplace_back(LVal, CAT->getElementType(), IdxListCopy);
7411 }
7412 } else if (const auto *RT = dyn_cast<RecordType>(T)) {
7413 const RecordDecl *Record = RT->getDecl()->getDefinitionOrSelf();
7414 assert(!Record->isUnion() && "Union types not supported in flat cast.");
7415
7416 const CXXRecordDecl *CXXD = dyn_cast<CXXRecordDecl>(Record);
7417
7419 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7420 ReverseList;
7421 if (CXXD && CXXD->isStandardLayout())
7423
7424 // deal with potential base classes
7425 if (CXXD && !CXXD->isStandardLayout()) {
7426 if (CXXD->getNumBases() > 0) {
7427 assert(CXXD->getNumBases() == 1 &&
7428 "HLSL doesn't support multiple inheritance.");
7429 auto Base = CXXD->bases_begin();
7430 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7431 IdxListCopy.push_back(llvm::ConstantInt::get(
7432 IdxTy, 0)); // base struct should be at index zero
7433 ReverseList.emplace_back(LVal, Base->getType(), IdxListCopy);
7434 }
7435 }
7436
7437 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(Record);
7438
7439 llvm::Type *LLVMT = ConvertTypeForMem(T);
7441 LValue RLValue;
7442 bool createdGEP = false;
7443 for (auto *FD : Record->fields()) {
7444 if (FD->isBitField()) {
7445 if (FD->isUnnamedBitField())
7446 continue;
7447 if (!createdGEP) {
7448 createdGEP = true;
7449 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7450 LLVMT, Align, "gep");
7451 RLValue = MakeAddrLValue(GEP, T);
7452 }
7453 LValue FieldLVal = EmitLValueForField(RLValue, FD, true);
7454 ReverseList.push_back({FieldLVal, FD->getType(), {}});
7455 } else {
7456 llvm::SmallVector<llvm::Value *, 4> IdxListCopy = IdxList;
7457 IdxListCopy.push_back(
7458 llvm::ConstantInt::get(IdxTy, Layout.getLLVMFieldNo(FD)));
7459 ReverseList.emplace_back(LVal, FD->getType(), IdxListCopy);
7460 }
7461 }
7462
7463 std::reverse(ReverseList.begin(), ReverseList.end());
7464 llvm::append_range(WorkList, ReverseList);
7465 } else if (const auto *VT = dyn_cast<VectorType>(T)) {
7466 llvm::Type *LLVMT = ConvertTypeForMem(T);
7468 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7469 Align, "vector.gep");
7470 LValue Base = MakeAddrLValue(GEP, T);
7471 for (unsigned I = 0, E = VT->getNumElements(); I < E; I++) {
7472 llvm::Constant *Idx = llvm::ConstantInt::get(IdxTy, I);
7473 LValue LV =
7474 LValue::MakeVectorElt(Base.getAddress(), Idx, VT->getElementType(),
7475 Base.getBaseInfo(), TBAAAccessInfo());
7476 AccessList.emplace_back(LV);
7477 }
7478 } else if (const auto *MT = dyn_cast<ConstantMatrixType>(T)) {
7479 // Matrices are represented as flat arrays in memory, but has a vector
7480 // value type. So we use ConvertMatrixAddress to convert the address from
7481 // array to vector, and extract elements similar to the vector case above.
7482 // The matrix elements are iterated over in row-major order regardless of
7483 // the memory layout of the matrix.
7484 llvm::Type *LLVMT = ConvertTypeForMem(T);
7486 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7487 Align, "matrix.gep");
7488 LValue Base = MakeAddrLValue(GEP, T);
7489 Address MatAddr = MaybeConvertMatrixAddress(Base.getAddress(), *this);
7490 unsigned NumRows = MT->getNumRows();
7491 unsigned NumCols = MT->getNumColumns();
7492 bool IsMatrixRowMajor = isMatrixRowMajor(getLangOpts(), T);
7493 llvm::MatrixBuilder MB(Builder);
7494 for (unsigned Row = 0; Row < MT->getNumRows(); Row++) {
7495 for (unsigned Col = 0; Col < MT->getNumColumns(); Col++) {
7496 llvm::Value *RowIdx = llvm::ConstantInt::get(IdxTy, Row);
7497 llvm::Value *ColIdx = llvm::ConstantInt::get(IdxTy, Col);
7498 llvm::Value *Idx = MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols,
7499 IsMatrixRowMajor);
7500 LValue LV =
7501 LValue::MakeMatrixElt(MatAddr, Idx, MT->getElementType(),
7502 Base.getBaseInfo(), TBAAAccessInfo());
7503 AccessList.emplace_back(LV);
7504 }
7505 }
7506 } else { // a scalar/builtin type
7507 if (!IdxList.empty()) {
7508 llvm::Type *LLVMT = ConvertTypeForMem(T);
7510 Address GEP = Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7511 LLVMT, Align, "gep");
7512 AccessList.emplace_back(MakeAddrLValue(GEP, T));
7513 } else // must be a bitfield we already created an lvalue for
7514 AccessList.emplace_back(LVal);
7515 }
7516 }
7517}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
Definition CGExpr.cpp:3268
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM)
Named Registers are named metadata pointing to the register name which will be read from/written to a...
Definition CGExpr.cpp:3548
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool StrictBool, bool IsBool)
Definition CGExpr.cpp:2091
static llvm::Value * emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc, llvm::Value *Ptr)
Definition CGExpr.cpp:728
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer,...
Definition CGExpr.cpp:4689
static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, int64_t &Offset)
The offset of a field from the beginning of the record.
Definition CGExpr.cpp:4890
static bool hasBPFPreserveStaticOffset(const RecordDecl *D)
Definition CGExpr.cpp:4754
ConstantEmissionKind
Can we constant-emit a load of a reference to a variable of the given type?
Definition CGExpr.cpp:1939
@ CEK_AsReferenceOnly
Definition CGExpr.cpp:1941
@ CEK_AsValueOnly
Definition CGExpr.cpp:1943
@ CEK_None
Definition CGExpr.cpp:1940
@ CEK_AsValueOrReference
Definition CGExpr.cpp:1942
static Address emitRawAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, and without respect for po...
Definition CGExpr.cpp:5717
static bool isConstantEmittableObjectType(QualType type)
Given an object of the given canonical type, can we safely copy a value out of it based on its initia...
Definition CGExpr.cpp:1912
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
Definition CGExpr.cpp:3536
static std::optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
Definition CGExpr.cpp:6028
static CheckRecoverableKind getRecoverableKind(SanitizerKind::SanitizerOrdinal Ordinal)
Definition CGExpr.cpp:4128
static bool RecordContainsField(const RecordDecl *RD, const FieldDecl *Field)
Returns true if Field is reachable from RD either as a direct field or through a chain of nested reco...
Definition CGExpr.cpp:1065
static llvm::Value * emitArraySubscriptGEP(CodeGenFunction &CGF, llvm::Type *elemType, llvm::Value *ptr, ArrayRef< llvm::Value * > indices, bool inbounds, bool signedIndices, SourceLocation loc, const llvm::Twine &name="arrayidx")
Definition CGExpr.cpp:4703
SmallVector< llvm::Value *, 8 > RecIndicesTy
Definition CGExpr.cpp:1191
static GlobalDecl getGlobalDeclForDirectCall(const FunctionDecl *FD)
Definition CGExpr.cpp:6595
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, GlobalDecl GD)
Definition CGExpr.cpp:3523
static RawAddress MaybeConvertMatrixAddress(RawAddress Addr, CodeGenFunction &CGF, bool IsVector=true)
Definition CGExpr.cpp:2332
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
Definition CGExpr.cpp:7312
static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, Address &Addr)
Definition CGExpr.cpp:4770
static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID)
Definition CGExpr.cpp:95
static llvm::Value * getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel)
If Base is known to point to the start of an array, return the length of that array.
Definition CGExpr.cpp:1020
static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, CodeGenFunction &CGF)
Definition CGExpr.cpp:2508
static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type)
Definition CGExpr.cpp:1945
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, wrapping the address in an...
Definition CGExpr.cpp:5747
static std::optional< int64_t > getOffsetDifferenceInBits(CodeGenFunction &CGF, const FieldDecl *FD1, const FieldDecl *FD2)
Returns the relative offset difference between FD1 and FD2.
Definition CGExpr.cpp:4921
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD)
Definition CGExpr.cpp:6543
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
Definition CGExpr.cpp:3365
static bool getGEPIndicesToField(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, RecIndicesTy &Indices)
Definition CGExpr.cpp:1193
static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD)
Definition CGExpr.cpp:6536
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
Definition CGExpr.cpp:3463
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
Definition CGExpr.cpp:5770
static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase)
Given an array base, check whether its member access belongs to a record with preserve_access_index a...
Definition CGExpr.cpp:4783
static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T)
Definition CGExpr.cpp:3379
VariableTypeDescriptorKind
Definition CGExpr.cpp:80
@ TK_Float
A floating-point type.
Definition CGExpr.cpp:84
@ TK_Unknown
Any other type. The value representation is unspecified.
Definition CGExpr.cpp:88
@ TK_Integer
An integer type.
Definition CGExpr.cpp:82
@ TK_BitInt
An _BitInt(N) type.
Definition CGExpr.cpp:86
static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, bool isInit, CodeGenFunction &CGF)
Definition CGExpr.cpp:2429
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
Definition CGExpr.cpp:1482
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, Address addr, const FieldDecl *field)
Definition CGExpr.cpp:5757
const SanitizerHandlerInfo SanitizerHandlers[]
Definition CGExpr.cpp:4145
static void emitCheckHandlerCall(CodeGenFunction &CGF, llvm::FunctionType *FnType, ArrayRef< llvm::Value * > FnArgs, SanitizerHandler CheckHandler, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB, bool NoMerge)
Definition CGExpr.cpp:4151
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
Definition CGExpr.cpp:5259
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static Address createReferenceTemporary(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *inner)
static bool isAAPCS(const TargetInfo &targetInfo)
Helper method to check if the underlying ABI is AAPCS.
static CharUnits getArrayElementAlign(CharUnits arrayAlign, mlir::Value idx, CharUnits eltSize)
static void pushTemporaryCleanup(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *e, Address referenceTemporary)
static QualType getFixedSizeElementType(const ASTContext &astContext, const VariableArrayType *vla)
static bool canEmitSpuriousReferenceToVariable(CIRGenFunction &cgf, const DeclRefExpr *e, const VarDecl *vd)
Determine whether we can emit a reference to vd from the current context, despite not necessarily hav...
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CIRGenFunction &cgf, const MemberExpr *me)
static Address emitAddrOfZeroSizeField(CIRGenFunction &cgf, Address base, const FieldDecl *field)
Get the address of a zero-sized field within a record.
FormatToken * Previous
The previous token in the unwrapped line.
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Record Record
Definition MachO.h:31
Defines AST-level helper utilities for matrix types.
Defines the clang::Module class, which describes a module in the source code.
llvm::json::Object Object
static const SanitizerMask AlwaysRecoverable
static const SanitizerMask Unrecoverable
#define LIST_SANITIZER_CHECKS
SanitizerHandler
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
a trap message and trap category.
const LValueBase getLValueBase() const
Definition APValue.cpp:1001
bool isLValue() const
Definition APValue.h:490
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
SourceManager & getSourceManager()
Definition ASTContext.h:869
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
bool isPFPField(const FieldDecl *Field) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Builtin::Context & BuiltinInfo
Definition ASTContext.h:810
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType BoolTy
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition Expr.h:7231
Expr * getBase()
Get base of the array section.
Definition Expr.h:7309
Expr * getLength()
Get length of array section.
Definition Expr.h:7319
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition Expr.cpp:5403
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:7348
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7313
bool isOpenACCArraySection() const
Definition Expr.h:7306
SourceLocation getColonLocFirst() const
Definition Expr.h:7340
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2782
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
SourceLocation getExprLoc() const
Definition Expr.h:4085
Expr * getRHS() const
Definition Expr.h:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
Opcode getOpcode() const
Definition Expr.h:4089
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8299
unsigned getNumBits() const
Definition TypeBase.h:8311
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition Builtins.h:321
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
CXXTemporary * getTemporary()
Definition ExprCXX.h:1515
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1377
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1230
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
base_class_iterator bases_begin()
Definition DeclCXX.h:615
bool isDynamicClass() const
Definition DeclCXX.h:574
bool hasDefinition() const
Definition DeclCXX.h:561
const CXXRecordDecl * getStandardLayoutBaseWithFields() const
If this is a standard-layout class or union, any and all data members will be declared in the same ty...
Definition DeclCXX.cpp:563
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:852
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1072
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
SourceLocation getBeginLoc() const
Definition Expr.h:3283
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
Expr * getCallee()
Definition Expr.h:3096
bool isCoroElideSafe() const
Definition Expr.h:3123
arg_range arguments()
Definition Expr.h:3201
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
bool changesVolatileQualification() const
Return.
Definition Expr.h:3816
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:207
llvm::MaybeAlign getAsMaybeAlign() const
getAsMaybeAlign - Returns Quantity as a valid llvm::Align or std::nullopt, Beware llvm::MaybeAlign as...
Definition CharUnits.h:194
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:214
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
@ None
Trap Messages are omitted.
@ Detailed
Trap Message includes more context (e.g.
@ Strict
In-memory bool values are assumed to be 0 or 1, and any other value is UB.
bool isOptimizedBuild() const
Are we building at -O1 or higher?
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Definition Address.h:261
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
Address withAlignment(CharUnits NewAlignment) const
Return address with different alignment, but same pointer and element type.
Definition Address.h:269
bool isValid() const
Definition Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
An aggregate value slot.
Definition CGValue.h:551
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
Address getAddress() const
Definition CGValue.h:691
void setExternallyDestructed(bool destructed=true)
Definition CGValue.h:660
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:649
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
Definition CGValue.h:634
RValue asRValue() const
Definition CGValue.h:713
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Definition CGBuilder.h:315
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:302
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition CGBuilder.h:341
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Definition CGBuilder.h:251
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:229
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
Address CreateConstByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Definition CGBuilder.h:325
Address CreatePreserveStructAccessIndex(Address Addr, unsigned Index, unsigned FieldIndex, llvm::MDNode *DbgInfo)
Definition CGBuilder.h:445
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:199
virtual llvm::Function * getKernelStub(llvm::GlobalValue *Handle)=0
Get kernel stub by kernel handle.
virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
virtual bool usesThreadWrapperFunction(const VarDecl *VD) const =0
Abstract information about a function or function prototype.
Definition CGCall.h:43
const GlobalDecl getCalleeDecl() const
Definition CGCall.h:61
All available information about a concrete callee.
Definition CGCall.h:65
CGCalleeInfo getAbstractInfo() const
Definition CGCall.h:182
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
Definition CGCall.h:174
bool isPseudoDestructor() const
Definition CGCall.h:171
static CGCallee forBuiltin(unsigned builtinID, const FunctionDecl *builtinDecl)
Definition CGCall.h:125
unsigned getBuiltinID() const
Definition CGCall.h:166
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:139
bool isBuiltin() const
Definition CGCall.h:159
const FunctionDecl * getBuiltinDecl() const
Definition CGCall.h:162
static CGCallee forPseudoDestructor(const CXXPseudoDestructorExpr *E)
Definition CGCall.h:133
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
CGFunctionInfo - Class to encapsulate the information about a function definition.
std::optional< LValue > emitGlobalResourceArrayAsLValue(CodeGenFunction &CGF, const VarDecl *ArrayDecl)
RawAddress createBufferMatrixTempAddress(const LValue &LV, CodeGenFunction &CGF)
virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
bool containsFieldDecl(const FieldDecl *FD) const
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:276
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr)
Definition CGCall.h:322
void add(RValue rvalue, QualType type)
Definition CGCall.h:304
An object to manage conditionally-evaluated expressions.
llvm::BasicBlock * getStartingBlock() const
Returns a block which will be executed prior to each evaluation of the conditional code.
static ConstantEmission forValue(llvm::Constant *C)
static ConstantEmission forReference(llvm::Constant *C)
A non-RAII class containing all the information about a bound opaque value.
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E)
Definition CGExpr.cpp:5236
LValue EmitCoawaitLValue(const CoawaitExpr *E)
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition CGClass.cpp:2940
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
Definition CGObjC.cpp:2184
void EmitBoundsCheckImpl(const Expr *ArrayExpr, QualType ArrayBaseType, llvm::Value *IndexVal, QualType IndexType, llvm::Value *BoundsVal, QualType BoundsType, bool Accessed)
Definition CGExpr.cpp:1301
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
Definition CGExpr.cpp:3436
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
Definition CGObjC.cpp:591
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
LValue EmitCXXConstructLValue(const CXXConstructExpr *E)
Definition CGExpr.cpp:6849
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
Definition CGExpr.cpp:6133
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
Definition CGObjC.cpp:3711
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
Definition CGExpr.cpp:1382
void SetDivFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:7283
SanitizerSet SanOpts
Sanitizers enabled for this function.
LValue EmitInitListLValue(const InitListExpr *E)
Definition CGExpr.cpp:6015
bool isUnderlyingBasePointerConstantNull(const Expr *E)
Check whether the underlying base pointer is a constant null.
Definition CGExpr.cpp:5560
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
Definition CGObjC.cpp:2695
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, bool Accessed=false)
Definition CGExpr.cpp:5001
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E)
Definition CGExpr.cpp:6881
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Definition CGExpr.cpp:1224
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
const CastExpr * CurCast
If a cast expression is being visited, this holds the current cast's expression.
llvm::Type * ConvertType(QualType T)
Address EmitCXXUuidofExpr(const CXXUuidofExpr *E)
Definition CGExpr.cpp:6862
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
CGCapturedStmtInfo * CapturedStmtInfo
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
Definition CGObjC.cpp:2360
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
Definition CGClass.cpp:282
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst)
Definition CGExpr.cpp:3133
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
Definition CGExpr.cpp:3911
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
Definition CGExpr.cpp:5988
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition CGExpr.cpp:7235
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
Definition CGExpr.cpp:3054
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4063
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
Definition CGExpr.cpp:6867
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:7261
RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
Emit a CallExpr without considering whether it might be a subclass.
Definition CGExpr.cpp:6525
static bool isNullPointerAllowed(TypeCheckKind TCK)
Determine whether the pointer type check TCK permits null pointers.
Definition CGExpr.cpp:737
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:7384
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex)
Get the record field index as represented in debug info.
Definition CGExpr.cpp:5683
const LangOptions & getLangOpts() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
Definition CGExpr.cpp:4431
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
Definition CGExpr.cpp:700
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition CGObjC.cpp:2577
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
Definition CGExpr.cpp:7212
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Definition CGExpr.cpp:6915
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
Definition CGClass.cpp:389
void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E)
Definition CGExpr.cpp:6115
void EmitCountedByBoundsChecking(const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst, QualType IndexType, llvm::Value *IndexVal, bool Accessed, bool FlexibleArray)
EmitCountedByBoundsChecking - If the array being accessed has a "counted_by" attribute,...
Definition CGExpr.cpp:4951
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition CGDecl.cpp:2306
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
Definition CGDecl.cpp:795
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
Definition CGDecl.cpp:773
llvm::Value * EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType PointerType, Address StorageAddress, bool IsKnownNonNull)
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
Definition CGExpr.cpp:3445
RValue EmitLoadOfGlobalRegLValue(LValue LV)
Load of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:2769
void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
Definition CGClass.cpp:3081
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_DowncastPointer
Checking the operand of a static_cast to a derived pointer type.
@ TCK_DowncastReference
Checking the operand of a static_cast to a derived reference type.
@ TCK_MemberAccess
Checking the object expression in a non-static data member access.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_UpcastToVirtualBase
Checking the operand of a cast to a virtual base object.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
@ TCK_DynamicOperation
Checking the operand of a dynamic_cast or a typeid expression.
@ TCK_ReferenceBinding
Checking the bound value in a reference binding.
@ TCK_Upcast
Checking the operand of a cast to a base object.
LValue EmitBinaryOperatorLValue(const BinaryOperator *E)
Definition CGExpr.cpp:6692
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition CGDecl.cpp:2279
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty, SourceLocation Loc)
Definition CGExpr.cpp:2125
void EmitBitfieldConversionCheck(llvm::Value *Src, QualType SrcType, llvm::Value *Dst, QualType DstType, const CGBitFieldInfo &Info, SourceLocation Loc)
Emit a check that an [implicit] conversion of a bitfield.
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
Definition CGExpr.cpp:7389
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:3953
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
Definition CGExpr.cpp:6371
llvm::Value * LoadPassedObjectSize(const Expr *E, QualType EltTy)
If E references a parameter with pass_object_size info or a constant array size modifier,...
Definition CGExpr.cpp:979
@ ForceLeftToRight
! Language semantics require left-to-right evaluation.
@ Default
! No language constraints on evaluation order.
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
llvm::Value * EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition CGExpr.cpp:6907
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
Definition CGExpr.cpp:2524
LValue EmitLValueForField(LValue Base, const FieldDecl *Field, bool IsInBounds=true)
Definition CGExpr.cpp:5789
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:183
const TargetInfo & getTarget() const
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, bool IsInBounds, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Emit the address of a field using a member data pointer.
Definition CGClass.cpp:151
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty)
Definition CGExpr.cpp:6399
static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty)
Determine whether the pointer type check TCK requires a vptr check.
Definition CGExpr.cpp:742
CGCallee EmitCallee(const Expr *E)
Definition CGExpr.cpp:6601
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:259
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6475
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2542
LValue EmitMatrixSingleSubscriptExpr(const MatrixSingleSubscriptExpr *E)
Definition CGExpr.cpp:5221
LValue EmitArraySectionExpr(const ArraySectionExpr *E, bool IsLowerBound=true)
Definition CGExpr.cpp:5298
Address GetAddrOfBlockDecl(const VarDecl *var)
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
void pushCleanupAfterFullExpr(CleanupKind Kind, As... A)
Queue a cleanup to be pushed after finishing the current full-expression, potentially with an active ...
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
Definition CGExpr.cpp:4393
RawAddress CreateIRTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateIRTempWithoutCast - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:190
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
void SetFPAccuracy(llvm::Value *Val, float Accuracy)
SetFPAccuracy - Set the minimum required accuracy of the given floating point operation,...
Definition CGExpr.cpp:7250
Address mergeAddressesInConditionalExpr(Address LHS, Address RHS, llvm::BasicBlock *LHSBlock, llvm::BasicBlock *RHSBlock, llvm::BasicBlock *MergeBlock, QualType MergedType)
Address emitAddrOfImagComponent(Address complex, QualType complexType)
void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
Definition CGExpr.cpp:1285
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:240
LValue EmitPredefinedLValue(const PredefinedExpr *E)
Definition CGExpr.cpp:3916
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:4211
LValue EmitDeclRefLValue(const DeclRefExpr *E)
Definition CGExpr.cpp:3620
LValue EmitStringLiteralLValue(const StringLiteral *E)
Definition CGExpr.cpp:3906
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6428
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
Definition CGExpr.cpp:2067
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1364
LValue EmitUnsupportedLValue(const Expr *E, const char *Name)
EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue an ErrorUnsupported style ...
Definition CGExpr.cpp:1670
LValue MakeRawAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, AlignmentSource Source=AlignmentSource::Type)
Same as MakeAddrLValue above except that the pointer is known to be unsigned.
llvm::MDNode * buildAllocToken(QualType AllocType)
Build metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1346
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
Definition CGExpr.cpp:5963
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2267
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:160
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6414
bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, SourceLocation Loc)
Check if the scalar Value is within the valid range for the given type Ty.
Definition CGExpr.cpp:2139
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5570
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
LValue EmitHLSLArrayAssignLValue(const BinaryOperator *E)
Definition CGExpr.cpp:6807
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:232
LValue EmitVAArgExprLValue(const VAArgExpr *E)
Definition CGExpr.cpp:6844
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
Definition CGExpr.cpp:300
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
LValue EmitStmtExprLValue(const StmtExpr *E)
Definition CGExpr.cpp:6947
llvm::Value * EmitARCLoadWeakRetained(Address addr)
i8* @objc_loadWeakRetained(i8** addr)
Definition CGObjC.cpp:2675
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition CGExpr.cpp:109
llvm::Value * EmitWithOriginalRHSBitfieldAssignment(const BinaryOperator *E, llvm::Value **Previous, QualType *SrcType)
Retrieve the implicit cast expression of the rhs in a binary operator expression by passing pointers ...
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E)
Definition CGExpr.cpp:6923
Address EmitAddressOfPFPField(Address RecordPtr, const PFPField &Field)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2793
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition CGExpr.cpp:4643
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2359
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
Definition CGExpr.cpp:1638
llvm::Instruction * getPostAllocaInsertPoint()
Return PostAllocaInsertPt.
void EmitAllocToken(llvm::CallBase *CB, QualType AllocType)
Emit and set additional metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1360
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
LValue EmitCastLValue(const CastExpr *E)
EmitCastLValue - Casts are never lvalues unless that cast is to a reference type.
Definition CGExpr.cpp:6183
llvm::Value * EmitPointerArithmetic(const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer, Expr *indexOperand, llvm::Value *index, bool isSubtraction)
Emit pointer + index arithmetic.
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
Definition CGExpr.cpp:523
LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy)
Definition CGExpr.cpp:3455
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:4025
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:310
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:281
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E)
Definition CGExpr.cpp:5462
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
RValue EmitUnsupportedRValue(const Expr *E, const char *Name)
EmitUnsupportedRValue - Emit a dummy r-value using the type of E and issue an ErrorUnsupported style ...
Definition CGExpr.cpp:1664
CleanupKind getCleanupKind(QualType::DestructionKind kind)
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
std::pair< LValue, LValue > EmitHLSLOutArgLValues(const HLSLOutArgExpr *E, QualType Ty)
Definition CGExpr.cpp:6377
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
Definition CGExpr.cpp:6895
llvm::Type * ConvertTypeForMem(QualType T)
LValue EmitCallExprLValue(const CallExpr *E, llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6829
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition CGExpr.cpp:2656
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
Definition CGObjC.cpp:2668
LValue EmitLValueForLambdaField(const FieldDecl *Field)
Definition CGExpr.cpp:5677
void markStmtMaybeUsed(const Stmt *S)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
Definition CGExpr.cpp:6901
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
Definition CGExpr.cpp:7393
LValue EmitCoyieldLValue(const CoyieldExpr *E)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
void EmitCfiSlowPathCheck(SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond, llvm::ConstantInt *TypeId, llvm::Value *Ptr, ArrayRef< llvm::Constant * > StaticArgs)
Emit a slow path cross-DSO CFI check which calls __cfi_slowpath if Cond if false.
Definition CGExpr.cpp:4345
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
LValue EmitUnaryOpLValue(const UnaryOperator *E)
Definition CGExpr.cpp:3839
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1621
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1702
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:196
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
Definition CGExpr.cpp:3403
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
Definition CGExpr.cpp:6447
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
Definition CGObjC.cpp:2192
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
Definition CGExpr.cpp:6873
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Definition CGExpr.cpp:750
Address EmitExtVectorElementLValue(LValue V)
Generates lvalue for partial ext_vector access.
Definition CGExpr.cpp:2751
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
Definition CGExpr.cpp:340
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Address emitAddrOfRealComponent(Address complex, QualType complexType)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
RValue EmitLoadOfExtVectorElementLValue(LValue V)
Definition CGExpr.cpp:2693
static bool hasAggregateEvaluationKind(QualType T)
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
Definition CGExpr.cpp:1679
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
Definition CGCall.cpp:4979
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
Definition CGExpr.cpp:5213
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified.
Definition CGExpr.cpp:4628
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
Definition CGExpr.cpp:4550
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2301
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
Definition CGExpr.cpp:1277
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
Definition CGExpr.cpp:4538
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E)
Definition CGExpr.cpp:6858
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object.
LValue EmitMemberExpr(const MemberExpr *E)
Definition CGExpr.cpp:5567
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition CGExpr.cpp:1964
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1737
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Store of global named registers are always calls to intrinsics.
Definition CGExpr.cpp:3243
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
Definition CGExpr.cpp:6441
std::pair< llvm::Value *, CGPointerAuthInfo > EmitOrigPointerRValue(const Expr *E)
Retrieve a pointer rvalue and its ptrauth info.
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition CGObjC.cpp:2683
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitMatrixElementExpr(const MatrixElementExpr *E)
Definition CGExpr.cpp:2360
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...
Definition CGExpr.cpp:722
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
Definition CGExpr.cpp:1631
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:648
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
This class organizes the cross-function state that is used while generating LLVM code.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition CGExpr.cpp:1417
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
Definition CGExpr.cpp:3511
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition CGCXX.cpp:281
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type)
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
ASTContext & getContext() const
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
A specialization of Address that requires the address to be an LLVM Constant.
Definition Address.h:296
llvm::Constant * getPointer() const
Definition Address.h:308
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
llvm::Constant * tryEmitConstantExpr(const ConstantExpr *CE)
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:377
AlignmentSource getAlignmentSource() const
Definition CGValue.h:172
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getMatrixRowIdx() const
Definition CGValue.h:412
static LValue MakeMatrixRow(Address Addr, llvm::Value *RowIdx, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:510
bool isBitField() const
Definition CGValue.h:288
bool isMatrixElt() const
Definition CGValue.h:291
Expr * getBaseIvarExp() const
Definition CGValue.h:344
llvm::Constant * getExtVectorElts() const
Definition CGValue.h:431
static LValue MakeGlobalReg(llvm::Value *V, CharUnits alignment, QualType type)
Definition CGValue.h:500
llvm::Constant * getMatrixRowElts() const
Definition CGValue.h:417
bool isObjCStrong() const
Definition CGValue.h:336
bool isMatrixRowSwizzle() const
Definition CGValue.h:293
bool isGlobalObjCRef() const
Definition CGValue.h:318
bool isVectorElt() const
Definition CGValue.h:287
bool isSimple() const
Definition CGValue.h:286
bool isVolatileQualified() const
Definition CGValue.h:297
RValue asAggregateRValue() const
Definition CGValue.h:545
llvm::Value * getPointer(CodeGenFunction &CGF) const
llvm::Value * getMatrixIdx() const
Definition CGValue.h:407
llvm::Value * getGlobalReg() const
Definition CGValue.h:452
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:454
bool isVolatile() const
Definition CGValue.h:340
const Qualifiers & getQuals() const
Definition CGValue.h:350
bool isGlobalReg() const
Definition CGValue.h:290
static LValue MakeExtVectorElt(Address Addr, llvm::Constant *Elts, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:474
bool isObjCWeak() const
Definition CGValue.h:333
Address getAddress() const
Definition CGValue.h:373
unsigned getVRQualifiers() const
Definition CGValue.h:299
bool isMatrixRow() const
Definition CGValue.h:292
LValue setKnownNonNull()
Definition CGValue.h:362
bool isNonGC() const
Definition CGValue.h:315
bool isExtVectorElt() const
Definition CGValue.h:289
llvm::Value * getVectorIdx() const
Definition CGValue.h:394
void setNontemporal(bool Value)
Definition CGValue.h:331
LValueBaseInfo getBaseInfo() const
Definition CGValue.h:358
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
Definition CGValue.h:327
QualType getType() const
Definition CGValue.h:303
const CGBitFieldInfo & getBitFieldInfo() const
Definition CGValue.h:446
bool isThreadLocalRef() const
Definition CGValue.h:321
KnownNonNull_t isKnownNonNull() const
Definition CGValue.h:361
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:347
void setNonGC(bool Value)
Definition CGValue.h:316
static LValue MakeMatrixRowSwizzle(Address MatAddr, llvm::Value *RowIdx, llvm::Constant *Cols, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:521
Address getVectorAddress() const
Definition CGValue.h:382
bool isNontemporal() const
Definition CGValue.h:330
static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Create a new object to represent a bit-field access.
Definition CGValue.h:490
bool isObjCIvar() const
Definition CGValue.h:309
static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:464
void setAddress(Address address)
Definition CGValue.h:375
Address getExtVectorAddress() const
Definition CGValue.h:423
static LValue MakeMatrixElt(Address matAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition CGValue.h:535
Address getMatrixAddress() const
Definition CGValue.h:399
Address getBitFieldAddress() const
Definition CGValue.h:437
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
An abstract representation of an aligned address.
Definition Address.h:42
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition Address.h:93
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:77
llvm::Value * getPointer() const
Definition Address.h:66
unsigned getAddressSpace() const
Return the address space that this address resides in.
Definition Address.h:83
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:383
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
QualType getElementType() const
Definition TypeBase.h:3349
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
bool isFileScope() const
Definition Expr.h:3643
const Expr * getInitializer() const
Definition Expr.h:3639
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1088
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1480
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:494
ValueDecl * getDecl()
Definition Expr.h:1344
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1474
SourceLocation getLocation() const
Definition Expr.h:1352
T * getAttr() const
Definition DeclBase.h:581
SourceLocation getLocation() const
Definition DeclBase.h:447
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
const Expr * getBase() const
Definition Expr.h:6593
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3934
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3126
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Decl * getReferencedDeclOfCallee()
Definition Expr.cpp:1552
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition Expr.cpp:3010
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6622
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4446
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4559
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3307
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3289
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition Decl.cpp:4853
const Expr * getSubExpr() const
Definition Expr.h:1068
Represents a function declaration or definition.
Definition Decl.h:2029
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3740
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
const Decl * getDecl() const
Definition GlobalDecl.h:106
This class represents temporary values used to represent inout and out arguments in HLSL.
Definition Expr.h:7409
const OpaqueValueExpr * getCastedTemporary() const
Definition Expr.h:7460
const OpaqueValueExpr * getOpaqueArgLValue() const
Definition Expr.h:7441
bool isInOut() const
returns true if the parameter is inout and false if the parameter is out.
Definition Expr.h:7468
const Expr * getWritebackCast() const
Definition Expr.h:7455
const Expr * getArgLValue() const
Return the l-value expression that was written as the argument in source.
Definition Expr.h:7450
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5600
Describes an C or C++ initializer list.
Definition Expr.h:5314
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
Definition Expr.cpp:2471
const Expr * getInit(unsigned Init) const
Definition Expr.h:5369
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:4970
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4591
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2801
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2871
bool isIncomplete() const
Definition Expr.h:2891
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:3594
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
bool isObjCBOOLType(QualType T) const
Returns true if.
Definition NSAPI.cpp:481
This represents a decl that may have a name.
Definition Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
A C++ nested-name-specifier augmented with source location information.
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:441
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:580
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:610
bool isArrow() const
Definition ExprObjC.h:618
const Expr * getBase() const
Definition ExprObjC.h:614
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:971
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1395
QualType getReturnType() const
Definition DeclObjC.h:329
ObjCSelectorExpr used for @selector in Objective-C.
Definition ExprObjC.h:486
Selector getSelector() const
Definition ExprObjC.h:500
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1234
bool isUnique() const
Definition Expr.h:1242
const Expr * getSubExpr() const
Definition Expr.h:2205
Pointer-authentication qualifiers.
Definition TypeBase.h:152
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2011
StringRef getIdentKindName() const
Definition Expr.h:2068
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2046
StringLiteral * getFunctionName()
Definition Expr.h:2055
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6816
semantics_iterator semantics_end()
Definition Expr.h:6881
semantics_iterator semantics_begin()
Definition Expr.h:6877
const Expr *const * const_semantics_iterator
Definition Expr.h:6876
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6864
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1229
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition TypeBase.h:1036
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasConst() const
Definition TypeBase.h:457
void addCVRQualifiers(unsigned mask)
Definition TypeBase.h:502
void removeObjCGCAttr()
Definition TypeBase.h:523
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
Definition TypeBase.h:650
void removePointerAuth()
Definition TypeBase.h:610
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Represents a struct/union/class.
Definition Decl.h:4369
field_range fields() const
Definition Decl.h:4572
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4553
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4557
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4601
StmtClass getStmtClass() const
Definition Stmt.h:1503
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
bool isUnion() const
Definition Decl.h:3972
Exposes information about the current target.
Definition TargetInfo.h:227
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual StringRef getABI() const
Get the ABI currently in use.
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:455
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2000
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9353
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8787
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8783
bool isFunctionPointerType() const
Definition TypeBase.h:8751
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2426
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isVariableArrayType() const
Definition TypeBase.h:8795
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
bool isBitIntType() const
Definition TypeBase.h:8959
bool isConstantMatrixBoolType() const
Definition TypeBase.h:8837
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool hasPointeeToCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8736
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isAtomicType() const
Definition TypeBase.h:8876
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
bool isHLSLResourceRecord() const
Definition Type.cpp:5514
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isVectorType() const
Definition TypeBase.h:8823
bool isAnyPointerType() const
Definition TypeBase.h:8692
bool isSubscriptableVectorType() const
Definition TypeBase.h:8843
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isRecordType() const
Definition TypeBase.h:8811
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5518
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2448
bool isCFIUncheckedCalleeFunctionType() const
Definition TypeBase.h:8730
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
SourceLocation getExprLoc() const
Definition Expr.h:2374
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4963
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
TLSKind getTLSKind() const
Definition Decl.cpp:2147
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2345
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1190
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition Decl.h:958
@ TLS_None
Not a TLS variable.
Definition Decl.h:952
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
#define INT_MIN
Definition limits.h:55
Definition SPIR.cpp:35
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
Definition CGValue.h:142
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
bool isEmptyFieldForLayout(const ASTContext &Context, const FieldDecl *FD)
isEmptyFieldForLayout - Return true iff the field is "empty", that is, either a zero-width bit-field ...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ ARCImpreciseLifetime
Definition CGValue.h:137
static AlignmentSource getFieldAlignmentSource(AlignmentSource Source)
Given that the base address has the given alignment source, what's our confidence in the alignment of...
Definition CGValue.h:160
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const AstTypeMatcher< FunctionType > functionType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:155
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
Definition MatrixUtils.h:29
@ SC_Register
Definition Specifiers.h:258
Expr * Cond
};
@ Asm
Assembly: we accept this only so that we can preprocess it.
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
Definition Specifiers.h:340
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:343
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:342
@ SD_Dynamic
Dynamic storage duration.
Definition Specifiers.h:345
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
LangAS
Defines the address space values used by the address space qualifier of QualType.
llvm::cl::opt< bool > ClSanitizeGuardChecks
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5975
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
@ Other
Other implicit parameter.
Definition Decl.h:1774
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:178
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:181
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
Structure with information about how a bitfield should be accessed.
CharUnits VolatileStorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned VolatileOffset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned VolatileStorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
llvm::MDNode * AccessType
AccessType - The final access type.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
static TBAAAccessInfo getMayAliasInfo()
Definition CodeGenTBAA.h:63
uint64_t Size
Size - The size of access, in bytes.
llvm::MDNode * BaseType
BaseType - The base/leading access type.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition Sanitizers.h:187
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition Sanitizers.h:174
An adjustment to be made to the temporary created when emitting a reference binding,...
Definition Expr.h:68