1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
16 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CGRecordLayout.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenModule.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/NSAPI.h"
28 #include "clang/Frontend/CodeGenOptions.h"
29 #include "llvm/ADT/Hashing.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/MDBuilder.h"
35 #include "llvm/Support/ConvertUTF.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Transforms/Utils/SanitizerStats.h"
42 using namespace clang;
43 using namespace CodeGen;
45 //===--------------------------------------------------------------------===//
46 // Miscellaneous Helper Methods
47 //===--------------------------------------------------------------------===//
49 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
50 unsigned addressSpace =
51 cast<llvm::PointerType>(value->getType())->getAddressSpace();
53 llvm::PointerType *destType = Int8PtrTy;
55 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
57 if (value->getType() == destType) return value;
58 return Builder.CreateBitCast(value, destType);
61 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
63 Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
65 auto Alloca = CreateTempAlloca(Ty, Name);
66 Alloca->setAlignment(Align.getQuantity());
67 return Address(Alloca, Align);
70 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
72 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
74 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
75 nullptr, Name, AllocaInsertPt);
78 /// CreateDefaultAlignTempAlloca - This creates an alloca with the
79 /// default alignment of the corresponding LLVM type, which is *not*
80 /// guaranteed to be related in any way to the expected alignment of
81 /// an AST type that might have been lowered to Ty.
82 Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
85 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
86 return CreateTempAlloca(Ty, Align, Name);
89 void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
90 assert(isa<llvm::AllocaInst>(Var.getPointer()));
91 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
92 Store->setAlignment(Var.getAlignment().getQuantity());
93 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
94 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
97 Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
98 CharUnits Align = getContext().getTypeAlignInChars(Ty);
99 return CreateTempAlloca(ConvertType(Ty), Align, Name);
102 Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
103 // FIXME: Should we prefer the preferred type alignment here?
104 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
107 Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
109 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
112 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
113 /// expression and compare the result against zero, returning an Int1Ty value.
114 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
115 PGO.setCurrentStmt(E);
116 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
117 llvm::Value *MemPtr = EmitScalarExpr(E);
118 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
121 QualType BoolTy = getContext().BoolTy;
122 SourceLocation Loc = E->getExprLoc();
123 if (!E->getType()->isAnyComplexType())
124 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
126 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
130 /// EmitIgnoredExpr - Emit code to compute the specified expression,
131 /// ignoring the result.
132 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
134 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
136 // Just emit it as an l-value and drop the result.
140 /// EmitAnyExpr - Emit code to compute the specified expression which
141 /// can have any type. The result is returned as an RValue struct.
142 /// If this is an aggregate expression, AggSlot indicates where the
143 /// result should be returned.
144 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
145 AggValueSlot aggSlot,
147 switch (getEvaluationKind(E->getType())) {
149 return RValue::get(EmitScalarExpr(E, ignoreResult));
151 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
153 if (!ignoreResult && aggSlot.isIgnored())
154 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
155 EmitAggExpr(E, aggSlot);
156 return aggSlot.asRValue();
158 llvm_unreachable("bad evaluation kind");
161 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
162 /// always be accessible even if no aggregate location is provided.
163 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
164 AggValueSlot AggSlot = AggValueSlot::ignored();
166 if (hasAggregateEvaluationKind(E->getType()))
167 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
168 return EmitAnyExpr(E, AggSlot);
171 /// EmitAnyExprToMem - Evaluate an expression into a given memory
173 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
177 // FIXME: This function should take an LValue as an argument.
178 switch (getEvaluationKind(E->getType())) {
180 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
184 case TEK_Aggregate: {
185 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
186 AggValueSlot::IsDestructed_t(IsInit),
187 AggValueSlot::DoesNotNeedGCBarriers,
188 AggValueSlot::IsAliased_t(!IsInit)));
193 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
194 LValue LV = MakeAddrLValue(Location, E->getType());
195 EmitStoreThroughLValue(RV, LV);
199 llvm_unreachable("bad evaluation kind");
203 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
204 const Expr *E, Address ReferenceTemporary) {
205 // Objective-C++ ARC:
206 // If we are binding a reference to a temporary that has ownership, we
207 // need to perform retain/release operations on the temporary.
209 // FIXME: This should be looking at E, not M.
210 if (auto Lifetime = M->getType().getObjCLifetime()) {
212 case Qualifiers::OCL_None:
213 case Qualifiers::OCL_ExplicitNone:
214 // Carry on to normal cleanup handling.
217 case Qualifiers::OCL_Autoreleasing:
218 // Nothing to do; cleaned up by an autorelease pool.
221 case Qualifiers::OCL_Strong:
222 case Qualifiers::OCL_Weak:
223 switch (StorageDuration Duration = M->getStorageDuration()) {
225 // Note: we intentionally do not register a cleanup to release
226 // the object on program termination.
230 // FIXME: We should probably register a cleanup in this case.
234 case SD_FullExpression:
235 CodeGenFunction::Destroyer *Destroy;
236 CleanupKind CleanupKind;
237 if (Lifetime == Qualifiers::OCL_Strong) {
238 const ValueDecl *VD = M->getExtendingDecl();
240 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
241 CleanupKind = CGF.getARCCleanupKind();
242 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
243 : &CodeGenFunction::destroyARCStrongImprecise;
245 // __weak objects always get EH cleanups; otherwise, exceptions
246 // could cause really nasty crashes instead of mere leaks.
247 CleanupKind = NormalAndEHCleanup;
248 Destroy = &CodeGenFunction::destroyARCWeak;
250 if (Duration == SD_FullExpression)
251 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
252 M->getType(), *Destroy,
253 CleanupKind & EHCleanup);
255 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
257 *Destroy, CleanupKind & EHCleanup);
261 llvm_unreachable("temporary cannot have dynamic storage duration");
263 llvm_unreachable("unknown storage duration");
267 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
268 if (const RecordType *RT =
269 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
270 // Get the destructor for the reference temporary.
271 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
272 if (!ClassDecl->hasTrivialDestructor())
273 ReferenceTemporaryDtor = ClassDecl->getDestructor();
276 if (!ReferenceTemporaryDtor)
279 // Call the destructor for the temporary.
280 switch (M->getStorageDuration()) {
283 llvm::Constant *CleanupFn;
284 llvm::Constant *CleanupArg;
285 if (E->getType()->isArrayType()) {
286 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
287 ReferenceTemporary, E->getType(),
288 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
289 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
290 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
292 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
293 StructorType::Complete);
294 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
296 CGF.CGM.getCXXABI().registerGlobalDtor(
297 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
301 case SD_FullExpression:
302 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
303 CodeGenFunction::destroyCXXObject,
304 CGF.getLangOpts().Exceptions);
308 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
309 ReferenceTemporary, E->getType(),
310 CodeGenFunction::destroyCXXObject,
311 CGF.getLangOpts().Exceptions);
315 llvm_unreachable("temporary cannot have dynamic storage duration");
320 createReferenceTemporary(CodeGenFunction &CGF,
321 const MaterializeTemporaryExpr *M, const Expr *Inner) {
322 switch (M->getStorageDuration()) {
323 case SD_FullExpression:
325 // If we have a constant temporary array or record try to promote it into a
326 // constant global under the same rules a normal constant would've been
327 // promoted. This is easier on the optimizer and generally emits fewer
329 QualType Ty = Inner->getType();
330 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
331 (Ty->isArrayType() || Ty->isRecordType()) &&
332 CGF.CGM.isTypeConstant(Ty, true))
333 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
334 auto *GV = new llvm::GlobalVariable(
335 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
336 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
337 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
338 GV->setAlignment(alignment.getQuantity());
339 // FIXME: Should we put the new global into a COMDAT?
340 return Address(GV, alignment);
342 return CGF.CreateMemTemp(Ty, "ref.tmp");
346 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
349 llvm_unreachable("temporary can't have dynamic storage duration");
351 llvm_unreachable("unknown storage duration");
354 LValue CodeGenFunction::
355 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
356 const Expr *E = M->GetTemporaryExpr();
358 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
359 // as that will cause the lifetime adjustment to be lost for ARC
360 auto ownership = M->getType().getObjCLifetime();
361 if (ownership != Qualifiers::OCL_None &&
362 ownership != Qualifiers::OCL_ExplicitNone) {
363 Address Object = createReferenceTemporary(*this, M, E);
364 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
365 Object = Address(llvm::ConstantExpr::getBitCast(Var,
366 ConvertTypeForMem(E->getType())
367 ->getPointerTo(Object.getAddressSpace())),
368 Object.getAlignment());
370 // createReferenceTemporary will promote the temporary to a global with a
371 // constant initializer if it can. It can only do this to a value of
372 // ARC-manageable type if the value is global and therefore "immune" to
373 // ref-counting operations. Therefore we have no need to emit either a
374 // dynamic initialization or a cleanup and we can just return the address
376 if (Var->hasInitializer())
377 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
379 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
381 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
382 AlignmentSource::Decl);
384 switch (getEvaluationKind(E->getType())) {
385 default: llvm_unreachable("expected scalar or aggregate expression");
387 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
389 case TEK_Aggregate: {
390 EmitAggExpr(E, AggValueSlot::forAddr(Object,
391 E->getType().getQualifiers(),
392 AggValueSlot::IsDestructed,
393 AggValueSlot::DoesNotNeedGCBarriers,
394 AggValueSlot::IsNotAliased));
399 pushTemporaryCleanup(*this, M, E, Object);
403 SmallVector<const Expr *, 2> CommaLHSs;
404 SmallVector<SubobjectAdjustment, 2> Adjustments;
405 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
407 for (const auto &Ignored : CommaLHSs)
408 EmitIgnoredExpr(Ignored);
410 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
411 if (opaque->getType()->isRecordType()) {
412 assert(Adjustments.empty());
413 return EmitOpaqueValueLValue(opaque);
417 // Create and initialize the reference temporary.
418 Address Object = createReferenceTemporary(*this, M, E);
419 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
420 Object = Address(llvm::ConstantExpr::getBitCast(
421 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
422 Object.getAlignment());
423 // If the temporary is a global and has a constant initializer or is a
424 // constant temporary that we promoted to a global, we may have already
426 if (!Var->hasInitializer()) {
427 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
428 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
431 switch (M->getStorageDuration()) {
433 case SD_FullExpression:
434 if (auto *Size = EmitLifetimeStart(
435 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
436 Object.getPointer())) {
437 if (M->getStorageDuration() == SD_Automatic)
438 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
441 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
448 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
450 pushTemporaryCleanup(*this, M, E, Object);
452 // Perform derived-to-base casts and/or field accesses, to get from the
453 // temporary object we created (and, potentially, for which we extended
454 // the lifetime) to the subobject we're binding the reference to.
455 for (unsigned I = Adjustments.size(); I != 0; --I) {
456 SubobjectAdjustment &Adjustment = Adjustments[I-1];
457 switch (Adjustment.Kind) {
458 case SubobjectAdjustment::DerivedToBaseAdjustment:
460 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
461 Adjustment.DerivedToBase.BasePath->path_begin(),
462 Adjustment.DerivedToBase.BasePath->path_end(),
463 /*NullCheckValue=*/ false, E->getExprLoc());
466 case SubobjectAdjustment::FieldAdjustment: {
467 LValue LV = MakeAddrLValue(Object, E->getType(),
468 AlignmentSource::Decl);
469 LV = EmitLValueForField(LV, Adjustment.Field);
470 assert(LV.isSimple() &&
471 "materialized temporary field is not a simple lvalue");
472 Object = LV.getAddress();
476 case SubobjectAdjustment::MemberPointerAdjustment: {
477 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
478 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
485 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
489 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
490 // Emit the expression as an lvalue.
491 LValue LV = EmitLValue(E);
492 assert(LV.isSimple());
493 llvm::Value *Value = LV.getPointer();
495 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
496 // C++11 [dcl.ref]p5 (as amended by core issue 453):
497 // If a glvalue to which a reference is directly bound designates neither
498 // an existing object or function of an appropriate type nor a region of
499 // storage of suitable size and alignment to contain an object of the
500 // reference's type, the behavior is undefined.
501 QualType Ty = E->getType();
502 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
505 return RValue::get(Value);
509 /// getAccessedFieldNo - Given an encoded value and a result number, return the
510 /// input field number being accessed.
511 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
512 const llvm::Constant *Elts) {
513 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
517 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
518 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
520 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
521 llvm::Value *K47 = Builder.getInt64(47);
522 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
523 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
524 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
525 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
526 return Builder.CreateMul(B1, KMul);
529 bool CodeGenFunction::sanitizePerformTypeCheck() const {
530 return SanOpts.has(SanitizerKind::Null) |
531 SanOpts.has(SanitizerKind::Alignment) |
532 SanOpts.has(SanitizerKind::ObjectSize) |
533 SanOpts.has(SanitizerKind::Vptr);
536 /// Check if a runtime null check for \p Ptr can be omitted.
537 static bool canOmitPointerNullCheck(llvm::Value *Ptr) {
538 // Note: do not perform any constant-folding in this function. That is best
539 // left to the IR builder.
541 // Pointers to alloca'd memory are non-null.
542 return isa<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
545 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
546 llvm::Value *Ptr, QualType Ty,
548 SanitizerSet SkippedChecks) {
549 if (!sanitizePerformTypeCheck())
552 // Don't check pointers outside the default address space. The null check
553 // isn't correct, the object-size check isn't supported by LLVM, and we can't
554 // communicate the addresses to the runtime handler for the vptr check.
555 if (Ptr->getType()->getPointerAddressSpace())
558 SanitizerScope SanScope(this);
560 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
561 llvm::BasicBlock *Done = nullptr;
563 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
564 TCK == TCK_UpcastToVirtualBase;
565 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
566 !SkippedChecks.has(SanitizerKind::Null) &&
567 !canOmitPointerNullCheck(Ptr)) {
568 // The glvalue must not be an empty glvalue.
569 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
571 // The IR builder can constant-fold the null check if the pointer points to
574 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
576 // Skip the null check if the pointer is known to be non-null.
578 if (AllowNullPointers) {
579 // When performing pointer casts, it's OK if the value is null.
580 // Skip the remaining checks in that case.
581 Done = createBasicBlock("null");
582 llvm::BasicBlock *Rest = createBasicBlock("not.null");
583 Builder.CreateCondBr(IsNonNull, Rest, Done);
586 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
591 if (SanOpts.has(SanitizerKind::ObjectSize) &&
592 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
593 !Ty->isIncompleteType()) {
594 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
596 // The glvalue must refer to a large enough storage region.
597 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
599 // FIXME: Get object address space
600 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
601 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
602 llvm::Value *Min = Builder.getFalse();
603 llvm::Value *NullIsUnknown = Builder.getFalse();
604 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
605 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
606 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
607 llvm::ConstantInt::get(IntPtrTy, Size));
608 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
611 uint64_t AlignVal = 0;
613 if (SanOpts.has(SanitizerKind::Alignment) &&
614 !SkippedChecks.has(SanitizerKind::Alignment)) {
615 AlignVal = Alignment.getQuantity();
616 if (!Ty->isIncompleteType() && !AlignVal)
617 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
619 // The glvalue must be suitably aligned.
622 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
623 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
624 llvm::Value *Aligned =
625 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
626 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
630 if (Checks.size() > 0) {
631 // Make sure we're not losing information. Alignment needs to be a power of
633 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
634 llvm::Constant *StaticData[] = {
635 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
636 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
637 llvm::ConstantInt::get(Int8Ty, TCK)};
638 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
641 // If possible, check that the vptr indicates that there is a subobject of
642 // type Ty at offset zero within this object.
644 // C++11 [basic.life]p5,6:
645 // [For storage which does not refer to an object within its lifetime]
646 // The program has undefined behavior if:
647 // -- the [pointer or glvalue] is used to access a non-static data member
648 // or call a non-static member function
649 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
650 if (SanOpts.has(SanitizerKind::Vptr) &&
651 !SkippedChecks.has(SanitizerKind::Vptr) &&
652 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
653 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
654 TCK == TCK_UpcastToVirtualBase) &&
655 RD && RD->hasDefinition() && RD->isDynamicClass()) {
656 // Compute a hash of the mangled name of the type.
658 // FIXME: This is not guaranteed to be deterministic! Move to a
659 // fingerprinting mechanism once LLVM provides one. For the time
660 // being the implementation happens to be deterministic.
661 SmallString<64> MangledName;
662 llvm::raw_svector_ostream Out(MangledName);
663 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
666 // Blacklist based on the mangled type.
667 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
669 llvm::hash_code TypeHash = hash_value(Out.str());
671 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
672 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
673 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
674 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
675 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
676 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
678 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
679 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
681 // Look the hash up in our cache.
682 const int CacheSize = 128;
683 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
684 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
685 "__ubsan_vptr_type_cache");
686 llvm::Value *Slot = Builder.CreateAnd(Hash,
687 llvm::ConstantInt::get(IntPtrTy,
689 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
690 llvm::Value *CacheVal =
691 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
694 // If the hash isn't in the cache, call a runtime handler to perform the
695 // hard work of checking whether the vptr is for an object of the right
696 // type. This will either fill in the cache and return, or produce a
698 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
699 llvm::Constant *StaticData[] = {
700 EmitCheckSourceLocation(Loc),
701 EmitCheckTypeDescriptor(Ty),
702 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
703 llvm::ConstantInt::get(Int8Ty, TCK)
705 llvm::Value *DynamicData[] = { Ptr, Hash };
706 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
707 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
713 Builder.CreateBr(Done);
718 /// Determine whether this expression refers to a flexible array member in a
719 /// struct. We disable array bounds checks for such members.
720 static bool isFlexibleArrayMemberExpr(const Expr *E) {
721 // For compatibility with existing code, we treat arrays of length 0 or
722 // 1 as flexible array members.
723 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
724 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
725 if (CAT->getSize().ugt(1))
727 } else if (!isa<IncompleteArrayType>(AT))
730 E = E->IgnoreParens();
732 // A flexible array member must be the last member in the class.
733 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
734 // FIXME: If the base type of the member expr is not FD->getParent(),
735 // this should not be treated as a flexible array member access.
736 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
737 RecordDecl::field_iterator FI(
738 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
739 return ++FI == FD->getParent()->field_end();
741 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
742 return IRE->getDecl()->getNextIvar() == nullptr;
748 /// If Base is known to point to the start of an array, return the length of
749 /// that array. Return 0 if the length cannot be determined.
750 static llvm::Value *getArrayIndexingBound(
751 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
752 // For the vector indexing extension, the bound is the number of elements.
753 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
754 IndexedType = Base->getType();
755 return CGF.Builder.getInt32(VT->getNumElements());
758 Base = Base->IgnoreParens();
760 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
761 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
762 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
763 IndexedType = CE->getSubExpr()->getType();
764 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
765 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
766 return CGF.Builder.getInt(CAT->getSize());
767 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
768 return CGF.getVLASize(VAT).first;
775 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
776 llvm::Value *Index, QualType IndexType,
778 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
779 "should not be called unless adding bounds checks");
780 SanitizerScope SanScope(this);
782 QualType IndexedType;
783 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
787 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
788 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
789 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
791 llvm::Constant *StaticData[] = {
792 EmitCheckSourceLocation(E->getExprLoc()),
793 EmitCheckTypeDescriptor(IndexedType),
794 EmitCheckTypeDescriptor(IndexType)
796 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
797 : Builder.CreateICmpULE(IndexVal, BoundVal);
798 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
799 SanitizerHandler::OutOfBounds, StaticData, Index);
803 CodeGenFunction::ComplexPairTy CodeGenFunction::
804 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
805 bool isInc, bool isPre) {
806 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
808 llvm::Value *NextVal;
809 if (isa<llvm::IntegerType>(InVal.first->getType())) {
810 uint64_t AmountVal = isInc ? 1 : -1;
811 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
813 // Add the inc/dec to the real part.
814 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
816 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
817 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
820 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
822 // Add the inc/dec to the real part.
823 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
826 ComplexPairTy IncVal(NextVal, InVal.second);
828 // Store the updated result through the lvalue.
829 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
831 // If this is a postinc, return the value read from memory, otherwise use the
833 return isPre ? IncVal : InVal;
836 void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
837 CodeGenFunction *CGF) {
838 // Bind VLAs in the cast type.
839 if (CGF && E->getType()->isVariablyModifiedType())
840 CGF->EmitVariablyModifiedType(E->getType());
842 if (CGDebugInfo *DI = getModuleDebugInfo())
843 DI->EmitExplicitCastType(E->getType());
846 //===----------------------------------------------------------------------===//
847 // LValue Expression Emission
848 //===----------------------------------------------------------------------===//
850 /// EmitPointerWithAlignment - Given an expression of pointer type, try to
851 /// derive a more accurate bound on the alignment of the pointer.
852 Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
853 AlignmentSource *Source) {
854 // We allow this with ObjC object pointers because of fragile ABIs.
855 assert(E->getType()->isPointerType() ||
856 E->getType()->isObjCObjectPointerType());
857 E = E->IgnoreParens();
860 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
861 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
862 CGM.EmitExplicitCastExprType(ECE, this);
864 switch (CE->getCastKind()) {
865 // Non-converting casts (but not C's implicit conversion from void*).
868 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
869 if (PtrTy->getPointeeType()->isVoidType())
872 AlignmentSource InnerSource;
873 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
874 if (Source) *Source = InnerSource;
876 // If this is an explicit bitcast, and the source l-value is
877 // opaque, honor the alignment of the casted-to type.
878 if (isa<ExplicitCastExpr>(CE) &&
879 InnerSource != AlignmentSource::Decl) {
880 Addr = Address(Addr.getPointer(),
881 getNaturalPointeeTypeAlignment(E->getType(), Source));
884 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
885 CE->getCastKind() == CK_BitCast) {
886 if (auto PT = E->getType()->getAs<PointerType>())
887 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
889 CodeGenFunction::CFITCK_UnrelatedCast,
893 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
897 // Array-to-pointer decay.
898 case CK_ArrayToPointerDecay:
899 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
901 // Derived-to-base conversions.
902 case CK_UncheckedDerivedToBase:
903 case CK_DerivedToBase: {
904 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
905 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
906 return GetAddressOfBaseClass(Addr, Derived,
907 CE->path_begin(), CE->path_end(),
908 ShouldNullCheckClassCastValue(CE),
912 // TODO: Is there any reason to treat base-to-derived conversions
920 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
921 if (UO->getOpcode() == UO_AddrOf) {
922 LValue LV = EmitLValue(UO->getSubExpr());
923 if (Source) *Source = LV.getAlignmentSource();
924 return LV.getAddress();
928 // TODO: conditional operators, comma.
930 // Otherwise, use the alignment of the type.
931 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
932 return Address(EmitScalarExpr(E), Align);
935 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
936 if (Ty->isVoidType())
937 return RValue::get(nullptr);
939 switch (getEvaluationKind(Ty)) {
942 ConvertType(Ty->castAs<ComplexType>()->getElementType());
943 llvm::Value *U = llvm::UndefValue::get(EltTy);
944 return RValue::getComplex(std::make_pair(U, U));
947 // If this is a use of an undefined aggregate type, the aggregate must have an
948 // identifiable address. Just because the contents of the value are undefined
949 // doesn't mean that the address can't be taken and compared.
950 case TEK_Aggregate: {
951 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
952 return RValue::getAggregate(DestPtr);
956 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
958 llvm_unreachable("bad evaluation kind");
961 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
963 ErrorUnsupported(E, Name);
964 return GetUndefRValue(E->getType());
967 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
969 ErrorUnsupported(E, Name);
970 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
971 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
975 bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
976 const Expr *Base = Obj;
977 while (!isa<CXXThisExpr>(Base)) {
978 // The result of a dynamic_cast can be null.
979 if (isa<CXXDynamicCastExpr>(Base))
982 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
983 Base = CE->getSubExpr();
984 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
985 Base = PE->getSubExpr();
986 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
987 if (UO->getOpcode() == UO_Extension)
988 Base = UO->getSubExpr();
998 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1000 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1001 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1004 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1005 SanitizerSet SkippedChecks;
1006 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1007 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1009 SkippedChecks.set(SanitizerKind::Alignment, true);
1010 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1011 SkippedChecks.set(SanitizerKind::Null, true);
1013 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
1014 E->getType(), LV.getAlignment(), SkippedChecks);
1019 /// EmitLValue - Emit code to compute a designator that specifies the location
1020 /// of the expression.
1022 /// This can return one of two things: a simple address or a bitfield reference.
1023 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1024 /// an LLVM pointer type.
1026 /// If this returns a bitfield reference, nothing about the pointee type of the
1027 /// LLVM value is known: For example, it may not be a pointer to an integer.
1029 /// If this returns a normal address, and if the lvalue's C type is fixed size,
1030 /// this method guarantees that the returned pointer type will point to an LLVM
1031 /// type of the same size of the lvalue's type. If the lvalue has a variable
1032 /// length type, this is not possible.
1034 LValue CodeGenFunction::EmitLValue(const Expr *E) {
1035 ApplyDebugLocation DL(*this, E);
1036 switch (E->getStmtClass()) {
1037 default: return EmitUnsupportedLValue(E, "l-value expression");
1039 case Expr::ObjCPropertyRefExprClass:
1040 llvm_unreachable("cannot emit a property reference directly");
1042 case Expr::ObjCSelectorExprClass:
1043 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1044 case Expr::ObjCIsaExprClass:
1045 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1046 case Expr::BinaryOperatorClass:
1047 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1048 case Expr::CompoundAssignOperatorClass: {
1049 QualType Ty = E->getType();
1050 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1051 Ty = AT->getValueType();
1052 if (!Ty->isAnyComplexType())
1053 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1054 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1056 case Expr::CallExprClass:
1057 case Expr::CXXMemberCallExprClass:
1058 case Expr::CXXOperatorCallExprClass:
1059 case Expr::UserDefinedLiteralClass:
1060 return EmitCallExprLValue(cast<CallExpr>(E));
1061 case Expr::VAArgExprClass:
1062 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1063 case Expr::DeclRefExprClass:
1064 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
1065 case Expr::ParenExprClass:
1066 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1067 case Expr::GenericSelectionExprClass:
1068 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1069 case Expr::PredefinedExprClass:
1070 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1071 case Expr::StringLiteralClass:
1072 return EmitStringLiteralLValue(cast<StringLiteral>(E));
1073 case Expr::ObjCEncodeExprClass:
1074 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1075 case Expr::PseudoObjectExprClass:
1076 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1077 case Expr::InitListExprClass:
1078 return EmitInitListLValue(cast<InitListExpr>(E));
1079 case Expr::CXXTemporaryObjectExprClass:
1080 case Expr::CXXConstructExprClass:
1081 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1082 case Expr::CXXBindTemporaryExprClass:
1083 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1084 case Expr::CXXUuidofExprClass:
1085 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1086 case Expr::LambdaExprClass:
1087 return EmitLambdaLValue(cast<LambdaExpr>(E));
1089 case Expr::ExprWithCleanupsClass: {
1090 const auto *cleanups = cast<ExprWithCleanups>(E);
1091 enterFullExpression(cleanups);
1092 RunCleanupsScope Scope(*this);
1093 LValue LV = EmitLValue(cleanups->getSubExpr());
1094 if (LV.isSimple()) {
1095 // Defend against branches out of gnu statement expressions surrounded by
1097 llvm::Value *V = LV.getPointer();
1098 Scope.ForceCleanup({&V});
1099 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1100 getContext(), LV.getAlignmentSource(),
1103 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1104 // bitfield lvalue or some other non-simple lvalue?
1108 case Expr::CXXDefaultArgExprClass:
1109 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1110 case Expr::CXXDefaultInitExprClass: {
1111 CXXDefaultInitExprScope Scope(*this);
1112 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1114 case Expr::CXXTypeidExprClass:
1115 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1117 case Expr::ObjCMessageExprClass:
1118 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1119 case Expr::ObjCIvarRefExprClass:
1120 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1121 case Expr::StmtExprClass:
1122 return EmitStmtExprLValue(cast<StmtExpr>(E));
1123 case Expr::UnaryOperatorClass:
1124 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1125 case Expr::ArraySubscriptExprClass:
1126 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1127 case Expr::OMPArraySectionExprClass:
1128 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1129 case Expr::ExtVectorElementExprClass:
1130 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1131 case Expr::MemberExprClass:
1132 return EmitMemberExpr(cast<MemberExpr>(E));
1133 case Expr::CompoundLiteralExprClass:
1134 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1135 case Expr::ConditionalOperatorClass:
1136 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1137 case Expr::BinaryConditionalOperatorClass:
1138 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1139 case Expr::ChooseExprClass:
1140 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1141 case Expr::OpaqueValueExprClass:
1142 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1143 case Expr::SubstNonTypeTemplateParmExprClass:
1144 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1145 case Expr::ImplicitCastExprClass:
1146 case Expr::CStyleCastExprClass:
1147 case Expr::CXXFunctionalCastExprClass:
1148 case Expr::CXXStaticCastExprClass:
1149 case Expr::CXXDynamicCastExprClass:
1150 case Expr::CXXReinterpretCastExprClass:
1151 case Expr::CXXConstCastExprClass:
1152 case Expr::ObjCBridgedCastExprClass:
1153 return EmitCastLValue(cast<CastExpr>(E));
1155 case Expr::MaterializeTemporaryExprClass:
1156 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1160 /// Given an object of the given canonical type, can we safely copy a
1161 /// value out of it based on its initializer?
1162 static bool isConstantEmittableObjectType(QualType type) {
1163 assert(type.isCanonical());
1164 assert(!type->isReferenceType());
1166 // Must be const-qualified but non-volatile.
1167 Qualifiers qs = type.getLocalQualifiers();
1168 if (!qs.hasConst() || qs.hasVolatile()) return false;
1170 // Otherwise, all object types satisfy this except C++ classes with
1171 // mutable subobjects or non-trivial copy/destroy behavior.
1172 if (const auto *RT = dyn_cast<RecordType>(type))
1173 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1174 if (RD->hasMutableFields() || !RD->isTrivial())
1180 /// Can we constant-emit a load of a reference to a variable of the
1181 /// given type? This is different from predicates like
1182 /// Decl::isUsableInConstantExpressions because we do want it to apply
1183 /// in situations that don't necessarily satisfy the language's rules
1184 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
1185 /// to do this with const float variables even if those variables
1186 /// aren't marked 'constexpr'.
1187 enum ConstantEmissionKind {
1189 CEK_AsReferenceOnly,
1190 CEK_AsValueOrReference,
1193 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1194 type = type.getCanonicalType();
1195 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1196 if (isConstantEmittableObjectType(ref->getPointeeType()))
1197 return CEK_AsValueOrReference;
1198 return CEK_AsReferenceOnly;
1200 if (isConstantEmittableObjectType(type))
1201 return CEK_AsValueOnly;
1205 /// Try to emit a reference to the given value without producing it as
1206 /// an l-value. This is actually more than an optimization: we can't
1207 /// produce an l-value for variables that we never actually captured
1208 /// in a block or lambda, which means const int variables or constexpr
1209 /// literals or similar.
1210 CodeGenFunction::ConstantEmission
1211 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1212 ValueDecl *value = refExpr->getDecl();
1214 // The value needs to be an enum constant or a constant variable.
1215 ConstantEmissionKind CEK;
1216 if (isa<ParmVarDecl>(value)) {
1218 } else if (auto *var = dyn_cast<VarDecl>(value)) {
1219 CEK = checkVarTypeForConstantEmission(var->getType());
1220 } else if (isa<EnumConstantDecl>(value)) {
1221 CEK = CEK_AsValueOnly;
1225 if (CEK == CEK_None) return ConstantEmission();
1227 Expr::EvalResult result;
1228 bool resultIsReference;
1229 QualType resultType;
1231 // It's best to evaluate all the way as an r-value if that's permitted.
1232 if (CEK != CEK_AsReferenceOnly &&
1233 refExpr->EvaluateAsRValue(result, getContext())) {
1234 resultIsReference = false;
1235 resultType = refExpr->getType();
1237 // Otherwise, try to evaluate as an l-value.
1238 } else if (CEK != CEK_AsValueOnly &&
1239 refExpr->EvaluateAsLValue(result, getContext())) {
1240 resultIsReference = true;
1241 resultType = value->getType();
1245 return ConstantEmission();
1248 // In any case, if the initializer has side-effects, abandon ship.
1249 if (result.HasSideEffects)
1250 return ConstantEmission();
1252 // Emit as a constant.
1253 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1255 // Make sure we emit a debug reference to the global variable.
1256 // This should probably fire even for
1257 if (isa<VarDecl>(value)) {
1258 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1259 EmitDeclRefExprDbgValue(refExpr, result.Val);
1261 assert(isa<EnumConstantDecl>(value));
1262 EmitDeclRefExprDbgValue(refExpr, result.Val);
1265 // If we emitted a reference constant, we need to dereference that.
1266 if (resultIsReference)
1267 return ConstantEmission::forReference(C);
1269 return ConstantEmission::forValue(C);
1272 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1273 SourceLocation Loc) {
1274 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1275 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1276 lvalue.getTBAAInfo(),
1277 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1278 lvalue.isNontemporal());
1281 static bool hasBooleanRepresentation(QualType Ty) {
1282 if (Ty->isBooleanType())
1285 if (const EnumType *ET = Ty->getAs<EnumType>())
1286 return ET->getDecl()->getIntegerType()->isBooleanType();
1288 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1289 return hasBooleanRepresentation(AT->getValueType());
1294 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1295 llvm::APInt &Min, llvm::APInt &End,
1296 bool StrictEnums, bool IsBool) {
1297 const EnumType *ET = Ty->getAs<EnumType>();
1298 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1299 ET && !ET->getDecl()->isFixed();
1300 if (!IsBool && !IsRegularCPlusPlusEnum)
1304 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1305 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1307 const EnumDecl *ED = ET->getDecl();
1308 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1309 unsigned Bitwidth = LTy->getScalarSizeInBits();
1310 unsigned NumNegativeBits = ED->getNumNegativeBits();
1311 unsigned NumPositiveBits = ED->getNumPositiveBits();
1313 if (NumNegativeBits) {
1314 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1315 assert(NumBits <= Bitwidth);
1316 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1319 assert(NumPositiveBits <= Bitwidth);
1320 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1321 Min = llvm::APInt(Bitwidth, 0);
1327 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1328 llvm::APInt Min, End;
1329 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1330 hasBooleanRepresentation(Ty)))
1333 llvm::MDBuilder MDHelper(getLLVMContext());
1334 return MDHelper.createRange(Min, End);
1337 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1338 SourceLocation Loc) {
1339 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1340 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1341 if (!HasBoolCheck && !HasEnumCheck)
1344 bool IsBool = hasBooleanRepresentation(Ty) ||
1345 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1346 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1347 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1348 if (!NeedsBoolCheck && !NeedsEnumCheck)
1351 // Single-bit booleans don't need to be checked. Special-case this to avoid
1352 // a bit width mismatch when handling bitfield values. This is handled by
1353 // EmitFromMemory for the non-bitfield case.
1355 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1358 llvm::APInt Min, End;
1359 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1362 SanitizerScope SanScope(this);
1366 Check = Builder.CreateICmpULE(
1367 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1369 llvm::Value *Upper = Builder.CreateICmpSLE(
1370 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1371 llvm::Value *Lower = Builder.CreateICmpSGE(
1372 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1373 Check = Builder.CreateAnd(Upper, Lower);
1375 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1376 EmitCheckTypeDescriptor(Ty)};
1377 SanitizerMask Kind =
1378 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1379 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1380 StaticArgs, EmitCheckValue(Value));
1384 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1387 AlignmentSource AlignSource,
1388 llvm::MDNode *TBAAInfo,
1389 QualType TBAABaseType,
1390 uint64_t TBAAOffset,
1391 bool isNontemporal) {
1392 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1393 // For better performance, handle vector loads differently.
1394 if (Ty->isVectorType()) {
1395 const llvm::Type *EltTy = Addr.getElementType();
1397 const auto *VTy = cast<llvm::VectorType>(EltTy);
1399 // Handle vectors of size 3 like size 4 for better performance.
1400 if (VTy->getNumElements() == 3) {
1402 // Bitcast to vec4 type.
1403 llvm::VectorType *vec4Ty =
1404 llvm::VectorType::get(VTy->getElementType(), 4);
1405 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1407 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1409 // Shuffle vector to get vec3.
1410 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1411 {0, 1, 2}, "extractVec");
1412 return EmitFromMemory(V, Ty);
1417 // Atomic operations have to be done on integral types.
1418 LValue AtomicLValue =
1419 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1420 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1421 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1424 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1425 if (isNontemporal) {
1426 llvm::MDNode *Node = llvm::MDNode::get(
1427 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1428 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1431 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1434 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1435 false /*ConvertTypeToTag*/);
1438 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1439 // In order to prevent the optimizer from throwing away the check, don't
1440 // attach range metadata to the load.
1441 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1442 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1443 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1445 return EmitFromMemory(Load, Ty);
1448 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1449 // Bool has a different representation in memory than in registers.
1450 if (hasBooleanRepresentation(Ty)) {
1451 // This should really always be an i1, but sometimes it's already
1452 // an i8, and it's awkward to track those cases down.
1453 if (Value->getType()->isIntegerTy(1))
1454 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1455 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1456 "wrong value rep of bool");
1462 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1463 // Bool has a different representation in memory than in registers.
1464 if (hasBooleanRepresentation(Ty)) {
1465 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1466 "wrong value rep of bool");
1467 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1473 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1474 bool Volatile, QualType Ty,
1475 AlignmentSource AlignSource,
1476 llvm::MDNode *TBAAInfo,
1477 bool isInit, QualType TBAABaseType,
1478 uint64_t TBAAOffset,
1479 bool isNontemporal) {
1481 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1482 // Handle vectors differently to get better performance.
1483 if (Ty->isVectorType()) {
1484 llvm::Type *SrcTy = Value->getType();
1485 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1486 // Handle vec3 special.
1487 if (VecTy->getNumElements() == 3) {
1488 // Our source is a vec3, do a shuffle vector to make it a vec4.
1489 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1490 Builder.getInt32(2),
1491 llvm::UndefValue::get(Builder.getInt32Ty())};
1492 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1493 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1494 MaskV, "extractVec");
1495 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1497 if (Addr.getElementType() != SrcTy) {
1498 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1503 Value = EmitToMemory(Value, Ty);
1505 LValue AtomicLValue =
1506 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
1507 if (Ty->isAtomicType() ||
1508 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1509 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1513 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1514 if (isNontemporal) {
1515 llvm::MDNode *Node =
1516 llvm::MDNode::get(Store->getContext(),
1517 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1518 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1521 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1524 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1525 false /*ConvertTypeToTag*/);
1529 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1531 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1532 lvalue.getType(), lvalue.getAlignmentSource(),
1533 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1534 lvalue.getTBAAOffset(), lvalue.isNontemporal());
1537 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1538 /// method emits the address of the lvalue, then loads the result as an rvalue,
1539 /// returning the rvalue.
1540 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1541 if (LV.isObjCWeak()) {
1542 // load of a __weak object.
1543 Address AddrWeakObj = LV.getAddress();
1544 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1547 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1548 // In MRC mode, we do a load+autorelease.
1549 if (!getLangOpts().ObjCAutoRefCount) {
1550 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1553 // In ARC mode, we load retained and then consume the value.
1554 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1555 Object = EmitObjCConsumeObject(LV.getType(), Object);
1556 return RValue::get(Object);
1559 if (LV.isSimple()) {
1560 assert(!LV.getType()->isFunctionType());
1562 // Everything needs a load.
1563 return RValue::get(EmitLoadOfScalar(LV, Loc));
1566 if (LV.isVectorElt()) {
1567 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1568 LV.isVolatileQualified());
1569 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1573 // If this is a reference to a subset of the elements of a vector, either
1574 // shuffle the input or extract/insert them as appropriate.
1575 if (LV.isExtVectorElt())
1576 return EmitLoadOfExtVectorElementLValue(LV);
1578 // Global Register variables always invoke intrinsics
1579 if (LV.isGlobalReg())
1580 return EmitLoadOfGlobalRegLValue(LV);
1582 assert(LV.isBitField() && "Unknown LValue type!");
1583 return EmitLoadOfBitfieldLValue(LV, Loc);
1586 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1587 SourceLocation Loc) {
1588 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1590 // Get the output type.
1591 llvm::Type *ResLTy = ConvertType(LV.getType());
1593 Address Ptr = LV.getBitFieldAddress();
1594 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1596 if (Info.IsSigned) {
1597 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1598 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1600 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1601 if (Info.Offset + HighBits)
1602 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1605 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1606 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1607 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1611 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1612 EmitScalarRangeCheck(Val, LV.getType(), Loc);
1613 return RValue::get(Val);
1616 // If this is a reference to a subset of the elements of a vector, create an
1617 // appropriate shufflevector.
1618 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1619 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1620 LV.isVolatileQualified());
1622 const llvm::Constant *Elts = LV.getExtVectorElts();
1624 // If the result of the expression is a non-vector type, we must be extracting
1625 // a single element. Just codegen as an extractelement.
1626 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1628 unsigned InIdx = getAccessedFieldNo(0, Elts);
1629 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1630 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1633 // Always use shuffle vector to try to retain the original program structure
1634 unsigned NumResultElts = ExprVT->getNumElements();
1636 SmallVector<llvm::Constant*, 4> Mask;
1637 for (unsigned i = 0; i != NumResultElts; ++i)
1638 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1640 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1641 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1643 return RValue::get(Vec);
1646 /// @brief Generates lvalue for partial ext_vector access.
1647 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1648 Address VectorAddress = LV.getExtVectorAddress();
1649 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1650 QualType EQT = ExprVT->getElementType();
1651 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1653 Address CastToPointerElement =
1654 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1655 "conv.ptr.element");
1657 const llvm::Constant *Elts = LV.getExtVectorElts();
1658 unsigned ix = getAccessedFieldNo(0, Elts);
1660 Address VectorBasePtrPlusIx =
1661 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1662 getContext().getTypeSizeInChars(EQT),
1665 return VectorBasePtrPlusIx;
1668 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1669 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1670 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1671 "Bad type for register variable");
1672 llvm::MDNode *RegName = cast<llvm::MDNode>(
1673 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1675 // We accept integer and pointer types only
1676 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1677 llvm::Type *Ty = OrigTy;
1678 if (OrigTy->isPointerTy())
1679 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1680 llvm::Type *Types[] = { Ty };
1682 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1683 llvm::Value *Call = Builder.CreateCall(
1684 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1685 if (OrigTy->isPointerTy())
1686 Call = Builder.CreateIntToPtr(Call, OrigTy);
1687 return RValue::get(Call);
1691 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1692 /// lvalue, where both are guaranteed to the have the same type, and that type
1694 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1696 if (!Dst.isSimple()) {
1697 if (Dst.isVectorElt()) {
1698 // Read/modify/write the vector, inserting the new element.
1699 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1700 Dst.isVolatileQualified());
1701 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1702 Dst.getVectorIdx(), "vecins");
1703 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1704 Dst.isVolatileQualified());
1708 // If this is an update of extended vector elements, insert them as
1710 if (Dst.isExtVectorElt())
1711 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1713 if (Dst.isGlobalReg())
1714 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1716 assert(Dst.isBitField() && "Unknown LValue type");
1717 return EmitStoreThroughBitfieldLValue(Src, Dst);
1720 // There's special magic for assigning into an ARC-qualified l-value.
1721 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1723 case Qualifiers::OCL_None:
1724 llvm_unreachable("present but none");
1726 case Qualifiers::OCL_ExplicitNone:
1730 case Qualifiers::OCL_Strong:
1732 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1735 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1738 case Qualifiers::OCL_Weak:
1740 // Initialize and then skip the primitive store.
1741 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1743 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1746 case Qualifiers::OCL_Autoreleasing:
1747 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1748 Src.getScalarVal()));
1749 // fall into the normal path
1754 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1755 // load of a __weak object.
1756 Address LvalueDst = Dst.getAddress();
1757 llvm::Value *src = Src.getScalarVal();
1758 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1762 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1763 // load of a __strong object.
1764 Address LvalueDst = Dst.getAddress();
1765 llvm::Value *src = Src.getScalarVal();
1766 if (Dst.isObjCIvar()) {
1767 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1768 llvm::Type *ResultType = IntPtrTy;
1769 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1770 llvm::Value *RHS = dst.getPointer();
1771 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1773 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1774 "sub.ptr.lhs.cast");
1775 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1776 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1778 } else if (Dst.isGlobalObjCRef()) {
1779 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1780 Dst.isThreadLocalRef());
1783 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1787 assert(Src.isScalar() && "Can't emit an agg store with this method");
1788 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1791 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1792 llvm::Value **Result) {
1793 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1794 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1795 Address Ptr = Dst.getBitFieldAddress();
1797 // Get the source value, truncated to the width of the bit-field.
1798 llvm::Value *SrcVal = Src.getScalarVal();
1800 // Cast the source to the storage type and shift it into place.
1801 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1802 /*IsSigned=*/false);
1803 llvm::Value *MaskedVal = SrcVal;
1805 // See if there are other bits in the bitfield's storage we'll need to load
1806 // and mask together with source before storing.
1807 if (Info.StorageSize != Info.Size) {
1808 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1810 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1812 // Mask the source value as needed.
1813 if (!hasBooleanRepresentation(Dst.getType()))
1814 SrcVal = Builder.CreateAnd(SrcVal,
1815 llvm::APInt::getLowBitsSet(Info.StorageSize,
1820 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1822 // Mask out the original value.
1823 Val = Builder.CreateAnd(Val,
1824 ~llvm::APInt::getBitsSet(Info.StorageSize,
1826 Info.Offset + Info.Size),
1829 // Or together the unchanged values and the source value.
1830 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1832 assert(Info.Offset == 0);
1835 // Write the new value back out.
1836 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1838 // Return the new value of the bit-field, if requested.
1840 llvm::Value *ResultVal = MaskedVal;
1842 // Sign extend the value if needed.
1843 if (Info.IsSigned) {
1844 assert(Info.Size <= Info.StorageSize);
1845 unsigned HighBits = Info.StorageSize - Info.Size;
1847 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1848 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1852 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1854 *Result = EmitFromMemory(ResultVal, Dst.getType());
1858 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1860 // This access turns into a read/modify/write of the vector. Load the input
1862 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1863 Dst.isVolatileQualified());
1864 const llvm::Constant *Elts = Dst.getExtVectorElts();
1866 llvm::Value *SrcVal = Src.getScalarVal();
1868 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1869 unsigned NumSrcElts = VTy->getNumElements();
1870 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1871 if (NumDstElts == NumSrcElts) {
1872 // Use shuffle vector is the src and destination are the same number of
1873 // elements and restore the vector mask since it is on the side it will be
1875 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1876 for (unsigned i = 0; i != NumSrcElts; ++i)
1877 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1879 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1880 Vec = Builder.CreateShuffleVector(SrcVal,
1881 llvm::UndefValue::get(Vec->getType()),
1883 } else if (NumDstElts > NumSrcElts) {
1884 // Extended the source vector to the same length and then shuffle it
1885 // into the destination.
1886 // FIXME: since we're shuffling with undef, can we just use the indices
1887 // into that? This could be simpler.
1888 SmallVector<llvm::Constant*, 4> ExtMask;
1889 for (unsigned i = 0; i != NumSrcElts; ++i)
1890 ExtMask.push_back(Builder.getInt32(i));
1891 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1892 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1893 llvm::Value *ExtSrcVal =
1894 Builder.CreateShuffleVector(SrcVal,
1895 llvm::UndefValue::get(SrcVal->getType()),
1898 SmallVector<llvm::Constant*, 4> Mask;
1899 for (unsigned i = 0; i != NumDstElts; ++i)
1900 Mask.push_back(Builder.getInt32(i));
1902 // When the vector size is odd and .odd or .hi is used, the last element
1903 // of the Elts constant array will be one past the size of the vector.
1904 // Ignore the last element here, if it is greater than the mask size.
1905 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1908 // modify when what gets shuffled in
1909 for (unsigned i = 0; i != NumSrcElts; ++i)
1910 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1911 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1912 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1914 // We should never shorten the vector
1915 llvm_unreachable("unexpected shorten vector length");
1918 // If the Src is a scalar (not a vector) it must be updating one element.
1919 unsigned InIdx = getAccessedFieldNo(0, Elts);
1920 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1921 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1924 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1925 Dst.isVolatileQualified());
1928 /// @brief Store of global named registers are always calls to intrinsics.
1929 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1930 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1931 "Bad type for register variable");
1932 llvm::MDNode *RegName = cast<llvm::MDNode>(
1933 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1934 assert(RegName && "Register LValue is not metadata");
1936 // We accept integer and pointer types only
1937 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1938 llvm::Type *Ty = OrigTy;
1939 if (OrigTy->isPointerTy())
1940 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1941 llvm::Type *Types[] = { Ty };
1943 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1944 llvm::Value *Value = Src.getScalarVal();
1945 if (OrigTy->isPointerTy())
1946 Value = Builder.CreatePtrToInt(Value, Ty);
1948 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
1951 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1952 // generating write-barries API. It is currently a global, ivar,
1954 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1956 bool IsMemberAccess=false) {
1957 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1960 if (isa<ObjCIvarRefExpr>(E)) {
1961 QualType ExpTy = E->getType();
1962 if (IsMemberAccess && ExpTy->isPointerType()) {
1963 // If ivar is a structure pointer, assigning to field of
1964 // this struct follows gcc's behavior and makes it a non-ivar
1965 // writer-barrier conservatively.
1966 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1967 if (ExpTy->isRecordType()) {
1968 LV.setObjCIvar(false);
1972 LV.setObjCIvar(true);
1973 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1974 LV.setBaseIvarExp(Exp->getBase());
1975 LV.setObjCArray(E->getType()->isArrayType());
1979 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1980 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1981 if (VD->hasGlobalStorage()) {
1982 LV.setGlobalObjCRef(true);
1983 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1986 LV.setObjCArray(E->getType()->isArrayType());
1990 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1991 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1995 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1996 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1997 if (LV.isObjCIvar()) {
1998 // If cast is to a structure pointer, follow gcc's behavior and make it
1999 // a non-ivar write-barrier.
2000 QualType ExpTy = E->getType();
2001 if (ExpTy->isPointerType())
2002 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2003 if (ExpTy->isRecordType())
2004 LV.setObjCIvar(false);
2009 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2010 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2014 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2015 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2019 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2020 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2024 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2025 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2029 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2030 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2031 if (LV.isObjCIvar() && !LV.isObjCArray())
2032 // Using array syntax to assigning to what an ivar points to is not
2033 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2034 LV.setObjCIvar(false);
2035 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2036 // Using array syntax to assigning to what global points to is not
2037 // same as assigning to the global itself. {id *G;} G[i] = 0;
2038 LV.setGlobalObjCRef(false);
2042 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2043 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2044 // We don't know if member is an 'ivar', but this flag is looked at
2045 // only in the context of LV.isObjCIvar().
2046 LV.setObjCArray(E->getType()->isArrayType());
2051 static llvm::Value *
2052 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2053 llvm::Value *V, llvm::Type *IRType,
2054 StringRef Name = StringRef()) {
2055 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2056 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2059 static LValue EmitThreadPrivateVarDeclLValue(
2060 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2061 llvm::Type *RealVarTy, SourceLocation Loc) {
2062 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2063 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2064 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2067 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2068 const ReferenceType *RefTy,
2069 AlignmentSource *Source) {
2070 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2071 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2072 Source, /*forPointee*/ true));
2076 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2077 const ReferenceType *RefTy) {
2078 AlignmentSource Source;
2079 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
2080 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
2083 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2084 const PointerType *PtrTy,
2085 AlignmentSource *Source) {
2086 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2087 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
2088 /*forPointeeType=*/true));
2091 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2092 const PointerType *PtrTy) {
2093 AlignmentSource Source;
2094 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2095 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2098 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2099 const Expr *E, const VarDecl *VD) {
2100 QualType T = E->getType();
2102 // If it's thread_local, emit a call to its wrapper function instead.
2103 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2104 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2105 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2107 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2108 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2109 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2110 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2111 Address Addr(V, Alignment);
2113 // Emit reference to the private copy of the variable if it is an OpenMP
2114 // threadprivate variable.
2115 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2116 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2118 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2119 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2121 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2123 setObjCGCLValueClass(CGF.getContext(), E, LV);
2127 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2128 const FunctionDecl *FD) {
2129 if (FD->hasAttr<WeakRefAttr>()) {
2130 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2131 return aliasee.getPointer();
2134 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2135 if (!FD->hasPrototype()) {
2136 if (const FunctionProtoType *Proto =
2137 FD->getType()->getAs<FunctionProtoType>()) {
2138 // Ugly case: for a K&R-style definition, the type of the definition
2139 // isn't the same as the type of a use. Correct for this with a
2141 QualType NoProtoType =
2142 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2143 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2144 V = llvm::ConstantExpr::getBitCast(V,
2145 CGM.getTypes().ConvertType(NoProtoType));
2151 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2152 const Expr *E, const FunctionDecl *FD) {
2153 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2154 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2155 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
2158 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2159 llvm::Value *ThisValue) {
2160 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2161 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2162 return CGF.EmitLValueForField(LV, FD);
2165 /// Named Registers are named metadata pointing to the register name
2166 /// which will be read from/written to as an argument to the intrinsic
2167 /// @llvm.read/write_register.
2168 /// So far, only the name is being passed down, but other options such as
2169 /// register type, allocation type or even optimization options could be
2170 /// passed down via the metadata node.
2171 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2172 SmallString<64> Name("llvm.named.register.");
2173 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2174 assert(Asm->getLabel().size() < 64-Name.size() &&
2175 "Register name too big");
2176 Name.append(Asm->getLabel());
2177 llvm::NamedMDNode *M =
2178 CGM.getModule().getOrInsertNamedMetadata(Name);
2179 if (M->getNumOperands() == 0) {
2180 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2182 llvm::Metadata *Ops[] = {Str};
2183 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2186 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2189 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2190 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2193 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2194 const NamedDecl *ND = E->getDecl();
2195 QualType T = E->getType();
2197 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2198 // Global Named registers access via intrinsics only
2199 if (VD->getStorageClass() == SC_Register &&
2200 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2201 return EmitGlobalNamedRegister(VD, CGM);
2203 // A DeclRefExpr for a reference initialized by a constant expression can
2204 // appear without being odr-used. Directly emit the constant initializer.
2205 const Expr *Init = VD->getAnyInitializer(VD);
2206 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2207 VD->isUsableInConstantExpressions(getContext()) &&
2208 VD->checkInitIsICE() &&
2209 // Do not emit if it is private OpenMP variable.
2210 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2211 LocalDeclMap.count(VD))) {
2212 llvm::Constant *Val =
2213 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2214 assert(Val && "failed to emit reference constant expression");
2215 // FIXME: Eventually we will want to emit vector element references.
2217 // Should we be using the alignment of the constant pointer we emitted?
2218 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2221 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
2224 // Check for captured variables.
2225 if (E->refersToEnclosingVariableOrCapture()) {
2226 if (auto *FD = LambdaCaptureFields.lookup(VD))
2227 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2228 else if (CapturedStmtInfo) {
2229 auto I = LocalDeclMap.find(VD);
2230 if (I != LocalDeclMap.end()) {
2231 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2232 return EmitLoadOfReferenceLValue(I->second, RefTy);
2233 return MakeAddrLValue(I->second, T);
2236 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2237 CapturedStmtInfo->getContextValue());
2238 return MakeAddrLValue(
2239 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2240 CapLVal.getType(), AlignmentSource::Decl);
2243 assert(isa<BlockDecl>(CurCodeDecl));
2244 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2245 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2249 // FIXME: We should be able to assert this for FunctionDecls as well!
2250 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2251 // those with a valid source location.
2252 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2253 !E->getLocation().isValid()) &&
2254 "Should not use decl without marking it used!");
2256 if (ND->hasAttr<WeakRefAttr>()) {
2257 const auto *VD = cast<ValueDecl>(ND);
2258 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2259 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2262 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2263 // Check if this is a global variable.
2264 if (VD->hasLinkage() || VD->isStaticDataMember())
2265 return EmitGlobalVarDeclLValue(*this, E, VD);
2267 Address addr = Address::invalid();
2269 // The variable should generally be present in the local decl map.
2270 auto iter = LocalDeclMap.find(VD);
2271 if (iter != LocalDeclMap.end()) {
2272 addr = iter->second;
2274 // Otherwise, it might be static local we haven't emitted yet for
2275 // some reason; most likely, because it's in an outer function.
2276 } else if (VD->isStaticLocal()) {
2277 addr = Address(CGM.getOrCreateStaticVarDecl(
2278 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2279 getContext().getDeclAlign(VD));
2281 // No other cases for now.
2283 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2287 // Check for OpenMP threadprivate variables.
2288 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2289 return EmitThreadPrivateVarDeclLValue(
2290 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2294 // Drill into block byref variables.
2295 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2297 addr = emitBlockByrefAddress(addr, VD);
2300 // Drill into reference types.
2302 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2303 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2305 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
2308 bool isLocalStorage = VD->hasLocalStorage();
2310 bool NonGCable = isLocalStorage &&
2311 !VD->getType()->isReferenceType() &&
2314 LV.getQuals().removeObjCGCAttr();
2318 bool isImpreciseLifetime =
2319 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2320 if (isImpreciseLifetime)
2321 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2322 setObjCGCLValueClass(getContext(), E, LV);
2326 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2327 return EmitFunctionDeclLValue(*this, E, FD);
2329 // FIXME: While we're emitting a binding from an enclosing scope, all other
2330 // DeclRefExprs we see should be implicitly treated as if they also refer to
2331 // an enclosing scope.
2332 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2333 return EmitLValue(BD->getBinding());
2335 llvm_unreachable("Unhandled DeclRefExpr");
2338 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2339 // __extension__ doesn't affect lvalue-ness.
2340 if (E->getOpcode() == UO_Extension)
2341 return EmitLValue(E->getSubExpr());
2343 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2344 switch (E->getOpcode()) {
2345 default: llvm_unreachable("Unknown unary operator lvalue!");
2347 QualType T = E->getSubExpr()->getType()->getPointeeType();
2348 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2350 AlignmentSource AlignSource;
2351 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2352 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
2353 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2355 // We should not generate __weak write barrier on indirect reference
2356 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2357 // But, we continue to generate __strong write barrier on indirect write
2358 // into a pointer to object.
2359 if (getLangOpts().ObjC1 &&
2360 getLangOpts().getGC() != LangOptions::NonGC &&
2362 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2367 LValue LV = EmitLValue(E->getSubExpr());
2368 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2370 // __real is valid on scalars. This is a faster way of testing that.
2371 // __imag can only produce an rvalue on scalars.
2372 if (E->getOpcode() == UO_Real &&
2373 !LV.getAddress().getElementType()->isStructTy()) {
2374 assert(E->getSubExpr()->getType()->isArithmeticType());
2378 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2381 (E->getOpcode() == UO_Real
2382 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2383 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2384 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2385 ElemLV.getQuals().addQualifiers(LV.getQuals());
2390 LValue LV = EmitLValue(E->getSubExpr());
2391 bool isInc = E->getOpcode() == UO_PreInc;
2393 if (E->getType()->isAnyComplexType())
2394 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2396 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2402 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2403 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2404 E->getType(), AlignmentSource::Decl);
2407 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2408 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2409 E->getType(), AlignmentSource::Decl);
2412 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2413 auto SL = E->getFunctionName();
2414 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2415 StringRef FnName = CurFn->getName();
2416 if (FnName.startswith("\01"))
2417 FnName = FnName.substr(1);
2418 StringRef NameItems[] = {
2419 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2420 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2421 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2422 std::string Name = SL->getString();
2423 if (!Name.empty()) {
2424 unsigned Discriminator =
2425 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2427 Name += "_" + Twine(Discriminator + 1).str();
2428 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2429 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2431 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2432 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2435 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2436 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2439 /// Emit a type description suitable for use by a runtime sanitizer library. The
2440 /// format of a type descriptor is
2443 /// { i16 TypeKind, i16 TypeInfo }
2446 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2447 /// integer, 1 for a floating point value, and -1 for anything else.
2448 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2449 // Only emit each type's descriptor once.
2450 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2453 uint16_t TypeKind = -1;
2454 uint16_t TypeInfo = 0;
2456 if (T->isIntegerType()) {
2458 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2459 (T->isSignedIntegerType() ? 1 : 0);
2460 } else if (T->isFloatingType()) {
2462 TypeInfo = getContext().getTypeSize(T);
2465 // Format the type name as if for a diagnostic, including quotes and
2466 // optionally an 'aka'.
2467 SmallString<32> Buffer;
2468 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2469 (intptr_t)T.getAsOpaquePtr(),
2470 StringRef(), StringRef(), None, Buffer,
2473 llvm::Constant *Components[] = {
2474 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2475 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2477 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2479 auto *GV = new llvm::GlobalVariable(
2480 CGM.getModule(), Descriptor->getType(),
2481 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2482 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2483 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2485 // Remember the descriptor for this type.
2486 CGM.setTypeDescriptorInMap(T, GV);
2491 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2492 llvm::Type *TargetTy = IntPtrTy;
2494 // Floating-point types which fit into intptr_t are bitcast to integers
2495 // and then passed directly (after zero-extension, if necessary).
2496 if (V->getType()->isFloatingPointTy()) {
2497 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2498 if (Bits <= TargetTy->getIntegerBitWidth())
2499 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2503 // Integers which fit in intptr_t are zero-extended and passed directly.
2504 if (V->getType()->isIntegerTy() &&
2505 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2506 return Builder.CreateZExt(V, TargetTy);
2508 // Pointers are passed directly, everything else is passed by address.
2509 if (!V->getType()->isPointerTy()) {
2510 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2511 Builder.CreateStore(V, Ptr);
2512 V = Ptr.getPointer();
2514 return Builder.CreatePtrToInt(V, TargetTy);
2517 /// \brief Emit a representation of a SourceLocation for passing to a handler
2518 /// in a sanitizer runtime library. The format for this data is:
2520 /// struct SourceLocation {
2521 /// const char *Filename;
2522 /// int32_t Line, Column;
2525 /// For an invalid SourceLocation, the Filename pointer is null.
2526 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2527 llvm::Constant *Filename;
2530 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2531 if (PLoc.isValid()) {
2532 StringRef FilenameString = PLoc.getFilename();
2534 int PathComponentsToStrip =
2535 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2536 if (PathComponentsToStrip < 0) {
2537 assert(PathComponentsToStrip != INT_MIN);
2538 int PathComponentsToKeep = -PathComponentsToStrip;
2539 auto I = llvm::sys::path::rbegin(FilenameString);
2540 auto E = llvm::sys::path::rend(FilenameString);
2541 while (I != E && --PathComponentsToKeep)
2544 FilenameString = FilenameString.substr(I - E);
2545 } else if (PathComponentsToStrip > 0) {
2546 auto I = llvm::sys::path::begin(FilenameString);
2547 auto E = llvm::sys::path::end(FilenameString);
2548 while (I != E && PathComponentsToStrip--)
2553 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2555 FilenameString = llvm::sys::path::filename(FilenameString);
2558 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2559 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2560 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2561 Filename = FilenameGV.getPointer();
2562 Line = PLoc.getLine();
2563 Column = PLoc.getColumn();
2565 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2569 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2570 Builder.getInt32(Column)};
2572 return llvm::ConstantStruct::getAnon(Data);
2576 /// \brief Specify under what conditions this check can be recovered
2577 enum class CheckRecoverableKind {
2578 /// Always terminate program execution if this check fails.
2580 /// Check supports recovering, runtime has both fatal (noreturn) and
2581 /// non-fatal handlers for this check.
2583 /// Runtime conditionally aborts, always need to support recovery.
2588 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2589 assert(llvm::countPopulation(Kind) == 1);
2591 case SanitizerKind::Vptr:
2592 return CheckRecoverableKind::AlwaysRecoverable;
2593 case SanitizerKind::Return:
2594 case SanitizerKind::Unreachable:
2595 return CheckRecoverableKind::Unrecoverable;
2597 return CheckRecoverableKind::Recoverable;
2602 struct SanitizerHandlerInfo {
2603 char const *const Name;
2608 const SanitizerHandlerInfo SanitizerHandlers[] = {
2609 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2610 LIST_SANITIZER_CHECKS
2611 #undef SANITIZER_CHECK
2614 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2615 llvm::FunctionType *FnType,
2616 ArrayRef<llvm::Value *> FnArgs,
2617 SanitizerHandler CheckHandler,
2618 CheckRecoverableKind RecoverKind, bool IsFatal,
2619 llvm::BasicBlock *ContBB) {
2620 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2621 bool NeedsAbortSuffix =
2622 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2623 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2624 const StringRef CheckName = CheckInfo.Name;
2625 std::string FnName =
2626 ("__ubsan_handle_" + CheckName +
2627 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
2628 (NeedsAbortSuffix ? "_abort" : ""))
2631 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2633 llvm::AttrBuilder B;
2635 B.addAttribute(llvm::Attribute::NoReturn)
2636 .addAttribute(llvm::Attribute::NoUnwind);
2638 B.addAttribute(llvm::Attribute::UWTable);
2640 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2642 llvm::AttributeList::get(CGF.getLLVMContext(),
2643 llvm::AttributeList::FunctionIndex, B),
2645 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2647 HandlerCall->setDoesNotReturn();
2648 CGF.Builder.CreateUnreachable();
2650 CGF.Builder.CreateBr(ContBB);
2654 void CodeGenFunction::EmitCheck(
2655 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2656 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2657 ArrayRef<llvm::Value *> DynamicArgs) {
2658 assert(IsSanitizerScope);
2659 assert(Checked.size() > 0);
2660 assert(CheckHandler >= 0 &&
2661 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2662 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2664 llvm::Value *FatalCond = nullptr;
2665 llvm::Value *RecoverableCond = nullptr;
2666 llvm::Value *TrapCond = nullptr;
2667 for (int i = 0, n = Checked.size(); i < n; ++i) {
2668 llvm::Value *Check = Checked[i].first;
2669 // -fsanitize-trap= overrides -fsanitize-recover=.
2670 llvm::Value *&Cond =
2671 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2673 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2676 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2680 EmitTrapCheck(TrapCond);
2681 if (!FatalCond && !RecoverableCond)
2684 llvm::Value *JointCond;
2685 if (FatalCond && RecoverableCond)
2686 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2688 JointCond = FatalCond ? FatalCond : RecoverableCond;
2691 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2692 assert(SanOpts.has(Checked[0].second));
2694 for (int i = 1, n = Checked.size(); i < n; ++i) {
2695 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2696 "All recoverable kinds in a single check must be same!");
2697 assert(SanOpts.has(Checked[i].second));
2701 llvm::BasicBlock *Cont = createBasicBlock("cont");
2702 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2703 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2704 // Give hint that we very much don't expect to execute the handler
2705 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2706 llvm::MDBuilder MDHelper(getLLVMContext());
2707 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2708 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2709 EmitBlock(Handlers);
2711 // Handler functions take an i8* pointing to the (handler-specific) static
2712 // information block, followed by a sequence of intptr_t arguments
2713 // representing operand values.
2714 SmallVector<llvm::Value *, 4> Args;
2715 SmallVector<llvm::Type *, 4> ArgTypes;
2716 Args.reserve(DynamicArgs.size() + 1);
2717 ArgTypes.reserve(DynamicArgs.size() + 1);
2719 // Emit handler arguments and create handler function type.
2720 if (!StaticArgs.empty()) {
2721 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2723 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2724 llvm::GlobalVariable::PrivateLinkage, Info);
2725 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2726 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2727 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2728 ArgTypes.push_back(Int8PtrTy);
2731 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2732 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2733 ArgTypes.push_back(IntPtrTy);
2736 llvm::FunctionType *FnType =
2737 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2739 if (!FatalCond || !RecoverableCond) {
2740 // Simple case: we need to generate a single handler call, either
2741 // fatal, or non-fatal.
2742 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2743 (FatalCond != nullptr), Cont);
2745 // Emit two handler calls: first one for set of unrecoverable checks,
2746 // another one for recoverable.
2747 llvm::BasicBlock *NonFatalHandlerBB =
2748 createBasicBlock("non_fatal." + CheckName);
2749 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2750 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2751 EmitBlock(FatalHandlerBB);
2752 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2754 EmitBlock(NonFatalHandlerBB);
2755 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2762 void CodeGenFunction::EmitCfiSlowPathCheck(
2763 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2764 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2765 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2767 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2768 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2770 llvm::MDBuilder MDHelper(getLLVMContext());
2771 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2772 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2776 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2778 llvm::CallInst *CheckCall;
2780 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2782 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2783 llvm::GlobalVariable::PrivateLinkage, Info);
2784 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2785 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2787 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2788 "__cfi_slowpath_diag",
2789 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2791 CheckCall = Builder.CreateCall(
2793 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2795 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2797 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2798 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2801 CheckCall->setDoesNotThrow();
2806 // Emit a stub for __cfi_check function so that the linker knows about this
2807 // symbol in LTO mode.
2808 void CodeGenFunction::EmitCfiCheckStub() {
2809 llvm::Module *M = &CGM.getModule();
2810 auto &Ctx = M->getContext();
2811 llvm::Function *F = llvm::Function::Create(
2812 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2813 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2814 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2815 // FIXME: consider emitting an intrinsic call like
2816 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2817 // which can be lowered in CrossDSOCFI pass to the actual contents of
2818 // __cfi_check. This would allow inlining of __cfi_check calls.
2819 llvm::CallInst::Create(
2820 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2821 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2824 // This function is basically a switch over the CFI failure kind, which is
2825 // extracted from CFICheckFailData (1st function argument). Each case is either
2826 // llvm.trap or a call to one of the two runtime handlers, based on
2827 // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2828 // failure kind) traps, but this should really never happen. CFICheckFailData
2829 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2830 // check kind; in this case __cfi_check_fail traps as well.
2831 void CodeGenFunction::EmitCfiCheckFail() {
2832 SanitizerScope SanScope(this);
2833 FunctionArgList Args;
2834 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2835 getContext().VoidPtrTy);
2836 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2837 getContext().VoidPtrTy);
2838 Args.push_back(&ArgData);
2839 Args.push_back(&ArgAddr);
2841 const CGFunctionInfo &FI =
2842 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2844 llvm::Function *F = llvm::Function::Create(
2845 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2846 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2847 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2849 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2853 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2854 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2856 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2857 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2859 // Data == nullptr means the calling module has trap behaviour for this check.
2860 llvm::Value *DataIsNotNullPtr =
2861 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2862 EmitTrapCheck(DataIsNotNullPtr);
2864 llvm::StructType *SourceLocationTy =
2865 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2866 llvm::StructType *CfiCheckFailDataTy =
2867 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2869 llvm::Value *V = Builder.CreateConstGEP2_32(
2871 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2873 Address CheckKindAddr(V, getIntAlign());
2874 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2876 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2877 CGM.getLLVMContext(),
2878 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2879 llvm::Value *ValidVtable = Builder.CreateZExt(
2880 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2881 {Addr, AllVtables}),
2884 const std::pair<int, SanitizerMask> CheckKinds[] = {
2885 {CFITCK_VCall, SanitizerKind::CFIVCall},
2886 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2887 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2888 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2889 {CFITCK_ICall, SanitizerKind::CFIICall}};
2891 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2892 for (auto CheckKindMaskPair : CheckKinds) {
2893 int Kind = CheckKindMaskPair.first;
2894 SanitizerMask Mask = CheckKindMaskPair.second;
2896 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
2897 if (CGM.getLangOpts().Sanitize.has(Mask))
2898 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
2899 {Data, Addr, ValidVtable});
2901 EmitTrapCheck(Cond);
2905 // The only reference to this function will be created during LTO link.
2906 // Make sure it survives until then.
2907 CGM.addUsedGlobal(F);
2910 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2911 llvm::BasicBlock *Cont = createBasicBlock("cont");
2913 // If we're optimizing, collapse all calls to trap down to just one per
2914 // function to save on code size.
2915 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2916 TrapBB = createBasicBlock("trap");
2917 Builder.CreateCondBr(Checked, Cont, TrapBB);
2919 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
2920 TrapCall->setDoesNotReturn();
2921 TrapCall->setDoesNotThrow();
2922 Builder.CreateUnreachable();
2924 Builder.CreateCondBr(Checked, Cont, TrapBB);
2930 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
2931 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
2933 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2934 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2935 CGM.getCodeGenOpts().TrapFuncName);
2936 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
2942 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2943 AlignmentSource *AlignSource) {
2944 assert(E->getType()->isArrayType() &&
2945 "Array to pointer decay must have array source type!");
2947 // Expressions of array type can't be bitfields or vector elements.
2948 LValue LV = EmitLValue(E);
2949 Address Addr = LV.getAddress();
2950 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2952 // If the array type was an incomplete type, we need to make sure
2953 // the decay ends up being the right type.
2954 llvm::Type *NewTy = ConvertType(E->getType());
2955 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2957 // Note that VLA pointers are always decayed, so we don't need to do
2959 if (!E->getType()->isVariableArrayType()) {
2960 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2961 "Expected pointer to array");
2962 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2965 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2966 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2969 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2970 /// array to pointer, return the array subexpression.
2971 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2972 // If this isn't just an array->pointer decay, bail out.
2973 const auto *CE = dyn_cast<CastExpr>(E);
2974 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2977 // If this is a decay from variable width array, bail out.
2978 const Expr *SubExpr = CE->getSubExpr();
2979 if (SubExpr->getType()->isVariableArrayType())
2985 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2987 ArrayRef<llvm::Value*> indices,
2989 const llvm::Twine &name = "arrayidx") {
2991 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2993 return CGF.Builder.CreateGEP(ptr, indices, name);
2997 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2999 CharUnits eltSize) {
3000 // If we have a constant index, we can use the exact offset of the
3001 // element we're accessing.
3002 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3003 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3004 return arrayAlign.alignmentAtOffset(offset);
3006 // Otherwise, use the worst-case alignment for any element.
3008 return arrayAlign.alignmentOfArrayElement(eltSize);
3012 static QualType getFixedSizeElementType(const ASTContext &ctx,
3013 const VariableArrayType *vla) {
3016 eltType = vla->getElementType();
3017 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3021 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3022 ArrayRef<llvm::Value*> indices,
3023 QualType eltType, bool inbounds,
3024 const llvm::Twine &name = "arrayidx") {
3025 // All the indices except that last must be zero.
3027 for (auto idx : indices.drop_back())
3028 assert(isa<llvm::ConstantInt>(idx) &&
3029 cast<llvm::ConstantInt>(idx)->isZero());
3032 // Determine the element size of the statically-sized base. This is
3033 // the thing that the indices are expressed in terms of.
3034 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3035 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3038 // We can use that to compute the best alignment of the element.
3039 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3040 CharUnits eltAlign =
3041 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3043 llvm::Value *eltPtr =
3044 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
3045 return Address(eltPtr, eltAlign);
3048 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3050 // The index must always be an integer, which is not an aggregate. Emit it
3051 // in lexical order (this complexity is, sadly, required by C++17).
3052 llvm::Value *IdxPre =
3053 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3054 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3056 if (E->getLHS() != E->getIdx()) {
3057 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3058 Idx = EmitScalarExpr(E->getIdx());
3061 QualType IdxTy = E->getIdx()->getType();
3062 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3064 if (SanOpts.has(SanitizerKind::ArrayBounds))
3065 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3067 // Extend or truncate the index type to 32 or 64-bits.
3068 if (Promote && Idx->getType() != IntPtrTy)
3069 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3075 // If the base is a vector type, then we are forming a vector element lvalue
3076 // with this subscript.
3077 if (E->getBase()->getType()->isVectorType() &&
3078 !isa<ExtVectorElementExpr>(E->getBase())) {
3079 // Emit the vector as an lvalue to get its address.
3080 LValue LHS = EmitLValue(E->getBase());
3081 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3082 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3083 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
3084 E->getBase()->getType(),
3085 LHS.getAlignmentSource());
3088 // All the other cases basically behave like simple offsetting.
3090 // Handle the extvector case we ignored above.
3091 if (isa<ExtVectorElementExpr>(E->getBase())) {
3092 LValue LV = EmitLValue(E->getBase());
3093 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3094 Address Addr = EmitExtVectorElementLValue(LV);
3096 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3097 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
3098 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
3101 AlignmentSource AlignSource;
3102 Address Addr = Address::invalid();
3103 if (const VariableArrayType *vla =
3104 getContext().getAsVariableArrayType(E->getType())) {
3105 // The base must be a pointer, which is not an aggregate. Emit
3106 // it. It needs to be emitted first in case it's what captures
3108 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3109 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3111 // The element count here is the total number of non-VLA elements.
3112 llvm::Value *numElements = getVLASize(vla).first;
3114 // Effectively, the multiply by the VLA size is part of the GEP.
3115 // GEP indexes are signed, and scaling an index isn't permitted to
3116 // signed-overflow, so we use the same semantics for our explicit
3117 // multiply. We suppress this if overflow is not undefined behavior.
3118 if (getLangOpts().isSignedOverflowDefined()) {
3119 Idx = Builder.CreateMul(Idx, numElements);
3121 Idx = Builder.CreateNSWMul(Idx, numElements);
3124 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3125 !getLangOpts().isSignedOverflowDefined());
3127 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3128 // Indexing over an interface, as in "NSString *P; P[4];"
3130 // Emit the base pointer.
3131 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3132 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3134 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3135 llvm::Value *InterfaceSizeVal =
3136 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3138 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3140 // We don't necessarily build correct LLVM struct types for ObjC
3141 // interfaces, so we can't rely on GEP to do this scaling
3142 // correctly, so we need to cast to i8*. FIXME: is this actually
3143 // true? A lot of other things in the fragile ABI would break...
3144 llvm::Type *OrigBaseTy = Addr.getType();
3145 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3148 CharUnits EltAlign =
3149 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3150 llvm::Value *EltPtr =
3151 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3152 Addr = Address(EltPtr, EltAlign);
3155 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3156 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3157 // If this is A[i] where A is an array, the frontend will have decayed the
3158 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3159 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3160 // "gep x, i" here. Emit one "gep A, 0, i".
3161 assert(Array->getType()->isArrayType() &&
3162 "Array to pointer decay must have array source type!");
3164 // For simple multidimensional array indexing, set the 'accessed' flag for
3165 // better bounds-checking of the base expression.
3166 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3167 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3169 ArrayLV = EmitLValue(Array);
3170 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3172 // Propagate the alignment from the array itself to the result.
3173 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3174 {CGM.getSize(CharUnits::Zero()), Idx},
3176 !getLangOpts().isSignedOverflowDefined());
3177 AlignSource = ArrayLV.getAlignmentSource();
3179 // The base must be a pointer; emit it with an estimate of its alignment.
3180 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3181 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3182 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3183 !getLangOpts().isSignedOverflowDefined());
3186 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
3188 // TODO: Preserve/extend path TBAA metadata?
3190 if (getLangOpts().ObjC1 &&
3191 getLangOpts().getGC() != LangOptions::NonGC) {
3192 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3193 setObjCGCLValueClass(getContext(), E, LV);
3198 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3199 AlignmentSource &AlignSource,
3200 QualType BaseTy, QualType ElTy,
3201 bool IsLowerBound) {
3203 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3204 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3205 if (BaseTy->isArrayType()) {
3206 Address Addr = BaseLVal.getAddress();
3207 AlignSource = BaseLVal.getAlignmentSource();
3209 // If the array type was an incomplete type, we need to make sure
3210 // the decay ends up being the right type.
3211 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3212 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3214 // Note that VLA pointers are always decayed, so we don't need to do
3216 if (!BaseTy->isVariableArrayType()) {
3217 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3218 "Expected pointer to array");
3219 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3223 return CGF.Builder.CreateElementBitCast(Addr,
3224 CGF.ConvertTypeForMem(ElTy));
3226 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3227 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3229 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3232 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3233 bool IsLowerBound) {
3236 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3237 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3239 BaseTy = E->getBase()->getType();
3240 QualType ResultExprTy;
3241 if (auto *AT = getContext().getAsArrayType(BaseTy))
3242 ResultExprTy = AT->getElementType();
3244 ResultExprTy = BaseTy->getPointeeType();
3245 llvm::Value *Idx = nullptr;
3246 if (IsLowerBound || E->getColonLoc().isInvalid()) {
3247 // Requesting lower bound or upper bound, but without provided length and
3248 // without ':' symbol for the default length -> length = 1.
3249 // Idx = LowerBound ?: 0;
3250 if (auto *LowerBound = E->getLowerBound()) {
3251 Idx = Builder.CreateIntCast(
3252 EmitScalarExpr(LowerBound), IntPtrTy,
3253 LowerBound->getType()->hasSignedIntegerRepresentation());
3255 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3257 // Try to emit length or lower bound as constant. If this is possible, 1
3258 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3259 // IR (LB + Len) - 1.
3260 auto &C = CGM.getContext();
3261 auto *Length = E->getLength();
3262 llvm::APSInt ConstLength;
3264 // Idx = LowerBound + Length - 1;
3265 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3266 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3269 auto *LowerBound = E->getLowerBound();
3270 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3271 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3272 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3273 LowerBound = nullptr;
3277 else if (!LowerBound)
3280 if (Length || LowerBound) {
3281 auto *LowerBoundVal =
3283 ? Builder.CreateIntCast(
3284 EmitScalarExpr(LowerBound), IntPtrTy,
3285 LowerBound->getType()->hasSignedIntegerRepresentation())
3286 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3289 ? Builder.CreateIntCast(
3290 EmitScalarExpr(Length), IntPtrTy,
3291 Length->getType()->hasSignedIntegerRepresentation())
3292 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3293 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3295 !getLangOpts().isSignedOverflowDefined());
3296 if (Length && LowerBound) {
3297 Idx = Builder.CreateSub(
3298 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3299 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3302 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3304 // Idx = ArraySize - 1;
3305 QualType ArrayTy = BaseTy->isPointerType()
3306 ? E->getBase()->IgnoreParenImpCasts()->getType()
3308 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3309 Length = VAT->getSizeExpr();
3310 if (Length->isIntegerConstantExpr(ConstLength, C))
3313 auto *CAT = C.getAsConstantArrayType(ArrayTy);
3314 ConstLength = CAT->getSize();
3317 auto *LengthVal = Builder.CreateIntCast(
3318 EmitScalarExpr(Length), IntPtrTy,
3319 Length->getType()->hasSignedIntegerRepresentation());
3320 Idx = Builder.CreateSub(
3321 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3322 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3324 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3326 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3332 Address EltPtr = Address::invalid();
3333 AlignmentSource AlignSource;
3334 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3335 // The base must be a pointer, which is not an aggregate. Emit
3336 // it. It needs to be emitted first in case it's what captures
3339 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3340 VLA->getElementType(), IsLowerBound);
3341 // The element count here is the total number of non-VLA elements.
3342 llvm::Value *NumElements = getVLASize(VLA).first;
3344 // Effectively, the multiply by the VLA size is part of the GEP.
3345 // GEP indexes are signed, and scaling an index isn't permitted to
3346 // signed-overflow, so we use the same semantics for our explicit
3347 // multiply. We suppress this if overflow is not undefined behavior.
3348 if (getLangOpts().isSignedOverflowDefined())
3349 Idx = Builder.CreateMul(Idx, NumElements);
3351 Idx = Builder.CreateNSWMul(Idx, NumElements);
3352 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3353 !getLangOpts().isSignedOverflowDefined());
3354 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3355 // If this is A[i] where A is an array, the frontend will have decayed the
3356 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3357 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3358 // "gep x, i" here. Emit one "gep A, 0, i".
3359 assert(Array->getType()->isArrayType() &&
3360 "Array to pointer decay must have array source type!");
3362 // For simple multidimensional array indexing, set the 'accessed' flag for
3363 // better bounds-checking of the base expression.
3364 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3365 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3367 ArrayLV = EmitLValue(Array);
3369 // Propagate the alignment from the array itself to the result.
3370 EltPtr = emitArraySubscriptGEP(
3371 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3372 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3373 AlignSource = ArrayLV.getAlignmentSource();
3375 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3376 BaseTy, ResultExprTy, IsLowerBound);
3377 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3378 !getLangOpts().isSignedOverflowDefined());
3381 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
3384 LValue CodeGenFunction::
3385 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3386 // Emit the base vector as an l-value.
3389 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3391 // If it is a pointer to a vector, emit the address and form an lvalue with
3393 AlignmentSource AlignSource;
3394 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
3395 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3396 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
3397 Base.getQuals().removeObjCGCAttr();
3398 } else if (E->getBase()->isGLValue()) {
3399 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3400 // emit the base as an lvalue.
3401 assert(E->getBase()->getType()->isVectorType());
3402 Base = EmitLValue(E->getBase());
3404 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3405 assert(E->getBase()->getType()->isVectorType() &&
3406 "Result must be a vector");
3407 llvm::Value *Vec = EmitScalarExpr(E->getBase());
3409 // Store the vector to memory (because LValue wants an address).
3410 Address VecMem = CreateMemTemp(E->getBase()->getType());
3411 Builder.CreateStore(Vec, VecMem);
3412 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3413 AlignmentSource::Decl);
3417 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3419 // Encode the element access list into a vector of unsigned indices.
3420 SmallVector<uint32_t, 4> Indices;
3421 E->getEncodedElementAccess(Indices);
3423 if (Base.isSimple()) {
3424 llvm::Constant *CV =
3425 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3426 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3427 Base.getAlignmentSource());
3429 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3431 llvm::Constant *BaseElts = Base.getExtVectorElts();
3432 SmallVector<llvm::Constant *, 4> CElts;
3434 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3435 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3436 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3437 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3438 Base.getAlignmentSource());
3441 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3442 Expr *BaseExpr = E->getBase();
3444 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3447 AlignmentSource AlignSource;
3448 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
3449 QualType PtrTy = BaseExpr->getType()->getPointeeType();
3450 SanitizerSet SkippedChecks;
3451 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3453 SkippedChecks.set(SanitizerKind::Alignment, true);
3454 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3455 SkippedChecks.set(SanitizerKind::Null, true);
3456 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3457 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3458 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
3460 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3462 NamedDecl *ND = E->getMemberDecl();
3463 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3464 LValue LV = EmitLValueForField(BaseLV, Field);
3465 setObjCGCLValueClass(getContext(), E, LV);
3469 if (auto *VD = dyn_cast<VarDecl>(ND))
3470 return EmitGlobalVarDeclLValue(*this, E, VD);
3472 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3473 return EmitFunctionDeclLValue(*this, E, FD);
3475 llvm_unreachable("Unhandled member declaration!");
3478 /// Given that we are currently emitting a lambda, emit an l-value for
3479 /// one of its members.
3480 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3481 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3482 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3483 QualType LambdaTagType =
3484 getContext().getTagDeclType(Field->getParent());
3485 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3486 return EmitLValueForField(LambdaLV, Field);
3489 /// Drill down to the storage of a field without walking into
3490 /// reference types.
3492 /// The resulting address doesn't necessarily have the right type.
3493 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3494 const FieldDecl *field) {
3495 const RecordDecl *rec = field->getParent();
3498 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3501 // Adjust the alignment down to the given offset.
3502 // As a special case, if the LLVM field index is 0, we know that this
3504 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3505 .getFieldOffset(field->getFieldIndex()) == 0) &&
3506 "LLVM field at index zero had non-zero offset?");
3508 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3509 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3510 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3513 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3516 LValue CodeGenFunction::EmitLValueForField(LValue base,
3517 const FieldDecl *field) {
3518 AlignmentSource fieldAlignSource =
3519 getFieldAlignmentSource(base.getAlignmentSource());
3521 if (field->isBitField()) {
3522 const CGRecordLayout &RL =
3523 CGM.getTypes().getCGRecordLayout(field->getParent());
3524 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3525 Address Addr = base.getAddress();
3526 unsigned Idx = RL.getLLVMFieldNo(field);
3528 // For structs, we GEP to the field that the record layout suggests.
3529 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3531 // Get the access type.
3532 llvm::Type *FieldIntTy =
3533 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3534 if (Addr.getElementType() != FieldIntTy)
3535 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3537 QualType fieldType =
3538 field->getType().withCVRQualifiers(base.getVRQualifiers());
3539 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
3542 const RecordDecl *rec = field->getParent();
3543 QualType type = field->getType();
3545 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3547 Address addr = base.getAddress();
3548 unsigned cvr = base.getVRQualifiers();
3549 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3550 if (rec->isUnion()) {
3551 // For unions, there is no pointer adjustment.
3552 assert(!type->isReferenceType() && "union has reference member");
3553 // TODO: handle path-aware TBAA for union.
3556 // For structs, we GEP to the field that the record layout suggests.
3557 addr = emitAddrOfFieldStorage(*this, addr, field);
3559 // If this is a reference field, load the reference right now.
3560 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3561 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3562 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3564 // Loading the reference will disable path-aware TBAA.
3566 if (CGM.shouldUseTBAA()) {
3569 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3571 tbaa = CGM.getTBAAInfo(type);
3573 CGM.DecorateInstructionWithTBAA(load, tbaa);
3577 type = refType->getPointeeType();
3579 CharUnits alignment =
3580 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3581 addr = Address(load, alignment);
3583 // Qualifiers on the struct don't apply to the referencee, and
3584 // we'll pick up CVR from the actual type later, so reset these
3585 // additional qualifiers now.
3590 // Make sure that the address is pointing to the right type. This is critical
3591 // for both unions and structs. A union needs a bitcast, a struct element
3592 // will need a bitcast if the LLVM type laid out doesn't match the desired
3594 addr = Builder.CreateElementBitCast(addr,
3595 CGM.getTypes().ConvertTypeForMem(type),
3598 if (field->hasAttr<AnnotateAttr>())
3599 addr = EmitFieldAnnotations(field, addr);
3601 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
3602 LV.getQuals().addCVRQualifiers(cvr);
3604 const ASTRecordLayout &Layout =
3605 getContext().getASTRecordLayout(field->getParent());
3606 // Set the base type to be the base type of the base LValue and
3607 // update offset to be relative to the base type.
3608 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3609 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
3610 Layout.getFieldOffset(field->getFieldIndex()) /
3611 getContext().getCharWidth());
3614 // __weak attribute on a field is ignored.
3615 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3616 LV.getQuals().removeObjCGCAttr();
3618 // Fields of may_alias structs act like 'char' for TBAA purposes.
3619 // FIXME: this should get propagated down through anonymous structs
3621 if (mayAlias && LV.getTBAAInfo())
3622 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3628 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3629 const FieldDecl *Field) {
3630 QualType FieldType = Field->getType();
3632 if (!FieldType->isReferenceType())
3633 return EmitLValueForField(Base, Field);
3635 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3637 // Make sure that the address is pointing to the right type.
3638 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3639 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3641 // TODO: access-path TBAA?
3642 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3643 return MakeAddrLValue(V, FieldType, FieldAlignSource);
3646 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3647 if (E->isFileScope()) {
3648 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3649 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
3651 if (E->getType()->isVariablyModifiedType())
3652 // make sure to emit the VLA size.
3653 EmitVariablyModifiedType(E->getType());
3655 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3656 const Expr *InitExpr = E->getInitializer();
3657 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
3659 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3665 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3666 if (!E->isGLValue())
3667 // Initializing an aggregate temporary in C++11: T{...}.
3668 return EmitAggExprToLValue(E);
3670 // An lvalue initializer list must be initializing a reference.
3671 assert(E->isTransparent() && "non-transparent glvalue init list");
3672 return EmitLValue(E->getInit(0));
3675 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3676 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3677 /// LValue is returned and the current block has been terminated.
3678 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3679 const Expr *Operand) {
3680 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3681 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3685 return CGF.EmitLValue(Operand);
3688 LValue CodeGenFunction::
3689 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3690 if (!expr->isGLValue()) {
3691 // ?: here should be an aggregate.
3692 assert(hasAggregateEvaluationKind(expr->getType()) &&
3693 "Unexpected conditional operator!");
3694 return EmitAggExprToLValue(expr);
3697 OpaqueValueMapping binding(*this, expr);
3699 const Expr *condExpr = expr->getCond();
3701 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3702 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3703 if (!CondExprBool) std::swap(live, dead);
3705 if (!ContainsLabel(dead)) {
3706 // If the true case is live, we need to track its region.
3708 incrementProfileCounter(expr);
3709 return EmitLValue(live);
3713 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3714 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3715 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3717 ConditionalEvaluation eval(*this);
3718 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3720 // Any temporaries created here are conditional.
3721 EmitBlock(lhsBlock);
3722 incrementProfileCounter(expr);
3724 Optional<LValue> lhs =
3725 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3728 if (lhs && !lhs->isSimple())
3729 return EmitUnsupportedLValue(expr, "conditional operator");
3731 lhsBlock = Builder.GetInsertBlock();
3733 Builder.CreateBr(contBlock);
3735 // Any temporaries created here are conditional.
3736 EmitBlock(rhsBlock);
3738 Optional<LValue> rhs =
3739 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3741 if (rhs && !rhs->isSimple())
3742 return EmitUnsupportedLValue(expr, "conditional operator");
3743 rhsBlock = Builder.GetInsertBlock();
3745 EmitBlock(contBlock);
3748 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3750 phi->addIncoming(lhs->getPointer(), lhsBlock);
3751 phi->addIncoming(rhs->getPointer(), rhsBlock);
3752 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3753 AlignmentSource alignSource =
3754 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3755 return MakeAddrLValue(result, expr->getType(), alignSource);
3757 assert((lhs || rhs) &&
3758 "both operands of glvalue conditional are throw-expressions?");
3759 return lhs ? *lhs : *rhs;
3763 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3764 /// type. If the cast is to a reference, we can have the usual lvalue result,
3765 /// otherwise if a cast is needed by the code generator in an lvalue context,
3766 /// then it must mean that we need the address of an aggregate in order to
3767 /// access one of its members. This can happen for all the reasons that casts
3768 /// are permitted with aggregate result, including noop aggregate casts, and
3769 /// cast from scalar to union.
3770 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3771 switch (E->getCastKind()) {
3774 case CK_ArrayToPointerDecay:
3775 case CK_FunctionToPointerDecay:
3776 case CK_NullToMemberPointer:
3777 case CK_NullToPointer:
3778 case CK_IntegralToPointer:
3779 case CK_PointerToIntegral:
3780 case CK_PointerToBoolean:
3781 case CK_VectorSplat:
3782 case CK_IntegralCast:
3783 case CK_BooleanToSignedIntegral:
3784 case CK_IntegralToBoolean:
3785 case CK_IntegralToFloating:
3786 case CK_FloatingToIntegral:
3787 case CK_FloatingToBoolean:
3788 case CK_FloatingCast:
3789 case CK_FloatingRealToComplex:
3790 case CK_FloatingComplexToReal:
3791 case CK_FloatingComplexToBoolean:
3792 case CK_FloatingComplexCast:
3793 case CK_FloatingComplexToIntegralComplex:
3794 case CK_IntegralRealToComplex:
3795 case CK_IntegralComplexToReal:
3796 case CK_IntegralComplexToBoolean:
3797 case CK_IntegralComplexCast:
3798 case CK_IntegralComplexToFloatingComplex:
3799 case CK_DerivedToBaseMemberPointer:
3800 case CK_BaseToDerivedMemberPointer:
3801 case CK_MemberPointerToBoolean:
3802 case CK_ReinterpretMemberPointer:
3803 case CK_AnyPointerToBlockPointerCast:
3804 case CK_ARCProduceObject:
3805 case CK_ARCConsumeObject:
3806 case CK_ARCReclaimReturnedObject:
3807 case CK_ARCExtendBlockObject:
3808 case CK_CopyAndAutoreleaseBlockObject:
3809 case CK_AddressSpaceConversion:
3810 case CK_IntToOCLSampler:
3811 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3814 llvm_unreachable("dependent cast kind in IR gen!");
3816 case CK_BuiltinFnToFnPtr:
3817 llvm_unreachable("builtin functions are handled elsewhere");
3819 // These are never l-values; just use the aggregate emission code.
3820 case CK_NonAtomicToAtomic:
3821 case CK_AtomicToNonAtomic:
3822 return EmitAggExprToLValue(E);
3825 LValue LV = EmitLValue(E->getSubExpr());
3826 Address V = LV.getAddress();
3827 const auto *DCE = cast<CXXDynamicCastExpr>(E);
3828 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
3831 case CK_ConstructorConversion:
3832 case CK_UserDefinedConversion:
3833 case CK_CPointerToObjCPointerCast:
3834 case CK_BlockPointerToObjCPointerCast:
3836 case CK_LValueToRValue:
3837 return EmitLValue(E->getSubExpr());
3839 case CK_UncheckedDerivedToBase:
3840 case CK_DerivedToBase: {
3841 const RecordType *DerivedClassTy =
3842 E->getSubExpr()->getType()->getAs<RecordType>();
3843 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3845 LValue LV = EmitLValue(E->getSubExpr());
3846 Address This = LV.getAddress();
3848 // Perform the derived-to-base conversion
3849 Address Base = GetAddressOfBaseClass(
3850 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3851 /*NullCheckValue=*/false, E->getExprLoc());
3853 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
3856 return EmitAggExprToLValue(E);
3857 case CK_BaseToDerived: {
3858 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
3859 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
3861 LValue LV = EmitLValue(E->getSubExpr());
3863 // Perform the base-to-derived conversion
3865 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3866 E->path_begin(), E->path_end(),
3867 /*NullCheckValue=*/false);
3869 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3870 // performed and the object is not of the derived type.
3871 if (sanitizePerformTypeCheck())
3872 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3873 Derived.getPointer(), E->getType());
3875 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
3876 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3877 /*MayBeNull=*/false,
3878 CFITCK_DerivedCast, E->getLocStart());
3880 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
3882 case CK_LValueBitCast: {
3883 // This must be a reinterpret_cast (or c-style equivalent).
3884 const auto *CE = cast<ExplicitCastExpr>(E);
3886 CGM.EmitExplicitCastExprType(CE, this);
3887 LValue LV = EmitLValue(E->getSubExpr());
3888 Address V = Builder.CreateBitCast(LV.getAddress(),
3889 ConvertType(CE->getTypeAsWritten()));
3891 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
3892 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3893 /*MayBeNull=*/false,
3894 CFITCK_UnrelatedCast, E->getLocStart());
3896 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3898 case CK_ObjCObjectLValueCast: {
3899 LValue LV = EmitLValue(E->getSubExpr());
3900 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3901 ConvertType(E->getType()));
3902 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
3904 case CK_ZeroToOCLQueue:
3905 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
3906 case CK_ZeroToOCLEvent:
3907 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3910 llvm_unreachable("Unhandled lvalue cast kind?");
3913 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3914 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3915 return getOpaqueLValueMapping(e);
3918 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3919 const FieldDecl *FD,
3920 SourceLocation Loc) {
3921 QualType FT = FD->getType();
3922 LValue FieldLV = EmitLValueForField(LV, FD);
3923 switch (getEvaluationKind(FT)) {
3925 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3927 return FieldLV.asAggregateRValue();
3929 // This routine is used to load fields one-by-one to perform a copy, so
3930 // don't load reference fields.
3931 if (FD->getType()->isReferenceType())
3932 return RValue::get(FieldLV.getPointer());
3933 return EmitLoadOfLValue(FieldLV, Loc);
3935 llvm_unreachable("bad evaluation kind");
3938 //===--------------------------------------------------------------------===//
3939 // Expression Emission
3940 //===--------------------------------------------------------------------===//
3942 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3943 ReturnValueSlot ReturnValue) {
3944 // Builtins never have block type.
3945 if (E->getCallee()->getType()->isBlockPointerType())
3946 return EmitBlockCallExpr(E, ReturnValue);
3948 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3949 return EmitCXXMemberCallExpr(CE, ReturnValue);
3951 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3952 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3954 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3955 if (const CXXMethodDecl *MD =
3956 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
3957 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3959 CGCallee callee = EmitCallee(E->getCallee());
3961 if (callee.isBuiltin()) {
3962 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3966 if (callee.isPseudoDestructor()) {
3967 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3970 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3973 /// Emit a CallExpr without considering whether it might be a subclass.
3974 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3975 ReturnValueSlot ReturnValue) {
3976 CGCallee Callee = EmitCallee(E->getCallee());
3977 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3980 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3981 if (auto builtinID = FD->getBuiltinID()) {
3982 return CGCallee::forBuiltin(builtinID, FD);
3985 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3986 return CGCallee::forDirect(calleePtr, FD);
3989 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3990 E = E->IgnoreParens();
3992 // Look through function-to-pointer decay.
3993 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3994 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3995 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3996 return EmitCallee(ICE->getSubExpr());
3999 // Resolve direct calls.
4000 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4001 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4002 return EmitDirectCallee(*this, FD);
4004 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4005 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4006 EmitIgnoredExpr(ME->getBase());
4007 return EmitDirectCallee(*this, FD);
4010 // Look through template substitutions.
4011 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4012 return EmitCallee(NTTP->getReplacement());
4014 // Treat pseudo-destructor calls differently.
4015 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4016 return CGCallee::forPseudoDestructor(PDE);
4019 // Otherwise, we have an indirect reference.
4020 llvm::Value *calleePtr;
4021 QualType functionType;
4022 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4023 calleePtr = EmitScalarExpr(E);
4024 functionType = ptrType->getPointeeType();
4026 functionType = E->getType();
4027 calleePtr = EmitLValue(E).getPointer();
4029 assert(functionType->isFunctionType());
4030 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4031 E->getReferencedDeclOfCallee());
4032 CGCallee callee(calleeInfo, calleePtr);
4036 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4037 // Comma expressions just emit their LHS then their RHS as an l-value.
4038 if (E->getOpcode() == BO_Comma) {
4039 EmitIgnoredExpr(E->getLHS());
4040 EnsureInsertPoint();
4041 return EmitLValue(E->getRHS());
4044 if (E->getOpcode() == BO_PtrMemD ||
4045 E->getOpcode() == BO_PtrMemI)
4046 return EmitPointerToDataMemberBinaryExpr(E);
4048 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4050 // Note that in all of these cases, __block variables need the RHS
4051 // evaluated first just in case the variable gets moved by the RHS.
4053 switch (getEvaluationKind(E->getType())) {
4055 switch (E->getLHS()->getType().getObjCLifetime()) {
4056 case Qualifiers::OCL_Strong:
4057 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4059 case Qualifiers::OCL_Autoreleasing:
4060 return EmitARCStoreAutoreleasing(E).first;
4062 // No reason to do any of these differently.
4063 case Qualifiers::OCL_None:
4064 case Qualifiers::OCL_ExplicitNone:
4065 case Qualifiers::OCL_Weak:
4069 RValue RV = EmitAnyExpr(E->getRHS());
4070 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4071 EmitStoreThroughLValue(RV, LV);
4076 return EmitComplexAssignmentLValue(E);
4079 return EmitAggExprToLValue(E);
4081 llvm_unreachable("bad evaluation kind");
4084 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4085 RValue RV = EmitCallExpr(E);
4088 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4089 AlignmentSource::Decl);
4091 assert(E->getCallReturnType(getContext())->isReferenceType() &&
4092 "Can't have a scalar return unless the return type is a "
4095 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4098 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4099 // FIXME: This shouldn't require another copy.
4100 return EmitAggExprToLValue(E);
4103 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4104 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4105 && "binding l-value to type which needs a temporary");
4106 AggValueSlot Slot = CreateAggTemp(E->getType());
4107 EmitCXXConstructExpr(E, Slot);
4108 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4109 AlignmentSource::Decl);
4113 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4114 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4117 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4118 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4119 ConvertType(E->getType()));
4122 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4123 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4124 AlignmentSource::Decl);
4128 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4129 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4130 Slot.setExternallyDestructed();
4131 EmitAggExpr(E->getSubExpr(), Slot);
4132 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4133 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4134 AlignmentSource::Decl);
4138 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4139 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4140 EmitLambdaExpr(E, Slot);
4141 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4142 AlignmentSource::Decl);
4145 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4146 RValue RV = EmitObjCMessageExpr(E);
4149 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4150 AlignmentSource::Decl);
4152 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4153 "Can't have a scalar return unless the return type is a "
4156 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4159 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4161 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4162 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
4165 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4166 const ObjCIvarDecl *Ivar) {
4167 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4170 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4171 llvm::Value *BaseValue,
4172 const ObjCIvarDecl *Ivar,
4173 unsigned CVRQualifiers) {
4174 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4175 Ivar, CVRQualifiers);
4178 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4179 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4180 llvm::Value *BaseValue = nullptr;
4181 const Expr *BaseExpr = E->getBase();
4182 Qualifiers BaseQuals;
4185 BaseValue = EmitScalarExpr(BaseExpr);
4186 ObjectTy = BaseExpr->getType()->getPointeeType();
4187 BaseQuals = ObjectTy.getQualifiers();
4189 LValue BaseLV = EmitLValue(BaseExpr);
4190 BaseValue = BaseLV.getPointer();
4191 ObjectTy = BaseExpr->getType();
4192 BaseQuals = ObjectTy.getQualifiers();
4196 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4197 BaseQuals.getCVRQualifiers());
4198 setObjCGCLValueClass(getContext(), E, LV);
4202 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4203 // Can only get l-value for message expression returning aggregate type
4204 RValue RV = EmitAnyExprToTemp(E);
4205 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4206 AlignmentSource::Decl);
4209 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4210 const CallExpr *E, ReturnValueSlot ReturnValue,
4211 llvm::Value *Chain) {
4212 // Get the actual function type. The callee type will always be a pointer to
4213 // function type or a block pointer type.
4214 assert(CalleeType->isFunctionPointerType() &&
4215 "Call must have function pointer type!");
4217 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4219 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4220 // We can only guarantee that a function is called from the correct
4221 // context/function based on the appropriate target attributes,
4222 // so only check in the case where we have both always_inline and target
4223 // since otherwise we could be making a conditional call after a check for
4224 // the proper cpu features (and it won't cause code generation issues due to
4225 // function based code generation).
4226 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4227 TargetDecl->hasAttr<TargetAttr>())
4228 checkTargetFeatures(E, FD);
4230 CalleeType = getContext().getCanonicalType(CalleeType);
4232 const auto *FnType =
4233 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4235 CGCallee Callee = OrigCallee;
4237 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4238 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4239 if (llvm::Constant *PrefixSig =
4240 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4241 SanitizerScope SanScope(this);
4242 llvm::Constant *FTRTTIConst =
4243 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4244 llvm::Type *PrefixStructTyElems[] = {
4245 PrefixSig->getType(),
4246 FTRTTIConst->getType()
4248 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4249 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4251 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4253 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4254 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4255 llvm::Value *CalleeSigPtr =
4256 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4257 llvm::Value *CalleeSig =
4258 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4259 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4261 llvm::BasicBlock *Cont = createBasicBlock("cont");
4262 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4263 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4265 EmitBlock(TypeCheck);
4266 llvm::Value *CalleeRTTIPtr =
4267 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4268 llvm::Value *CalleeRTTI =
4269 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4270 llvm::Value *CalleeRTTIMatch =
4271 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4272 llvm::Constant *StaticData[] = {
4273 EmitCheckSourceLocation(E->getLocStart()),
4274 EmitCheckTypeDescriptor(CalleeType)
4276 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4277 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4279 Builder.CreateBr(Cont);
4284 // If we are checking indirect calls and this call is indirect, check that the
4285 // function pointer is a member of the bit set for the function type.
4286 if (SanOpts.has(SanitizerKind::CFIICall) &&
4287 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4288 SanitizerScope SanScope(this);
4289 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4291 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4292 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4294 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4295 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4296 llvm::Value *TypeTest = Builder.CreateCall(
4297 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4299 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4300 llvm::Constant *StaticData[] = {
4301 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4302 EmitCheckSourceLocation(E->getLocStart()),
4303 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4305 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4306 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4307 CastedCallee, StaticData);
4309 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4310 SanitizerHandler::CFICheckFail, StaticData,
4311 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4317 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4318 CGM.getContext().VoidPtrTy);
4320 // C++17 requires that we evaluate arguments to a call using assignment syntax
4321 // right-to-left, and that we evaluate arguments to certain other operators
4322 // left-to-right. Note that we allow this to override the order dictated by
4323 // the calling convention on the MS ABI, which means that parameter
4324 // destruction order is not necessarily reverse construction order.
4325 // FIXME: Revisit this based on C++ committee response to unimplementability.
4326 EvaluationOrder Order = EvaluationOrder::Default;
4327 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4328 if (OCE->isAssignmentOp())
4329 Order = EvaluationOrder::ForceRightToLeft;
4331 switch (OCE->getOperator()) {
4333 case OO_GreaterGreater:
4338 Order = EvaluationOrder::ForceLeftToRight;
4346 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4347 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4349 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4350 Args, FnType, /*isChainCall=*/Chain);
4353 // If the expression that denotes the called function has a type
4354 // that does not include a prototype, [the default argument
4355 // promotions are performed]. If the number of arguments does not
4356 // equal the number of parameters, the behavior is undefined. If
4357 // the function is defined with a type that includes a prototype,
4358 // and either the prototype ends with an ellipsis (, ...) or the
4359 // types of the arguments after promotion are not compatible with
4360 // the types of the parameters, the behavior is undefined. If the
4361 // function is defined with a type that does not include a
4362 // prototype, and the types of the arguments after promotion are
4363 // not compatible with those of the parameters after promotion,
4364 // the behavior is undefined [except in some trivial cases].
4365 // That is, in the general case, we should assume that a call
4366 // through an unprototyped function type works like a *non-variadic*
4367 // call. The way we make this work is to cast to the exact type
4368 // of the promoted arguments.
4370 // Chain calls use this same code path to add the invisible chain parameter
4371 // to the function type.
4372 if (isa<FunctionNoProtoType>(FnType) || Chain) {
4373 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4374 CalleeTy = CalleeTy->getPointerTo();
4376 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4377 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4378 Callee.setFunctionPointer(CalleePtr);
4381 return EmitCall(FnInfo, Callee, ReturnValue, Args);
4384 LValue CodeGenFunction::
4385 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4386 Address BaseAddr = Address::invalid();
4387 if (E->getOpcode() == BO_PtrMemI) {
4388 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4390 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4393 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4395 const MemberPointerType *MPT
4396 = E->getRHS()->getType()->getAs<MemberPointerType>();
4398 AlignmentSource AlignSource;
4399 Address MemberAddr =
4400 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4403 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
4406 /// Given the address of a temporary variable, produce an r-value of
4408 RValue CodeGenFunction::convertTempToRValue(Address addr,
4410 SourceLocation loc) {
4411 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
4412 switch (getEvaluationKind(type)) {
4414 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4416 return lvalue.asAggregateRValue();
4418 return RValue::get(EmitLoadOfScalar(lvalue, loc));
4420 llvm_unreachable("bad evaluation kind");
4423 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4424 assert(Val->getType()->isFPOrFPVectorTy());
4425 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4428 llvm::MDBuilder MDHelper(getLLVMContext());
4429 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4431 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4435 struct LValueOrRValue {
4441 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4442 const PseudoObjectExpr *E,
4444 AggValueSlot slot) {
4445 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4447 // Find the result expression, if any.
4448 const Expr *resultExpr = E->getResultExpr();
4449 LValueOrRValue result;
4451 for (PseudoObjectExpr::const_semantics_iterator
4452 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4453 const Expr *semantic = *i;
4455 // If this semantic expression is an opaque value, bind it
4456 // to the result of its source expression.
4457 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4459 // If this is the result expression, we may need to evaluate
4460 // directly into the slot.
4461 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4463 if (ov == resultExpr && ov->isRValue() && !forLValue &&
4464 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4465 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4467 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4468 AlignmentSource::Decl);
4469 opaqueData = OVMA::bind(CGF, ov, LV);
4470 result.RV = slot.asRValue();
4472 // Otherwise, emit as normal.
4474 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4476 // If this is the result, also evaluate the result now.
4477 if (ov == resultExpr) {
4479 result.LV = CGF.EmitLValue(ov);
4481 result.RV = CGF.EmitAnyExpr(ov, slot);
4485 opaques.push_back(opaqueData);
4487 // Otherwise, if the expression is the result, evaluate it
4488 // and remember the result.
4489 } else if (semantic == resultExpr) {
4491 result.LV = CGF.EmitLValue(semantic);
4493 result.RV = CGF.EmitAnyExpr(semantic, slot);
4495 // Otherwise, evaluate the expression in an ignored context.
4497 CGF.EmitIgnoredExpr(semantic);
4501 // Unbind all the opaques now.
4502 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4503 opaques[i].unbind(CGF);
4508 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4509 AggValueSlot slot) {
4510 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4513 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4514 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;