clang 20.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 "CGObjCRuntime.h"
20#include "CGOpenMPRuntime.h"
21#include "CGRecordLayout.h"
22#include "CodeGenFunction.h"
23#include "CodeGenModule.h"
24#include "ConstantEmitter.h"
25#include "TargetInfo.h"
27#include "clang/AST/Attr.h"
28#include "clang/AST/DeclObjC.h"
29#include "clang/AST/NSAPI.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/ScopeExit.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/MDBuilder.h"
41#include "llvm/IR/MatrixBuilder.h"
42#include "llvm/Support/ConvertUTF.h"
43#include "llvm/Support/Endian.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/Path.h"
46#include "llvm/Support/xxhash.h"
47#include "llvm/Transforms/Utils/SanitizerStats.h"
48
49#include <optional>
50#include <string>
51
52using namespace clang;
53using namespace CodeGen;
54
55// TODO: Introduce frontend options to enabled per sanitizers, similar to
56// `fsanitize-trap`.
57static llvm::cl::opt<bool> ClSanitizeGuardChecks(
58 "ubsan-guard-checks", llvm::cl::Optional,
59 llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."));
60
61//===--------------------------------------------------------------------===//
62// Defines for metadata
63//===--------------------------------------------------------------------===//
64
65// Those values are crucial to be the SAME as in ubsan runtime library.
67 /// An integer type.
68 TK_Integer = 0x0000,
69 /// A floating-point type.
70 TK_Float = 0x0001,
71 /// An _BitInt(N) type.
72 TK_BitInt = 0x0002,
73 /// Any other type. The value representation is unspecified.
74 TK_Unknown = 0xffff
75};
76
77//===--------------------------------------------------------------------===//
78// Miscellaneous Helper Methods
79//===--------------------------------------------------------------------===//
80
81/// CreateTempAlloca - This creates a alloca and inserts it into the entry
82/// block.
84CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits Align,
85 const Twine &Name,
86 llvm::Value *ArraySize) {
87 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
88 Alloca->setAlignment(Align.getAsAlign());
89 return RawAddress(Alloca, Ty, Align, KnownNonNull);
90}
91
92/// CreateTempAlloca - This creates a alloca and inserts it into the entry
93/// block. The alloca is casted to default address space if necessary.
95 const Twine &Name,
96 llvm::Value *ArraySize,
97 RawAddress *AllocaAddr) {
98 auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
99 if (AllocaAddr)
100 *AllocaAddr = Alloca;
101 llvm::Value *V = Alloca.getPointer();
102 // Alloca always returns a pointer in alloca address space, which may
103 // be different from the type defined by the language. For example,
104 // in C++ the auto variables are in the default address space. Therefore
105 // cast alloca to the default address space when necessary.
107 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
108 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
109 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
110 // otherwise alloca is inserted at the current insertion point of the
111 // builder.
112 if (!ArraySize)
113 Builder.SetInsertPoint(getPostAllocaInsertPoint());
116 Builder.getPtrTy(DestAddrSpace), /*non-null*/ true);
117 }
118
119 return RawAddress(V, Ty, Align, KnownNonNull);
120}
121
122/// CreateTempAlloca - This creates an alloca and inserts it into the entry
123/// block if \p ArraySize is nullptr, otherwise inserts it at the current
124/// insertion point of the builder.
125llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
126 const Twine &Name,
127 llvm::Value *ArraySize) {
128 llvm::AllocaInst *Alloca;
129 if (ArraySize)
130 Alloca = Builder.CreateAlloca(Ty, ArraySize, Name);
131 else
132 Alloca =
133 new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
134 ArraySize, Name, AllocaInsertPt->getIterator());
135 if (Allocas) {
136 Allocas->Add(Alloca);
137 }
138 return Alloca;
139}
140
141/// CreateDefaultAlignTempAlloca - This creates an alloca with the
142/// default alignment of the corresponding LLVM type, which is *not*
143/// guaranteed to be related in any way to the expected alignment of
144/// an AST type that might have been lowered to Ty.
146 const Twine &Name) {
147 CharUnits Align =
148 CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlign(Ty));
149 return CreateTempAlloca(Ty, Align, Name);
150}
151
154 return CreateTempAlloca(ConvertType(Ty), Align, Name);
155}
156
158 RawAddress *Alloca) {
159 // FIXME: Should we prefer the preferred type alignment here?
160 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
161}
162
164 const Twine &Name,
165 RawAddress *Alloca) {
167 /*ArraySize=*/nullptr, Alloca);
168
169 if (Ty->isConstantMatrixType()) {
170 auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
171 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
172 ArrayTy->getNumElements());
173
174 Result = Address(Result.getPointer(), VectorTy, Result.getAlignment(),
176 }
177 return Result;
178}
179
181 CharUnits Align,
182 const Twine &Name) {
183 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
184}
185
187 const Twine &Name) {
188 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
189 Name);
190}
191
192/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
193/// expression and compare the result against zero, returning an Int1Ty value.
194llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
195 PGO.setCurrentStmt(E);
196 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
197 llvm::Value *MemPtr = EmitScalarExpr(E);
198 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
199 }
200
201 QualType BoolTy = getContext().BoolTy;
203 CGFPOptionsRAII FPOptsRAII(*this, E);
204 if (!E->getType()->isAnyComplexType())
205 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
206
208 Loc);
209}
210
211/// EmitIgnoredExpr - Emit code to compute the specified expression,
212/// ignoring the result.
214 if (E->isPRValue())
215 return (void)EmitAnyExpr(E, AggValueSlot::ignored(), true);
216
217 // if this is a bitfield-resulting conditional operator, we can special case
218 // emit this. The normal 'EmitLValue' version of this is particularly
219 // difficult to codegen for, since creating a single "LValue" for two
220 // different sized arguments here is not particularly doable.
221 if (const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
223 if (CondOp->getObjectKind() == OK_BitField)
224 return EmitIgnoredConditionalOperator(CondOp);
225 }
226
227 // Just emit it as an l-value and drop the result.
228 EmitLValue(E);
229}
230
231/// EmitAnyExpr - Emit code to compute the specified expression which
232/// can have any type. The result is returned as an RValue struct.
233/// If this is an aggregate expression, AggSlot indicates where the
234/// result should be returned.
236 AggValueSlot aggSlot,
237 bool ignoreResult) {
238 switch (getEvaluationKind(E->getType())) {
239 case TEK_Scalar:
240 return RValue::get(EmitScalarExpr(E, ignoreResult));
241 case TEK_Complex:
242 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
243 case TEK_Aggregate:
244 if (!ignoreResult && aggSlot.isIgnored())
245 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
246 EmitAggExpr(E, aggSlot);
247 return aggSlot.asRValue();
248 }
249 llvm_unreachable("bad evaluation kind");
250}
251
252/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
253/// always be accessible even if no aggregate location is provided.
256
258 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
259 return EmitAnyExpr(E, AggSlot);
260}
261
262/// EmitAnyExprToMem - Evaluate an expression into a given memory
263/// location.
265 Address Location,
266 Qualifiers Quals,
267 bool IsInit) {
268 // FIXME: This function should take an LValue as an argument.
269 switch (getEvaluationKind(E->getType())) {
270 case TEK_Complex:
272 /*isInit*/ false);
273 return;
274
275 case TEK_Aggregate: {
276 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
281 return;
282 }
283
284 case TEK_Scalar: {
285 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
286 LValue LV = MakeAddrLValue(Location, E->getType());
288 return;
289 }
290 }
291 llvm_unreachable("bad evaluation kind");
292}
293
295 const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed) {
296 QualType Type = LV.getType();
297 switch (getEvaluationKind(Type)) {
298 case TEK_Complex:
299 EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
300 return;
301 case TEK_Aggregate:
305 AggValueSlot::MayOverlap, IsZeroed));
306 return;
307 case TEK_Scalar:
308 if (LV.isSimple())
309 EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
310 else
312 return;
313 }
314 llvm_unreachable("bad evaluation kind");
315}
316
317static void
319 const Expr *E, Address ReferenceTemporary) {
320 // Objective-C++ ARC:
321 // If we are binding a reference to a temporary that has ownership, we
322 // need to perform retain/release operations on the temporary.
323 //
324 // FIXME: This should be looking at E, not M.
325 if (auto Lifetime = M->getType().getObjCLifetime()) {
326 switch (Lifetime) {
329 // Carry on to normal cleanup handling.
330 break;
331
333 // Nothing to do; cleaned up by an autorelease pool.
334 return;
335
338 switch (StorageDuration Duration = M->getStorageDuration()) {
339 case SD_Static:
340 // Note: we intentionally do not register a cleanup to release
341 // the object on program termination.
342 return;
343
344 case SD_Thread:
345 // FIXME: We should probably register a cleanup in this case.
346 return;
347
348 case SD_Automatic:
352 if (Lifetime == Qualifiers::OCL_Strong) {
353 const ValueDecl *VD = M->getExtendingDecl();
354 bool Precise = isa_and_nonnull<VarDecl>(VD) &&
355 VD->hasAttr<ObjCPreciseLifetimeAttr>();
359 } else {
360 // __weak objects always get EH cleanups; otherwise, exceptions
361 // could cause really nasty crashes instead of mere leaks.
364 }
365 if (Duration == SD_FullExpression)
366 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
367 M->getType(), *Destroy,
369 else
370 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
371 M->getType(),
372 *Destroy, CleanupKind & EHCleanup);
373 return;
374
375 case SD_Dynamic:
376 llvm_unreachable("temporary cannot have dynamic storage duration");
377 }
378 llvm_unreachable("unknown storage duration");
379 }
380 }
381
382 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
383 if (const RecordType *RT =
385 // Get the destructor for the reference temporary.
386 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
387 if (!ClassDecl->hasTrivialDestructor())
388 ReferenceTemporaryDtor = ClassDecl->getDestructor();
389 }
390
391 if (!ReferenceTemporaryDtor)
392 return;
393
394 // Call the destructor for the temporary.
395 switch (M->getStorageDuration()) {
396 case SD_Static:
397 case SD_Thread: {
398 llvm::FunctionCallee CleanupFn;
399 llvm::Constant *CleanupArg;
400 if (E->getType()->isArrayType()) {
402 ReferenceTemporary, E->getType(),
404 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
405 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
406 } else {
407 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
408 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
409 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.emitRawPointer(CGF));
410 }
412 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
413 break;
414 }
415
417 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
419 CGF.getLangOpts().Exceptions);
420 break;
421
422 case SD_Automatic:
424 ReferenceTemporary, E->getType(),
426 CGF.getLangOpts().Exceptions);
427 break;
428
429 case SD_Dynamic:
430 llvm_unreachable("temporary cannot have dynamic storage duration");
431 }
432}
433
436 const Expr *Inner,
437 RawAddress *Alloca = nullptr) {
438 auto &TCG = CGF.getTargetHooks();
439 switch (M->getStorageDuration()) {
441 case SD_Automatic: {
442 // If we have a constant temporary array or record try to promote it into a
443 // constant global under the same rules a normal constant would've been
444 // promoted. This is easier on the optimizer and generally emits fewer
445 // instructions.
446 QualType Ty = Inner->getType();
447 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
448 (Ty->isArrayType() || Ty->isRecordType()) &&
449 Ty.isConstantStorage(CGF.getContext(), true, false))
450 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
451 auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
452 auto *GV = new llvm::GlobalVariable(
453 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
454 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
455 llvm::GlobalValue::NotThreadLocal,
457 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
458 GV->setAlignment(alignment.getAsAlign());
459 llvm::Constant *C = GV;
460 if (AS != LangAS::Default)
461 C = TCG.performAddrSpaceCast(
462 CGF.CGM, GV, AS, LangAS::Default,
463 llvm::PointerType::get(
464 CGF.getLLVMContext(),
466 // FIXME: Should we put the new global into a COMDAT?
467 return RawAddress(C, GV->getValueType(), alignment);
468 }
469 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
470 }
471 case SD_Thread:
472 case SD_Static:
473 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
474
475 case SD_Dynamic:
476 llvm_unreachable("temporary can't have dynamic storage duration");
477 }
478 llvm_unreachable("unknown storage duration");
479}
480
481/// Helper method to check if the underlying ABI is AAPCS
482static bool isAAPCS(const TargetInfo &TargetInfo) {
483 return TargetInfo.getABI().starts_with("aapcs");
484}
485
488 const Expr *E = M->getSubExpr();
489
490 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
491 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
492 "Reference should never be pseudo-strong!");
493
494 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
495 // as that will cause the lifetime adjustment to be lost for ARC
496 auto ownership = M->getType().getObjCLifetime();
497 if (ownership != Qualifiers::OCL_None &&
498 ownership != Qualifiers::OCL_ExplicitNone) {
500 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
501 llvm::Type *Ty = ConvertTypeForMem(E->getType());
502 Object = Object.withElementType(Ty);
503
504 // createReferenceTemporary will promote the temporary to a global with a
505 // constant initializer if it can. It can only do this to a value of
506 // ARC-manageable type if the value is global and therefore "immune" to
507 // ref-counting operations. Therefore we have no need to emit either a
508 // dynamic initialization or a cleanup and we can just return the address
509 // of the temporary.
510 if (Var->hasInitializer())
511 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
512
513 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
514 }
515 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
517
518 switch (getEvaluationKind(E->getType())) {
519 default: llvm_unreachable("expected scalar or aggregate expression");
520 case TEK_Scalar:
521 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
522 break;
523 case TEK_Aggregate: {
530 break;
531 }
532 }
533
534 pushTemporaryCleanup(*this, M, E, Object);
535 return RefTempDst;
536 }
537
540 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
541
542 for (const auto &Ignored : CommaLHSs)
543 EmitIgnoredExpr(Ignored);
544
545 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
546 if (opaque->getType()->isRecordType()) {
547 assert(Adjustments.empty());
548 return EmitOpaqueValueLValue(opaque);
549 }
550 }
551
552 // Create and initialize the reference temporary.
553 RawAddress Alloca = Address::invalid();
554 RawAddress Object = createReferenceTemporary(*this, M, E, &Alloca);
555 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
556 Object.getPointer()->stripPointerCasts())) {
557 llvm::Type *TemporaryType = ConvertTypeForMem(E->getType());
558 Object = Object.withElementType(TemporaryType);
559 // If the temporary is a global and has a constant initializer or is a
560 // constant temporary that we promoted to a global, we may have already
561 // initialized it.
562 if (!Var->hasInitializer()) {
563 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
564 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
565 }
566 } else {
567 switch (M->getStorageDuration()) {
568 case SD_Automatic:
569 if (auto *Size = EmitLifetimeStart(
570 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
571 Alloca.getPointer())) {
572 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
573 Alloca, Size);
574 }
575 break;
576
577 case SD_FullExpression: {
578 if (!ShouldEmitLifetimeMarkers)
579 break;
580
581 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
582 // marker. Instead, start the lifetime of a conditional temporary earlier
583 // so that it's unconditional. Don't do this with sanitizers which need
584 // more precise lifetime marks. However when inside an "await.suspend"
585 // block, we should always avoid conditional cleanup because it creates
586 // boolean marker that lives across await_suspend, which can destroy coro
587 // frame.
588 ConditionalEvaluation *OldConditional = nullptr;
589 CGBuilderTy::InsertPoint OldIP;
591 ((!SanOpts.has(SanitizerKind::HWAddress) &&
592 !SanOpts.has(SanitizerKind::Memory) &&
593 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
594 inSuspendBlock())) {
595 OldConditional = OutermostConditional;
596 OutermostConditional = nullptr;
597
598 OldIP = Builder.saveIP();
599 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
600 Builder.restoreIP(CGBuilderTy::InsertPoint(
601 Block, llvm::BasicBlock::iterator(Block->back())));
602 }
603
604 if (auto *Size = EmitLifetimeStart(
605 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
606 Alloca.getPointer())) {
607 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
608 Size);
609 }
610
611 if (OldConditional) {
612 OutermostConditional = OldConditional;
613 Builder.restoreIP(OldIP);
614 }
615 break;
616 }
617
618 default:
619 break;
620 }
621 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
622 }
623 pushTemporaryCleanup(*this, M, E, Object);
624
625 // Perform derived-to-base casts and/or field accesses, to get from the
626 // temporary object we created (and, potentially, for which we extended
627 // the lifetime) to the subobject we're binding the reference to.
628 for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
629 switch (Adjustment.Kind) {
631 Object =
632 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
633 Adjustment.DerivedToBase.BasePath->path_begin(),
634 Adjustment.DerivedToBase.BasePath->path_end(),
635 /*NullCheckValue=*/ false, E->getExprLoc());
636 break;
637
640 LV = EmitLValueForField(LV, Adjustment.Field);
641 assert(LV.isSimple() &&
642 "materialized temporary field is not a simple lvalue");
643 Object = LV.getAddress();
644 break;
645 }
646
648 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
650 Adjustment.Ptr.MPT);
651 break;
652 }
653 }
654 }
655
656 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
657}
658
659RValue
661 // Emit the expression as an lvalue.
662 LValue LV = EmitLValue(E);
663 assert(LV.isSimple());
664 llvm::Value *Value = LV.getPointer(*this);
665
667 // C++11 [dcl.ref]p5 (as amended by core issue 453):
668 // If a glvalue to which a reference is directly bound designates neither
669 // an existing object or function of an appropriate type nor a region of
670 // storage of suitable size and alignment to contain an object of the
671 // reference's type, the behavior is undefined.
672 QualType Ty = E->getType();
674 }
675
676 return RValue::get(Value);
677}
678
679
680/// getAccessedFieldNo - Given an encoded value and a result number, return the
681/// input field number being accessed.
682unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
683 const llvm::Constant *Elts) {
684 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
685 ->getZExtValue();
686}
687
688static llvm::Value *emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc,
689 llvm::Value *Ptr) {
690 llvm::Value *A0 =
691 Builder.CreateMul(Ptr, Builder.getInt64(0xbf58476d1ce4e5b9u));
692 llvm::Value *A1 =
693 Builder.CreateXor(A0, Builder.CreateLShr(A0, Builder.getInt64(31)));
694 return Builder.CreateXor(Acc, A1);
695}
696
697bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
698 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
700}
701
702bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
704 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
705 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
708}
709
711 return SanOpts.has(SanitizerKind::Null) ||
712 SanOpts.has(SanitizerKind::Alignment) ||
713 SanOpts.has(SanitizerKind::ObjectSize) ||
714 SanOpts.has(SanitizerKind::Vptr);
715}
716
718 llvm::Value *Ptr, QualType Ty,
719 CharUnits Alignment,
720 SanitizerSet SkippedChecks,
721 llvm::Value *ArraySize) {
723 return;
724
725 // Don't check pointers outside the default address space. The null check
726 // isn't correct, the object-size check isn't supported by LLVM, and we can't
727 // communicate the addresses to the runtime handler for the vptr check.
728 if (Ptr->getType()->getPointerAddressSpace())
729 return;
730
731 // Don't check pointers to volatile data. The behavior here is implementation-
732 // defined.
733 if (Ty.isVolatileQualified())
734 return;
735
736 SanitizerScope SanScope(this);
737
739 llvm::BasicBlock *Done = nullptr;
740
741 // Quickly determine whether we have a pointer to an alloca. It's possible
742 // to skip null checks, and some alignment checks, for these pointers. This
743 // can reduce compile-time significantly.
744 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
745
746 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
747 llvm::Value *IsNonNull = nullptr;
748 bool IsGuaranteedNonNull =
749 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
750 bool AllowNullPointers = isNullPointerAllowed(TCK);
751 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
752 !IsGuaranteedNonNull) {
753 // The glvalue must not be an empty glvalue.
754 IsNonNull = Builder.CreateIsNotNull(Ptr);
755
756 // The IR builder can constant-fold the null check if the pointer points to
757 // a constant.
758 IsGuaranteedNonNull = IsNonNull == True;
759
760 // Skip the null check if the pointer is known to be non-null.
761 if (!IsGuaranteedNonNull) {
762 if (AllowNullPointers) {
763 // When performing pointer casts, it's OK if the value is null.
764 // Skip the remaining checks in that case.
765 Done = createBasicBlock("null");
766 llvm::BasicBlock *Rest = createBasicBlock("not.null");
767 Builder.CreateCondBr(IsNonNull, Rest, Done);
768 EmitBlock(Rest);
769 } else {
770 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
771 }
772 }
773 }
774
775 if (SanOpts.has(SanitizerKind::ObjectSize) &&
776 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
777 !Ty->isIncompleteType()) {
779 llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
780 if (ArraySize)
781 Size = Builder.CreateMul(Size, ArraySize);
782
783 // Degenerate case: new X[0] does not need an objectsize check.
784 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
785 if (!ConstantSize || !ConstantSize->isNullValue()) {
786 // The glvalue must refer to a large enough storage region.
787 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
788 // to check this.
789 // FIXME: Get object address space
790 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
791 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
792 llvm::Value *Min = Builder.getFalse();
793 llvm::Value *NullIsUnknown = Builder.getFalse();
794 llvm::Value *Dynamic = Builder.getFalse();
795 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
796 Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
797 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
798 }
799 }
800
801 llvm::MaybeAlign AlignVal;
802 llvm::Value *PtrAsInt = nullptr;
803
804 if (SanOpts.has(SanitizerKind::Alignment) &&
805 !SkippedChecks.has(SanitizerKind::Alignment)) {
806 AlignVal = Alignment.getAsMaybeAlign();
807 if (!Ty->isIncompleteType() && !AlignVal)
808 AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
809 /*ForPointeeType=*/true)
811
812 // The glvalue must be suitably aligned.
813 if (AlignVal && *AlignVal > llvm::Align(1) &&
814 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
815 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
816 llvm::Value *Align = Builder.CreateAnd(
817 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal->value() - 1));
818 llvm::Value *Aligned =
819 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
820 if (Aligned != True)
821 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
822 }
823 }
824
825 if (Checks.size() > 0) {
826 llvm::Constant *StaticData[] = {
828 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
829 llvm::ConstantInt::get(Int8Ty, TCK)};
830 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
831 PtrAsInt ? PtrAsInt : Ptr);
832 }
833
834 // If possible, check that the vptr indicates that there is a subobject of
835 // type Ty at offset zero within this object.
836 //
837 // C++11 [basic.life]p5,6:
838 // [For storage which does not refer to an object within its lifetime]
839 // The program has undefined behavior if:
840 // -- the [pointer or glvalue] is used to access a non-static data member
841 // or call a non-static member function
842 if (SanOpts.has(SanitizerKind::Vptr) &&
843 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
844 // Ensure that the pointer is non-null before loading it. If there is no
845 // compile-time guarantee, reuse the run-time null check or emit a new one.
846 if (!IsGuaranteedNonNull) {
847 if (!IsNonNull)
848 IsNonNull = Builder.CreateIsNotNull(Ptr);
849 if (!Done)
850 Done = createBasicBlock("vptr.null");
851 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
852 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
853 EmitBlock(VptrNotNull);
854 }
855
856 // Compute a deterministic hash of the mangled name of the type.
857 SmallString<64> MangledName;
858 llvm::raw_svector_ostream Out(MangledName);
860 Out);
861
862 // Contained in NoSanitizeList based on the mangled type.
863 if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
864 Out.str())) {
865 // Load the vptr, and mix it with TypeHash.
866 llvm::Value *TypeHash =
867 llvm::ConstantInt::get(Int64Ty, xxh3_64bits(Out.str()));
868
869 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
870 Address VPtrAddr(Ptr, IntPtrTy, getPointerAlign());
871 llvm::Value *VPtrVal = GetVTablePtr(VPtrAddr, VPtrTy,
872 Ty->getAsCXXRecordDecl(),
874 VPtrVal = Builder.CreateBitOrPointerCast(VPtrVal, IntPtrTy);
875
876 llvm::Value *Hash =
877 emitHashMix(Builder, TypeHash, Builder.CreateZExt(VPtrVal, Int64Ty));
878 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
879
880 // Look the hash up in our cache.
881 const int CacheSize = 128;
882 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
883 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
884 "__ubsan_vptr_type_cache");
885 llvm::Value *Slot = Builder.CreateAnd(Hash,
886 llvm::ConstantInt::get(IntPtrTy,
887 CacheSize-1));
888 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
889 llvm::Value *CacheVal = Builder.CreateAlignedLoad(
890 IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
892
893 // If the hash isn't in the cache, call a runtime handler to perform the
894 // hard work of checking whether the vptr is for an object of the right
895 // type. This will either fill in the cache and return, or produce a
896 // diagnostic.
897 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
898 llvm::Constant *StaticData[] = {
902 llvm::ConstantInt::get(Int8Ty, TCK)
903 };
904 llvm::Value *DynamicData[] = { Ptr, Hash };
905 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
906 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
907 DynamicData);
908 }
909 }
910
911 if (Done) {
912 Builder.CreateBr(Done);
913 EmitBlock(Done);
914 }
915}
916
918 QualType EltTy) {
920 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
921 if (!EltSize)
922 return nullptr;
923
924 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
925 if (!ArrayDeclRef)
926 return nullptr;
927
928 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
929 if (!ParamDecl)
930 return nullptr;
931
932 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
933 if (!POSAttr)
934 return nullptr;
935
936 // Don't load the size if it's a lower bound.
937 int POSType = POSAttr->getType();
938 if (POSType != 0 && POSType != 1)
939 return nullptr;
940
941 // Find the implicit size parameter.
942 auto PassedSizeIt = SizeArguments.find(ParamDecl);
943 if (PassedSizeIt == SizeArguments.end())
944 return nullptr;
945
946 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
947 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
948 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
949 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
950 C.getSizeType(), E->getExprLoc());
951 llvm::Value *SizeOfElement =
952 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
953 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
954}
955
956/// If Base is known to point to the start of an array, return the length of
957/// that array. Return 0 if the length cannot be determined.
958static llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF,
959 const Expr *Base,
960 QualType &IndexedType,
962 StrictFlexArraysLevel) {
963 // For the vector indexing extension, the bound is the number of elements.
964 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
965 IndexedType = Base->getType();
966 return CGF.Builder.getInt32(VT->getNumElements());
967 }
968
969 Base = Base->IgnoreParens();
970
971 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
972 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
973 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.getContext(),
974 StrictFlexArraysLevel)) {
975 CodeGenFunction::SanitizerScope SanScope(&CGF);
976
977 IndexedType = CE->getSubExpr()->getType();
978 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
979 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
980 return CGF.Builder.getInt(CAT->getSize());
981
982 if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
983 return CGF.getVLASize(VAT).NumElts;
984 // Ignore pass_object_size here. It's not applicable on decayed pointers.
985 }
986 }
987
988 CodeGenFunction::SanitizerScope SanScope(&CGF);
989
990 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
991 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
992 IndexedType = Base->getType();
993 return POS;
994 }
995
996 return nullptr;
997}
998
999namespace {
1000
1001/// \p StructAccessBase returns the base \p Expr of a field access. It returns
1002/// either a \p DeclRefExpr, representing the base pointer to the struct, i.e.:
1003///
1004/// p in p-> a.b.c
1005///
1006/// or a \p MemberExpr, if the \p MemberExpr has the \p RecordDecl we're
1007/// looking for:
1008///
1009/// struct s {
1010/// struct s *ptr;
1011/// int count;
1012/// char array[] __attribute__((counted_by(count)));
1013/// };
1014///
1015/// If we have an expression like \p p->ptr->array[index], we want the
1016/// \p MemberExpr for \p p->ptr instead of \p p.
1017class StructAccessBase
1018 : public ConstStmtVisitor<StructAccessBase, const Expr *> {
1019 const RecordDecl *ExpectedRD;
1020
1021 bool IsExpectedRecordDecl(const Expr *E) const {
1022 QualType Ty = E->getType();
1023 if (Ty->isPointerType())
1024 Ty = Ty->getPointeeType();
1025 return ExpectedRD == Ty->getAsRecordDecl();
1026 }
1027
1028public:
1029 StructAccessBase(const RecordDecl *ExpectedRD) : ExpectedRD(ExpectedRD) {}
1030
1031 //===--------------------------------------------------------------------===//
1032 // Visitor Methods
1033 //===--------------------------------------------------------------------===//
1034
1035 // NOTE: If we build C++ support for counted_by, then we'll have to handle
1036 // horrors like this:
1037 //
1038 // struct S {
1039 // int x, y;
1040 // int blah[] __attribute__((counted_by(x)));
1041 // } s;
1042 //
1043 // int foo(int index, int val) {
1044 // int (S::*IHatePMDs)[] = &S::blah;
1045 // (s.*IHatePMDs)[index] = val;
1046 // }
1047
1048 const Expr *Visit(const Expr *E) {
1050 }
1051
1052 const Expr *VisitStmt(const Stmt *S) { return nullptr; }
1053
1054 // These are the types we expect to return (in order of most to least
1055 // likely):
1056 //
1057 // 1. DeclRefExpr - This is the expression for the base of the structure.
1058 // It's exactly what we want to build an access to the \p counted_by
1059 // field.
1060 // 2. MemberExpr - This is the expression that has the same \p RecordDecl
1061 // as the flexble array member's lexical enclosing \p RecordDecl. This
1062 // allows us to catch things like: "p->p->array"
1063 // 3. CompoundLiteralExpr - This is for people who create something
1064 // heretical like (struct foo has a flexible array member):
1065 //
1066 // (struct foo){ 1, 2 }.blah[idx];
1067 const Expr *VisitDeclRefExpr(const DeclRefExpr *E) {
1068 return IsExpectedRecordDecl(E) ? E : nullptr;
1069 }
1070 const Expr *VisitMemberExpr(const MemberExpr *E) {
1071 if (IsExpectedRecordDecl(E) && E->isArrow())
1072 return E;
1073 const Expr *Res = Visit(E->getBase());
1074 return !Res && IsExpectedRecordDecl(E) ? E : Res;
1075 }
1076 const Expr *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1077 return IsExpectedRecordDecl(E) ? E : nullptr;
1078 }
1079 const Expr *VisitCallExpr(const CallExpr *E) {
1080 return IsExpectedRecordDecl(E) ? E : nullptr;
1081 }
1082
1083 const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1084 if (IsExpectedRecordDecl(E))
1085 return E;
1086 return Visit(E->getBase());
1087 }
1088 const Expr *VisitCastExpr(const CastExpr *E) {
1089 if (E->getCastKind() == CK_LValueToRValue)
1090 return IsExpectedRecordDecl(E) ? E : nullptr;
1091 return Visit(E->getSubExpr());
1092 }
1093 const Expr *VisitParenExpr(const ParenExpr *E) {
1094 return Visit(E->getSubExpr());
1095 }
1096 const Expr *VisitUnaryAddrOf(const UnaryOperator *E) {
1097 return Visit(E->getSubExpr());
1098 }
1099 const Expr *VisitUnaryDeref(const UnaryOperator *E) {
1100 return Visit(E->getSubExpr());
1101 }
1102};
1103
1104} // end anonymous namespace
1105
1107
1109 const FieldDecl *Field,
1110 RecIndicesTy &Indices) {
1111 const CGRecordLayout &Layout = CGF.CGM.getTypes().getCGRecordLayout(RD);
1112 int64_t FieldNo = -1;
1113 for (const FieldDecl *FD : RD->fields()) {
1114 if (!Layout.containsFieldDecl(FD))
1115 // This could happen if the field has a struct type that's empty. I don't
1116 // know why either.
1117 continue;
1118
1119 FieldNo = Layout.getLLVMFieldNo(FD);
1120 if (FD == Field) {
1121 Indices.emplace_back(CGF.Builder.getInt32(FieldNo));
1122 return true;
1123 }
1124
1125 QualType Ty = FD->getType();
1126 if (Ty->isRecordType()) {
1127 if (getGEPIndicesToField(CGF, Ty->getAsRecordDecl(), Field, Indices)) {
1128 if (RD->isUnion())
1129 FieldNo = 0;
1130 Indices.emplace_back(CGF.Builder.getInt32(FieldNo));
1131 return true;
1132 }
1133 }
1134 }
1135
1136 return false;
1137}
1138
1140 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1141 const RecordDecl *RD = CountDecl->getParent()->getOuterLexicalRecordContext();
1142
1143 // Find the base struct expr (i.e. p in p->a.b.c.d).
1144 const Expr *StructBase = StructAccessBase(RD).Visit(Base);
1145 if (!StructBase || StructBase->HasSideEffects(getContext()))
1146 return nullptr;
1147
1148 llvm::Value *Res = nullptr;
1149 if (StructBase->getType()->isPointerType()) {
1150 LValueBaseInfo BaseInfo;
1151 TBAAAccessInfo TBAAInfo;
1152 Address Addr = EmitPointerWithAlignment(StructBase, &BaseInfo, &TBAAInfo);
1153 Res = Addr.emitRawPointer(*this);
1154 } else if (StructBase->isLValue()) {
1155 LValue LV = EmitLValue(StructBase);
1156 Address Addr = LV.getAddress();
1157 Res = Addr.emitRawPointer(*this);
1158 } else {
1159 return nullptr;
1160 }
1161
1162 RecIndicesTy Indices;
1163 getGEPIndicesToField(*this, RD, CountDecl, Indices);
1164 if (Indices.empty())
1165 return nullptr;
1166
1167 Indices.push_back(Builder.getInt32(0));
1169 ConvertType(QualType(RD->getTypeForDecl(), 0)), Res,
1170 RecIndicesTy(llvm::reverse(Indices)), "counted_by.gep");
1171}
1172
1173/// This method is typically called in contexts where we can't generate
1174/// side-effects, like in __builtin_dynamic_object_size. When finding
1175/// expressions, only choose those that have either already been emitted or can
1176/// be loaded without side-effects.
1177///
1178/// - \p FAMDecl: the \p Decl for the flexible array member. It may not be
1179/// within the top-level struct.
1180/// - \p CountDecl: must be within the same non-anonymous struct as \p FAMDecl.
1182 const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl) {
1183 if (llvm::Value *GEP = GetCountedByFieldExprGEP(Base, FAMDecl, CountDecl))
1184 return Builder.CreateAlignedLoad(ConvertType(CountDecl->getType()), GEP,
1185 getIntAlign(), "counted_by.load");
1186 return nullptr;
1187}
1188
1189void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
1190 llvm::Value *Index, QualType IndexType,
1191 bool Accessed) {
1192 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
1193 "should not be called unless adding bounds checks");
1194 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
1195 getLangOpts().getStrictFlexArraysLevel();
1196 QualType IndexedType;
1197 llvm::Value *Bound =
1198 getArrayIndexingBound(*this, Base, IndexedType, StrictFlexArraysLevel);
1199
1200 EmitBoundsCheckImpl(E, Bound, Index, IndexType, IndexedType, Accessed);
1201}
1202
1203void CodeGenFunction::EmitBoundsCheckImpl(const Expr *E, llvm::Value *Bound,
1204 llvm::Value *Index,
1205 QualType IndexType,
1206 QualType IndexedType, bool Accessed) {
1207 if (!Bound)
1208 return;
1209
1210 SanitizerScope SanScope(this);
1211
1212 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
1213 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
1214 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
1215
1216 llvm::Constant *StaticData[] = {
1218 EmitCheckTypeDescriptor(IndexedType),
1219 EmitCheckTypeDescriptor(IndexType)
1220 };
1221 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
1222 : Builder.CreateICmpULE(IndexVal, BoundVal);
1223 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
1224 SanitizerHandler::OutOfBounds, StaticData, Index);
1225}
1226
1229 bool isInc, bool isPre) {
1231
1232 llvm::Value *NextVal;
1233 if (isa<llvm::IntegerType>(InVal.first->getType())) {
1234 uint64_t AmountVal = isInc ? 1 : -1;
1235 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1236
1237 // Add the inc/dec to the real part.
1238 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1239 } else {
1240 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1241 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1242 if (!isInc)
1243 FVal.changeSign();
1244 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1245
1246 // Add the inc/dec to the real part.
1247 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1248 }
1249
1250 ComplexPairTy IncVal(NextVal, InVal.second);
1251
1252 // Store the updated result through the lvalue.
1253 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1254 if (getLangOpts().OpenMP)
1256 E->getSubExpr());
1257
1258 // If this is a postinc, return the value read from memory, otherwise use the
1259 // updated value.
1260 return isPre ? IncVal : InVal;
1261}
1262
1264 CodeGenFunction *CGF) {
1265 // Bind VLAs in the cast type.
1266 if (CGF && E->getType()->isVariablyModifiedType())
1268
1269 if (CGDebugInfo *DI = getModuleDebugInfo())
1270 DI->EmitExplicitCastType(E->getType());
1271}
1272
1273//===----------------------------------------------------------------------===//
1274// LValue Expression Emission
1275//===----------------------------------------------------------------------===//
1276
1278 TBAAAccessInfo *TBAAInfo,
1279 KnownNonNull_t IsKnownNonNull,
1280 CodeGenFunction &CGF) {
1281 // We allow this with ObjC object pointers because of fragile ABIs.
1282 assert(E->getType()->isPointerType() ||
1284 E = E->IgnoreParens();
1285
1286 // Casts:
1287 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1288 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1289 CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
1290
1291 switch (CE->getCastKind()) {
1292 // Non-converting casts (but not C's implicit conversion from void*).
1293 case CK_BitCast:
1294 case CK_NoOp:
1295 case CK_AddressSpaceConversion:
1296 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1297 if (PtrTy->getPointeeType()->isVoidType())
1298 break;
1299
1300 LValueBaseInfo InnerBaseInfo;
1301 TBAAAccessInfo InnerTBAAInfo;
1303 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1304 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1305 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1306
1307 if (isa<ExplicitCastExpr>(CE)) {
1308 LValueBaseInfo TargetTypeBaseInfo;
1309 TBAAAccessInfo TargetTypeTBAAInfo;
1311 E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1312 if (TBAAInfo)
1313 *TBAAInfo =
1314 CGF.CGM.mergeTBAAInfoForCast(*TBAAInfo, TargetTypeTBAAInfo);
1315 // If the source l-value is opaque, honor the alignment of the
1316 // casted-to type.
1317 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1318 if (BaseInfo)
1319 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1320 Addr.setAlignment(Align);
1321 }
1322 }
1323
1324 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1325 CE->getCastKind() == CK_BitCast) {
1326 if (auto PT = E->getType()->getAs<PointerType>())
1327 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr,
1328 /*MayBeNull=*/true,
1330 CE->getBeginLoc());
1331 }
1332
1333 llvm::Type *ElemTy =
1335 Addr = Addr.withElementType(ElemTy);
1336 if (CE->getCastKind() == CK_AddressSpaceConversion)
1337 Addr = CGF.Builder.CreateAddrSpaceCast(
1338 Addr, CGF.ConvertType(E->getType()), ElemTy);
1339 return CGF.authPointerToPointerCast(Addr, CE->getSubExpr()->getType(),
1340 CE->getType());
1341 }
1342 break;
1343
1344 // Array-to-pointer decay.
1345 case CK_ArrayToPointerDecay:
1346 return CGF.EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1347
1348 // Derived-to-base conversions.
1349 case CK_UncheckedDerivedToBase:
1350 case CK_DerivedToBase: {
1351 // TODO: Support accesses to members of base classes in TBAA. For now, we
1352 // conservatively pretend that the complete object is of the base class
1353 // type.
1354 if (TBAAInfo)
1355 *TBAAInfo = CGF.CGM.getTBAAAccessInfo(E->getType());
1357 CE->getSubExpr(), BaseInfo, nullptr,
1358 (KnownNonNull_t)(IsKnownNonNull ||
1359 CE->getCastKind() == CK_UncheckedDerivedToBase));
1360 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1361 return CGF.GetAddressOfBaseClass(
1362 Addr, Derived, CE->path_begin(), CE->path_end(),
1363 CGF.ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
1364 }
1365
1366 // TODO: Is there any reason to treat base-to-derived conversions
1367 // specially?
1368 default:
1369 break;
1370 }
1371 }
1372
1373 // Unary &.
1374 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1375 if (UO->getOpcode() == UO_AddrOf) {
1376 LValue LV = CGF.EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1377 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1378 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1379 return LV.getAddress();
1380 }
1381 }
1382
1383 // std::addressof and variants.
1384 if (auto *Call = dyn_cast<CallExpr>(E)) {
1385 switch (Call->getBuiltinCallee()) {
1386 default:
1387 break;
1388 case Builtin::BIaddressof:
1389 case Builtin::BI__addressof:
1390 case Builtin::BI__builtin_addressof: {
1391 LValue LV = CGF.EmitLValue(Call->getArg(0), IsKnownNonNull);
1392 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1393 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1394 return LV.getAddress();
1395 }
1396 }
1397 }
1398
1399 // TODO: conditional operators, comma.
1400
1401 // Otherwise, use the alignment of the type.
1404 /*ForPointeeType=*/true, BaseInfo, TBAAInfo, IsKnownNonNull);
1405}
1406
1407/// EmitPointerWithAlignment - Given an expression of pointer type, try to
1408/// derive a more accurate bound on the alignment of the pointer.
1410 const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo,
1411 KnownNonNull_t IsKnownNonNull) {
1412 Address Addr =
1413 ::EmitPointerWithAlignment(E, BaseInfo, TBAAInfo, IsKnownNonNull, *this);
1414 if (IsKnownNonNull && !Addr.isKnownNonNull())
1415 Addr.setKnownNonNull();
1416 return Addr;
1417}
1418
1420 llvm::Value *V = RV.getScalarVal();
1421 if (auto MPT = T->getAs<MemberPointerType>())
1422 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1423 return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1424}
1425
1427 if (Ty->isVoidType())
1428 return RValue::get(nullptr);
1429
1430 switch (getEvaluationKind(Ty)) {
1431 case TEK_Complex: {
1432 llvm::Type *EltTy =
1434 llvm::Value *U = llvm::UndefValue::get(EltTy);
1435 return RValue::getComplex(std::make_pair(U, U));
1436 }
1437
1438 // If this is a use of an undefined aggregate type, the aggregate must have an
1439 // identifiable address. Just because the contents of the value are undefined
1440 // doesn't mean that the address can't be taken and compared.
1441 case TEK_Aggregate: {
1442 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1443 return RValue::getAggregate(DestPtr);
1444 }
1445
1446 case TEK_Scalar:
1447 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1448 }
1449 llvm_unreachable("bad evaluation kind");
1450}
1451
1453 const char *Name) {
1454 ErrorUnsupported(E, Name);
1455 return GetUndefRValue(E->getType());
1456}
1457
1459 const char *Name) {
1460 ErrorUnsupported(E, Name);
1461 llvm::Type *ElTy = ConvertType(E->getType());
1462 llvm::Type *Ty = UnqualPtrTy;
1463 return MakeAddrLValue(
1464 Address(llvm::UndefValue::get(Ty), ElTy, CharUnits::One()), E->getType());
1465}
1466
1467bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1468 const Expr *Base = Obj;
1469 while (!isa<CXXThisExpr>(Base)) {
1470 // The result of a dynamic_cast can be null.
1471 if (isa<CXXDynamicCastExpr>(Base))
1472 return false;
1473
1474 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1475 Base = CE->getSubExpr();
1476 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1477 Base = PE->getSubExpr();
1478 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1479 if (UO->getOpcode() == UO_Extension)
1480 Base = UO->getSubExpr();
1481 else
1482 return false;
1483 } else {
1484 return false;
1485 }
1486 }
1487 return true;
1488}
1489
1490LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1491 LValue LV;
1492 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1493 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1494 else
1495 LV = EmitLValue(E);
1496 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1497 SanitizerSet SkippedChecks;
1498 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1499 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1500 if (IsBaseCXXThis)
1501 SkippedChecks.set(SanitizerKind::Alignment, true);
1502 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1503 SkippedChecks.set(SanitizerKind::Null, true);
1504 }
1505 EmitTypeCheck(TCK, E->getExprLoc(), LV, E->getType(), SkippedChecks);
1506 }
1507 return LV;
1508}
1509
1510/// EmitLValue - Emit code to compute a designator that specifies the location
1511/// of the expression.
1512///
1513/// This can return one of two things: a simple address or a bitfield reference.
1514/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1515/// an LLVM pointer type.
1516///
1517/// If this returns a bitfield reference, nothing about the pointee type of the
1518/// LLVM value is known: For example, it may not be a pointer to an integer.
1519///
1520/// If this returns a normal address, and if the lvalue's C type is fixed size,
1521/// this method guarantees that the returned pointer type will point to an LLVM
1522/// type of the same size of the lvalue's type. If the lvalue has a variable
1523/// length type, this is not possible.
1524///
1526 KnownNonNull_t IsKnownNonNull) {
1527 // Running with sufficient stack space to avoid deeply nested expressions
1528 // cause a stack overflow.
1529 LValue LV;
1531 E->getExprLoc(), [&] { LV = EmitLValueHelper(E, IsKnownNonNull); });
1532
1533 if (IsKnownNonNull && !LV.isKnownNonNull())
1534 LV.setKnownNonNull();
1535 return LV;
1536}
1537
1539 const ASTContext &Ctx) {
1540 const Expr *SE = E->getSubExpr()->IgnoreImplicit();
1541 if (isa<OpaqueValueExpr>(SE))
1542 return SE->getType();
1543 return cast<CallExpr>(SE)->getCallReturnType(Ctx)->getPointeeType();
1544}
1545
1546LValue CodeGenFunction::EmitLValueHelper(const Expr *E,
1547 KnownNonNull_t IsKnownNonNull) {
1548 ApplyDebugLocation DL(*this, E);
1549 switch (E->getStmtClass()) {
1550 default: return EmitUnsupportedLValue(E, "l-value expression");
1551
1552 case Expr::ObjCPropertyRefExprClass:
1553 llvm_unreachable("cannot emit a property reference directly");
1554
1555 case Expr::ObjCSelectorExprClass:
1556 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1557 case Expr::ObjCIsaExprClass:
1558 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1559 case Expr::BinaryOperatorClass:
1560 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1561 case Expr::CompoundAssignOperatorClass: {
1562 QualType Ty = E->getType();
1563 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1564 Ty = AT->getValueType();
1565 if (!Ty->isAnyComplexType())
1566 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1567 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1568 }
1569 case Expr::CallExprClass:
1570 case Expr::CXXMemberCallExprClass:
1571 case Expr::CXXOperatorCallExprClass:
1572 case Expr::UserDefinedLiteralClass:
1573 return EmitCallExprLValue(cast<CallExpr>(E));
1574 case Expr::CXXRewrittenBinaryOperatorClass:
1575 return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
1576 IsKnownNonNull);
1577 case Expr::VAArgExprClass:
1578 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1579 case Expr::DeclRefExprClass:
1580 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1581 case Expr::ConstantExprClass: {
1582 const ConstantExpr *CE = cast<ConstantExpr>(E);
1583 if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
1585 return MakeNaturalAlignAddrLValue(Result, RetType);
1586 }
1587 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr(), IsKnownNonNull);
1588 }
1589 case Expr::ParenExprClass:
1590 return EmitLValue(cast<ParenExpr>(E)->getSubExpr(), IsKnownNonNull);
1591 case Expr::GenericSelectionExprClass:
1592 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr(),
1593 IsKnownNonNull);
1594 case Expr::PredefinedExprClass:
1595 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1596 case Expr::StringLiteralClass:
1597 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1598 case Expr::ObjCEncodeExprClass:
1599 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1600 case Expr::PseudoObjectExprClass:
1601 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1602 case Expr::InitListExprClass:
1603 return EmitInitListLValue(cast<InitListExpr>(E));
1604 case Expr::CXXTemporaryObjectExprClass:
1605 case Expr::CXXConstructExprClass:
1606 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1607 case Expr::CXXBindTemporaryExprClass:
1608 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1609 case Expr::CXXUuidofExprClass:
1610 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1611 case Expr::LambdaExprClass:
1612 return EmitAggExprToLValue(E);
1613
1614 case Expr::ExprWithCleanupsClass: {
1615 const auto *cleanups = cast<ExprWithCleanups>(E);
1616 RunCleanupsScope Scope(*this);
1617 LValue LV = EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1618 if (LV.isSimple()) {
1619 // Defend against branches out of gnu statement expressions surrounded by
1620 // cleanups.
1621 Address Addr = LV.getAddress();
1622 llvm::Value *V = Addr.getBasePointer();
1623 Scope.ForceCleanup({&V});
1624 Addr.replaceBasePointer(V);
1625 return LValue::MakeAddr(Addr, LV.getType(), getContext(),
1626 LV.getBaseInfo(), LV.getTBAAInfo());
1627 }
1628 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1629 // bitfield lvalue or some other non-simple lvalue?
1630 return LV;
1631 }
1632
1633 case Expr::CXXDefaultArgExprClass: {
1634 auto *DAE = cast<CXXDefaultArgExpr>(E);
1635 CXXDefaultArgExprScope Scope(*this, DAE);
1636 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1637 }
1638 case Expr::CXXDefaultInitExprClass: {
1639 auto *DIE = cast<CXXDefaultInitExpr>(E);
1640 CXXDefaultInitExprScope Scope(*this, DIE);
1641 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1642 }
1643 case Expr::CXXTypeidExprClass:
1644 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1645
1646 case Expr::ObjCMessageExprClass:
1647 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1648 case Expr::ObjCIvarRefExprClass:
1649 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1650 case Expr::StmtExprClass:
1651 return EmitStmtExprLValue(cast<StmtExpr>(E));
1652 case Expr::UnaryOperatorClass:
1653 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1654 case Expr::ArraySubscriptExprClass:
1655 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1656 case Expr::MatrixSubscriptExprClass:
1657 return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
1658 case Expr::ArraySectionExprClass:
1659 return EmitArraySectionExpr(cast<ArraySectionExpr>(E));
1660 case Expr::ExtVectorElementExprClass:
1661 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1662 case Expr::CXXThisExprClass:
1664 case Expr::MemberExprClass:
1665 return EmitMemberExpr(cast<MemberExpr>(E));
1666 case Expr::CompoundLiteralExprClass:
1667 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1668 case Expr::ConditionalOperatorClass:
1669 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1670 case Expr::BinaryConditionalOperatorClass:
1671 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1672 case Expr::ChooseExprClass:
1673 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(), IsKnownNonNull);
1674 case Expr::OpaqueValueExprClass:
1675 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1676 case Expr::SubstNonTypeTemplateParmExprClass:
1677 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
1678 IsKnownNonNull);
1679 case Expr::ImplicitCastExprClass:
1680 case Expr::CStyleCastExprClass:
1681 case Expr::CXXFunctionalCastExprClass:
1682 case Expr::CXXStaticCastExprClass:
1683 case Expr::CXXDynamicCastExprClass:
1684 case Expr::CXXReinterpretCastExprClass:
1685 case Expr::CXXConstCastExprClass:
1686 case Expr::CXXAddrspaceCastExprClass:
1687 case Expr::ObjCBridgedCastExprClass:
1688 return EmitCastLValue(cast<CastExpr>(E));
1689
1690 case Expr::MaterializeTemporaryExprClass:
1691 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1692
1693 case Expr::CoawaitExprClass:
1694 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1695 case Expr::CoyieldExprClass:
1696 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1697 case Expr::PackIndexingExprClass:
1698 return EmitLValue(cast<PackIndexingExpr>(E)->getSelectedExpr());
1699 case Expr::HLSLOutArgExprClass:
1700 llvm_unreachable("cannot emit a HLSL out argument directly");
1701 }
1702}
1703
1704/// Given an object of the given canonical type, can we safely copy a
1705/// value out of it based on its initializer?
1707 assert(type.isCanonical());
1708 assert(!type->isReferenceType());
1709
1710 // Must be const-qualified but non-volatile.
1711 Qualifiers qs = type.getLocalQualifiers();
1712 if (!qs.hasConst() || qs.hasVolatile()) return false;
1713
1714 // Otherwise, all object types satisfy this except C++ classes with
1715 // mutable subobjects or non-trivial copy/destroy behavior.
1716 if (const auto *RT = dyn_cast<RecordType>(type))
1717 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1718 if (RD->hasMutableFields() || !RD->isTrivial())
1719 return false;
1720
1721 return true;
1722}
1723
1724/// Can we constant-emit a load of a reference to a variable of the
1725/// given type? This is different from predicates like
1726/// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1727/// in situations that don't necessarily satisfy the language's rules
1728/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1729/// to do this with const float variables even if those variables
1730/// aren't marked 'constexpr'.
1738 type = type.getCanonicalType();
1739 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1740 if (isConstantEmittableObjectType(ref->getPointeeType()))
1742 return CEK_AsReferenceOnly;
1743 }
1745 return CEK_AsValueOnly;
1746 return CEK_None;
1747}
1748
1749/// Try to emit a reference to the given value without producing it as
1750/// an l-value. This is just an optimization, but it avoids us needing
1751/// to emit global copies of variables if they're named without triggering
1752/// a formal use in a context where we can't emit a direct reference to them,
1753/// for instance if a block or lambda or a member of a local class uses a
1754/// const int variable or constexpr variable from an enclosing function.
1755CodeGenFunction::ConstantEmission
1757 ValueDecl *value = refExpr->getDecl();
1758
1759 // The value needs to be an enum constant or a constant variable.
1761 if (isa<ParmVarDecl>(value)) {
1762 CEK = CEK_None;
1763 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1764 CEK = checkVarTypeForConstantEmission(var->getType());
1765 } else if (isa<EnumConstantDecl>(value)) {
1766 CEK = CEK_AsValueOnly;
1767 } else {
1768 CEK = CEK_None;
1769 }
1770 if (CEK == CEK_None) return ConstantEmission();
1771
1772 Expr::EvalResult result;
1773 bool resultIsReference;
1774 QualType resultType;
1775
1776 // It's best to evaluate all the way as an r-value if that's permitted.
1777 if (CEK != CEK_AsReferenceOnly &&
1778 refExpr->EvaluateAsRValue(result, getContext())) {
1779 resultIsReference = false;
1780 resultType = refExpr->getType();
1781
1782 // Otherwise, try to evaluate as an l-value.
1783 } else if (CEK != CEK_AsValueOnly &&
1784 refExpr->EvaluateAsLValue(result, getContext())) {
1785 resultIsReference = true;
1786 resultType = value->getType();
1787
1788 // Failure.
1789 } else {
1790 return ConstantEmission();
1791 }
1792
1793 // In any case, if the initializer has side-effects, abandon ship.
1794 if (result.HasSideEffects)
1795 return ConstantEmission();
1796
1797 // In CUDA/HIP device compilation, a lambda may capture a reference variable
1798 // referencing a global host variable by copy. In this case the lambda should
1799 // make a copy of the value of the global host variable. The DRE of the
1800 // captured reference variable cannot be emitted as load from the host
1801 // global variable as compile time constant, since the host variable is not
1802 // accessible on device. The DRE of the captured reference variable has to be
1803 // loaded from captures.
1804 if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1806 auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1807 if (MD && MD->getParent()->isLambda() &&
1808 MD->getOverloadedOperator() == OO_Call) {
1809 const APValue::LValueBase &base = result.Val.getLValueBase();
1810 if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1811 if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1812 if (!VD->hasAttr<CUDADeviceAttr>()) {
1813 return ConstantEmission();
1814 }
1815 }
1816 }
1817 }
1818 }
1819
1820 // Emit as a constant.
1821 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1822 result.Val, resultType);
1823
1824 // Make sure we emit a debug reference to the global variable.
1825 // This should probably fire even for
1826 if (isa<VarDecl>(value)) {
1827 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1828 EmitDeclRefExprDbgValue(refExpr, result.Val);
1829 } else {
1830 assert(isa<EnumConstantDecl>(value));
1831 EmitDeclRefExprDbgValue(refExpr, result.Val);
1832 }
1833
1834 // If we emitted a reference constant, we need to dereference that.
1835 if (resultIsReference)
1837
1839}
1840
1842 const MemberExpr *ME) {
1843 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1844 // Try to emit static variable member expressions as DREs.
1845 return DeclRefExpr::Create(
1847 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1848 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
1849 }
1850 return nullptr;
1851}
1852
1853CodeGenFunction::ConstantEmission
1856 return tryEmitAsConstant(DRE);
1857 return ConstantEmission();
1858}
1859
1861 const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1862 assert(Constant && "not a constant");
1863 if (Constant.isReference())
1864 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1865 E->getExprLoc())
1866 .getScalarVal();
1867 return Constant.getValue();
1868}
1869
1870llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1872 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1873 lvalue.getType(), Loc, lvalue.getBaseInfo(),
1874 lvalue.getTBAAInfo(), lvalue.isNontemporal());
1875}
1876
1878 if (Ty->isBooleanType())
1879 return true;
1880
1881 if (const EnumType *ET = Ty->getAs<EnumType>())
1882 return ET->getDecl()->getIntegerType()->isBooleanType();
1883
1884 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1885 return hasBooleanRepresentation(AT->getValueType());
1886
1887 return false;
1888}
1889
1891 llvm::APInt &Min, llvm::APInt &End,
1892 bool StrictEnums, bool IsBool) {
1893 const EnumType *ET = Ty->getAs<EnumType>();
1894 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1895 ET && !ET->getDecl()->isFixed();
1896 if (!IsBool && !IsRegularCPlusPlusEnum)
1897 return false;
1898
1899 if (IsBool) {
1900 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1901 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1902 } else {
1903 const EnumDecl *ED = ET->getDecl();
1904 ED->getValueRange(End, Min);
1905 }
1906 return true;
1907}
1908
1909llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1910 llvm::APInt Min, End;
1911 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1913 return nullptr;
1914
1915 llvm::MDBuilder MDHelper(getLLVMContext());
1916 return MDHelper.createRange(Min, End);
1917}
1918
1921 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1922 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1923 if (!HasBoolCheck && !HasEnumCheck)
1924 return false;
1925
1926 bool IsBool = hasBooleanRepresentation(Ty) ||
1928 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1929 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1930 if (!NeedsBoolCheck && !NeedsEnumCheck)
1931 return false;
1932
1933 // Single-bit booleans don't need to be checked. Special-case this to avoid
1934 // a bit width mismatch when handling bitfield values. This is handled by
1935 // EmitFromMemory for the non-bitfield case.
1936 if (IsBool &&
1937 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1938 return false;
1939
1940 if (NeedsEnumCheck &&
1941 getContext().isTypeIgnoredBySanitizer(SanitizerKind::Enum, Ty))
1942 return false;
1943
1944 llvm::APInt Min, End;
1945 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1946 return true;
1947
1948 auto &Ctx = getLLVMContext();
1949 SanitizerScope SanScope(this);
1950 llvm::Value *Check;
1951 --End;
1952 if (!Min) {
1953 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1954 } else {
1955 llvm::Value *Upper =
1956 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1957 llvm::Value *Lower =
1958 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1959 Check = Builder.CreateAnd(Upper, Lower);
1960 }
1961 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1964 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1965 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1966 StaticArgs, EmitCheckValue(Value));
1967 return true;
1968}
1969
1970llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1971 QualType Ty,
1973 LValueBaseInfo BaseInfo,
1974 TBAAAccessInfo TBAAInfo,
1975 bool isNontemporal) {
1976 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
1977 if (GV->isThreadLocal())
1978 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
1980
1981 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
1982 // Boolean vectors use `iN` as storage type.
1983 if (ClangVecTy->isExtVectorBoolType()) {
1984 llvm::Type *ValTy = ConvertType(Ty);
1985 unsigned ValNumElems =
1986 cast<llvm::FixedVectorType>(ValTy)->getNumElements();
1987 // Load the `iP` storage object (P is the padded vector size).
1988 auto *RawIntV = Builder.CreateLoad(Addr, Volatile, "load_bits");
1989 const auto *RawIntTy = RawIntV->getType();
1990 assert(RawIntTy->isIntegerTy() && "compressed iN storage for bitvectors");
1991 // Bitcast iP --> <P x i1>.
1992 auto *PaddedVecTy = llvm::FixedVectorType::get(
1993 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
1994 llvm::Value *V = Builder.CreateBitCast(RawIntV, PaddedVecTy);
1995 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
1996 V = emitBoolVecConversion(V, ValNumElems, "extractvec");
1997
1998 return EmitFromMemory(V, Ty);
1999 }
2000
2001 // Handle vectors of size 3 like size 4 for better performance.
2002 const llvm::Type *EltTy = Addr.getElementType();
2003 const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
2004
2005 if (!CGM.getCodeGenOpts().PreserveVec3Type && VTy->getNumElements() == 3) {
2006
2007 llvm::VectorType *vec4Ty =
2008 llvm::FixedVectorType::get(VTy->getElementType(), 4);
2009 Address Cast = Addr.withElementType(vec4Ty);
2010 // Now load value.
2011 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
2012
2013 // Shuffle vector to get vec3.
2014 V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2}, "extractVec");
2015 return EmitFromMemory(V, Ty);
2016 }
2017 }
2018
2019 // Atomic operations have to be done on integral types.
2020 LValue AtomicLValue =
2021 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2022 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
2023 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
2024 }
2025
2026 Addr =
2028
2029 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
2030 if (isNontemporal) {
2031 llvm::MDNode *Node = llvm::MDNode::get(
2032 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2033 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2034 }
2035
2036 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
2037
2038 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
2039 // In order to prevent the optimizer from throwing away the check, don't
2040 // attach range metadata to the load.
2041 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
2042 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
2043 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
2044 Load->setMetadata(llvm::LLVMContext::MD_noundef,
2045 llvm::MDNode::get(getLLVMContext(), {}));
2046 }
2047
2048 return EmitFromMemory(Load, Ty);
2049}
2050
2051/// Converts a scalar value from its primary IR type (as returned
2052/// by ConvertType) to its load/store type (as returned by
2053/// convertTypeForLoadStore).
2054llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
2055 if (hasBooleanRepresentation(Ty) || Ty->isBitIntType()) {
2056 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2058 return Builder.CreateIntCast(Value, StoreTy, Signed, "storedv");
2059 }
2060
2061 if (Ty->isExtVectorBoolType()) {
2062 llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
2063 // Expand to the memory bit width.
2064 unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits();
2065 // <N x i1> --> <P x i1>.
2066 Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
2067 // <P x i1> --> iP.
2068 Value = Builder.CreateBitCast(Value, StoreTy);
2069 }
2070
2071 return Value;
2072}
2073
2074/// Converts a scalar value from its load/store type (as returned
2075/// by convertTypeForLoadStore) to its primary IR type (as returned
2076/// by ConvertType).
2077llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
2078 if (Ty->isExtVectorBoolType()) {
2079 const auto *RawIntTy = Value->getType();
2080 // Bitcast iP --> <P x i1>.
2081 auto *PaddedVecTy = llvm::FixedVectorType::get(
2082 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2083 auto *V = Builder.CreateBitCast(Value, PaddedVecTy);
2084 // Shuffle <P x i1> --> <N x i1> (N is the actual bit size).
2085 llvm::Type *ValTy = ConvertType(Ty);
2086 unsigned ValNumElems = cast<llvm::FixedVectorType>(ValTy)->getNumElements();
2087 return emitBoolVecConversion(V, ValNumElems, "extractvec");
2088 }
2089
2090 if (hasBooleanRepresentation(Ty) || Ty->isBitIntType()) {
2091 llvm::Type *ResTy = ConvertType(Ty);
2092 return Builder.CreateTrunc(Value, ResTy, "loadedv");
2093 }
2094
2095 return Value;
2096}
2097
2098// Convert the pointer of \p Addr to a pointer to a vector (the value type of
2099// MatrixType), if it points to a array (the memory type of MatrixType).
2101 CodeGenFunction &CGF,
2102 bool IsVector = true) {
2103 auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
2104 if (ArrayTy && IsVector) {
2105 auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
2106 ArrayTy->getNumElements());
2107
2108 return Addr.withElementType(VectorTy);
2109 }
2110 auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
2111 if (VectorTy && !IsVector) {
2112 auto *ArrayTy = llvm::ArrayType::get(
2113 VectorTy->getElementType(),
2114 cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
2115
2116 return Addr.withElementType(ArrayTy);
2117 }
2118
2119 return Addr;
2120}
2121
2122// Emit a store of a matrix LValue. This may require casting the original
2123// pointer to memory address (ArrayType) to a pointer to the value type
2124// (VectorType).
2125static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
2126 bool isInit, CodeGenFunction &CGF) {
2127 Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(), CGF,
2128 value->getType()->isVectorTy());
2129 CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
2130 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
2131 lvalue.isNontemporal());
2132}
2133
2134void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
2135 bool Volatile, QualType Ty,
2136 LValueBaseInfo BaseInfo,
2137 TBAAAccessInfo TBAAInfo,
2138 bool isInit, bool isNontemporal) {
2139 if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr.getBasePointer()))
2140 if (GV->isThreadLocal())
2141 Addr = Addr.withPointer(Builder.CreateThreadLocalAddress(GV),
2143
2144 llvm::Type *SrcTy = Value->getType();
2145 if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
2146 auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy);
2147 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
2148 // Handle vec3 special.
2149 if (VecTy && !ClangVecTy->isExtVectorBoolType() &&
2150 cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
2151 // Our source is a vec3, do a shuffle vector to make it a vec4.
2152 Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
2153 "extractVec");
2154 SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
2155 }
2156 if (Addr.getElementType() != SrcTy) {
2157 Addr = Addr.withElementType(SrcTy);
2158 }
2159 }
2160 }
2161
2162 Value = EmitToMemory(Value, Ty);
2163
2164 LValue AtomicLValue =
2165 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
2166 if (Ty->isAtomicType() ||
2167 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
2168 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
2169 return;
2170 }
2171
2172 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
2173 if (isNontemporal) {
2174 llvm::MDNode *Node =
2175 llvm::MDNode::get(Store->getContext(),
2176 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
2177 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2178 }
2179
2180 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2181}
2182
2183void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
2184 bool isInit) {
2185 if (lvalue.getType()->isConstantMatrixType()) {
2186 EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
2187 return;
2188 }
2189
2190 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
2191 lvalue.getType(), lvalue.getBaseInfo(),
2192 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
2193}
2194
2195// Emit a load of a LValue of matrix type. This may require casting the pointer
2196// to memory address (ArrayType) to a pointer to the value type (VectorType).
2198 CodeGenFunction &CGF) {
2199 assert(LV.getType()->isConstantMatrixType());
2201 LV.setAddress(Addr);
2202 return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
2203}
2204
2207 QualType Ty = LV.getType();
2208 switch (getEvaluationKind(Ty)) {
2209 case TEK_Scalar:
2210 return EmitLoadOfLValue(LV, Loc);
2211 case TEK_Complex:
2213 case TEK_Aggregate:
2214 EmitAggFinalDestCopy(Ty, Slot, LV, EVK_NonRValue);
2215 return Slot.asRValue();
2216 }
2217 llvm_unreachable("bad evaluation kind");
2218}
2219
2220/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
2221/// method emits the address of the lvalue, then loads the result as an rvalue,
2222/// returning the rvalue.
2224 if (LV.isObjCWeak()) {
2225 // load of a __weak object.
2226 Address AddrWeakObj = LV.getAddress();
2228 AddrWeakObj));
2229 }
2231 // In MRC mode, we do a load+autorelease.
2232 if (!getLangOpts().ObjCAutoRefCount) {
2234 }
2235
2236 // In ARC mode, we load retained and then consume the value.
2237 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
2238 Object = EmitObjCConsumeObject(LV.getType(), Object);
2239 return RValue::get(Object);
2240 }
2241
2242 if (LV.isSimple()) {
2243 assert(!LV.getType()->isFunctionType());
2244
2245 if (LV.getType()->isConstantMatrixType())
2246 return EmitLoadOfMatrixLValue(LV, Loc, *this);
2247
2248 // Everything needs a load.
2249 return RValue::get(EmitLoadOfScalar(LV, Loc));
2250 }
2251
2252 if (LV.isVectorElt()) {
2253 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
2254 LV.isVolatileQualified());
2255 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
2256 "vecext"));
2257 }
2258
2259 // If this is a reference to a subset of the elements of a vector, either
2260 // shuffle the input or extract/insert them as appropriate.
2261 if (LV.isExtVectorElt()) {
2263 }
2264
2265 // Global Register variables always invoke intrinsics
2266 if (LV.isGlobalReg())
2267 return EmitLoadOfGlobalRegLValue(LV);
2268
2269 if (LV.isMatrixElt()) {
2270 llvm::Value *Idx = LV.getMatrixIdx();
2271 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2272 const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
2273 llvm::MatrixBuilder MB(Builder);
2274 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2275 }
2276 llvm::LoadInst *Load =
2278 return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
2279 }
2280
2281 assert(LV.isBitField() && "Unknown LValue type!");
2282 return EmitLoadOfBitfieldLValue(LV, Loc);
2283}
2284
2287 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
2288
2289 // Get the output type.
2290 llvm::Type *ResLTy = ConvertType(LV.getType());
2291
2292 Address Ptr = LV.getBitFieldAddress();
2293 llvm::Value *Val =
2294 Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
2295
2296 bool UseVolatile = LV.isVolatileQualified() &&
2297 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2298 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2299 const unsigned StorageSize =
2300 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2301 if (Info.IsSigned) {
2302 assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2303 unsigned HighBits = StorageSize - Offset - Info.Size;
2304 if (HighBits)
2305 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2306 if (Offset + HighBits)
2307 Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2308 } else {
2309 if (Offset)
2310 Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2311 if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2312 Val = Builder.CreateAnd(
2313 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2314 }
2315 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2316 EmitScalarRangeCheck(Val, LV.getType(), Loc);
2317 return RValue::get(Val);
2318}
2319
2320// If this is a reference to a subset of the elements of a vector, create an
2321// appropriate shufflevector.
2323 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2324 LV.isVolatileQualified());
2325
2326 // HLSL allows treating scalars as one-element vectors. Converting the scalar
2327 // IR value to a vector here allows the rest of codegen to behave as normal.
2328 if (getLangOpts().HLSL && !Vec->getType()->isVectorTy()) {
2329 llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2330 llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
2331 Vec = Builder.CreateInsertElement(DstTy, Vec, Zero, "cast.splat");
2332 }
2333
2334 const llvm::Constant *Elts = LV.getExtVectorElts();
2335
2336 // If the result of the expression is a non-vector type, we must be extracting
2337 // a single element. Just codegen as an extractelement.
2338 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2339 if (!ExprVT) {
2340 unsigned InIdx = getAccessedFieldNo(0, Elts);
2341 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2342 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
2343 }
2344
2345 // Always use shuffle vector to try to retain the original program structure
2346 unsigned NumResultElts = ExprVT->getNumElements();
2347
2349 for (unsigned i = 0; i != NumResultElts; ++i)
2350 Mask.push_back(getAccessedFieldNo(i, Elts));
2351
2352 Vec = Builder.CreateShuffleVector(Vec, Mask);
2353 return RValue::get(Vec);
2354}
2355
2356/// Generates lvalue for partial ext_vector access.
2358 Address VectorAddress = LV.getExtVectorAddress();
2359 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2360 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2361
2362 Address CastToPointerElement = VectorAddress.withElementType(VectorElementTy);
2363
2364 const llvm::Constant *Elts = LV.getExtVectorElts();
2365 unsigned ix = getAccessedFieldNo(0, Elts);
2366
2367 Address VectorBasePtrPlusIx =
2368 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2369 "vector.elt");
2370
2371 return VectorBasePtrPlusIx;
2372}
2373
2374/// Load of global named registers are always calls to intrinsics.
2376 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2377 "Bad type for register variable");
2378 llvm::MDNode *RegName = cast<llvm::MDNode>(
2379 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2380
2381 // We accept integer and pointer types only
2382 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2383 llvm::Type *Ty = OrigTy;
2384 if (OrigTy->isPointerTy())
2385 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2386 llvm::Type *Types[] = { Ty };
2387
2388 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2389 llvm::Value *Call = Builder.CreateCall(
2390 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2391 if (OrigTy->isPointerTy())
2392 Call = Builder.CreateIntToPtr(Call, OrigTy);
2393 return RValue::get(Call);
2394}
2395
2396/// EmitStoreThroughLValue - Store the specified rvalue into the specified
2397/// lvalue, where both are guaranteed to the have the same type, and that type
2398/// is 'Ty'.
2400 bool isInit) {
2401 if (!Dst.isSimple()) {
2402 if (Dst.isVectorElt()) {
2403 // Read/modify/write the vector, inserting the new element.
2404 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2405 Dst.isVolatileQualified());
2406 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2407 if (IRStoreTy) {
2408 auto *IRVecTy = llvm::FixedVectorType::get(
2409 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2410 Vec = Builder.CreateBitCast(Vec, IRVecTy);
2411 // iN --> <N x i1>.
2412 }
2413 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2414 Dst.getVectorIdx(), "vecins");
2415 if (IRStoreTy) {
2416 // <N x i1> --> <iN>.
2417 Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2418 }
2420 Dst.isVolatileQualified());
2421 return;
2422 }
2423
2424 // If this is an update of extended vector elements, insert them as
2425 // appropriate.
2426 if (Dst.isExtVectorElt())
2428
2429 if (Dst.isGlobalReg())
2430 return EmitStoreThroughGlobalRegLValue(Src, Dst);
2431
2432 if (Dst.isMatrixElt()) {
2433 llvm::Value *Idx = Dst.getMatrixIdx();
2434 if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2435 const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2436 llvm::MatrixBuilder MB(Builder);
2437 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2438 }
2439 llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2440 llvm::Value *Vec =
2441 Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
2443 Dst.isVolatileQualified());
2444 return;
2445 }
2446
2447 assert(Dst.isBitField() && "Unknown LValue type");
2448 return EmitStoreThroughBitfieldLValue(Src, Dst);
2449 }
2450
2451 // There's special magic for assigning into an ARC-qualified l-value.
2452 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2453 switch (Lifetime) {
2455 llvm_unreachable("present but none");
2456
2458 // nothing special
2459 break;
2460
2462 if (isInit) {
2463 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2464 break;
2465 }
2466 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2467 return;
2468
2470 if (isInit)
2471 // Initialize and then skip the primitive store.
2473 else
2475 /*ignore*/ true);
2476 return;
2477
2480 Src.getScalarVal()));
2481 // fall into the normal path
2482 break;
2483 }
2484 }
2485
2486 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2487 // load of a __weak object.
2488 Address LvalueDst = Dst.getAddress();
2489 llvm::Value *src = Src.getScalarVal();
2490 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2491 return;
2492 }
2493
2494 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2495 // load of a __strong object.
2496 Address LvalueDst = Dst.getAddress();
2497 llvm::Value *src = Src.getScalarVal();
2498 if (Dst.isObjCIvar()) {
2499 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2500 llvm::Type *ResultType = IntPtrTy;
2502 llvm::Value *RHS = dst.emitRawPointer(*this);
2503 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2504 llvm::Value *LHS = Builder.CreatePtrToInt(LvalueDst.emitRawPointer(*this),
2505 ResultType, "sub.ptr.lhs.cast");
2506 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2507 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst, BytesBetween);
2508 } else if (Dst.isGlobalObjCRef()) {
2509 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2510 Dst.isThreadLocalRef());
2511 }
2512 else
2513 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2514 return;
2515 }
2516
2517 assert(Src.isScalar() && "Can't emit an agg store with this method");
2518 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2519}
2520
2522 llvm::Value **Result) {
2523 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2524 llvm::Type *ResLTy = convertTypeForLoadStore(Dst.getType());
2525 Address Ptr = Dst.getBitFieldAddress();
2526
2527 // Get the source value, truncated to the width of the bit-field.
2528 llvm::Value *SrcVal = Src.getScalarVal();
2529
2530 // Cast the source to the storage type and shift it into place.
2531 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2532 /*isSigned=*/false);
2533 llvm::Value *MaskedVal = SrcVal;
2534
2535 const bool UseVolatile =
2536 CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2537 Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2538 const unsigned StorageSize =
2539 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2540 const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2541 // See if there are other bits in the bitfield's storage we'll need to load
2542 // and mask together with source before storing.
2543 if (StorageSize != Info.Size) {
2544 assert(StorageSize > Info.Size && "Invalid bitfield size.");
2545 llvm::Value *Val =
2546 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2547
2548 // Mask the source value as needed.
2550 SrcVal = Builder.CreateAnd(
2551 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
2552 "bf.value");
2553 MaskedVal = SrcVal;
2554 if (Offset)
2555 SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
2556
2557 // Mask out the original value.
2558 Val = Builder.CreateAnd(
2559 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
2560 "bf.clear");
2561
2562 // Or together the unchanged values and the source value.
2563 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2564 } else {
2565 assert(Offset == 0);
2566 // According to the AACPS:
2567 // When a volatile bit-field is written, and its container does not overlap
2568 // with any non-bit-field member, its container must be read exactly once
2569 // and written exactly once using the access width appropriate to the type
2570 // of the container. The two accesses are not atomic.
2571 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
2572 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
2573 Builder.CreateLoad(Ptr, true, "bf.load");
2574 }
2575
2576 // Write the new value back out.
2577 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2578
2579 // Return the new value of the bit-field, if requested.
2580 if (Result) {
2581 llvm::Value *ResultVal = MaskedVal;
2582
2583 // Sign extend the value if needed.
2584 if (Info.IsSigned) {
2585 assert(Info.Size <= StorageSize);
2586 unsigned HighBits = StorageSize - Info.Size;
2587 if (HighBits) {
2588 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2589 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2590 }
2591 }
2592
2593 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2594 "bf.result.cast");
2595 *Result = EmitFromMemory(ResultVal, Dst.getType());
2596 }
2597}
2598
2600 LValue Dst) {
2601 // HLSL allows storing to scalar values through ExtVector component LValues.
2602 // To support this we need to handle the case where the destination address is
2603 // a scalar.
2604 Address DstAddr = Dst.getExtVectorAddress();
2605 if (!DstAddr.getElementType()->isVectorTy()) {
2606 assert(!Dst.getType()->isVectorType() &&
2607 "this should only occur for non-vector l-values");
2608 Builder.CreateStore(Src.getScalarVal(), DstAddr, Dst.isVolatileQualified());
2609 return;
2610 }
2611
2612 // This access turns into a read/modify/write of the vector. Load the input
2613 // value now.
2614 llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
2615 const llvm::Constant *Elts = Dst.getExtVectorElts();
2616
2617 llvm::Value *SrcVal = Src.getScalarVal();
2618
2619 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2620 unsigned NumSrcElts = VTy->getNumElements();
2621 unsigned NumDstElts =
2622 cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
2623 if (NumDstElts == NumSrcElts) {
2624 // Use shuffle vector is the src and destination are the same number of
2625 // elements and restore the vector mask since it is on the side it will be
2626 // stored.
2627 SmallVector<int, 4> Mask(NumDstElts);
2628 for (unsigned i = 0; i != NumSrcElts; ++i)
2629 Mask[getAccessedFieldNo(i, Elts)] = i;
2630
2631 Vec = Builder.CreateShuffleVector(SrcVal, Mask);
2632 } else if (NumDstElts > NumSrcElts) {
2633 // Extended the source vector to the same length and then shuffle it
2634 // into the destination.
2635 // FIXME: since we're shuffling with undef, can we just use the indices
2636 // into that? This could be simpler.
2637 SmallVector<int, 4> ExtMask;
2638 for (unsigned i = 0; i != NumSrcElts; ++i)
2639 ExtMask.push_back(i);
2640 ExtMask.resize(NumDstElts, -1);
2641 llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
2642 // build identity
2644 for (unsigned i = 0; i != NumDstElts; ++i)
2645 Mask.push_back(i);
2646
2647 // When the vector size is odd and .odd or .hi is used, the last element
2648 // of the Elts constant array will be one past the size of the vector.
2649 // Ignore the last element here, if it is greater than the mask size.
2650 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2651 NumSrcElts--;
2652
2653 // modify when what gets shuffled in
2654 for (unsigned i = 0; i != NumSrcElts; ++i)
2655 Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
2656 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2657 } else {
2658 // We should never shorten the vector
2659 llvm_unreachable("unexpected shorten vector length");
2660 }
2661 } else {
2662 // If the Src is a scalar (not a vector), and the target is a vector it must
2663 // be updating one element.
2664 unsigned InIdx = getAccessedFieldNo(0, Elts);
2665 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2666 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2667 }
2668
2670 Dst.isVolatileQualified());
2671}
2672
2673/// Store of global named registers are always calls to intrinsics.
2675 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2676 "Bad type for register variable");
2677 llvm::MDNode *RegName = cast<llvm::MDNode>(
2678 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2679 assert(RegName && "Register LValue is not metadata");
2680
2681 // We accept integer and pointer types only
2682 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2683 llvm::Type *Ty = OrigTy;
2684 if (OrigTy->isPointerTy())
2685 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2686 llvm::Type *Types[] = { Ty };
2687
2688 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2689 llvm::Value *Value = Src.getScalarVal();
2690 if (OrigTy->isPointerTy())
2691 Value = Builder.CreatePtrToInt(Value, Ty);
2692 Builder.CreateCall(
2693 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2694}
2695
2696// setObjCGCLValueClass - sets class of the lvalue for the purpose of
2697// generating write-barries API. It is currently a global, ivar,
2698// or neither.
2699static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2700 LValue &LV,
2701 bool IsMemberAccess=false) {
2702 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2703 return;
2704
2705 if (isa<ObjCIvarRefExpr>(E)) {
2706 QualType ExpTy = E->getType();
2707 if (IsMemberAccess && ExpTy->isPointerType()) {
2708 // If ivar is a structure pointer, assigning to field of
2709 // this struct follows gcc's behavior and makes it a non-ivar
2710 // writer-barrier conservatively.
2711 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2712 if (ExpTy->isRecordType()) {
2713 LV.setObjCIvar(false);
2714 return;
2715 }
2716 }
2717 LV.setObjCIvar(true);
2718 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2719 LV.setBaseIvarExp(Exp->getBase());
2721 return;
2722 }
2723
2724 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2725 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2726 if (VD->hasGlobalStorage()) {
2727 LV.setGlobalObjCRef(true);
2728 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2729 }
2730 }
2732 return;
2733 }
2734
2735 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2736 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2737 return;
2738 }
2739
2740 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2741 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2742 if (LV.isObjCIvar()) {
2743 // If cast is to a structure pointer, follow gcc's behavior and make it
2744 // a non-ivar write-barrier.
2745 QualType ExpTy = E->getType();
2746 if (ExpTy->isPointerType())
2747 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2748 if (ExpTy->isRecordType())
2749 LV.setObjCIvar(false);
2750 }
2751 return;
2752 }
2753
2754 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2755 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2756 return;
2757 }
2758
2759 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2760 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2761 return;
2762 }
2763
2764 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2765 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2766 return;
2767 }
2768
2769 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2770 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2771 return;
2772 }
2773
2774 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2775 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2776 if (LV.isObjCIvar() && !LV.isObjCArray())
2777 // Using array syntax to assigning to what an ivar points to is not
2778 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2779 LV.setObjCIvar(false);
2780 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2781 // Using array syntax to assigning to what global points to is not
2782 // same as assigning to the global itself. {id *G;} G[i] = 0;
2783 LV.setGlobalObjCRef(false);
2784 return;
2785 }
2786
2787 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2788 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2789 // We don't know if member is an 'ivar', but this flag is looked at
2790 // only in the context of LV.isObjCIvar().
2792 return;
2793 }
2794}
2795
2797 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2798 llvm::Type *RealVarTy, SourceLocation Loc) {
2799 if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
2801 CGF, VD, Addr, Loc);
2802 else
2803 Addr =
2804 CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2805
2806 Addr = Addr.withElementType(RealVarTy);
2807 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2808}
2809
2811 const VarDecl *VD, QualType T) {
2812 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2813 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2814 // Return an invalid address if variable is MT_To (or MT_Enter starting with
2815 // OpenMP 5.2) and unified memory is not enabled. For all other cases: MT_Link
2816 // and MT_To (or MT_Enter) with unified memory, return a valid address.
2817 if (!Res || ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2818 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
2820 return Address::invalid();
2821 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2822 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
2823 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
2825 "Expected link clause OR to clause with unified memory enabled.");
2826 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2828 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
2829}
2830
2831Address
2833 LValueBaseInfo *PointeeBaseInfo,
2834 TBAAAccessInfo *PointeeTBAAInfo) {
2835 llvm::LoadInst *Load =
2836 Builder.CreateLoad(RefLVal.getAddress(), RefLVal.isVolatile());
2838 return makeNaturalAddressForPointer(Load, RefLVal.getType()->getPointeeType(),
2839 CharUnits(), /*ForPointeeType=*/true,
2840 PointeeBaseInfo, PointeeTBAAInfo);
2841}
2842
2844 LValueBaseInfo PointeeBaseInfo;
2845 TBAAAccessInfo PointeeTBAAInfo;
2846 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2847 &PointeeTBAAInfo);
2848 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2849 PointeeBaseInfo, PointeeTBAAInfo);
2850}
2851
2853 const PointerType *PtrTy,
2854 LValueBaseInfo *BaseInfo,
2855 TBAAAccessInfo *TBAAInfo) {
2856 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2857 return makeNaturalAddressForPointer(Addr, PtrTy->getPointeeType(),
2858 CharUnits(), /*ForPointeeType=*/true,
2859 BaseInfo, TBAAInfo);
2860}
2861
2863 const PointerType *PtrTy) {
2864 LValueBaseInfo BaseInfo;
2865 TBAAAccessInfo TBAAInfo;
2866 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2867 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2868}
2869
2871 const Expr *E, const VarDecl *VD) {
2872 QualType T = E->getType();
2873
2874 // If it's thread_local, emit a call to its wrapper function instead.
2875 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2877 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2878 // Check if the variable is marked as declare target with link clause in
2879 // device codegen.
2880 if (CGF.getLangOpts().OpenMPIsTargetDevice) {
2881 Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
2882 if (Addr.isValid())
2883 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2884 }
2885
2886 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2887
2888 if (VD->getTLSKind() != VarDecl::TLS_None)
2889 V = CGF.Builder.CreateThreadLocalAddress(V);
2890
2891 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2892 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2893 Address Addr(V, RealVarTy, Alignment);
2894 // Emit reference to the private copy of the variable if it is an OpenMP
2895 // threadprivate variable.
2896 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2897 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2898 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2899 E->getExprLoc());
2900 }
2901 LValue LV = VD->getType()->isReferenceType() ?
2902 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2905 setObjCGCLValueClass(CGF.getContext(), E, LV);
2906 return LV;
2907}
2908
2910 llvm::Type *Ty) {
2911 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2912 if (FD->hasAttr<WeakRefAttr>()) {
2914 return aliasee.getPointer();
2915 }
2916
2917 llvm::Constant *V = GetAddrOfFunction(GD, Ty);
2918 return V;
2919}
2920
2922 GlobalDecl GD) {
2923 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2924 llvm::Constant *V = CGF.CGM.getFunctionPointer(GD);
2925 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2926 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2928}
2929
2931 llvm::Value *ThisValue) {
2932
2933 return CGF.EmitLValueForLambdaField(FD, ThisValue);
2934}
2935
2936/// Named Registers are named metadata pointing to the register name
2937/// which will be read from/written to as an argument to the intrinsic
2938/// @llvm.read/write_register.
2939/// So far, only the name is being passed down, but other options such as
2940/// register type, allocation type or even optimization options could be
2941/// passed down via the metadata node.
2943 SmallString<64> Name("llvm.named.register.");
2944 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2945 assert(Asm->getLabel().size() < 64-Name.size() &&
2946 "Register name too big");
2947 Name.append(Asm->getLabel());
2948 llvm::NamedMDNode *M =
2949 CGM.getModule().getOrInsertNamedMetadata(Name);
2950 if (M->getNumOperands() == 0) {
2951 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2952 Asm->getLabel());
2953 llvm::Metadata *Ops[] = {Str};
2954 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2955 }
2956
2957 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2958
2959 llvm::Value *Ptr =
2960 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2961 return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
2962}
2963
2964/// Determine whether we can emit a reference to \p VD from the current
2965/// context, despite not necessarily having seen an odr-use of the variable in
2966/// this context.
2968 const DeclRefExpr *E,
2969 const VarDecl *VD) {
2970 // For a variable declared in an enclosing scope, do not emit a spurious
2971 // reference even if we have a capture, as that will emit an unwarranted
2972 // reference to our capture state, and will likely generate worse code than
2973 // emitting a local copy.
2974 if (E->refersToEnclosingVariableOrCapture())
2975 return false;
2976
2977 // For a local declaration declared in this function, we can always reference
2978 // it even if we don't have an odr-use.
2979 if (VD->hasLocalStorage()) {
2980 return VD->getDeclContext() ==
2981 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2982 }
2983
2984 // For a global declaration, we can emit a reference to it if we know
2985 // for sure that we are able to emit a definition of it.
2986 VD = VD->getDefinition(CGF.getContext());
2987 if (!VD)
2988 return false;
2989
2990 // Don't emit a spurious reference if it might be to a variable that only
2991 // exists on a different device / target.
2992 // FIXME: This is unnecessarily broad. Check whether this would actually be a
2993 // cross-target reference.
2994 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
2995 CGF.getLangOpts().OpenCL) {
2996 return false;
2997 }
2998
2999 // We can emit a spurious reference only if the linkage implies that we'll
3000 // be emitting a non-interposable symbol that will be retained until link
3001 // time.
3002 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD)) {
3003 case llvm::GlobalValue::ExternalLinkage:
3004 case llvm::GlobalValue::LinkOnceODRLinkage:
3005 case llvm::GlobalValue::WeakODRLinkage:
3006 case llvm::GlobalValue::InternalLinkage:
3007 case llvm::GlobalValue::PrivateLinkage:
3008 return true;
3009 default:
3010 return false;
3011 }
3012}
3013
3015 const NamedDecl *ND = E->getDecl();
3016 QualType T = E->getType();
3017
3018 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
3019 "should not emit an unevaluated operand");
3020
3021 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3022 // Global Named registers access via intrinsics only
3023 if (VD->getStorageClass() == SC_Register &&
3024 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3025 return EmitGlobalNamedRegister(VD, CGM);
3026
3027 // If this DeclRefExpr does not constitute an odr-use of the variable,
3028 // we're not permitted to emit a reference to it in general, and it might
3029 // not be captured if capture would be necessary for a use. Emit the
3030 // constant value directly instead.
3031 if (E->isNonOdrUse() == NOUR_Constant &&
3032 (VD->getType()->isReferenceType() ||
3033 !canEmitSpuriousReferenceToVariable(*this, E, VD))) {
3034 VD->getAnyInitializer(VD);
3035 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
3036 E->getLocation(), *VD->evaluateValue(), VD->getType());
3037 assert(Val && "failed to emit constant expression");
3038
3039 Address Addr = Address::invalid();
3040 if (!VD->getType()->isReferenceType()) {
3041 // Spill the constant value to a global.
3042 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
3043 getContext().getDeclAlign(VD));
3044 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
3045 auto *PTy = llvm::PointerType::get(
3046 VarTy, getTypes().getTargetAddressSpace(VD->getType()));
3047 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
3048 } else {
3049 // Should we be using the alignment of the constant pointer we emitted?
3050 CharUnits Alignment =
3052 /* BaseInfo= */ nullptr,
3053 /* TBAAInfo= */ nullptr,
3054 /* forPointeeType= */ true);
3055 Addr = makeNaturalAddressForPointer(Val, T, Alignment);
3056 }
3057 return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
3058 }
3059
3060 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
3061
3062 // Check for captured variables.
3063 if (E->refersToEnclosingVariableOrCapture()) {
3064 VD = VD->getCanonicalDecl();
3065 if (auto *FD = LambdaCaptureFields.lookup(VD))
3066 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3067 if (CapturedStmtInfo) {
3068 auto I = LocalDeclMap.find(VD);
3069 if (I != LocalDeclMap.end()) {
3070 LValue CapLVal;
3071 if (VD->getType()->isReferenceType())
3072 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
3074 else
3075 CapLVal = MakeAddrLValue(I->second, T);
3076 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3077 // in simd context.
3078 if (getLangOpts().OpenMP &&
3080 CapLVal.setNontemporal(/*Value=*/true);
3081 return CapLVal;
3082 }
3083 LValue CapLVal =
3086 Address LValueAddress = CapLVal.getAddress();
3087 CapLVal = MakeAddrLValue(Address(LValueAddress.emitRawPointer(*this),
3088 LValueAddress.getElementType(),
3089 getContext().getDeclAlign(VD)),
3090 CapLVal.getType(),
3092 CapLVal.getTBAAInfo());
3093 // Mark lvalue as nontemporal if the variable is marked as nontemporal
3094 // in simd context.
3095 if (getLangOpts().OpenMP &&
3097 CapLVal.setNontemporal(/*Value=*/true);
3098 return CapLVal;
3099 }
3100
3101 assert(isa<BlockDecl>(CurCodeDecl));
3102 Address addr = GetAddrOfBlockDecl(VD);
3103 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
3104 }
3105 }
3106
3107 // FIXME: We should be able to assert this for FunctionDecls as well!
3108 // FIXME: We should be able to assert this for all DeclRefExprs, not just
3109 // those with a valid source location.
3110 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
3111 !E->getLocation().isValid()) &&
3112 "Should not use decl without marking it used!");
3113
3114 if (ND->hasAttr<WeakRefAttr>()) {
3115 const auto *VD = cast<ValueDecl>(ND);
3117 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
3118 }
3119
3120 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
3121 // Check if this is a global variable.
3122 if (VD->hasLinkage() || VD->isStaticDataMember())
3123 return EmitGlobalVarDeclLValue(*this, E, VD);
3124
3125 Address addr = Address::invalid();
3126
3127 // The variable should generally be present in the local decl map.
3128 auto iter = LocalDeclMap.find(VD);
3129 if (iter != LocalDeclMap.end()) {
3130 addr = iter->second;
3131
3132 // Otherwise, it might be static local we haven't emitted yet for
3133 // some reason; most likely, because it's in an outer function.
3134 } else if (VD->isStaticLocal()) {
3135 llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
3137 addr = Address(
3138 var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
3139
3140 // No other cases for now.
3141 } else {
3142 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
3143 }
3144
3145 // Handle threadlocal function locals.
3146 if (VD->getTLSKind() != VarDecl::TLS_None)
3147 addr = addr.withPointer(
3148 Builder.CreateThreadLocalAddress(addr.getBasePointer()),
3150
3151 // Check for OpenMP threadprivate variables.
3152 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
3153 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3155 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
3156 E->getExprLoc());
3157 }
3158
3159 // Drill into block byref variables.
3160 bool isBlockByref = VD->isEscapingByref();
3161 if (isBlockByref) {
3162 addr = emitBlockByrefAddress(addr, VD);
3163 }
3164
3165 // Drill into reference types.
3166 LValue LV = VD->getType()->isReferenceType() ?
3167 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
3169
3170 bool isLocalStorage = VD->hasLocalStorage();
3171
3172 bool NonGCable = isLocalStorage &&
3173 !VD->getType()->isReferenceType() &&
3174 !isBlockByref;
3175 if (NonGCable) {
3177 LV.setNonGC(true);
3178 }
3179
3180 bool isImpreciseLifetime =
3181 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3182 if (isImpreciseLifetime)
3185 return LV;
3186 }
3187
3188 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3189 return EmitFunctionDeclLValue(*this, E, FD);
3190
3191 // FIXME: While we're emitting a binding from an enclosing scope, all other
3192 // DeclRefExprs we see should be implicitly treated as if they also refer to
3193 // an enclosing scope.
3194 if (const auto *BD = dyn_cast<BindingDecl>(ND)) {
3195 if (E->refersToEnclosingVariableOrCapture()) {
3196 auto *FD = LambdaCaptureFields.lookup(BD);
3197 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
3198 }
3199 return EmitLValue(BD->getBinding());
3200 }
3201
3202 // We can form DeclRefExprs naming GUID declarations when reconstituting
3203 // non-type template parameters into expressions.
3204 if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
3207
3208 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3209 auto ATPO = CGM.GetAddrOfTemplateParamObject(TPO);
3210 auto AS = getLangASFromTargetAS(ATPO.getAddressSpace());
3211
3212 if (AS != T.getAddressSpace()) {
3213 auto TargetAS = getContext().getTargetAddressSpace(T.getAddressSpace());
3214 auto PtrTy = llvm::PointerType::get(CGM.getLLVMContext(), TargetAS);
3216 CGM, ATPO.getPointer(), AS, T.getAddressSpace(), PtrTy);
3217 ATPO = ConstantAddress(ASC, ATPO.getElementType(), ATPO.getAlignment());
3218 }
3219
3220 return MakeAddrLValue(ATPO, T, AlignmentSource::Decl);
3221 }
3222
3223 llvm_unreachable("Unhandled DeclRefExpr");
3224}
3225
3227 // __extension__ doesn't affect lvalue-ness.
3228 if (E->getOpcode() == UO_Extension)
3229 return EmitLValue(E->getSubExpr());
3230
3231 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
3232 switch (E->getOpcode()) {
3233 default: llvm_unreachable("Unknown unary operator lvalue!");
3234 case UO_Deref: {
3235 QualType T = E->getSubExpr()->getType()->getPointeeType();
3236 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3237
3238 LValueBaseInfo BaseInfo;
3239 TBAAAccessInfo TBAAInfo;
3240 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
3241 &TBAAInfo);
3242 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
3244
3245 // We should not generate __weak write barrier on indirect reference
3246 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
3247 // But, we continue to generate __strong write barrier on indirect write
3248 // into a pointer to object.
3249 if (getLangOpts().ObjC &&
3250 getLangOpts().getGC() != LangOptions::NonGC &&
3251 LV.isObjCWeak())
3253 return LV;
3254 }
3255 case UO_Real:
3256 case UO_Imag: {
3257 LValue LV = EmitLValue(E->getSubExpr());
3258 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
3259
3260 // __real is valid on scalars. This is a faster way of testing that.
3261 // __imag can only produce an rvalue on scalars.
3262 if (E->getOpcode() == UO_Real &&
3263 !LV.getAddress().getElementType()->isStructTy()) {
3264 assert(E->getSubExpr()->getType()->isArithmeticType());
3265 return LV;
3266 }
3267
3268 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
3269
3270 Address Component =
3271 (E->getOpcode() == UO_Real
3273 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
3274 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
3276 ElemLV.getQuals().addQualifiers(LV.getQuals());
3277 return ElemLV;
3278 }
3279 case UO_PreInc:
3280 case UO_PreDec: {
3281 LValue LV = EmitLValue(E->getSubExpr());
3282 bool isInc = E->getOpcode() == UO_PreInc;
3283
3284 if (E->getType()->isAnyComplexType())
3285 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
3286 else
3287 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
3288 return LV;
3289 }
3290 }
3291}
3292
3296}
3297
3301}
3302
3304 auto SL = E->getFunctionName();
3305 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3306 StringRef FnName = CurFn->getName();
3307 if (FnName.starts_with("\01"))
3308 FnName = FnName.substr(1);
3309 StringRef NameItems[] = {
3310 PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
3311 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3312 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3313 std::string Name = std::string(SL->getString());
3314 if (!Name.empty()) {
3315 unsigned Discriminator =
3317 if (Discriminator)
3318 Name += "_" + Twine(Discriminator + 1).str();
3319 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
3321 } else {
3322 auto C =
3323 CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
3325 }
3326 }
3327 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3329}
3330
3331/// Emit a type description suitable for use by a runtime sanitizer library. The
3332/// format of a type descriptor is
3333///
3334/// \code
3335/// { i16 TypeKind, i16 TypeInfo }
3336/// \endcode
3337///
3338/// followed by an array of i8 containing the type name with extra information
3339/// for BitInt. TypeKind is TK_Integer(0) for an integer, TK_Float(1) for a
3340/// floating point value, TK_BitInt(2) for BitInt and TK_Unknown(0xFFFF) for
3341/// anything else.
3343 // Only emit each type's descriptor once.
3344 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3345 return C;
3346
3347 uint16_t TypeKind = TK_Unknown;
3348 uint16_t TypeInfo = 0;
3349 bool IsBitInt = false;
3350
3351 if (T->isIntegerType()) {
3352 TypeKind = TK_Integer;
3353 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3354 (T->isSignedIntegerType() ? 1 : 0);
3355 // Follow suggestion from discussion of issue 64100.
3356 // So we can write the exact amount of bits in TypeName after '\0'
3357 // making it <diagnostic-like type name>.'\0'.<32-bit width>.
3358 if (T->isSignedIntegerType() && T->getAs<BitIntType>()) {
3359 // Do a sanity checks as we are using 32-bit type to store bit length.
3360 assert(getContext().getTypeSize(T) > 0 &&
3361 " non positive amount of bits in __BitInt type");
3362 assert(getContext().getTypeSize(T) <= 0xFFFFFFFF &&
3363 " too many bits in __BitInt type");
3364
3365 // Redefine TypeKind with the actual __BitInt type if we have signed
3366 // BitInt.
3367 TypeKind = TK_BitInt;
3368 IsBitInt = true;
3369 }
3370 } else if (T->isFloatingType()) {
3371 TypeKind = TK_Float;
3373 }
3374
3375 // Format the type name as if for a diagnostic, including quotes and
3376 // optionally an 'aka'.
3377 SmallString<32> Buffer;
3379 (intptr_t)T.getAsOpaquePtr(), StringRef(),
3380 StringRef(), {}, Buffer, {});
3381
3382 if (IsBitInt) {
3383 // The Structure is: 0 to end the string, 32 bit unsigned integer in target
3384 // endianness, zero.
3385 char S[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};
3386 const auto *EIT = T->castAs<BitIntType>();
3387 uint32_t Bits = EIT->getNumBits();
3388 llvm::support::endian::write32(S + 1, Bits,
3389 getTarget().isBigEndian()
3390 ? llvm::endianness::big
3391 : llvm::endianness::little);
3392 StringRef Str = StringRef(S, sizeof(S) / sizeof(decltype(S[0])));
3393 Buffer.append(Str);
3394 }
3395
3396 llvm::Constant *Components[] = {
3397 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3398 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3399 };
3400 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3401
3402 auto *GV = new llvm::GlobalVariable(
3403 CGM.getModule(), Descriptor->getType(),
3404 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3405 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3407
3408 // Remember the descriptor for this type.
3410
3411 return GV;
3412}
3413
3414llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3415 llvm::Type *TargetTy = IntPtrTy;
3416
3417 if (V->getType() == TargetTy)
3418 return V;
3419
3420 // Floating-point types which fit into intptr_t are bitcast to integers
3421 // and then passed directly (after zero-extension, if necessary).
3422 if (V->getType()->isFloatingPointTy()) {
3423 unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedValue();
3424 if (Bits <= TargetTy->getIntegerBitWidth())
3425 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
3426 Bits));
3427 }
3428
3429 // Integers which fit in intptr_t are zero-extended and passed directly.
3430 if (V->getType()->isIntegerTy() &&
3431 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
3432 return Builder.CreateZExt(V, TargetTy);
3433
3434 // Pointers are passed directly, everything else is passed by address.
3435 if (!V->getType()->isPointerTy()) {
3436 RawAddress Ptr = CreateDefaultAlignTempAlloca(V->getType());
3437 Builder.CreateStore(V, Ptr);
3438 V = Ptr.getPointer();
3439 }
3440 return Builder.CreatePtrToInt(V, TargetTy);
3441}
3442
3443/// Emit a representation of a SourceLocation for passing to a handler
3444/// in a sanitizer runtime library. The format for this data is:
3445/// \code
3446/// struct SourceLocation {
3447/// const char *Filename;
3448/// int32_t Line, Column;
3449/// };
3450/// \endcode
3451/// For an invalid SourceLocation, the Filename pointer is null.
3453 llvm::Constant *Filename;
3454 int Line, Column;
3455
3457 if (PLoc.isValid()) {
3458 StringRef FilenameString = PLoc.getFilename();
3459
3460 int PathComponentsToStrip =
3461 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3462 if (PathComponentsToStrip < 0) {
3463 assert(PathComponentsToStrip != INT_MIN);
3464 int PathComponentsToKeep = -PathComponentsToStrip;
3465 auto I = llvm::sys::path::rbegin(FilenameString);
3466 auto E = llvm::sys::path::rend(FilenameString);
3467 while (I != E && --PathComponentsToKeep)
3468 ++I;
3469
3470 FilenameString = FilenameString.substr(I - E);
3471 } else if (PathComponentsToStrip > 0) {
3472 auto I = llvm::sys::path::begin(FilenameString);
3473 auto E = llvm::sys::path::end(FilenameString);
3474 while (I != E && PathComponentsToStrip--)
3475 ++I;
3476
3477 if (I != E)
3478 FilenameString =
3479 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3480 else
3481 FilenameString = llvm::sys::path::filename(FilenameString);
3482 }
3483
3484 auto FilenameGV =
3485 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3487 cast<llvm::GlobalVariable>(
3488 FilenameGV.getPointer()->stripPointerCasts()));
3489 Filename = FilenameGV.getPointer();
3490 Line = PLoc.getLine();
3491 Column = PLoc.getColumn();
3492 } else {
3493 Filename = llvm::Constant::getNullValue(Int8PtrTy);
3494 Line = Column = 0;
3495 }
3496
3497 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3498 Builder.getInt32(Column)};
3499
3500 return llvm::ConstantStruct::getAnon(Data);
3501}
3502
3503namespace {
3504/// Specify under what conditions this check can be recovered
3505enum class CheckRecoverableKind {
3506 /// Always terminate program execution if this check fails.
3508 /// Check supports recovering, runtime has both fatal (noreturn) and
3509 /// non-fatal handlers for this check.
3510 Recoverable,
3511 /// Runtime conditionally aborts, always need to support recovery.
3513};
3514}
3515
3516static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
3517 assert(Kind.countPopulation() == 1);
3518 if (Kind == SanitizerKind::Vptr)
3519 return CheckRecoverableKind::AlwaysRecoverable;
3520 else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
3521 return CheckRecoverableKind::Unrecoverable;
3522 else
3523 return CheckRecoverableKind::Recoverable;
3524}
3525
3526namespace {
3527struct SanitizerHandlerInfo {
3528 char const *const Name;
3529 unsigned Version;
3530};
3531}
3532
3533const SanitizerHandlerInfo SanitizerHandlers[] = {
3534#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
3536#undef SANITIZER_CHECK
3537};
3538
3540 llvm::FunctionType *FnType,
3542 SanitizerHandler CheckHandler,
3543 CheckRecoverableKind RecoverKind, bool IsFatal,
3544 llvm::BasicBlock *ContBB, bool NoMerge) {
3545 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3546 std::optional<ApplyDebugLocation> DL;
3547 if (!CGF.Builder.getCurrentDebugLocation()) {
3548 // Ensure that the call has at least an artificial debug location.
3549 DL.emplace(CGF, SourceLocation());
3550 }
3551 bool NeedsAbortSuffix =
3552 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
3553 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3554 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3555 const StringRef CheckName = CheckInfo.Name;
3556 std::string FnName = "__ubsan_handle_" + CheckName.str();
3557 if (CheckInfo.Version && !MinimalRuntime)
3558 FnName += "_v" + llvm::utostr(CheckInfo.Version);
3559 if (MinimalRuntime)
3560 FnName += "_minimal";
3561 if (NeedsAbortSuffix)
3562 FnName += "_abort";
3563 bool MayReturn =
3564 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3565
3566 llvm::AttrBuilder B(CGF.getLLVMContext());
3567 if (!MayReturn) {
3568 B.addAttribute(llvm::Attribute::NoReturn)
3569 .addAttribute(llvm::Attribute::NoUnwind);
3570 }
3571 B.addUWTableAttr(llvm::UWTableKind::Default);
3572
3573 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3574 FnType, FnName,
3575 llvm::AttributeList::get(CGF.getLLVMContext(),
3576 llvm::AttributeList::FunctionIndex, B),
3577 /*Local=*/true);
3578 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3579 NoMerge = NoMerge || !CGF.CGM.getCodeGenOpts().OptimizationLevel ||
3580 (CGF.CurCodeDecl && CGF.CurCodeDecl->hasAttr<OptimizeNoneAttr>());
3581 if (NoMerge)
3582 HandlerCall->addFnAttr(llvm::Attribute::NoMerge);
3583 if (!MayReturn) {
3584 HandlerCall->setDoesNotReturn();
3585 CGF.Builder.CreateUnreachable();
3586 } else {
3587 CGF.Builder.CreateBr(ContBB);
3588 }
3589}
3590
3592 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3593 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3594 ArrayRef<llvm::Value *> DynamicArgs) {
3595 assert(IsSanitizerScope);
3596 assert(Checked.size() > 0);
3597 assert(CheckHandler >= 0 &&
3598 size_t(CheckHandler) < std::size(SanitizerHandlers));
3599 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3600
3601 llvm::Value *FatalCond = nullptr;
3602 llvm::Value *RecoverableCond = nullptr;
3603 llvm::Value *TrapCond = nullptr;
3604 bool NoMerge = false;
3605 for (int i = 0, n = Checked.size(); i < n; ++i) {
3606 llvm::Value *Check = Checked[i].first;
3607 // -fsanitize-trap= overrides -fsanitize-recover=.
3608 llvm::Value *&Cond =
3609 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3610 ? TrapCond
3611 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
3612 ? RecoverableCond
3613 : FatalCond;
3614 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
3615
3616 if (!CGM.getCodeGenOpts().SanitizeMergeHandlers.has(Checked[i].second))
3617 NoMerge = true;
3618 }
3619
3621 llvm::Value *Allow =
3622 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check),
3623 llvm::ConstantInt::get(CGM.Int8Ty, CheckHandler));
3624
3625 for (llvm::Value **Cond : {&FatalCond, &RecoverableCond, &TrapCond}) {
3626 if (*Cond)
3627 *Cond = Builder.CreateOr(*Cond, Builder.CreateNot(Allow));
3628 }
3629 }
3630
3631 if (TrapCond)
3632 EmitTrapCheck(TrapCond, CheckHandler, NoMerge);
3633 if (!FatalCond && !RecoverableCond)
3634 return;
3635
3636 llvm::Value *JointCond;
3637 if (FatalCond && RecoverableCond)
3638 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3639 else
3640 JointCond = FatalCond ? FatalCond : RecoverableCond;
3641 assert(JointCond);
3642
3643 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3644 assert(SanOpts.has(Checked[0].second));
3645#ifndef NDEBUG
3646 for (int i = 1, n = Checked.size(); i < n; ++i) {
3647 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3648 "All recoverable kinds in a single check must be same!");
3649 assert(SanOpts.has(Checked[i].second));
3650 }
3651#endif
3652
3653 llvm::BasicBlock *Cont = createBasicBlock("cont");
3654 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3655 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3656 // Give hint that we very much don't expect to execute the handler
3657 llvm::MDBuilder MDHelper(getLLVMContext());
3658 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
3659 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3660 EmitBlock(Handlers);
3661
3662 // Handler functions take an i8* pointing to the (handler-specific) static
3663 // information block, followed by a sequence of intptr_t arguments
3664 // representing operand values.
3667 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3668 Args.reserve(DynamicArgs.size() + 1);
3669 ArgTypes.reserve(DynamicArgs.size() + 1);
3670
3671 // Emit handler arguments and create handler function type.
3672 if (!StaticArgs.empty()) {
3673 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3674 auto *InfoPtr = new llvm::GlobalVariable(
3675 CGM.getModule(), Info->getType(), false,
3676 llvm::GlobalVariable::PrivateLinkage, Info, "", nullptr,
3677 llvm::GlobalVariable::NotThreadLocal,
3678 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
3679 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3681 Args.push_back(InfoPtr);
3682 ArgTypes.push_back(Args.back()->getType());
3683 }
3684
3685 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3686 Args.push_back(EmitCheckValue(DynamicArgs[i]));
3687 ArgTypes.push_back(IntPtrTy);
3688 }
3689 }
3690
3691 llvm::FunctionType *FnType =
3692 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
3693
3694 if (!FatalCond || !RecoverableCond) {
3695 // Simple case: we need to generate a single handler call, either
3696 // fatal, or non-fatal.
3697 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
3698 (FatalCond != nullptr), Cont, NoMerge);
3699 } else {
3700 // Emit two handler calls: first one for set of unrecoverable checks,
3701 // another one for recoverable.
3702 llvm::BasicBlock *NonFatalHandlerBB =
3703 createBasicBlock("non_fatal." + CheckName);
3704 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3705 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3706 EmitBlock(FatalHandlerBB);
3707 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
3708 NonFatalHandlerBB, NoMerge);
3709 EmitBlock(NonFatalHandlerBB);
3710 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
3711 Cont, NoMerge);
3712 }
3713
3714 EmitBlock(Cont);
3715}
3716
3718 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3719 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
3720 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3721
3722 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3723 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3724
3725 llvm::MDBuilder MDHelper(getLLVMContext());
3726 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
3727 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3728
3729 EmitBlock(CheckBB);
3730
3731 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3732
3733 llvm::CallInst *CheckCall;
3734 llvm::FunctionCallee SlowPathFn;
3735 if (WithDiag) {
3736 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3737 auto *InfoPtr =
3738 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3739 llvm::GlobalVariable::PrivateLinkage, Info);
3740 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3742
3743 SlowPathFn = CGM.getModule().getOrInsertFunction(
3744 "__cfi_slowpath_diag",
3745 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3746 false));
3747 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr, InfoPtr});
3748 } else {
3749 SlowPathFn = CGM.getModule().getOrInsertFunction(
3750 "__cfi_slowpath",
3751 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3752 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3753 }
3754
3756 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
3757 CheckCall->setDoesNotThrow();
3758
3759 EmitBlock(Cont);
3760}
3761
3762// Emit a stub for __cfi_check function so that the linker knows about this
3763// symbol in LTO mode.
3765 llvm::Module *M = &CGM.getModule();
3766 ASTContext &C = getContext();
3767 QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
3768
3770 ImplicitParamDecl ArgCallsiteTypeId(C, QInt64Ty, ImplicitParamKind::Other);
3771 ImplicitParamDecl ArgAddr(C, C.VoidPtrTy, ImplicitParamKind::Other);
3772 ImplicitParamDecl ArgCFICheckFailData(C, C.VoidPtrTy,
3774 FnArgs.push_back(&ArgCallsiteTypeId);
3775 FnArgs.push_back(&ArgAddr);
3776 FnArgs.push_back(&ArgCFICheckFailData);
3777 const CGFunctionInfo &FI =
3779
3780 llvm::Function *F = llvm::Function::Create(
3781 llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false),
3782 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3783 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3785 F->setAlignment(llvm::Align(4096));
3786 CGM.setDSOLocal(F);
3787
3788 llvm::LLVMContext &Ctx = M->getContext();
3789 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3790 // CrossDSOCFI pass is not executed if there is no executable code.
3791 SmallVector<llvm::Value*> Args{F->getArg(2), F->getArg(1)};
3792 llvm::CallInst::Create(M->getFunction("__cfi_check_fail"), Args, "", BB);
3793 llvm::ReturnInst::Create(Ctx, nullptr, BB);
3794}
3795
3796// This function is basically a switch over the CFI failure kind, which is
3797// extracted from CFICheckFailData (1st function argument). Each case is either
3798// llvm.trap or a call to one of the two runtime handlers, based on
3799// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
3800// failure kind) traps, but this should really never happen. CFICheckFailData
3801// can be nullptr if the calling module has -fsanitize-trap behavior for this
3802// check kind; in this case __cfi_check_fail traps as well.
3804 SanitizerScope SanScope(this);
3805 FunctionArgList Args;
3810 Args.push_back(&ArgData);
3811 Args.push_back(&ArgAddr);
3812
3813 const CGFunctionInfo &FI =
3815
3816 llvm::Function *F = llvm::Function::Create(
3817 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3818 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3819
3820 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3822 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3823
3824 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3825 SourceLocation());
3826
3827 // This function is not affected by NoSanitizeList. This function does
3828 // not have a source location, but "src:*" would still apply. Revert any
3829 // changes to SanOpts made in StartFunction.
3831
3832 llvm::Value *Data =
3833 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3834 CGM.getContext().VoidPtrTy, ArgData.getLocation());
3835 llvm::Value *Addr =
3836 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3837 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3838
3839 // Data == nullptr means the calling module has trap behaviour for this check.
3840 llvm::Value *DataIsNotNullPtr =
3841 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3842 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
3843
3844 llvm::StructType *SourceLocationTy =
3845 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3846 llvm::StructType *CfiCheckFailDataTy =
3847 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3848
3849 llvm::Value *V = Builder.CreateConstGEP2_32(
3850 CfiCheckFailDataTy, Builder.CreatePointerCast(Data, UnqualPtrTy), 0, 0);
3851
3852 Address CheckKindAddr(V, Int8Ty, getIntAlign());
3853 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3854
3855 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3857 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3858 llvm::Value *ValidVtable = Builder.CreateZExt(
3859 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3860 {Addr, AllVtables}),
3861 IntPtrTy);
3862
3863 const std::pair<int, SanitizerMask> CheckKinds[] = {
3864 {CFITCK_VCall, SanitizerKind::CFIVCall},
3865 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3866 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3867 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3868 {CFITCK_ICall, SanitizerKind::CFIICall}};
3869
3871 for (auto CheckKindMaskPair : CheckKinds) {
3872 int Kind = CheckKindMaskPair.first;
3873 SanitizerMask Mask = CheckKindMaskPair.second;
3874 llvm::Value *Cond =
3875 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3876 if (CGM.getLangOpts().Sanitize.has(Mask))
3877 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3878 {Data, Addr, ValidVtable});
3879 else
3880 EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
3881 }
3882
3884 // The only reference to this function will be created during LTO link.
3885 // Make sure it survives until then.
3886 CGM.addUsedGlobal(F);
3887}
3888
3890 if (SanOpts.has(SanitizerKind::Unreachable)) {
3891 SanitizerScope SanScope(this);
3892 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3893 SanitizerKind::Unreachable),
3894 SanitizerHandler::BuiltinUnreachable,
3896 }
3897 Builder.CreateUnreachable();
3898}
3899
3900void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3901 SanitizerHandler CheckHandlerID,
3902 bool NoMerge) {
3903 llvm::BasicBlock *Cont = createBasicBlock("cont");
3904
3905 // If we're optimizing, collapse all calls to trap down to just one per
3906 // check-type per function to save on code size.
3907 if ((int)TrapBBs.size() <= CheckHandlerID)
3908 TrapBBs.resize(CheckHandlerID + 1);
3909
3910 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3911
3912 NoMerge = NoMerge || !CGM.getCodeGenOpts().OptimizationLevel ||
3913 (CurCodeDecl && CurCodeDecl->hasAttr<OptimizeNoneAttr>());
3914
3915 if (TrapBB && !NoMerge) {
3916 auto Call = TrapBB->begin();
3917 assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3918
3919 Call->applyMergedLocation(Call->getDebugLoc(),
3920 Builder.getCurrentDebugLocation());
3921 Builder.CreateCondBr(Checked, Cont, TrapBB);
3922 } else {
3923 TrapBB = createBasicBlock("trap");
3924 Builder.CreateCondBr(Checked, Cont, TrapBB);
3925 EmitBlock(TrapBB);
3926
3927 llvm::CallInst *TrapCall =
3928 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3929 llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3930
3931 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3932 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3934 TrapCall->addFnAttr(A);
3935 }
3936 if (NoMerge)
3937 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
3938 TrapCall->setDoesNotReturn();
3939 TrapCall->setDoesNotThrow();
3940 Builder.CreateUnreachable();
3941 }
3942
3943 EmitBlock(Cont);
3944}
3945
3946llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3947 llvm::CallInst *TrapCall =
3948 Builder.CreateCall(CGM.getIntrinsic(IntrID));
3949
3950 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3951 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3953 TrapCall->addFnAttr(A);
3954 }
3955
3957 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
3958 return TrapCall;
3959}
3960
3962 LValueBaseInfo *BaseInfo,
3963 TBAAAccessInfo *TBAAInfo) {
3964 assert(E->getType()->isArrayType() &&
3965 "Array to pointer decay must have array source type!");
3966
3967 // Expressions of array type can't be bitfields or vector elements.
3968 LValue LV = EmitLValue(E);
3969 Address Addr = LV.getAddress();
3970
3971 // If the array type was an incomplete type, we need to make sure
3972 // the decay ends up being the right type.
3973 llvm::Type *NewTy = ConvertType(E->getType());
3974 Addr = Addr.withElementType(NewTy);
3975
3976 // Note that VLA pointers are always decayed, so we don't need to do
3977 // anything here.
3978 if (!E->getType()->isVariableArrayType()) {
3979 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3980 "Expected pointer to array");
3981 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3982 }
3983
3984 // The result of this decay conversion points to an array element within the
3985 // base lvalue. However, since TBAA currently does not support representing
3986 // accesses to elements of member arrays, we conservatively represent accesses
3987 // to the pointee object as if it had no any base lvalue specified.
3988 // TODO: Support TBAA for member arrays.
3990 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3991 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3992
3993 return Addr.withElementType(ConvertTypeForMem(EltType));
3994}
3995
3996/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3997/// array to pointer, return the array subexpression.
3998static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3999 // If this isn't just an array->pointer decay, bail out.
4000 const auto *CE = dyn_cast<CastExpr>(E);
4001 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4002 return nullptr;
4003
4004 // If this is a decay from variable width array, bail out.
4005 const Expr *SubExpr = CE->getSubExpr();
4006 if (SubExpr->getType()->isVariableArrayType())
4007 return nullptr;
4008
4009 return SubExpr;
4010}
4011
4013 llvm::Type *elemType,
4014 llvm::Value *ptr,
4015 ArrayRef<llvm::Value*> indices,
4016 bool inbounds,
4017 bool signedIndices,
4018 SourceLocation loc,
4019 const llvm::Twine &name = "arrayidx") {
4020 if (inbounds) {
4021 return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
4023 name);
4024 } else {
4025 return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
4026 }
4027}
4028
4031 llvm::Type *elementType, bool inbounds,
4032 bool signedIndices, SourceLocation loc,
4033 CharUnits align,
4034 const llvm::Twine &name = "arrayidx") {
4035 if (inbounds) {
4036 return CGF.EmitCheckedInBoundsGEP(addr, indices, elementType, signedIndices,
4038 align, name);
4039 } else {
4040 return CGF.Builder.CreateGEP(addr, indices, elementType, align, name);
4041 }
4042}
4043
4045 llvm::Value *idx,
4046 CharUnits eltSize) {
4047 // If we have a constant index, we can use the exact offset of the
4048 // element we're accessing.
4049 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
4050 CharUnits offset = constantIdx->getZExtValue() * eltSize;
4051 return arrayAlign.alignmentAtOffset(offset);
4052
4053 // Otherwise, use the worst-case alignment for any element.
4054 } else {
4055 return arrayAlign.alignmentOfArrayElement(eltSize);
4056 }
4057}
4058
4060 const VariableArrayType *vla) {
4061 QualType eltType;
4062 do {
4063 eltType = vla->getElementType();
4064 } while ((vla = ctx.getAsVariableArrayType(eltType)));
4065 return eltType;
4066}
4067
4069 return D && D->hasAttr<BPFPreserveStaticOffsetAttr>();
4070}
4071
4072static bool hasBPFPreserveStaticOffset(const Expr *E) {
4073 if (!E)
4074 return false;
4075 QualType PointeeType = E->getType()->getPointeeType();
4076 if (PointeeType.isNull())
4077 return false;
4078 if (const auto *BaseDecl = PointeeType->getAsRecordDecl())
4079 return hasBPFPreserveStaticOffset(BaseDecl);
4080 return false;
4081}
4082
4083// Wraps Addr with a call to llvm.preserve.static.offset intrinsic.
4085 Address &Addr) {
4086 if (!CGF.getTarget().getTriple().isBPF())
4087 return Addr;
4088
4089 llvm::Function *Fn =
4090 CGF.CGM.getIntrinsic(llvm::Intrinsic::preserve_static_offset);
4091 llvm::CallInst *Call = CGF.Builder.CreateCall(Fn, {Addr.emitRawPointer(CGF)});
4092 return Address(Call, Addr.getElementType(), Addr.getAlignment());
4093}
4094
4095/// Given an array base, check whether its member access belongs to a record
4096/// with preserve_access_index attribute or not.
4097static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
4098 if (!ArrayBase || !CGF.getDebugInfo())
4099 return false;
4100
4101 // Only support base as either a MemberExpr or DeclRefExpr.
4102 // DeclRefExpr to cover cases like:
4103 // struct s { int a; int b[10]; };
4104 // struct s *p;
4105 // p[1].a
4106 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
4107 // p->b[5] is a MemberExpr example.
4108 const Expr *E = ArrayBase->IgnoreImpCasts();
4109 if (const auto *ME = dyn_cast<MemberExpr>(E))
4110 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4111
4112 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
4113 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
4114 if (!VarDef)
4115 return false;
4116
4117 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
4118 if (!PtrT)
4119 return false;
4120
4121 const auto *PointeeT = PtrT->getPointeeType()
4123 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
4124 return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4125 return false;
4126 }
4127
4128 return false;
4129}
4130
4133 QualType eltType, bool inbounds,
4134 bool signedIndices, SourceLocation loc,
4135 QualType *arrayType = nullptr,
4136 const Expr *Base = nullptr,
4137 const llvm::Twine &name = "arrayidx") {
4138 // All the indices except that last must be zero.
4139#ifndef NDEBUG
4140 for (auto *idx : indices.drop_back())
4141 assert(isa<llvm::ConstantInt>(idx) &&
4142 cast<llvm::ConstantInt>(idx)->isZero());
4143#endif
4144
4145 // Determine the element size of the statically-sized base. This is
4146 // the thing that the indices are expressed in terms of.
4147 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
4148 eltType = getFixedSizeElementType(CGF.getContext(), vla);
4149 }
4150
4151 // We can use that to compute the best alignment of the element.
4152 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
4153 CharUnits eltAlign =
4154 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
4155
4157 addr = wrapWithBPFPreserveStaticOffset(CGF, addr);
4158
4159 llvm::Value *eltPtr;
4160 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4161 if (!LastIndex ||
4163 addr = emitArraySubscriptGEP(CGF, addr, indices,
4164 CGF.ConvertTypeForMem(eltType), inbounds,
4165 signedIndices, loc, eltAlign, name);
4166 return addr;
4167 } else {
4168 // Remember the original array subscript for bpf target
4169 unsigned idx = LastIndex->getZExtValue();
4170 llvm::DIType *DbgInfo = nullptr;
4171 if (arrayType)
4172 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
4173 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(
4174 addr.getElementType(), addr.emitRawPointer(CGF), indices.size() - 1,
4175 idx, DbgInfo);
4176 }
4177
4178 return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
4179}
4180
4181/// The offset of a field from the beginning of the record.
4183 const FieldDecl *Field, int64_t &Offset) {
4184 ASTContext &Ctx = CGF.getContext();
4185 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
4186 unsigned FieldNo = 0;
4187
4188 for (const FieldDecl *FD : RD->fields()) {
4189 if (FD == Field) {
4190 Offset += Layout.getFieldOffset(FieldNo);
4191 return true;
4192 }
4193
4194 QualType Ty = FD->getType();
4195 if (Ty->isRecordType())
4196 if (getFieldOffsetInBits(CGF, Ty->getAsRecordDecl(), Field, Offset)) {
4197 Offset += Layout.getFieldOffset(FieldNo);
4198 return true;
4199 }
4200
4201 if (!RD->isUnion())
4202 ++FieldNo;
4203 }
4204
4205 return false;
4206}
4207
4208/// Returns the relative offset difference between \p FD1 and \p FD2.
4209/// \code
4210/// offsetof(struct foo, FD1) - offsetof(struct foo, FD2)
4211/// \endcode
4212/// Both fields must be within the same struct.
4213static std::optional<int64_t> getOffsetDifferenceInBits(CodeGenFunction &CGF,
4214 const FieldDecl *FD1,
4215 const FieldDecl *FD2) {
4216 const RecordDecl *FD1OuterRec =
4218 const RecordDecl *FD2OuterRec =
4220
4221 if (FD1OuterRec != FD2OuterRec)
4222 // Fields must be within the same RecordDecl.
4223 return std::optional<int64_t>();
4224
4225 int64_t FD1Offset = 0;
4226 if (!getFieldOffsetInBits(CGF, FD1OuterRec, FD1, FD1Offset))
4227 return std::optional<int64_t>();
4228
4229 int64_t FD2Offset = 0;
4230 if (!getFieldOffsetInBits(CGF, FD2OuterRec, FD2, FD2Offset))
4231 return std::optional<int64_t>();
4232
4233 return std::make_optional<int64_t>(FD1Offset - FD2Offset);
4234}
4235
4237 bool Accessed) {
4238 // The index must always be an integer, which is not an aggregate. Emit it
4239 // in lexical order (this complexity is, sadly, required by C++17).
4240 llvm::Value *IdxPre =
4241 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
4242 bool SignedIndices = false;
4243 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
4244 auto *Idx = IdxPre;
4245 if (E->getLHS() != E->getIdx()) {
4246 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
4247 Idx = EmitScalarExpr(E->getIdx());
4248 }
4249
4250 QualType IdxTy = E->getIdx()->getType();
4251 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
4252 SignedIndices |= IdxSigned;
4253
4254 if (SanOpts.has(SanitizerKind::ArrayBounds))
4255 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
4256
4257 // Extend or truncate the index type to 32 or 64-bits.
4258 if (Promote && Idx->getType() != IntPtrTy)
4259 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
4260
4261 return Idx;
4262 };
4263 IdxPre = nullptr;
4264
4265 // If the base is a vector type, then we are forming a vector element lvalue
4266 // with this subscript.
4267 if (E->getBase()->getType()->isSubscriptableVectorType() &&
4268 !isa<ExtVectorElementExpr>(E->getBase())) {
4269 // Emit the vector as an lvalue to get its address.
4270 LValue LHS = EmitLValue(E->getBase());
4271 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
4272 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
4273 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
4274 LHS.getBaseInfo(), TBAAAccessInfo());
4275 }
4276
4277 // All the other cases basically behave like simple offsetting.
4278
4279 // Handle the extvector case we ignored above.
4280 if (isa<ExtVectorElementExpr>(E->getBase())) {
4281 LValue LV = EmitLValue(E->getBase());
4282 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4284
4285 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
4286 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
4287 SignedIndices, E->getExprLoc());
4288 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
4289 CGM.getTBAAInfoForSubobject(LV, EltType));
4290 }
4291
4292 LValueBaseInfo EltBaseInfo;
4293 TBAAAccessInfo EltTBAAInfo;
4294 Address Addr = Address::invalid();
4295 if (const VariableArrayType *vla =
4296 getContext().getAsVariableArrayType(E->getType())) {
4297 // The base must be a pointer, which is not an aggregate. Emit
4298 // it. It needs to be emitted first in case it's what captures
4299 // the VLA bounds.
4300 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
4301 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4302
4303 // The element count here is the total number of non-VLA elements.
4304 llvm::Value *numElements = getVLASize(vla).NumElts;
4305
4306 // Effectively, the multiply by the VLA size is part of the GEP.
4307 // GEP indexes are signed, and scaling an index isn't permitted to
4308 // signed-overflow, so we use the same semantics for our explicit
4309 // multiply. We suppress this if overflow is not undefined behavior.
4310 if (getLangOpts().isSignedOverflowDefined()) {
4311 Idx = Builder.CreateMul(Idx, numElements);
4312 } else {
4313 Idx = Builder.CreateNSWMul(Idx, numElements);
4314 }
4315
4316 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
4317 !getLangOpts().isSignedOverflowDefined(),
4318 SignedIndices, E->getExprLoc());
4319
4320 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
4321 // Indexing over an interface, as in "NSString *P; P[4];"
4322
4323 // Emit the base pointer.
4324 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
4325 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4326
4327 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
4328 llvm::Value *InterfaceSizeVal =
4329 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
4330
4331 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
4332
4333 // We don't necessarily build correct LLVM struct types for ObjC
4334 // interfaces, so we can't rely on GEP to do this scaling
4335 // correctly, so we need to cast to i8*. FIXME: is this actually
4336 // true? A lot of other things in the fragile ABI would break...
4337 llvm::Type *OrigBaseElemTy = Addr.getElementType();
4338
4339 // Do the GEP.
4340 CharUnits EltAlign =
4341 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
4342 llvm::Value *EltPtr =
4343 emitArraySubscriptGEP(*this, Int8Ty, Addr.emitRawPointer(*this),
4344 ScaledIdx, false, SignedIndices, E->getExprLoc());
4345 Addr = Address(EltPtr, OrigBaseElemTy, EltAlign);
4346 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4347 // If this is A[i] where A is an array, the frontend will have decayed the
4348 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
4349 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4350 // "gep x, i" here. Emit one "gep A, 0, i".
4351 assert(Array->getType()->isArrayType() &&
4352 "Array to pointer decay must have array source type!");
4353 LValue ArrayLV;
4354 // For simple multidimensional array indexing, set the 'accessed' flag for
4355 // better bounds-checking of the base expression.
4356 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4357 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4358 else
4359 ArrayLV = EmitLValue(Array);
4360 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4361
4362 if (SanOpts.has(SanitizerKind::ArrayBounds)) {
4363 // If the array being accessed has a "counted_by" attribute, generate
4364 // bounds checking code. The "count" field is at the top level of the
4365 // struct or in an anonymous struct, that's also at the top level. Future
4366 // expansions may allow the "count" to reside at any place in the struct,
4367 // but the value of "counted_by" will be a "simple" path to the count,
4368 // i.e. "a.b.count", so we shouldn't need the full force of EmitLValue or
4369 // similar to emit the correct GEP.
4370 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
4371 getLangOpts().getStrictFlexArraysLevel();
4372
4373 if (const auto *ME = dyn_cast<MemberExpr>(Array);
4374 ME &&
4375 ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel) &&
4377 const FieldDecl *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
4378 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
4379 if (std::optional<int64_t> Diff =
4380 getOffsetDifferenceInBits(*this, CountFD, FAMDecl)) {
4381 CharUnits OffsetDiff = CGM.getContext().toCharUnitsFromBits(*Diff);
4382
4383 // Create a GEP with a byte offset between the FAM and count and
4384 // use that to load the count value.
4386 ArrayLV.getAddress(), Int8PtrTy, Int8Ty);
4387
4388 llvm::Type *CountTy = ConvertType(CountFD->getType());
4389 llvm::Value *Res = Builder.CreateInBoundsGEP(
4390 Int8Ty, Addr.emitRawPointer(*this),
4391 Builder.getInt32(OffsetDiff.getQuantity()), ".counted_by.gep");
4392 Res = Builder.CreateAlignedLoad(CountTy, Res, getIntAlign(),
4393 ".counted_by.load");
4394
4395 // Now emit the bounds checking.
4396 EmitBoundsCheckImpl(E, Res, Idx, E->getIdx()->getType(),
4397 Array->getType(), Accessed);
4398 }
4399 }
4400 }
4401 }
4402
4403 // Propagate the alignment from the array itself to the result.
4404 QualType arrayType = Array->getType();
4405 Addr = emitArraySubscriptGEP(
4406 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
4407 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
4408 E->getExprLoc(), &arrayType, E->getBase());
4409 EltBaseInfo = ArrayLV.getBaseInfo();
4410 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
4411 } else {
4412 // The base must be a pointer; emit it with an estimate of its alignment.
4413 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
4414 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
4415 QualType ptrType = E->getBase()->getType();
4416 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
4417 !getLangOpts().isSignedOverflowDefined(),
4418 SignedIndices, E->getExprLoc(), &ptrType,
4419 E->getBase());
4420 }
4421
4422 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
4423
4424 if (getLangOpts().ObjC &&
4425 getLangOpts().getGC() != LangOptions::NonGC) {
4428 }
4429 return LV;
4430}
4431
4432llvm::Value *CodeGenFunction::EmitMatrixIndexExpr(const Expr *E) {
4433 llvm::Value *Idx = EmitScalarExpr(E);
4434 if (Idx->getType() == IntPtrTy)
4435 return Idx;
4436 bool IsSigned = E->getType()->isSignedIntegerOrEnumerationType();
4437 return Builder.CreateIntCast(Idx, IntPtrTy, IsSigned);
4438}
4439
4441 assert(
4442 !E->isIncomplete() &&
4443 "incomplete matrix subscript expressions should be rejected during Sema");
4444 LValue Base = EmitLValue(E->getBase());
4445
4446 // Extend or truncate the index type to 32 or 64-bits if needed.
4447 llvm::Value *RowIdx = EmitMatrixIndexExpr(E->getRowIdx());
4448 llvm::Value *ColIdx = EmitMatrixIndexExpr(E->getColumnIdx());
4449
4450 llvm::Value *NumRows = Builder.getIntN(
4451 RowIdx->getType()->getScalarSizeInBits(),
4452 E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
4453 llvm::Value *FinalIdx =
4454 Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
4455 return LValue::MakeMatrixElt(
4456 MaybeConvertMatrixAddress(Base.getAddress(), *this), FinalIdx,
4457 E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
4458}
4459
4461 LValueBaseInfo &BaseInfo,
4462 TBAAAccessInfo &TBAAInfo,
4463 QualType BaseTy, QualType ElTy,
4464 bool IsLowerBound) {
4465 LValue BaseLVal;
4466 if (auto *ASE = dyn_cast<ArraySectionExpr>(Base->IgnoreParenImpCasts())) {
4467 BaseLVal = CGF.EmitArraySectionExpr(ASE, IsLowerBound);
4468 if (BaseTy->isArrayType()) {
4469 Address Addr = BaseLVal.getAddress();
4470 BaseInfo = BaseLVal.getBaseInfo();
4471
4472 // If the array type was an incomplete type, we need to make sure
4473 // the decay ends up being the right type.
4474 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
4475 Addr = Addr.withElementType(NewTy);
4476
4477 // Note that VLA pointers are always decayed, so we don't need to do
4478 // anything here.
4479 if (!BaseTy->isVariableArrayType()) {
4480 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
4481 "Expected pointer to array");
4482 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
4483 }
4484
4485 return Addr.withElementType(CGF.ConvertTypeForMem(ElTy));
4486 }
4487 LValueBaseInfo TypeBaseInfo;
4488 TBAAAccessInfo TypeTBAAInfo;
4489 CharUnits Align =
4490 CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
4491 BaseInfo.mergeForCast(TypeBaseInfo);
4492 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
4493 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()),
4494 CGF.ConvertTypeForMem(ElTy), Align);
4495 }
4496 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
4497}
4498
4500 bool IsLowerBound) {
4501
4502 assert(!E->isOpenACCArraySection() &&
4503 "OpenACC Array section codegen not implemented");
4504
4506 QualType ResultExprTy;
4507 if (auto *AT = getContext().getAsArrayType(BaseTy))
4508 ResultExprTy = AT->getElementType();
4509 else
4510 ResultExprTy = BaseTy->getPointeeType();
4511 llvm::Value *Idx = nullptr;
4512 if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
4513 // Requesting lower bound or upper bound, but without provided length and
4514 // without ':' symbol for the default length -> length = 1.
4515 // Idx = LowerBound ?: 0;
4516 if (auto *LowerBound = E->getLowerBound()) {
4517 Idx = Builder.CreateIntCast(
4518 EmitScalarExpr(LowerBound), IntPtrTy,
4519 LowerBound->getType()->hasSignedIntegerRepresentation());
4520 } else
4521 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
4522 } else {
4523 // Try to emit length or lower bound as constant. If this is possible, 1
4524 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
4525 // IR (LB + Len) - 1.
4526 auto &C = CGM.getContext();
4527 auto *Length = E->getLength();
4528 llvm::APSInt ConstLength;
4529 if (Length) {
4530 // Idx = LowerBound + Length - 1;
4531 if (std::optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4532 ConstLength = CL->zextOrTrunc(PointerWidthInBits);
4533 Length = nullptr;
4534 }
4535 auto *LowerBound = E->getLowerBound();
4536 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4537 if (LowerBound) {
4538 if (std::optional<llvm::APSInt> LB =
4539 LowerBound->getIntegerConstantExpr(C)) {
4540 ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
4541 LowerBound = nullptr;
4542 }
4543 }
4544 if (!Length)
4545 --ConstLength;
4546 else if (!LowerBound)
4547 --ConstLowerBound;
4548
4549 if (Length || LowerBound) {
4550 auto *LowerBoundVal =
4551 LowerBound
4552 ? Builder.CreateIntCast(
4553 EmitScalarExpr(LowerBound), IntPtrTy,
4554 LowerBound->getType()->hasSignedIntegerRepresentation())
4555 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
4556 auto *LengthVal =
4557 Length
4558 ? Builder.CreateIntCast(
4559 EmitScalarExpr(Length), IntPtrTy,
4560 Length->getType()->hasSignedIntegerRepresentation())
4561 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
4562 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
4563 /*HasNUW=*/false,
4564 !getLangOpts().isSignedOverflowDefined());
4565 if (Length && LowerBound) {
4566 Idx = Builder.CreateSub(
4567 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
4568 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4569 }
4570 } else
4571 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
4572 } else {
4573 // Idx = ArraySize - 1;
4574 QualType ArrayTy = BaseTy->isPointerType()
4575 ? E->getBase()->IgnoreParenImpCasts()->getType()
4576 : BaseTy;
4577 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
4578 Length = VAT->getSizeExpr();
4579 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4580 ConstLength = *L;
4581 Length = nullptr;
4582 }
4583 } else {
4584 auto *CAT = C.getAsConstantArrayType(ArrayTy);
4585 assert(CAT && "unexpected type for array initializer");
4586 ConstLength = CAT->getSize();
4587 }
4588 if (Length) {
4589 auto *LengthVal = Builder.CreateIntCast(
4590 EmitScalarExpr(Length), IntPtrTy,
4591 Length->getType()->hasSignedIntegerRepresentation());
4592 Idx = Builder.CreateSub(
4593 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
4594 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4595 } else {
4596 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
4597 --ConstLength;
4598 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
4599 }
4600 }
4601 }
4602 assert(Idx);
4603
4604 Address EltPtr = Address::invalid();
4605 LValueBaseInfo BaseInfo;
4606 TBAAAccessInfo TBAAInfo;
4607 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
4608 // The base must be a pointer, which is not an aggregate. Emit
4609 // it. It needs to be emitted first in case it's what captures
4610 // the VLA bounds.
4611 Address Base =
4612 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
4613 BaseTy, VLA->getElementType(), IsLowerBound);
4614 // The element count here is the total number of non-VLA elements.
4615 llvm::Value *NumElements = getVLASize(VLA).NumElts;
4616
4617 // Effectively, the multiply by the VLA size is part of the GEP.
4618 // GEP indexes are signed, and scaling an index isn't permitted to
4619 // signed-overflow, so we use the same semantics for our explicit
4620 // multiply. We suppress this if overflow is not undefined behavior.
4621 if (getLangOpts().isSignedOverflowDefined())
4622 Idx = Builder.CreateMul(Idx, NumElements);
4623 else
4624 Idx = Builder.CreateNSWMul(Idx, NumElements);
4625 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
4626 !getLangOpts().isSignedOverflowDefined(),
4627 /*signedIndices=*/false, E->getExprLoc());
4628 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4629 // If this is A[i] where A is an array, the frontend will have decayed the
4630 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
4631 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4632 // "gep x, i" here. Emit one "gep A, 0, i".
4633 assert(Array->getType()->isArrayType() &&
4634 "Array to pointer decay must have array source type!");
4635 LValue ArrayLV;
4636 // For simple multidimensional array indexing, set the 'accessed' flag for
4637 // better bounds-checking of the base expression.
4638 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4639 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4640 else
4641 ArrayLV = EmitLValue(Array);
4642
4643 // Propagate the alignment from the array itself to the result.
4644 EltPtr = emitArraySubscriptGEP(
4645 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
4646 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
4647 /*signedIndices=*/false, E->getExprLoc());
4648 BaseInfo = ArrayLV.getBaseInfo();
4649 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
4650 } else {
4651 Address Base =
4652 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo, BaseTy,
4653 ResultExprTy, IsLowerBound);
4654 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
4655 !getLangOpts().isSignedOverflowDefined(),
4656 /*signedIndices=*/false, E->getExprLoc());
4657 }
4658
4659 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
4660}
4661
4664 // Emit the base vector as an l-value.
4665 LValue Base;
4666
4667 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
4668 if (E->isArrow()) {
4669 // If it is a pointer to a vector, emit the address and form an lvalue with
4670 // it.
4671 LValueBaseInfo BaseInfo;
4672 TBAAAccessInfo TBAAInfo;
4673 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4674 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
4675 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
4676 Base.getQuals().removeObjCGCAttr();
4677 } else if (E->getBase()->isGLValue()) {
4678 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
4679 // emit the base as an lvalue.
4680 assert(E->getBase()->getType()->isVectorType());
4681 Base = EmitLValue(E->getBase());
4682 } else {
4683 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
4684 assert(E->getBase()->getType()->isVectorType() &&
4685 "Result must be a vector");
4686 llvm::Value *Vec = EmitScalarExpr(E->getBase());
4687
4688 // Store the vector to memory (because LValue wants an address).
4689 Address VecMem = CreateMemTemp(E->getBase()->getType());
4690 Builder.CreateStore(Vec, VecMem);
4691 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
4693 }
4694
4695 QualType type =
4696 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
4697
4698 // Encode the element access list into a vector of unsigned indices.
4700 E->getEncodedElementAccess(Indices);
4701
4702 if (Base.isSimple()) {
4703 llvm::Constant *CV =
4704 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4705 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
4706 Base.getBaseInfo(), TBAAAccessInfo());
4707 }
4708 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
4709
4710 llvm::Constant *BaseElts = Base.getExtVectorElts();
4712
4713 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
4714 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
4715 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
4716 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
4717 Base.getBaseInfo(), TBAAAccessInfo());
4718}
4719
4722 EmitIgnoredExpr(E->getBase());
4723 return EmitDeclRefLValue(DRE);
4724 }
4725
4726 Expr *BaseExpr = E->getBase();
4727 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
4728 LValue BaseLV;
4729 if (E->isArrow()) {
4730 LValueBaseInfo BaseInfo;
4731 TBAAAccessInfo TBAAInfo;
4732 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
4733 QualType PtrTy = BaseExpr->getType()->getPointeeType();
4734 SanitizerSet SkippedChecks;
4735 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
4736 if (IsBaseCXXThis)
4737 SkippedChecks.set(SanitizerKind::Alignment, true);
4738 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
4739 SkippedChecks.set(SanitizerKind::Null, true);
4740 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr, PtrTy,
4741 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
4742 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
4743 } else
4744 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
4745
4746 NamedDecl *ND = E->getMemberDecl();
4747 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
4748 LValue LV = EmitLValueForField(BaseLV, Field);
4750 if (getLangOpts().OpenMP) {
4751 // If the member was explicitly marked as nontemporal, mark it as
4752 // nontemporal. If the base lvalue is marked as nontemporal, mark access
4753 // to children as nontemporal too.
4754 if ((IsWrappedCXXThis(BaseExpr) &&
4756 BaseLV.isNontemporal())
4757 LV.setNontemporal(/*Value=*/true);
4758 }
4759 return LV;
4760 }
4761
4762 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
4763 return EmitFunctionDeclLValue(*this, E, FD);
4764
4765 llvm_unreachable("Unhandled member declaration!");
4766}
4767
4768/// Given that we are currently emitting a lambda, emit an l-value for
4769/// one of its members.
4770///
4772 llvm::Value *ThisValue) {
4773 bool HasExplicitObjectParameter = false;
4774 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(CurCodeDecl);
4775 if (MD) {
4776 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
4777 assert(MD->getParent()->isLambda());
4778 assert(MD->getParent() == Field->getParent());
4779 }
4780 LValue LambdaLV;
4781 if (HasExplicitObjectParameter) {
4782 const VarDecl *D = cast<CXXMethodDecl>(CurCodeDecl)->getParamDecl(0);
4783 auto It = LocalDeclMap.find(D);
4784 assert(It != LocalDeclMap.end() && "explicit parameter not loaded?");
4785 Address AddrOfExplicitObject = It->getSecond();
4786 if (D->getType()->isReferenceType())
4787 LambdaLV = EmitLoadOfReferenceLValue(AddrOfExplicitObject, D->getType(),
4789 else
4790 LambdaLV = MakeAddrLValue(AddrOfExplicitObject,
4791 D->getType().getNonReferenceType());
4792
4793 // Make sure we have an lvalue to the lambda itself and not a derived class.
4794 auto *ThisTy = D->getType().getNonReferenceType()->getAsCXXRecordDecl();
4795 auto *LambdaTy = cast<CXXRecordDecl>(Field->getParent());
4796 if (ThisTy != LambdaTy) {
4797 const CXXCastPath &BasePathArray = getContext().LambdaCastPaths.at(MD);
4799 LambdaLV.getAddress(), ThisTy, BasePathArray.begin(),
4800 BasePathArray.end(), /*NullCheckValue=*/false, SourceLocation());
4801 LambdaLV = MakeAddrLValue(Base, QualType{LambdaTy->getTypeForDecl(), 0});
4802 }
4803 } else {
4804 QualType LambdaTagType = getContext().getTagDeclType(Field->getParent());
4805 LambdaLV = MakeNaturalAlignAddrLValue(ThisValue, LambdaTagType);
4806 }
4807 return EmitLValueForField(LambdaLV, Field);
4808}
4809
4811 return EmitLValueForLambdaField(Field, CXXABIThisValue);
4812}
4813
4814/// Get the field index in the debug info. The debug info structure/union
4815/// will ignore the unnamed bitfields.
4817 unsigned FieldIndex) {
4818 unsigned I = 0, Skipped = 0;
4819
4820 for (auto *F : Rec->getDefinition()->fields()) {
4821 if (I == FieldIndex)
4822 break;
4823 if (F->isUnnamedBitField())
4824 Skipped++;
4825 I++;
4826 }
4827
4828 return FieldIndex - Skipped;
4829}
4830
4831/// Get the address of a zero-sized field within a record. The resulting
4832/// address doesn't necessarily have the right type.
4834 const FieldDecl *Field) {
4836 CGF.getContext().getFieldOffset(Field));
4837 if (Offset.isZero())
4838 return Base;
4839 Base = Base.withElementType(CGF.Int8Ty);
4840 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4841}
4842
4843/// Drill down to the storage of a field without walking into
4844/// reference types.
4845///
4846/// The resulting address doesn't necessarily have the right type.
4848 const FieldDecl *field) {
4849 if (isEmptyFieldForLayout(CGF.getContext(), field))
4850 return emitAddrOfZeroSizeField(CGF, base, field);
4851
4852 const RecordDecl *rec = field->getParent();
4853
4854 unsigned idx =
4855 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4856
4857 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
4858}
4859
4861 Address addr, const FieldDecl *field) {
4862 const RecordDecl *rec = field->getParent();
4863 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
4864 base.getType(), rec->getLocation());
4865
4866 unsigned idx =
4867 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4868
4870 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
4871}
4872
4873static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4874 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4875 if (!RD)
4876 return false;
4877
4878 if (RD->isDynamicClass())
4879 return true;
4880
4881 for (const auto &Base : RD->bases())
4882 if (hasAnyVptr(Base.getType(), Context))
4883 return true;
4884
4885 for (const FieldDecl *Field : RD->fields())
4886 if (hasAnyVptr(Field->getType(), Context))
4887 return true;
4888
4889 return false;
4890}
4891
4893 const FieldDecl *field) {
4894 LValueBaseInfo BaseInfo = base.getBaseInfo();
4895
4896 if (field->isBitField()) {
4897 const CGRecordLayout &RL =
4899 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4900 const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4901 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4902 Info.VolatileStorageSize != 0 &&
4903 field->getType()
4906 Address Addr = base.getAddress();
4907 unsigned Idx = RL.getLLVMFieldNo(field);
4908 const RecordDecl *rec = field->getParent();
4910 Addr = wrapWithBPFPreserveStaticOffset(*this, Addr);
4911 if (!UseVolatile) {
4912 if (!IsInPreservedAIRegion &&
4913 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4914 if (Idx != 0)
4915 // For structs, we GEP to the field that the record layout suggests.
4916 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4917 } else {
4918 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4919 getContext().getRecordType(rec), rec->getLocation());
4921 Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4922 DbgInfo);
4923 }
4924 }
4925 const unsigned SS =
4926 UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
4927 // Get the access type.
4928 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4929 Addr = Addr.withElementType(FieldIntTy);
4930 if (UseVolatile) {
4931 const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4932 if (VolatileOffset)
4933 Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4934 }
4935
4936 QualType fieldType =
4937 field->getType().withCVRQualifiers(base.getVRQualifiers());
4938 // TODO: Support TBAA for bit fields.
4939 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
4940 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
4941 TBAAAccessInfo());
4942 }
4943
4944 // Fields of may-alias structures are may-alias themselves.
4945 // FIXME: this should get propagated down through anonymous structs
4946 // and unions.
4947 QualType FieldType = field->getType();
4948 const RecordDecl *rec = field->getParent();
4949 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
4950 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
4951 TBAAAccessInfo FieldTBAAInfo;
4952 if (base.getTBAAInfo().isMayAlias() ||
4953 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
4954 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4955 } else if (rec->isUnion()) {
4956 // TODO: Support TBAA for unions.
4957 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4958 } else {
4959 // If no base type been assigned for the base access, then try to generate
4960 // one for this base lvalue.
4961 FieldTBAAInfo = base.getTBAAInfo();
4962 if (!FieldTBAAInfo.BaseType) {
4963 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4964 assert(!FieldTBAAInfo.Offset &&
4965 "Nonzero offset for an access with no base type!");
4966 }
4967
4968 // Adjust offset to be relative to the base type.
4969 const ASTRecordLayout &Layout =
4971 unsigned CharWidth = getContext().getCharWidth();
4972 if (FieldTBAAInfo.BaseType)
4973 FieldTBAAInfo.Offset +=
4974 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
4975
4976 // Update the final access type and size.
4977 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
4978 FieldTBAAInfo.Size =
4980 }
4981
4982 Address addr = base.getAddress();
4984 addr = wrapWithBPFPreserveStaticOffset(*this, addr);
4985 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4986 if (CGM.getCodeGenOpts().StrictVTablePointers &&
4987 ClassDef->isDynamicClass()) {
4988 // Getting to any field of dynamic object requires stripping dynamic
4989 // information provided by invariant.group. This is because accessing
4990 // fields may leak the real address of dynamic object, which could result
4991 // in miscompilation when leaked pointer would be compared.
4992 auto *stripped =
4994 addr = Address(stripped, addr.getElementType(), addr.getAlignment());
4995 }
4996 }
4997
4998 unsigned RecordCVR = base.getVRQualifiers();
4999 if (rec->isUnion()) {
5000 // For unions, there is no pointer adjustment.
5001 if (CGM.getCodeGenOpts().StrictVTablePointers &&
5002 hasAnyVptr(FieldType, getContext()))
5003 // Because unions can easily skip invariant.barriers, we need to add
5004 // a barrier every time CXXRecord field with vptr is referenced.
5006
5008 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
5009 // Remember the original union field index
5010 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
5011 rec->getLocation());
5012 addr =
5014 addr.emitRawPointer(*this),
5015 getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
5016 addr.getElementType(), addr.getAlignment());
5017 }
5018
5019 if (FieldType->isReferenceType())
5020 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5021 } else {
5022 if (!IsInPreservedAIRegion &&
5023 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
5024 // For structs, we GEP to the field that the record layout suggests.
5025 addr = emitAddrOfFieldStorage(*this, addr, field);
5026 else
5027 // Remember the original struct field index
5028 addr = emitPreserveStructAccess(*this, base, addr, field);
5029 }
5030
5031 // If this is a reference field, load the reference right now.
5032 if (FieldType->isReferenceType()) {
5033 LValue RefLVal =
5034 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5035 if (RecordCVR & Qualifiers::Volatile)
5036 RefLVal.getQuals().addVolatile();
5037 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
5038
5039 // Qualifiers on the struct don't apply to the referencee.
5040 RecordCVR = 0;
5041 FieldType = FieldType->getPointeeType();
5042 }
5043
5044 // Make sure that the address is pointing to the right type. This is critical
5045 // for both unions and structs.
5046 addr = addr.withElementType(CGM.getTypes().ConvertTypeForMem(FieldType));
5047
5048 if (field->hasAttr<AnnotateAttr>())
5049 addr = EmitFieldAnnotations(field, addr);
5050
5051 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
5052 LV.getQuals().addCVRQualifiers(RecordCVR);
5053
5054 // __weak attribute on a field is ignored.
5057
5058 return LV;
5059}
5060
5061LValue
5063 const FieldDecl *Field) {
5064 QualType FieldType = Field->getType();
5065
5066 if (!FieldType->isReferenceType())
5067 return EmitLValueForField(Base, Field);
5068
5069 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
5070
5071 // Make sure that the address is pointing to the right type.
5072 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
5073 V = V.withElementType(llvmType);
5074
5075 // TODO: Generate TBAA information that describes this access as a structure
5076 // member access and not just an access to an object of the field's type. This
5077 // should be similar to what we do in EmitLValueForField().
5078 LValueBaseInfo BaseInfo = Base.getBaseInfo();
5079 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
5080 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
5081 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
5082 CGM.getTBAAInfoForSubobject(Base, FieldType));
5083}
5084
5086 if (E->isFileScope()) {
5088 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
5089 }
5091 // make sure to emit the VLA size.
5093
5094 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
5095 const Expr *InitExpr = E->getInitializer();
5097
5098 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
5099 /*Init*/ true);
5100
5101 // Block-scope compound literals are destroyed at the end of the enclosing
5102 // scope in C.
5103 if (!getLangOpts().CPlusPlus)
5106 E->getType(), getDestroyer(DtorKind),
5107 DtorKind & EHCleanup);
5108
5109 return Result;
5110}
5111
5113 if (!E->isGLValue())
5114 // Initializing an aggregate temporary in C++11: T{...}.
5115 return EmitAggExprToLValue(E);
5116
5117 // An lvalue initializer list must be initializing a reference.
5118 assert(E->isTransparent() && "non-transparent glvalue init list");
5119 return EmitLValue(E->getInit(0));
5120}
5121
5122/// Emit the operand of a glvalue conditional operator. This is either a glvalue
5123/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
5124/// LValue is returned and the current block has been terminated.
5125static std::optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
5126 const Expr *Operand) {
5127 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
5128 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
5129 return std::nullopt;
5130 }
5131
5132 return CGF.EmitLValue(Operand);
5133}
5134
5135namespace {
5136// Handle the case where the condition is a constant evaluatable simple integer,
5137// which means we don't have to separately handle the true/false blocks.
5138std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
5140 const Expr *condExpr = E->getCond();
5141 bool CondExprBool;
5142 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
5143 const Expr *Live = E->getTrueExpr(), *Dead = E->getFalseExpr();
5144 if (!CondExprBool)
5145 std::swap(Live, Dead);
5146
5147 if (!CGF.ContainsLabel(Dead)) {
5148 // If the true case is live, we need to track its region.
5149 if (CondExprBool)
5151 // If a throw expression we emit it and return an undefined lvalue
5152 // because it can't be used.
5153 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->IgnoreParens())) {
5154 CGF.EmitCXXThrowExpr(ThrowExpr);
5155 llvm::Type *ElemTy = CGF.ConvertType(Dead->getType());
5156 llvm::Type *Ty = CGF.UnqualPtrTy;
5157 return CGF.MakeAddrLValue(
5158 Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
5159 Dead->getType());
5160 }
5161 return CGF.EmitLValue(Live);
5162 }
5163 }
5164 return std::nullopt;
5165}
5166struct ConditionalInfo {
5167 llvm::BasicBlock *lhsBlock, *rhsBlock;
5168 std::optional<LValue> LHS, RHS;
5169};
5170
5171// Create and generate the 3 blocks for a conditional operator.
5172// Leaves the 'current block' in the continuation basic block.
5173template<typename FuncTy>
5174ConditionalInfo EmitConditionalBlocks(CodeGenFunction &CGF,
5176 const FuncTy &BranchGenFunc) {
5177 ConditionalInfo Info{CGF.createBasicBlock("cond.true"),
5178 CGF.createBasicBlock("cond.false"), std::nullopt,
5179 std::nullopt};
5180 llvm::BasicBlock *endBlock = CGF.createBasicBlock("cond.end");
5181
5182 CodeGenFunction::ConditionalEvaluation eval(CGF);
5183 CGF.EmitBranchOnBoolExpr(E->getCond(), Info.lhsBlock, Info.rhsBlock,
5184 CGF.getProfileCount(E));
5185
5186 // Any temporaries created here are conditional.
5187 CGF.EmitBlock(Info.lhsBlock);
5189 eval.begin(CGF);
5190 Info.LHS = BranchGenFunc(CGF, E->getTrueExpr());
5191 eval.end(CGF);
5192 Info.lhsBlock = CGF.Builder.GetInsertBlock();
5193
5194 if (Info.LHS)
5195 CGF.Builder.CreateBr(endBlock);
5196
5197 // Any temporaries created here are conditional.
5198 CGF.EmitBlock(Info.rhsBlock);
5199 eval.begin(CGF);
5200 Info.RHS = BranchGenFunc(CGF, E->getFalseExpr());
5201 eval.end(CGF);
5202 Info.rhsBlock = CGF.Builder.GetInsertBlock();
5203 CGF.EmitBlock(endBlock);
5204
5205 return Info;
5206}
5207} // namespace
5208
5211 if (!E->isGLValue()) {
5212 // ?: here should be an aggregate.
5214 "Unexpected conditional operator!");
5215 return (void)EmitAggExprToLValue(E);
5216 }
5217
5218 OpaqueValueMapping binding(*this, E);
5219 if (HandleConditionalOperatorLValueSimpleCase(*this, E))
5220 return;
5221
5222 EmitConditionalBlocks(*this, E, [](CodeGenFunction &CGF, const Expr *E) {
5223 CGF.EmitIgnoredExpr(E);
5224 return LValue{};
5225 });
5226}
5229 if (!expr->isGLValue()) {
5230 // ?: here should be an aggregate.
5231 assert(hasAggregateEvaluationKind(expr->getType()) &&
5232 "Unexpected conditional operator!");
5233 return EmitAggExprToLValue(expr);
5234 }
5235
5236 OpaqueValueMapping binding(*this, expr);
5237 if (std::optional<LValue> Res =
5238 HandleConditionalOperatorLValueSimpleCase(*this, expr))
5239 return *Res;
5240
5241 ConditionalInfo Info = EmitConditionalBlocks(
5242 *this, expr, [](CodeGenFunction &CGF, const Expr *E) {
5243 return EmitLValueOrThrowExpression(CGF, E);
5244 });
5245
5246 if ((Info.LHS && !Info.LHS->isSimple()) ||
5247 (Info.RHS && !Info.RHS->isSimple()))
5248 return EmitUnsupportedLValue(expr, "conditional operator");
5249
5250 if (Info.LHS && Info.RHS) {
5251 Address lhsAddr = Info.LHS->getAddress();
5252 Address rhsAddr = Info.RHS->getAddress();
5254 lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock,
5255 Builder.GetInsertBlock(), expr->getType());
5256 AlignmentSource alignSource =
5257 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
5258 Info.RHS->getBaseInfo().getAlignmentSource());
5260 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
5261 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
5262 TBAAInfo);
5263 } else {
5264 assert((Info.LHS || Info.RHS) &&
5265 "both operands of glvalue conditional are throw-expressions?");
5266 return Info.LHS ? *Info.LHS : *Info.RHS;
5267 }
5268}
5269
5270/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
5271/// type. If the cast is to a reference, we can have the usual lvalue result,
5272/// otherwise if a cast is needed by the code generator in an lvalue context,
5273/// then it must mean that we need the address of an aggregate in order to
5274/// access one of its members. This can happen for all the reasons that casts
5275/// are permitted with aggregate result, including noop aggregate casts, and
5276/// cast from scalar to union.
5278 switch (E->getCastKind()) {
5279 case CK_ToVoid:
5280 case CK_BitCast:
5281 case CK_LValueToRValueBitCast:
5282 case CK_ArrayToPointerDecay:
5283 case CK_FunctionToPointerDecay:
5284 case CK_NullToMemberPointer:
5285 case CK_NullToPointer:
5286 case CK_IntegralToPointer:
5287 case CK_PointerToIntegral:
5288 case CK_PointerToBoolean:
5289 case CK_IntegralCast:
5290 case CK_BooleanToSignedIntegral:
5291 case CK_IntegralToBoolean:
5292 case CK_IntegralToFloating:
5293 case CK_FloatingToIntegral:
5294 case CK_FloatingToBoolean:
5295 case CK_FloatingCast:
5296 case CK_FloatingRealToComplex:
5297 case CK_FloatingComplexToReal:
5298 case CK_FloatingComplexToBoolean:
5299 case CK_FloatingComplexCast:
5300 case CK_FloatingComplexToIntegralComplex:
5301 case CK_IntegralRealToComplex:
5302 case CK_IntegralComplexToReal:
5303 case CK_IntegralComplexToBoolean:
5304 case CK_IntegralComplexCast:
5305 case CK_IntegralComplexToFloatingComplex:
5306 case CK_DerivedToBaseMemberPointer:
5307 case CK_BaseToDerivedMemberPointer:
5308 case CK_MemberPointerToBoolean:
5309 case CK_ReinterpretMemberPointer:
5310 case CK_AnyPointerToBlockPointerCast:
5311 case CK_ARCProduceObject:
5312 case CK_ARCConsumeObject:
5313 case CK_ARCReclaimReturnedObject:
5314 case CK_ARCExtendBlockObject:
5315 case CK_CopyAndAutoreleaseBlockObject:
5316 case CK_IntToOCLSampler:
5317 case CK_FloatingToFixedPoint:
5318 case CK_FixedPointToFloating:
5319 case CK_FixedPointCast:
5320 case CK_FixedPointToBoolean:
5321 case CK_FixedPointToIntegral:
5322 case CK_IntegralToFixedPoint:
5323 case CK_MatrixCast:
5324 case CK_HLSLVectorTruncation:
5325 case CK_HLSLArrayRValue:
5326 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
5327
5328 case CK_Dependent:
5329 llvm_unreachable("dependent cast kind in IR gen!");
5330
5331 case CK_BuiltinFnToFnPtr:
5332 llvm_unreachable("builtin functions are handled elsewhere");
5333
5334 // These are never l-values; just use the aggregate emission code.
5335 case CK_NonAtomicToAtomic:
5336 case CK_AtomicToNonAtomic:
5337 return EmitAggExprToLValue(E);
5338
5339 case CK_Dynamic: {
5340 LValue LV = EmitLValue(E->getSubExpr());
5341 Address V = LV.getAddress();
5342 const auto *DCE = cast<CXXDynamicCastExpr>(E);
5344 }
5345
5346 case CK_ConstructorConversion:
5347 case CK_UserDefinedConversion:
5348 case CK_CPointerToObjCPointerCast:
5349 case CK_BlockPointerToObjCPointerCast:
5350 case CK_LValueToRValue:
5351 return EmitLValue(E->getSubExpr());
5352
5353 case CK_NoOp: {
5354 // CK_NoOp can model a qualification conversion, which can remove an array
5355 // bound and change the IR type.
5356 // FIXME: Once pointee types are removed from IR, remove this.
5357 LValue LV = EmitLValue(E->getSubExpr());
5358 // Propagate the volatile qualifer to LValue, if exist in E.
5359 if (E->changesVolatileQualification())
5360 LV.getQuals() = E->getType().getQualifiers();
5361 if (LV.isSimple()) {
5362 Address V = LV.getAddress();
5363 if (V.isValid()) {
5364 llvm::Type *T = ConvertTypeForMem(E->getType());
5365 if (V.getElementType() != T)
5366 LV.setAddress(V.withElementType(T));
5367 }
5368 }
5369 return LV;
5370 }
5371
5372 case CK_UncheckedDerivedToBase:
5373 case CK_DerivedToBase: {
5374 const auto *DerivedClassTy =
5375 E->getSubExpr()->getType()->castAs<RecordType>();
5376 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
5377
5378 LValue LV = EmitLValue(E->getSubExpr());
5379 Address This = LV.getAddress();
5380
5381 // Perform the derived-to-base conversion
5383 This, DerivedClassDecl, E->path_begin(), E->path_end(),
5384 /*NullCheckValue=*/false, E->getExprLoc());
5385
5386 // TODO: Support accesses to members of base classes in TBAA. For now, we
5387 // conservatively pretend that the complete object is of the base class
5388 // type.
5389 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
5391 }
5392 case CK_ToUnion:
5393 return EmitAggExprToLValue(E);
5394 case CK_BaseToDerived: {
5395 const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
5396 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
5397
5398 LValue LV = EmitLValue(E->getSubExpr());
5399
5400 // Perform the base-to-derived conversion
5402 LV.getAddress(), DerivedClassDecl, E->path_begin(), E->path_end(),
5403 /*NullCheckValue=*/false);
5404
5405 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
5406 // performed and the object is not of the derived type.
5409 E->getType());
5410
5411 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
5413 /*MayBeNull=*/false, CFITCK_DerivedCast,
5414 E->getBeginLoc());
5415
5416 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
5418 }
5419 case CK_LValueBitCast: {
5420 // This must be a reinterpret_cast (or c-style equivalent).
5421 const auto *CE = cast<ExplicitCastExpr>(E);
5422
5423 CGM.EmitExplicitCastExprType(CE, this);
5424 LValue LV = EmitLValue(E->getSubExpr());
5426 ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
5427
5428 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
5430 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
5431 E->getBeginLoc());
5432
5433 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
5435 }
5436 case CK_AddressSpaceConversion: {
5437 LValue LV = EmitLValue(E->getSubExpr());
5439 llvm::Value *V = getTargetHooks().performAddrSpaceCast(
5440 *this, LV.getPointer(*this),
5441 E->getSubExpr()->getType().getAddressSpace(),
5442 E->getType().getAddressSpace(), ConvertType(DestTy));
5444 LV.getAddress().getAlignment()),
5445 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
5446 }
5447 case CK_ObjCObjectLValueCast: {
5448 LValue LV = EmitLValue(E->getSubExpr());
5450 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
5452 }
5453 case CK_ZeroToOCLOpaqueType:
5454 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
5455
5456 case CK_VectorSplat: {
5457 // LValue results of vector splats are only supported in HLSL.
5458 if (!getLangOpts().HLSL)
5459 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
5460 return EmitLValue(E->getSubExpr());
5461 }
5462 }
5463
5464 llvm_unreachable("Unhandled lvalue cast kind?");
5465}
5466
5470}
5471
5472std::pair<LValue, LValue>
5474 // Emitting the casted temporary through an opaque value.
5475 LValue BaseLV = EmitLValue(E->getArgLValue());
5476 OpaqueValueMappingData::bind(*this, E->getOpaqueArgLValue(), BaseLV);
5477
5478 QualType ExprTy = E->getType();
5479 Address OutTemp = CreateIRTemp(ExprTy);
5480 LValue TempLV = MakeAddrLValue(OutTemp, ExprTy);
5481
5482 if (E->isInOut())
5483 EmitInitializationToLValue(E->getCastedTemporary()->getSourceExpr(),
5484 TempLV);
5485
5486 OpaqueValueMappingData::bind(*this, E->getCastedTemporary(), TempLV);
5487 return std::make_pair(BaseLV, TempLV);
5488}
5489
5491 CallArgList &Args, QualType Ty) {
5492
5493 auto [BaseLV, TempLV] = EmitHLSLOutArgLValues(E, Ty);
5494
5495 llvm::Value *Addr = TempLV.getAddress().getBasePointer();
5496 llvm::Type *ElTy = ConvertTypeForMem(TempLV.getType());
5497
5498 llvm::TypeSize Sz = CGM.getDataLayout().getTypeAllocSize(ElTy);
5499
5500 llvm::Value *LifetimeSize = EmitLifetimeStart(Sz, Addr);
5501
5502 Address TmpAddr(Addr, ElTy, TempLV.getAlignment());
5503 Args.addWriteback(BaseLV, TmpAddr, nullptr, E->getWritebackCast(),
5504 LifetimeSize);
5505 Args.add(RValue::get(TmpAddr, *this), Ty);
5506 return TempLV;
5507}
5508
5509LValue
5512
5513 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
5514 it = OpaqueLValues.find(e);
5515
5516 if (it != OpaqueLValues.end())
5517 return it->second;
5518
5519 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
5520 return EmitLValue(e->getSourceExpr());
5521}
5522
5523RValue
5526
5527 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
5528 it = OpaqueRValues.find(e);
5529
5530 if (it != OpaqueRValues.end())
5531 return it->second;
5532
5533 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
5534 return EmitAnyExpr(e->getSourceExpr());
5535}
5536
5538 const FieldDecl *FD,
5540 QualType FT = FD->getType();
5541 LValue FieldLV = EmitLValueForField(LV, FD);
5542 switch (getEvaluationKind(FT)) {
5543 case TEK_Complex:
5544 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
5545 case TEK_Aggregate:
5546 return FieldLV.asAggregateRValue();
5547 case TEK_Scalar:
5548 // This routine is used to load fields one-by-one to perform a copy, so
5549 // don't load reference fields.
5550 if (FD->getType()->isReferenceType())
5551 return RValue::get(FieldLV.getPointer(*this));
5552 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
5553 // primitive load.
5554 if (FieldLV.isBitField())
5555 return EmitLoadOfLValue(FieldLV, Loc);
5556 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
5557 }
5558 llvm_unreachable("bad evaluation kind");
5559}
5560
5561//===--------------------------------------------------------------------===//
5562// Expression Emission
5563//===--------------------------------------------------------------------===//
5564
5566 ReturnValueSlot ReturnValue,
5567 llvm::CallBase **CallOrInvoke) {
5568 llvm::CallBase *CallOrInvokeStorage;
5569 if (!CallOrInvoke) {
5570 CallOrInvoke = &CallOrInvokeStorage;
5571 }
5572
5573 auto AddCoroElideSafeOnExit = llvm::make_scope_exit([&] {
5574 if (E->isCoroElideSafe()) {
5575 auto *I = *CallOrInvoke;
5576 if (I)
5577 I->addFnAttr(llvm::Attribute::CoroElideSafe);
5578 }
5579 });
5580
5581 // Builtins never have block type.
5582 if (E->getCallee()->getType()->isBlockPointerType())
5583 return EmitBlockCallExpr(E, ReturnValue, CallOrInvoke);
5584
5585 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
5586 return EmitCXXMemberCallExpr(CE, ReturnValue, CallOrInvoke);
5587
5588 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
5589 return EmitCUDAKernelCallExpr(CE, ReturnValue, CallOrInvoke);
5590
5591 // A CXXOperatorCallExpr is created even for explicit object methods, but
5592 // these should be treated like static function call.
5593 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
5594 if (const auto *MD =
5595 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
5596 MD && MD->isImplicitObjectMemberFunction())
5597 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue, CallOrInvoke);
5598
5599 CGCallee callee = EmitCallee(E->getCallee());
5600
5601 if (callee.isBuiltin()) {
5602 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
5603 E, ReturnValue);
5604 }
5605
5606 if (callee.isPseudoDestructor()) {
5608 }
5609
5610 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue,
5611 /*Chain=*/nullptr, CallOrInvoke);
5612}
5613
5614/// Emit a CallExpr without considering whether it might be a subclass.
5616 ReturnValueSlot ReturnValue,
5617 llvm::CallBase **CallOrInvoke) {
5618 CGCallee Callee = EmitCallee(E->getCallee());
5619 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
5620 /*Chain=*/nullptr, CallOrInvoke);
5621}
5622
5623// Detect the unusual situation where an inline version is shadowed by a
5624// non-inline version. In that case we should pick the external one
5625// everywhere. That's GCC behavior too.
5627 for (const FunctionDecl *PD = FD; PD; PD = PD->getPreviousDecl())
5628 if (!PD->isInlineBuiltinDeclaration())
5629 return false;
5630 return true;
5631}
5632
5634 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
5635
5636 if (auto builtinID = FD->getBuiltinID()) {
5637 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
5638 std::string NoBuiltins = "no-builtins";
5639
5640 StringRef Ident = CGF.CGM.getMangledName(GD);
5641 std::string FDInlineName = (Ident + ".inline").str();
5642
5643 bool IsPredefinedLibFunction =
5645 bool HasAttributeNoBuiltin =
5646 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
5647 CGF.CurFn->getAttributes().hasFnAttr(NoBuiltins);
5648
5649 // When directing calling an inline builtin, call it through it's mangled
5650 // name to make it clear it's not the actual builtin.
5651 if (CGF.CurFn->getName() != FDInlineName &&
5653 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
5654 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
5655 llvm::Module *M = Fn->getParent();
5656 llvm::Function *Clone = M->getFunction(FDInlineName);
5657 if (!Clone) {
5658 Clone = llvm::Function::Create(Fn->getFunctionType(),
5659 llvm::GlobalValue::InternalLinkage,
5660 Fn->getAddressSpace(), FDInlineName, M);
5661 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
5662 }
5663 return CGCallee::forDirect(Clone, GD);
5664 }
5665
5666 // Replaceable builtins provide their own implementation of a builtin. If we
5667 // are in an inline builtin implementation, avoid trivial infinite
5668 // recursion. Honor __attribute__((no_builtin("foo"))) or
5669 // __attribute__((no_builtin)) on the current function unless foo is
5670 // not a predefined library function which means we must generate the
5671 // builtin no matter what.
5672 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
5673 return CGCallee::forBuiltin(builtinID, FD);
5674 }
5675
5676 llvm::Constant *CalleePtr = CGF.CGM.getRawFunctionPointer(GD);
5677 if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
5678 FD->hasAttr<CUDAGlobalAttr>())
5679 CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
5680 cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
5681
5682 return CGCallee::forDirect(CalleePtr, GD);
5683}
5684
5686 E = E->IgnoreParens();
5687
5688 // Look through function-to-pointer decay.
5689 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
5690 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
5691 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
5692 return EmitCallee(ICE->getSubExpr());
5693 }
5694
5695 // Resolve direct calls.
5696 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
5697 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
5698 return EmitDirectCallee(*this, FD);
5699 }
5700 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
5701 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
5702 EmitIgnoredExpr(ME->getBase());
5703 return EmitDirectCallee(*this, FD);
5704 }
5705
5706 // Look through template substitutions.
5707 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
5708 return EmitCallee(NTTP->getReplacement());
5709
5710 // Treat pseudo-destructor calls differently.
5711 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
5713 }
5714
5715 // Otherwise, we have an indirect reference.
5716 llvm::Value *calleePtr;
5718 if (auto ptrType = E->getType()->getAs<PointerType>()) {
5719 calleePtr = EmitScalarExpr(E);
5720 functionType = ptrType->getPointeeType();
5721 } else {
5722 functionType = E->getType();
5723 calleePtr = EmitLValue(E, KnownNonNull).getPointer(*this);
5724 }
5725 assert(functionType->isFunctionType());
5726
5727 GlobalDecl GD;
5728 if (const auto *VD =
5729 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
5730 GD = GlobalDecl(VD);
5731
5732 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
5734 CGCallee callee(calleeInfo, calleePtr, pointerAuth);
5735 return callee;
5736}
5737
5739 // Comma expressions just emit their LHS then their RHS as an l-value.
5740 if (E->getOpcode() == BO_Comma) {
5741 EmitIgnoredExpr(E->getLHS());
5743 return EmitLValue(E->getRHS());
5744 }
5745
5746 if (E->getOpcode() == BO_PtrMemD ||
5747 E->getOpcode() == BO_PtrMemI)
5749
5750 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
5751
5752 // Note that in all of these cases, __block variables need the RHS
5753 // evaluated first just in case the variable gets moved by the RHS.
5754
5755 switch (getEvaluationKind(E->getType())) {
5756 case TEK_Scalar: {
5757 switch (E->getLHS()->getType().getObjCLifetime()) {
5759 return EmitARCStoreStrong(E, /*ignored*/ false).first;
5760
5762 return EmitARCStoreAutoreleasing(E).first;
5763
5764 // No reason to do any of these differently.
5768 break;
5769 }
5770
5771 // TODO: Can we de-duplicate this code with the corresponding code in
5772 // CGExprScalar, similar to the way EmitCompoundAssignmentLValue works?
5773 RValue RV;
5774 llvm::Value *Previous = nullptr;
5775 QualType SrcType = E->getRHS()->getType();
5776 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
5777 // we want to extract that value and potentially (if the bitfield sanitizer
5778 // is enabled) use it to check for an implicit conversion.
5779 if (E->getLHS()->refersToBitField()) {
5780 llvm::Value *RHS =
5782 RV = RValue::get(RHS);
5783 } else
5784 RV = EmitAnyExpr(E->getRHS());
5785
5786 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
5787
5788 if (RV.isScalar())
5790
5791 if (LV.isBitField()) {
5792 llvm::Value *Result = nullptr;
5793 // If bitfield sanitizers are enabled we want to use the result
5794 // to check whether a truncation or sign change has occurred.
5795 if (SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
5797 else
5799
5800 // If the expression contained an implicit conversion, make sure
5801 // to use the value before the scalar conversion.
5802 llvm::Value *Src = Previous ? Previous : RV.getScalarVal();
5803 QualType DstType = E->getLHS()->getType();
5804 EmitBitfieldConversionCheck(Src, SrcType, Result, DstType,
5805 LV.getBitFieldInfo(), E->getExprLoc());
5806 } else
5807 EmitStoreThroughLValue(RV, LV);
5808
5809 if (getLangOpts().OpenMP)
5811 E->getLHS());
5812 return LV;
5813 }
5814
5815 case TEK_Complex:
5817
5818 case TEK_Aggregate:
5819 // If the lang opt is HLSL and the LHS is a constant array
5820 // then we are performing a copy assignment and call a special
5821 // function because EmitAggExprToLValue emits to a temporary LValue
5822 if (getLangOpts().HLSL && E->getLHS()->getType()->isConstantArrayType())
5824
5825 return EmitAggExprToLValue(E);
5826 }
5827 llvm_unreachable("bad evaluation kind");
5828}
5829
5830// This function implements trivial copy assignment for HLSL's
5831// assignable constant arrays.
5833 // Don't emit an LValue for the RHS because it might not be an LValue
5834 LValue LHS = EmitLValue(E->getLHS());
5835 // In C the RHS of an assignment operator is an RValue.
5836 // EmitAggregateAssign takes anan LValue for the RHS. Instead we can call
5837 // EmitInitializationToLValue to emit an RValue into an LValue.
5838 EmitInitializationToLValue(E->getRHS(), LHS);
5839 return LHS;
5840}
5841
5843 llvm::CallBase **CallOrInvoke) {
5844 RValue RV = EmitCallExpr(E, ReturnValueSlot(), CallOrInvoke);
5845
5846 if (!RV.isScalar())
5849
5850 assert(E->getCallReturnType(getContext())->isReferenceType() &&
5851 "Can't have a scalar return unless the return type is a "
5852 "reference type!");
5853
5855}
5856
5858 // FIXME: This shouldn't require another copy.
5859 return EmitAggExprToLValue(E);
5860}
5861
5864 && "binding l-value to type which needs a temporary");
5866 EmitCXXConstructExpr(E, Slot);
5868}
5869
5870LValue
5873}
5874
5876 return CGM.GetAddrOfMSGuidDecl(E->getGuidDecl())
5878}
5879
5883}
5884
5885LValue
5887 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
5889 EmitAggExpr(E->getSubExpr(), Slot);
5890 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
5892}
5893
5896
5897 if (!RV.isScalar())
5900
5901 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
5902 "Can't have a scalar return unless the return type is a "
5903 "reference type!");
5904
5906}
5907
5909 Address V =
5910 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
5912}
5913
5915 const ObjCIvarDecl *Ivar) {
5916 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
5917}
5918
5919llvm::Value *
5921 const ObjCIvarDecl *Ivar) {
5922 llvm::Value *OffsetValue = EmitIvarOffset(Interface, Ivar);
5923 QualType PointerDiffType = getContext().getPointerDiffType();
5924 return Builder.CreateZExtOrTrunc(OffsetValue,
5925 getTypes().ConvertType(PointerDiffType));
5926}
5927
5929 llvm::Value *BaseValue,
5930 const ObjCIvarDecl *Ivar,
5931 unsigned CVRQualifiers) {
5932 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
5933 Ivar, CVRQualifiers);
5934}
5935
5937 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
5938 llvm::Value *BaseValue = nullptr;
5939 const Expr *BaseExpr = E->getBase();
5940 Qualifiers BaseQuals;
5941 QualType ObjectTy;
5942 if (E->isArrow()) {
5943 BaseValue = EmitScalarExpr(BaseExpr);
5944 ObjectTy = BaseExpr->getType()->getPointeeType();
5945 BaseQuals = ObjectTy.getQualifiers();
5946 } else {
5947 LValue BaseLV = EmitLValue(BaseExpr);
5948 BaseValue = BaseLV.getPointer(*this);
5949 ObjectTy = BaseExpr->getType();
5950 BaseQuals = ObjectTy.getQualifiers();
5951 }
5952
5953 LValue LV =
5954 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
5955 BaseQuals.getCVRQualifiers());
5957 return LV;
5958}
5959
5961 // Can only get l-value for message expression returning aggregate type
5965}
5966
5968 const CGCallee &OrigCallee, const CallExpr *E,
5969 ReturnValueSlot ReturnValue,
5970 llvm::Value *Chain,
5971 llvm::CallBase **CallOrInvoke,
5972 CGFunctionInfo const **ResolvedFnInfo) {
5973 // Get the actual function type. The callee type will always be a pointer to
5974 // function type or a block pointer type.
5975 assert(CalleeType->isFunctionPointerType() &&
5976 "Call must have function pointer type!");
5977
5978 const Decl *TargetDecl =
5979 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
5980
5981 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
5982 !cast<FunctionDecl>(TargetDecl)->isImmediateFunction()) &&
5983 "trying to emit a call to an immediate function");
5984
5985 CalleeType = getContext().getCanonicalType(CalleeType);
5986
5987 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
5988
5989 CGCallee Callee = OrigCallee;
5990
5991 if (SanOpts.has(SanitizerKind::Function) &&
5992 (!TargetDecl || !isa<FunctionDecl>(TargetDecl)) &&
5993 !isa<FunctionNoProtoType>(PointeeType)) {
5994 if (llvm::Constant *PrefixSig =
5996 SanitizerScope SanScope(this);
5997 auto *TypeHash = getUBSanFunctionTypeHash(PointeeType);
5998
5999 llvm::Type *PrefixSigType = PrefixSig->getType();
6000 llvm::StructType *PrefixStructTy = llvm::StructType::get(
6001 CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
6002
6003 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6005 // Use raw pointer since we are using the callee pointer as data here.
6006 Address Addr =
6007 Address(CalleePtr, CalleePtr->getType(),
6009 CalleePtr->getPointerAlignment(CGM.getDataLayout())),
6010 Callee.getPointerAuthInfo(), nullptr);
6011 CalleePtr = Addr.emitRawPointer(*this);
6012 }
6013
6014 // On 32-bit Arm, the low bit of a function pointer indicates whether
6015 // it's using the Arm or Thumb instruction set. The actual first
6016 // instruction lives at the same address either way, so we must clear
6017 // that low bit before using the function address to find the prefix
6018 // structure.
6019 //
6020 // This applies to both Arm and Thumb target triples, because
6021 // either one could be used in an interworking context where it
6022 // might be passed function pointers of both types.
6023 llvm::Value *AlignedCalleePtr;
6024 if (CGM.getTriple().isARM() || CGM.getTriple().isThumb()) {
6025 llvm::Value *CalleeAddress =
6026 Builder.CreatePtrToInt(CalleePtr, IntPtrTy);
6027 llvm::Value *Mask = llvm::ConstantInt::get(IntPtrTy, ~1);
6028 llvm::Value *AlignedCalleeAddress =
6029 Builder.CreateAnd(CalleeAddress, Mask);
6030 AlignedCalleePtr =
6031 Builder.CreateIntToPtr(AlignedCalleeAddress, CalleePtr->getType());
6032 } else {
6033 AlignedCalleePtr = CalleePtr;
6034 }
6035
6036 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
6037 llvm::Value *CalleeSigPtr =
6038 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
6039 llvm::Value *CalleeSig =
6040 Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
6041 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
6042
6043 llvm::BasicBlock *Cont = createBasicBlock("cont");
6044 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
6045 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
6046
6047 EmitBlock(TypeCheck);
6048 llvm::Value *CalleeTypeHash = Builder.CreateAlignedLoad(
6049 Int32Ty,
6050 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
6051 getPointerAlign());
6052 llvm::Value *CalleeTypeHashMatch =
6053 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
6054 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
6055 EmitCheckTypeDescriptor(CalleeType)};
6056 EmitCheck(std::make_pair(CalleeTypeHashMatch, SanitizerKind::Function),
6057 SanitizerHandler::FunctionTypeMismatch, StaticData,
6058 {CalleePtr});
6059
6060 Builder.CreateBr(Cont);
6061 EmitBlock(Cont);
6062 }
6063 }
6064
6065 const auto *FnType = cast<FunctionType>(PointeeType);
6066
6067 // If we are checking indirect calls and this call is indirect, check that the
6068 // function pointer is a member of the bit set for the function type.
6069 if (SanOpts.has(SanitizerKind::CFIICall) &&
6070 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
6071 SanitizerScope SanScope(this);
6072 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
6073
6074 llvm::Metadata *MD;
6075 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
6077 else
6079
6080 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
6081
6082 llvm::Value *CalleePtr = Callee.getFunctionPointer();
6083 llvm::Value *TypeTest = Builder.CreateCall(
6084 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
6085
6086 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
6087 llvm::Constant *StaticData[] = {
6088 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
6091 };
6092 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
6093 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
6094 CalleePtr, StaticData);
6095 } else {
6096 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
6097 SanitizerHandler::CFICheckFail, StaticData,
6098 {CalleePtr, llvm::UndefValue::get(IntPtrTy)});
6099 }
6100 }
6101
6102 CallArgList Args;
6103 if (Chain)
6104 Args.add(RValue::get(Chain), CGM.getContext().VoidPtrTy);
6105
6106 // C++17 requires that we evaluate arguments to a call using assignment syntax
6107 // right-to-left, and that we evaluate arguments to certain other operators
6108 // left-to-right. Note that we allow this to override the order dictated by
6109 // the calling convention on the MS ABI, which means that parameter
6110 // destruction order is not necessarily reverse construction order.
6111 // FIXME: Revisit this based on C++ committee response to unimplementability.
6113 bool StaticOperator = false;
6114 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6115 if (OCE->isAssignmentOp())
6117 else {
6118 switch (OCE->getOperator()) {
6119 case OO_LessLess:
6120 case OO_GreaterGreater:
6121 case OO_AmpAmp:
6122 case OO_PipePipe:
6123 case OO_Comma:
6124 case OO_ArrowStar:
6126 break;
6127 default:
6128 break;
6129 }
6130 }
6131
6132 if (const auto *MD =
6133 dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
6134 MD && MD->isStatic())
6135 StaticOperator = true;
6136 }
6137
6138 auto Arguments = E->arguments();
6139 if (StaticOperator) {
6140 // If we're calling a static operator, we need to emit the object argument
6141 // and ignore it.
6142 EmitIgnoredExpr(E->getArg(0));
6143 Arguments = drop_begin(Arguments, 1);
6144 }
6145 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
6146 E->getDirectCallee(), /*ParamsToSkip=*/0, Order);
6147
6149 Args, FnType, /*ChainCall=*/Chain);
6150
6151 if (ResolvedFnInfo)
6152 *ResolvedFnInfo = &FnInfo;
6153
6154 // HIP function pointer contains kernel handle when it is used in triple
6155 // chevron. The kernel stub needs to be loaded from kernel handle and used
6156 // as callee.
6157 if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
6158 isa<CUDAKernelCallExpr>(E) &&
6159 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
6160 llvm::Value *Handle = Callee.getFunctionPointer();
6161 auto *Stub = Builder.CreateLoad(
6162 Address(Handle, Handle->getType(), CGM.getPointerAlign()));
6163 Callee.setFunctionPointer(Stub);
6164 }
6165 llvm::CallBase *LocalCallOrInvoke = nullptr;
6166 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &LocalCallOrInvoke,
6167 E == MustTailCall, E->getExprLoc());
6168
6169 // Generate function declaration DISuprogram in order to be used
6170 // in debug info about call sites.
6171 if (CGDebugInfo *DI = getDebugInfo()) {
6172 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
6173 FunctionArgList Args;
6174 QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
6175 DI->EmitFuncDeclForCallSite(LocalCallOrInvoke,
6176 DI->getFunctionType(CalleeDecl, ResTy, Args),
6177 CalleeDecl);
6178 }
6179 }
6180 if (CallOrInvoke)
6181 *CallOrInvoke = LocalCallOrInvoke;
6182
6183 return Call;
6184}
6185
6188 Address BaseAddr = Address::invalid();
6189 if (E->getOpcode() == BO_PtrMemI) {
6190 BaseAddr = EmitPointerWithAlignment(E->getLHS());
6191 } else {
6192 BaseAddr = EmitLValue(E->getLHS()).getAddress();
6193 }
6194
6195 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
6196 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
6197
6198 LValueBaseInfo BaseInfo;
6199 TBAAAccessInfo TBAAInfo;
6200 Address MemberAddr =
6201 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
6202 &TBAAInfo);
6203
6204 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
6205}
6206
6207/// Given the address of a temporary variable, produce an r-value of
6208/// its type.
6210 QualType type,
6211 SourceLocation loc) {
6213 switch (getEvaluationKind(type)) {
6214 case TEK_Complex:
6215 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
6216 case TEK_Aggregate:
6217 return lvalue.asAggregateRValue();
6218 case TEK_Scalar:
6219 return RValue::get(EmitLoadOfScalar(lvalue, loc));
6220 }
6221 llvm_unreachable("bad evaluation kind");
6222}
6223
6224void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
6225 assert(Val->getType()->isFPOrFPVectorTy());
6226 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
6227 return;
6228
6229 llvm::MDBuilder MDHelper(getLLVMContext());
6230 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
6231
6232 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
6233}
6234
6235void CodeGenFunction::SetSqrtFPAccuracy(llvm::Value *Val) {
6236 llvm::Type *EltTy = Val->getType()->getScalarType();
6237 if (!EltTy->isFloatTy())
6238 return;
6239
6240 if ((getLangOpts().OpenCL &&
6241 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
6242 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
6243 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
6244 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 3ulp
6245 //
6246 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
6247 // build option allows an application to specify that single precision
6248 // floating-point divide (x/y and 1/x) and sqrt used in the program
6249 // source are correctly rounded.
6250 //
6251 // TODO: CUDA has a prec-sqrt flag
6252 SetFPAccuracy(Val, 3.0f);
6253 }
6254}
6255
6256void CodeGenFunction::SetDivFPAccuracy(llvm::Value *Val) {
6257 llvm::Type *EltTy = Val->getType()->getScalarType();
6258 if (!EltTy->isFloatTy())
6259 return;
6260
6261 if ((getLangOpts().OpenCL &&
6262 !CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
6263 (getLangOpts().HIP && getLangOpts().CUDAIsDevice &&
6264 !CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
6265 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
6266 //
6267 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
6268 // build option allows an application to specify that single precision
6269 // floating-point divide (x/y and 1/x) and sqrt used in the program
6270 // source are correctly rounded.
6271 //
6272 // TODO: CUDA has a prec-div flag
6273 SetFPAccuracy(Val, 2.5f);
6274 }
6275}
6276
6277namespace {
6278 struct LValueOrRValue {
6279 LValue LV;
6280 RValue RV;
6281 };
6282}
6283
6284static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
6285 const PseudoObjectExpr *E,
6286 bool forLValue,
6287 AggValueSlot slot) {
6289
6290 // Find the result expression, if any.
6291 const Expr *resultExpr = E->getResultExpr();
6292 LValueOrRValue result;
6293
6295 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
6296 const Expr *semantic = *i;
6297
6298 // If this semantic expression is an opaque value, bind it
6299 // to the result of its source expression.
6300 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
6301 // Skip unique OVEs.
6302 if (ov->isUnique()) {
6303 assert(ov != resultExpr &&
6304 "A unique OVE cannot be used as the result expression");
6305 continue;
6306 }
6307
6308 // If this is the result expression, we may need to evaluate
6309 // directly into the slot.
6310 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
6311 OVMA opaqueData;
6312 if (ov == resultExpr && ov->isPRValue() && !forLValue &&
6314 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
6315 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
6317 opaqueData = OVMA::bind(CGF, ov, LV);
6318 result.RV = slot.asRValue();
6319
6320 // Otherwise, emit as normal.
6321 } else {
6322 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
6323
6324 // If this is the result, also evaluate the result now.
6325 if (ov == resultExpr) {
6326 if (forLValue)
6327 result.LV = CGF.EmitLValue(ov);
6328 else
6329 result.RV = CGF.EmitAnyExpr(ov, slot);
6330 }
6331 }
6332
6333 opaques.push_back(opaqueData);
6334
6335 // Otherwise, if the expression is the result, evaluate it
6336 // and remember the result.
6337 } else if (semantic == resultExpr) {
6338 if (forLValue)
6339 result.LV = CGF.EmitLValue(semantic);
6340 else
6341 result.RV = CGF.EmitAnyExpr(semantic, slot);
6342
6343 // Otherwise, evaluate the expression in an ignored context.
6344 } else {
6345 CGF.EmitIgnoredExpr(semantic);
6346 }
6347 }
6348
6349 // Unbind all the opaques now.
6350 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
6351 opaques[i].unbind(CGF);
6352
6353 return result;
6354}
6355
6357 AggValueSlot slot) {
6358 return emitPseudoObjectExpr(*this, E, false, slot).RV;
6359}
6360
6362 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
6363}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
DynTypedNode Node
Defines enum values for all the target-independent builtin functions.
CodeGenFunction::ComplexPairTy ComplexPairTy
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
Definition: CGExpr.cpp:2699
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:2942
static llvm::Value * emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc, llvm::Value *Ptr)
Definition: CGExpr.cpp:688
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer,...
Definition: CGExpr.cpp:3998
static llvm::cl::opt< bool > ClSanitizeGuardChecks("ubsan-guard-checks", llvm::cl::Optional, llvm::cl::desc("Guard UBSAN checks with `llvm.allow.ubsan.check()`."))
static bool hasBooleanRepresentation(QualType Ty)
Definition: CGExpr.cpp:1877
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:4182
static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind)
Definition: CGExpr.cpp:3516
static bool hasBPFPreserveStaticOffset(const RecordDecl *D)
Definition: CGExpr.cpp:4068
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field)
Drill down to the storage of a field without walking into reference types.
Definition: CGExpr.cpp:4847
ConstantEmissionKind
Can we constant-emit a load of a reference to a variable of the given type? This is different from pr...
Definition: CGExpr.cpp:1731
@ CEK_AsReferenceOnly
Definition: CGExpr.cpp:1733
@ CEK_AsValueOnly
Definition: CGExpr.cpp:1735
@ CEK_None
Definition: CGExpr.cpp:1732
@ CEK_AsValueOrReference
Definition: CGExpr.cpp:1734
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:1706
static QualType getFixedSizeElementType(const ASTContext &ctx, const VariableArrayType *vla)
Definition: CGExpr.cpp:4059
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
Definition: CGExpr.cpp:2930
static std::optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
Definition: CGExpr.cpp:5125
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:4012
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, GlobalDecl GD)
Definition: CGExpr.cpp:2921
static RawAddress MaybeConvertMatrixAddress(RawAddress Addr, CodeGenFunction &CGF, bool IsVector=true)
Definition: CGExpr.cpp:2100
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
Definition: CGExpr.cpp:6284
static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, Address &Addr)
Definition: CGExpr.cpp:4084
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF, const MemberExpr *ME)
Definition: CGExpr.cpp:1841
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:958
static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, CodeGenFunction &CGF)
Definition: CGExpr.cpp:2197
static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type)
Definition: CGExpr.cpp:1737
static QualType getConstantExprReferredType(const FullExpr *E, const ASTContext &Ctx)
Definition: CGExpr.cpp:1538
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool IsBool)
Definition: CGExpr.cpp:1890
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:4213
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD)
Definition: CGExpr.cpp:5633
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
Definition: CGExpr.cpp:2796
static bool getGEPIndicesToField(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, RecIndicesTy &Indices)
Definition: CGExpr.cpp:1108
static bool OnlyHasInlineBuiltinDeclaration(const FunctionDecl *FD)
Definition: CGExpr.cpp:5626
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
Definition: CGExpr.cpp:2870
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
Definition: CGExpr.cpp:4873
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:4097
static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T)
Definition: CGExpr.cpp:2810
static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF, const DeclRefExpr *E, const VarDecl *VD)
Determine whether we can emit a reference to VD from the current context, despite not necessarily hav...
Definition: CGExpr.cpp:2967
VariableTypeDescriptorKind
Definition: CGExpr.cpp:66
@ TK_Float
A floating-point type.
Definition: CGExpr.cpp:70
@ TK_Unknown
Any other type. The value representation is unspecified.
Definition: CGExpr.cpp:74
@ TK_Integer
An integer type.
Definition: CGExpr.cpp:68
@ TK_BitInt
An _BitInt(N) type.
Definition: CGExpr.cpp:72
static CharUnits getArrayElementAlign(CharUnits arrayAlign, llvm::Value *idx, CharUnits eltSize)
Definition: CGExpr.cpp:4044
static RawAddress createReferenceTemporary(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, const Expr *Inner, RawAddress *Alloca=nullptr)
Definition: CGExpr.cpp:434
static bool isAAPCS(const TargetInfo &TargetInfo)
Helper method to check if the underlying ABI is AAPCS.
Definition: CGExpr.cpp:482
static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, bool isInit, CodeGenFunction &CGF)
Definition: CGExpr.cpp:2125
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
Definition: CGExpr.cpp:1277
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, Address addr, const FieldDecl *field)
Definition: CGExpr.cpp:4860
const SanitizerHandlerInfo SanitizerHandlers[]
Definition: CGExpr.cpp:3533
static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base, const FieldDecl *Field)
Get the address of a zero-sized field within a record.
Definition: CGExpr.cpp:4833
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:3539
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
Definition: CGExpr.cpp:4460
static void pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M, const Expr *E, Address ReferenceTemporary)
Definition: CGExpr.cpp:318
const Decl * D
Expr * E
StringRef Filename
Definition: Format.cpp:3032
static const SanitizerMask AlwaysRecoverable
static const SanitizerMask Unrecoverable
static const RecordType * getRecordType(QualType QT)
Checks that the passed in QualType either is of RecordType or points to RecordType.
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
StateNode * Previous
const LValueBase getLValueBase() const
Definition: APValue.cpp:973
bool isLValue() const
Definition: APValue.h:448
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
SourceManager & getSourceManager()
Definition: ASTContext.h:741
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.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
Definition: ASTContext.cpp:854
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType BoolTy
Definition: ASTContext.h:1161
const NoSanitizeList & getNoSanitizeList() const
Definition: ASTContext.h:844
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
Definition: ASTContext.h:1256
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.
Definition: ASTContext.h:2482
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1160
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2918
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
unsigned getTargetAddressSpace(LangAS AS) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4224
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition: Expr.h:6986
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition: Expr.cpp:5177
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
A fixed int type of a specified bitwidth.
Definition: Type.h:7814
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:158
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
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:1378
bool isDynamicClass() const
Definition: DeclCXX.h:586
bool hasDefinition() const
Definition: DeclCXX.h:572
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3547
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
SanitizerSet SanitizeMergeHandlers
Set of sanitizer checks that can merge handlers (smaller code size at the expense of debuggability).
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
SanitizerSet SanitizeTrap
Set of sanitizer checks that trap rather than diagnose.
SanitizerSet SanitizeRecover
Set of sanitizer checks that are non-fatal (i.e.
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
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:193
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:251
CharUnits getAlignment() const
Definition: Address.h:189
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:207
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Definition: Address.h:259
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
KnownNonNull_t isKnownNonNull() const
Whether the pointer is known not to be null.
Definition: Address.h:231
Address setKnownNonNull()
Definition: Address.h:236
void setAlignment(CharUnits Value)
Definition: Address.h:191
void replaceBasePointer(llvm::Value *P)
This function is used in situations where the caller is doing some sort of opaque "laundering" of the...
Definition: Address.h:181
bool isValid() const
Definition: Address.h:177
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:199
An aggregate value slot.
Definition: CGValue.h:504
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition: CGValue.h:572
Address getAddress() const
Definition: CGValue.h:644
void setExternallyDestructed(bool destructed=true)
Definition: CGValue.h:613
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:602
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:587
RValue asRValue() const
Definition: CGValue.h:666
A scoped helper to set the current debug location to the specified location or preferred location of ...
Definition: CGDebugInfo.h:856
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
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:305
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:292
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition: CGBuilder.h:203
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Definition: CGBuilder.h:331
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:241
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition: CGBuilder.h:219
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
Address CreatePreserveStructAccessIndex(Address Addr, unsigned Index, unsigned FieldIndex, llvm::MDNode *DbgInfo)
Definition: CGBuilder.h:413
Address CreateLaunderInvariantGroup(Address Addr)
Definition: CGBuilder.h:437
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
Address CreatePreserveUnionAccessIndex(Address Addr, unsigned FieldIndex, llvm::MDNode *DbgInfo)
Definition: CGBuilder.h:429
Address CreateStripInvariantGroup(Address Addr)
Definition: CGBuilder.h:443
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition: CGBuilder.h:189
Address CreateConstInBoundsGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = T* ... produce name = getelementptr inbounds addr, i64 index where i64 is actually the t...
Definition: CGBuilder.h:261
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition: CGBuilder.h:346
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 llvm::Value * EmitMemberPointerIsNotNull(CodeGenFunction &CGF, llvm::Value *MemPtr, const MemberPointerType *MPT)
Determine if a member pointer is non-null. Returns an i1.
Definition: CGCXXABI.cpp:97
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
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:113
Abstract information about a function or function prototype.
Definition: CGCall.h:41
const GlobalDecl getCalleeDecl() const
Definition: CGCall.h:59
All available information about a concrete callee.
Definition: CGCall.h:63
CGCalleeInfo getAbstractInfo() const
Definition: CGCall.h:180
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
Definition: CGCall.h:172
bool isPseudoDestructor() const
Definition: CGCall.h:169
static CGCallee forBuiltin(unsigned builtinID, const FunctionDecl *builtinDecl)
Definition: CGCall.h:123
unsigned getBuiltinID() const
Definition: CGCall.h:164
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:137
bool isBuiltin() const
Definition: CGCall.h:157
const FunctionDecl * getBuiltinDecl() const
Definition: CGCall.h:160
static CGCallee forPseudoDestructor(const CXXPseudoDestructorExpr *E)
Definition: CGCall.h:131
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:58
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
CGFunctionInfo - Class to encapsulate the information about a function definition.
virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, llvm::Value *ivarOffset)=0
virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest)=0
virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy, llvm::Value *BaseValue, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)=0
virtual llvm::Value * EmitIvarOffset(CodeGen::CodeGenFunction &CGF, const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)=0
virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF, Address AddrWeakObj)=0
virtual Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel)=0
Get the address of a selector for the specified name and type values.
virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest)=0
virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF, llvm::Value *src, Address dest, bool threadlocal=false)=0
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.
bool isNontemporalDecl(const ValueDecl *VD) const
Checks if the VD variable is marked as nontemporal declaration in current context.
virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, const Expr *LHS)
Checks if the provided LVal is lastprivate conditional and emits the code to update the value of the ...
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
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:274
void add(RValue rvalue, QualType type)
Definition: CGCall.h:305
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr, llvm::Value *lifetimeSz=nullptr)
Definition: CGCall.h:326
virtual const FieldDecl * lookup(const VarDecl *VD) const
Lookup the captured field decl for a variable.
static ConstantEmission forValue(llvm::Constant *C)
static ConstantEmission forReference(llvm::Constant *C)
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
RValue EmitLoadOfGlobalRegLValue(LValue LV)
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E)
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
llvm::Value * EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr)
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.
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
LValue EmitCastLValue(const CastExpr *E)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified.
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
SanitizerSet SanOpts
Sanitizers enabled for this function.
LValue EmitCoawaitLValue(const CoawaitExpr *E)
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
llvm::Value * EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
CGCapturedStmtInfo * CapturedStmtInfo
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
LValue EmitCallExprLValue(const CallExpr *E, llvm::CallBase **CallOrInvoke=nullptr)
void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
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.
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
LValue EmitHLSLArrayAssignLValue(const BinaryOperator *E)
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty)
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
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.
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
LValue EmitBinaryOperatorLValue(const BinaryOperator *E)
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
llvm::Value * EmitARCLoadWeakRetained(Address addr)
const LangOptions & getLangOpts() const
llvm::Value * LoadPassedObjectSize(const Expr *E, QualType EltTy)
If E references a parameter with pass_object_size info or a constant array size modifier,...
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
LValue EmitInitListLValue(const InitListExpr *E)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
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...
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 EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Address EmitExtVectorElementLValue(LValue V)
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...
@ 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.
void SetDivFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
LValue EmitUnsupportedLValue(const Expr *E, const char *Name)
EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue an ErrorUnsupported style ...
llvm::Type * ConvertTypeForMem(QualType T)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
unsigned getDebugInfoFIndex(const RecordDecl *Rec, unsigned FieldIndex)
Get the record field index as represented in debug info.
LValue EmitLValueForField(LValue Base, const FieldDecl *Field)
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
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...
@ ForceLeftToRight
! Language semantics require left-to-right evaluation.
@ Default
! No language constraints on evaluation order.
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr)
llvm::Value * EmitARCLoadWeak(Address addr)
const TargetInfo & getTarget() const
LValue EmitCXXConstructLValue(const CXXConstructExpr *E)
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
LValue EmitVAArgExprLValue(const VAArgExpr *E)
bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, SourceLocation Loc)
Check if the scalar Value is within the valid range for the given type Ty.
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
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...
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
LValue EmitCoyieldLValue(const CoyieldExpr *E)
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Address mergeAddressesInConditionalExpr(Address LHS, Address RHS, llvm::BasicBlock *LHSBlock, llvm::BasicBlock *RHSBlock, llvm::BasicBlock *MergeBlock, QualType MergedType)
LValue EmitUnaryOpLValue(const UnaryOperator *E)
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
RValue EmitUnsupportedRValue(const Expr *E, const char *Name)
EmitUnsupportedRValue - Emit a dummy r-value using the type of E and issue an ErrorUnsupported style ...
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
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.
void EmitBoundsCheckImpl(const Expr *E, llvm::Value *Bound, llvm::Value *Index, QualType IndexType, QualType IndexedType, bool Accessed)
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.
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
RValue EmitLoadOfExtVectorElementLValue(LValue V)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
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...
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
Address emitAddrOfImagComponent(Address complex, QualType complexType)
LValue EmitDeclRefLValue(const DeclRefExpr *E)
const TargetCodeGenInfo & getTargetHooks() const
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
LValue EmitPredefinedLValue(const PredefinedExpr *E)
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst)
RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
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,...
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E)
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...
CGCallee EmitCallee(const Expr *E)
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.
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy)
std::pair< LValue, LValue > EmitHLSLOutArgLValues(const HLSLOutArgExpr *E, QualType Ty)
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
llvm::Instruction * getPostAllocaInsertPoint()
Return PostAllocaInsertPt.
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 ...
LValue EmitMemberExpr(const MemberExpr *E)
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, bool Accessed=false)
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FAMDecl, const FieldDecl *CountDecl)
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
CleanupKind getCleanupKind(QualType::DestructionKind kind)
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
llvm::Type * ConvertType(QualType T)
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
Address GetAddrOfBlockDecl(const VarDecl *var)
CodeGenTypes & getTypes() const
void EmitARCInitWeak(Address addr, llvm::Value *value)
LValue EmitArraySectionExpr(const ArraySectionExpr *E, bool IsLowerBound=true)
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E)
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Address EmitCXXUuidofExpr(const CXXUuidofExpr *E)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
LValue EmitStringLiteralLValue(const StringLiteral *E)
static Destroyer destroyARCStrongPrecise
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
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 * 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...
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E)
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
static bool hasAggregateEvaluationKind(QualType T)
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
void SetFPAccuracy(llvm::Value *Val, float Accuracy)
SetFPAccuracy - Set the minimum required accuracy of the given floating point operation,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitCfiSlowPathCheck(SanitizerMask Kind, 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.
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
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...
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
static bool isNullPointerAllowed(TypeCheckKind TCK)
Determine whether the pointer type check TCK permits null pointers.
static Destroyer destroyARCStrongImprecise
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
LValue EmitStmtExprLValue(const StmtExpr *E)
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
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 ...
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
bool LValueIsSuitableForInlineAtomic(LValue Src)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
Address emitAddrOfRealComponent(Address complex, QualType complexType)
static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty)
Determine whether the pointer type check TCK requires a vptr check.
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
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...
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E)
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
LValue EmitLValueForLambdaField(const FieldDecl *Field)
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
This class organizes the cross-function state that is used while generating LLVM code.
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition: CGExpr.cpp:1263
void setDSOLocal(llvm::GlobalValue *GV) const
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.
CGDebugInfo * getModuleDebugInfo()
ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E)
Returns a pointer to a constant global variable for the given file-scope compound literal expression.
llvm::ConstantInt * CreateCrossDsoCfiTypeId(llvm::Metadata *MD)
Generate a cross-DSO type identifier for MD.
void setTypeDescriptorInMap(QualType Ty, llvm::Constant *C)
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
Definition: CGExpr.cpp:2909
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition: CGCXX.cpp:218
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
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.
Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant, CharUnits Align)
Definition: CGDecl.cpp:1105
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
DiagnosticsEngine & getDiags() const
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
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)
const TargetInfo & getTarget() const
llvm::Metadata * CreateMetadataIdentifierForType(QualType T)
Create a metadata identifier for the given type.
llvm::Constant * getTypeDescriptorFromMap(QualType Ty)
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
llvm::MDNode * getTBAABaseTypeInfo(QualType QTy)
getTBAABaseTypeInfo - Get metadata that describes the given base access type.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
const llvm::DataLayout & getDataLayout() const
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
CGPointerAuthInfo getFunctionPointerAuthInfo(QualType T)
Return the abstract pointer authentication schema for a pointer to the given function type.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
SanitizerMetadata * getSanitizerMetadata()
llvm::Metadata * CreateMetadataIdentifierGeneralized(QualType T)
Create a metadata identifier for the generalization of the given type.
const llvm::Triple & getTriple() const
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:245
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
TBAAAccessInfo getTBAAInfoForSubobject(LValue Base, QualType AccessType)
getTBAAInfoForSubobject - Get TBAA information for an access with a given base lvalue.
llvm::Constant * CreateRuntimeVariable(llvm::Type *Ty, StringRef Name)
Create a new runtime global variable with the specified type and name.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
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.
llvm::MDNode * getTBAATypeInfo(QualType QTy)
getTBAATypeInfo - Get metadata used to describe accesses to objects of the given type.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
TBAAAccessInfo mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, TBAAAccessInfo InfoB)
mergeTBAAInfoForConditionalOperator - Get merged TBAA information for the purposes of conditional ope...
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
void SetLLVMFunctionAttributes(GlobalDecl GD, const CGFunctionInfo &Info, llvm::Function *F, bool IsThunk)
Set the LLVM function attributes (sext, zext, etc).
CharUnits getMinimumObjectSize(QualType Ty)
Returns the minimum object size for an object of the given type.
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character.
void setCurrentStmt(const Stmt *S)
If the execution count for the current statement is known, record that as the current count.
Definition: CodeGenPGO.h:76
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:679
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.
const llvm::DataLayout & getDataLayout() const
Definition: CodeGenTypes.h:99
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall)
Figure out the rules for calling a function with the given formal type using the given arguments.
Definition: CGCall.cpp:638
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:294
ConstantAddress withElementType(llvm::Type *ElemTy) const
Definition: Address.h:310
llvm::Constant * getPointer() const
Definition: Address.h:306
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:382
void mergeForCast(const LValueBaseInfo &Info)
Definition: CGValue.h:174
AlignmentSource getAlignmentSource() const
Definition: CGValue.h:171
LValue - This represents an lvalue references.
Definition: CGValue.h:182
bool isBitField() const
Definition: CGValue.h:280
bool isMatrixElt() const
Definition: CGValue.h:283
Expr * getBaseIvarExp() const
Definition: CGValue.h:332
llvm::Constant * getExtVectorElts() const
Definition: CGValue.h:409
static LValue MakeGlobalReg(llvm::Value *V, CharUnits alignment, QualType type)
Definition: CGValue.h:478
void setObjCIvar(bool Value)
Definition: CGValue.h:298
bool isObjCArray() const
Definition: CGValue.h:300
bool isObjCStrong() const
Definition: CGValue.h:324
bool isGlobalObjCRef() const
Definition: CGValue.h:306
bool isVectorElt() const
Definition: CGValue.h:279
void setObjCArray(bool Value)
Definition: CGValue.h:301
bool isSimple() const
Definition: CGValue.h:278
bool isVolatileQualified() const
Definition: CGValue.h:285
RValue asAggregateRValue() const
Definition: CGValue.h:498
CharUnits getAlignment() const
Definition: CGValue.h:343
llvm::Value * getPointer(CodeGenFunction &CGF) const
llvm::Value * getMatrixIdx() const
Definition: CGValue.h:395
llvm::Value * getGlobalReg() const
Definition: CGValue.h:430
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:432
bool isVolatile() const
Definition: CGValue.h:328
const Qualifiers & getQuals() const
Definition: CGValue.h:338
bool isGlobalReg() const
Definition: CGValue.h:282
static LValue MakeExtVectorElt(Address Addr, llvm::Constant *Elts, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:452
bool isObjCWeak() const
Definition: CGValue.h:321
Address getAddress() const
Definition: CGValue.h:361
unsigned getVRQualifiers() const
Definition: CGValue.h:287
void setThreadLocalRef(bool Value)
Definition: CGValue.h:310
LValue setKnownNonNull()
Definition: CGValue.h:350
bool isNonGC() const
Definition: CGValue.h:303
void setGlobalObjCRef(bool Value)
Definition: CGValue.h:307
bool isExtVectorElt() const
Definition: CGValue.h:281
llvm::Value * getVectorIdx() const
Definition: CGValue.h:382
void setNontemporal(bool Value)
Definition: CGValue.h:319
LValueBaseInfo getBaseInfo() const
Definition: CGValue.h:346
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
Definition: CGValue.h:315
QualType getType() const
Definition: CGValue.h:291
const CGBitFieldInfo & getBitFieldInfo() const
Definition: CGValue.h:424
bool isThreadLocalRef() const
Definition: CGValue.h:309
KnownNonNull_t isKnownNonNull() const
Definition: CGValue.h:349
TBAAAccessInfo getTBAAInfo() const
Definition: CGValue.h:335
void setNonGC(bool Value)
Definition: CGValue.h:304
Address getVectorAddress() const
Definition: CGValue.h:370
bool isNontemporal() const
Definition: CGValue.h:318
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:468
bool isObjCIvar() const
Definition: CGValue.h:297
static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:442
void setAddress(Address address)
Definition: CGValue.h:363
void setBaseIvarExp(Expr *V)
Definition: CGValue.h:333
Address getExtVectorAddress() const
Definition: CGValue.h:401
static LValue MakeMatrixElt(Address matAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Definition: CGValue.h:488
Address getMatrixAddress() const
Definition: CGValue.h:387
Address getBitFieldAddress() const
Definition: CGValue.h:415
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:98
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition: CGValue.h:125
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition: CGValue.h:108
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:83
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:71
An abstract representation of an aligned address.
Definition: Address.h:42
RawAddress withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:100
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
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:386
void disableSanitizerForGlobal(llvm::GlobalVariable *GV)
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information,...
Definition: TargetInfo.h:237
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3477
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:195
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2016
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1463
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:488
ValueDecl * getDecl()
Definition: Expr.h:1333
SourceLocation getLocation() const
Definition: Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:576
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:549
DeclContext * getDeclContext()
Definition: DeclBase.h:451
bool hasAttr() const
Definition: DeclBase.h:580
void ConvertArgToString(ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, ArrayRef< intptr_t > QualTypeVals) const
Converts a diagnostic argument (as an intptr_t) into the string that represents it.
Definition: Diagnostic.h:903
Represents an enum.
Definition: Decl.h:3847
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4061
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition: Decl.cpp:4996
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3799
This represents one expression.
Definition: Expr.h:110
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:82
bool isGLValue() const
Definition: Expr.h:280
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:3117
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3078
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3086
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:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
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:1543
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:3587
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3070
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
bool isFlexibleArrayMemberLike(ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
Definition: Expr.cpp:206
QualType getType() const
Definition: Expr.h:142
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
Definition: Expr.cpp:3001
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6354
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4654
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition: Decl.cpp:4705
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1044
const Expr * getSubExpr() const
Definition: Expr.h:1057
Represents a function declaration or definition.
Definition: Decl.h:1935
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
const Decl * getDecl() const
Definition: GlobalDecl.h:103
This class represents temporary values used to represent inout and out arguments in HLSL.
Definition: Expr.h:7152
Describes an C or C++ initializer list.
Definition: Expr.h:5088
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:505
virtual void mangleCXXRTTI(QualType T, raw_ostream &)=0
unsigned getBlockId(const BlockDecl *BD, bool Local)
Definition: Mangle.h:84
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4734
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4759
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition: ExprCXX.h:4751
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition: ExprCXX.h:4784
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2796
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why? This is only meaningful if the named memb...
Definition: Expr.h:3460
Expr * getBase() const
Definition: Expr.h:3313
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3431
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
bool isObjCBOOLType(QualType T) const
Returns true if.
Definition: NSAPI.cpp:481
This represents a decl that may have a name.
Definition: Decl.h:253
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
A C++ nested-name-specifier augmented with source location information.
bool containsType(SanitizerMask Mask, StringRef MangledTypeName, StringRef Category=StringRef()) const
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
Represents a class type in Objective C.
Definition: Type.h:7326
ObjCSelectorExpr used for @selector in Objective-C.
Definition: ExprObjC.h:455
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition: Expr.h:1223
bool isUnique() const
Definition: Expr.h:1231
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
StringRef getIdentKindName() const
Definition: Expr.h:2048
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.
bool isValid() const
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
const Expr *const * const_semantics_iterator
Definition: Expr.h:6611
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1174
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition: Type.h:1028
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:512
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasConst() const
Definition: Type.h:450
void addCVRQualifiers(unsigned mask)
Definition: Type.h:495
void removeObjCGCAttr()
Definition: Type.h:516
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
Definition: Type.h:643
void setAddressSpace(LangAS space)
Definition: Type.h:584
bool hasVolatile() const
Definition: Type.h:460
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
void addVolatile()
Definition: Type.h:463
Represents a struct/union/class.
Definition: Decl.h:4148
field_range fields() const
Definition: Decl.h:4354
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4339
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
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.
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:4466
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
bool isUnion() const
Definition: Decl.h:3770
Exposes information about the current target.
Definition: TargetInfo.h:220
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
virtual StringRef getABI() const
Get the ABI currently in use.
Definition: TargetInfo.h:1330
const Type * getTypeForDecl() const
Definition: Decl.h:3395
The type-property cache.
Definition: Type.cpp:4501
The base class of the type hierarchy.
Definition: Type.h:1828
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
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:1933
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8809
bool isConstantArrayType() const
Definition: Type.h:8262
bool isArrayType() const
Definition: Type.h:8258
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isCountAttributedType() const
Definition: Type.cpp:727
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isConstantMatrixType() const
Definition: Type.h:8320
bool isPointerType() const
Definition: Type.h:8186
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isVariableArrayType() const
Definition: Type.h:8270
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isExtVectorBoolType() const
Definition: Type.h:8306
bool isBitIntType() const
Definition: Type.h:8424
bool isAnyComplexType() const
Definition: Type.h:8294
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8681
bool isAtomicType() const
Definition: Type.h:8341
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool isVectorType() const
Definition: Type.h:8298
bool isFloatingType() const
Definition: Type.cpp:2283
bool isSubscriptableVectorType() const
Definition: Type.h:8312
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:638
bool isRecordType() const
Definition: Type.h:8286
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4750
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:882
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:908
@ TLS_None
Not a TLS variable.
Definition: Decl.h:902
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
#define INT_MIN
Definition: limits.h:55
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
Definition: CGValue.h:141
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
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...
Definition: EHScopeStack.h:80
@ ARCImpreciseLifetime
Definition: CGValue.h:136
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:159
@ NotKnownNonNull
Definition: Address.h:33
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const AstTypeMatcher< FunctionType > functionType
Matches FunctionType nodes.
constexpr Variable var(Literal L)
Returns the variable of L.
Definition: CNFFormula.h:64
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Definition: StoreRef.h:27
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2445
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2408
bool IsNonNull(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2433
bool Load(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1748
bool Cast(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2181
The JSON file list parser is used to communicate input to InstallAPI.
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus
Definition: LangStandard.h:55
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:154
@ SC_Register
Definition: Specifiers.h:257
@ 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:327
@ SD_Thread
Thread storage duration.
Definition: Specifiers.h:330
@ SD_Static
Static storage duration.
Definition: Specifiers.h:331
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:328
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:329
@ SD_Dynamic
Dynamic storage duration.
Definition: Specifiers.h:332
@ Result
The result type of a method or function.
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
const FunctionProtoType * T
LangAS getLangASFromTargetAS(unsigned TargetAS)
Definition: AddressSpaces.h:86
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:180
unsigned long uint64_t
unsigned int uint32_t
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
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.
Definition: CodeGenTBAA.h:105
uint64_t Offset
Offset - The byte offset of the final access within the base one.
Definition: CodeGenTBAA.h:109
static TBAAAccessInfo getMayAliasInfo()
Definition: CodeGenTBAA.h:63
uint64_t Size
Size - The size of access, in bytes.
Definition: CodeGenTBAA.h:112
llvm::MDNode * BaseType
BaseType - The base/leading access type.
Definition: CodeGenTBAA.h:101
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
PointerAuthSchema FunctionPointers
The ABI for C function pointers.
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition: Sanitizers.h:168
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:159
An adjustment to be made to the temporary created when emitting a reference binding,...
Definition: Expr.h:66