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