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