1 //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenFunction.h"
15 #include "CGCXXABI.h"
16 #include "CGCall.h"
17 #include "CGDebugInfo.h"
18 #include "CGObjCRuntime.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CGRecordLayout.h"
21 #include "CodeGenModule.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/Frontend/CodeGenOptions.h"
27 #include "llvm/ADT/Hashing.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/MDBuilder.h"
33 #include "llvm/Support/ConvertUTF.h"
34
35 using namespace clang;
36 using namespace CodeGen;
37
38 //===--------------------------------------------------------------------===//
39 // Miscellaneous Helper Methods
40 //===--------------------------------------------------------------------===//
41
EmitCastToVoidPtr(llvm::Value * value)42 llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
43 unsigned addressSpace =
44 cast<llvm::PointerType>(value->getType())->getAddressSpace();
45
46 llvm::PointerType *destType = Int8PtrTy;
47 if (addressSpace)
48 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
49
50 if (value->getType() == destType) return value;
51 return Builder.CreateBitCast(value, destType);
52 }
53
54 /// CreateTempAlloca - This creates a alloca and inserts it into the entry
55 /// block.
CreateTempAlloca(llvm::Type * Ty,const Twine & Name)56 llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
57 const Twine &Name) {
58 if (!Builder.isNamePreserving())
59 return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
60 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
61 }
62
InitTempAlloca(llvm::AllocaInst * Var,llvm::Value * Init)63 void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
64 llvm::Value *Init) {
65 auto *Store = new llvm::StoreInst(Init, Var);
66 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
67 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
68 }
69
CreateIRTemp(QualType Ty,const Twine & Name)70 llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
71 const Twine &Name) {
72 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
73 // FIXME: Should we prefer the preferred type alignment here?
74 CharUnits Align = getContext().getTypeAlignInChars(Ty);
75 Alloc->setAlignment(Align.getQuantity());
76 return Alloc;
77 }
78
CreateMemTemp(QualType Ty,const Twine & Name)79 llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
80 const Twine &Name) {
81 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
82 // FIXME: Should we prefer the preferred type alignment here?
83 CharUnits Align = getContext().getTypeAlignInChars(Ty);
84 Alloc->setAlignment(Align.getQuantity());
85 return Alloc;
86 }
87
88 /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
89 /// expression and compare the result against zero, returning an Int1Ty value.
EvaluateExprAsBool(const Expr * E)90 llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
91 PGO.setCurrentStmt(E);
92 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
93 llvm::Value *MemPtr = EmitScalarExpr(E);
94 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
95 }
96
97 QualType BoolTy = getContext().BoolTy;
98 if (!E->getType()->isAnyComplexType())
99 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
100
101 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
102 }
103
104 /// EmitIgnoredExpr - Emit code to compute the specified expression,
105 /// ignoring the result.
EmitIgnoredExpr(const Expr * E)106 void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
107 if (E->isRValue())
108 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
109
110 // Just emit it as an l-value and drop the result.
111 EmitLValue(E);
112 }
113
114 /// EmitAnyExpr - Emit code to compute the specified expression which
115 /// can have any type. The result is returned as an RValue struct.
116 /// If this is an aggregate expression, AggSlot indicates where the
117 /// result should be returned.
EmitAnyExpr(const Expr * E,AggValueSlot aggSlot,bool ignoreResult)118 RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
119 AggValueSlot aggSlot,
120 bool ignoreResult) {
121 switch (getEvaluationKind(E->getType())) {
122 case TEK_Scalar:
123 return RValue::get(EmitScalarExpr(E, ignoreResult));
124 case TEK_Complex:
125 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
126 case TEK_Aggregate:
127 if (!ignoreResult && aggSlot.isIgnored())
128 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
129 EmitAggExpr(E, aggSlot);
130 return aggSlot.asRValue();
131 }
132 llvm_unreachable("bad evaluation kind");
133 }
134
135 /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
136 /// always be accessible even if no aggregate location is provided.
EmitAnyExprToTemp(const Expr * E)137 RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
138 AggValueSlot AggSlot = AggValueSlot::ignored();
139
140 if (hasAggregateEvaluationKind(E->getType()))
141 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
142 return EmitAnyExpr(E, AggSlot);
143 }
144
145 /// EmitAnyExprToMem - Evaluate an expression into a given memory
146 /// location.
EmitAnyExprToMem(const Expr * E,llvm::Value * Location,Qualifiers Quals,bool IsInit)147 void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
148 llvm::Value *Location,
149 Qualifiers Quals,
150 bool IsInit) {
151 // FIXME: This function should take an LValue as an argument.
152 switch (getEvaluationKind(E->getType())) {
153 case TEK_Complex:
154 EmitComplexExprIntoLValue(E,
155 MakeNaturalAlignAddrLValue(Location, E->getType()),
156 /*isInit*/ false);
157 return;
158
159 case TEK_Aggregate: {
160 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
161 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
162 AggValueSlot::IsDestructed_t(IsInit),
163 AggValueSlot::DoesNotNeedGCBarriers,
164 AggValueSlot::IsAliased_t(!IsInit)));
165 return;
166 }
167
168 case TEK_Scalar: {
169 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
170 LValue LV = MakeAddrLValue(Location, E->getType());
171 EmitStoreThroughLValue(RV, LV);
172 return;
173 }
174 }
175 llvm_unreachable("bad evaluation kind");
176 }
177
178 static void
pushTemporaryCleanup(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * E,llvm::Value * ReferenceTemporary)179 pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
180 const Expr *E, llvm::Value *ReferenceTemporary) {
181 // Objective-C++ ARC:
182 // If we are binding a reference to a temporary that has ownership, we
183 // need to perform retain/release operations on the temporary.
184 //
185 // FIXME: This should be looking at E, not M.
186 if (CGF.getLangOpts().ObjCAutoRefCount &&
187 M->getType()->isObjCLifetimeType()) {
188 QualType ObjCARCReferenceLifetimeType = M->getType();
189 switch (Qualifiers::ObjCLifetime Lifetime =
190 ObjCARCReferenceLifetimeType.getObjCLifetime()) {
191 case Qualifiers::OCL_None:
192 case Qualifiers::OCL_ExplicitNone:
193 // Carry on to normal cleanup handling.
194 break;
195
196 case Qualifiers::OCL_Autoreleasing:
197 // Nothing to do; cleaned up by an autorelease pool.
198 return;
199
200 case Qualifiers::OCL_Strong:
201 case Qualifiers::OCL_Weak:
202 switch (StorageDuration Duration = M->getStorageDuration()) {
203 case SD_Static:
204 // Note: we intentionally do not register a cleanup to release
205 // the object on program termination.
206 return;
207
208 case SD_Thread:
209 // FIXME: We should probably register a cleanup in this case.
210 return;
211
212 case SD_Automatic:
213 case SD_FullExpression:
214 CodeGenFunction::Destroyer *Destroy;
215 CleanupKind CleanupKind;
216 if (Lifetime == Qualifiers::OCL_Strong) {
217 const ValueDecl *VD = M->getExtendingDecl();
218 bool Precise =
219 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
220 CleanupKind = CGF.getARCCleanupKind();
221 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
222 : &CodeGenFunction::destroyARCStrongImprecise;
223 } else {
224 // __weak objects always get EH cleanups; otherwise, exceptions
225 // could cause really nasty crashes instead of mere leaks.
226 CleanupKind = NormalAndEHCleanup;
227 Destroy = &CodeGenFunction::destroyARCWeak;
228 }
229 if (Duration == SD_FullExpression)
230 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
231 ObjCARCReferenceLifetimeType, *Destroy,
232 CleanupKind & EHCleanup);
233 else
234 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
235 ObjCARCReferenceLifetimeType,
236 *Destroy, CleanupKind & EHCleanup);
237 return;
238
239 case SD_Dynamic:
240 llvm_unreachable("temporary cannot have dynamic storage duration");
241 }
242 llvm_unreachable("unknown storage duration");
243 }
244 }
245
246 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
247 if (const RecordType *RT =
248 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
249 // Get the destructor for the reference temporary.
250 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
251 if (!ClassDecl->hasTrivialDestructor())
252 ReferenceTemporaryDtor = ClassDecl->getDestructor();
253 }
254
255 if (!ReferenceTemporaryDtor)
256 return;
257
258 // Call the destructor for the temporary.
259 switch (M->getStorageDuration()) {
260 case SD_Static:
261 case SD_Thread: {
262 llvm::Constant *CleanupFn;
263 llvm::Constant *CleanupArg;
264 if (E->getType()->isArrayType()) {
265 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
266 cast<llvm::Constant>(ReferenceTemporary), E->getType(),
267 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
268 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
269 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
270 } else {
271 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
272 StructorType::Complete);
273 CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
274 }
275 CGF.CGM.getCXXABI().registerGlobalDtor(
276 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
277 break;
278 }
279
280 case SD_FullExpression:
281 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
282 CodeGenFunction::destroyCXXObject,
283 CGF.getLangOpts().Exceptions);
284 break;
285
286 case SD_Automatic:
287 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
288 ReferenceTemporary, E->getType(),
289 CodeGenFunction::destroyCXXObject,
290 CGF.getLangOpts().Exceptions);
291 break;
292
293 case SD_Dynamic:
294 llvm_unreachable("temporary cannot have dynamic storage duration");
295 }
296 }
297
298 static llvm::Value *
createReferenceTemporary(CodeGenFunction & CGF,const MaterializeTemporaryExpr * M,const Expr * Inner)299 createReferenceTemporary(CodeGenFunction &CGF,
300 const MaterializeTemporaryExpr *M, const Expr *Inner) {
301 switch (M->getStorageDuration()) {
302 case SD_FullExpression:
303 case SD_Automatic:
304 return CGF.CreateMemTemp(Inner->getType(), "ref.tmp");
305
306 case SD_Thread:
307 case SD_Static:
308 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
309
310 case SD_Dynamic:
311 llvm_unreachable("temporary can't have dynamic storage duration");
312 }
313 llvm_unreachable("unknown storage duration");
314 }
315
316 LValue CodeGenFunction::
EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr * M)317 EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
318 const Expr *E = M->GetTemporaryExpr();
319
320 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
321 // as that will cause the lifetime adjustment to be lost for ARC
322 if (getLangOpts().ObjCAutoRefCount &&
323 M->getType()->isObjCLifetimeType() &&
324 M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
325 M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
326 llvm::Value *Object = createReferenceTemporary(*this, M, E);
327 LValue RefTempDst = MakeAddrLValue(Object, M->getType());
328
329 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
330 // We should not have emitted the initializer for this temporary as a
331 // constant.
332 assert(!Var->hasInitializer());
333 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
334 }
335
336 switch (getEvaluationKind(E->getType())) {
337 default: llvm_unreachable("expected scalar or aggregate expression");
338 case TEK_Scalar:
339 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
340 break;
341 case TEK_Aggregate: {
342 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
343 EmitAggExpr(E, AggValueSlot::forAddr(Object, Alignment,
344 E->getType().getQualifiers(),
345 AggValueSlot::IsDestructed,
346 AggValueSlot::DoesNotNeedGCBarriers,
347 AggValueSlot::IsNotAliased));
348 break;
349 }
350 }
351
352 pushTemporaryCleanup(*this, M, E, Object);
353 return RefTempDst;
354 }
355
356 SmallVector<const Expr *, 2> CommaLHSs;
357 SmallVector<SubobjectAdjustment, 2> Adjustments;
358 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
359
360 for (const auto &Ignored : CommaLHSs)
361 EmitIgnoredExpr(Ignored);
362
363 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
364 if (opaque->getType()->isRecordType()) {
365 assert(Adjustments.empty());
366 return EmitOpaqueValueLValue(opaque);
367 }
368 }
369
370 // Create and initialize the reference temporary.
371 llvm::Value *Object = createReferenceTemporary(*this, M, E);
372 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
373 // If the temporary is a global and has a constant initializer, we may
374 // have already initialized it.
375 if (!Var->hasInitializer()) {
376 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
377 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
378 }
379 } else {
380 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
381 }
382 pushTemporaryCleanup(*this, M, E, Object);
383
384 // Perform derived-to-base casts and/or field accesses, to get from the
385 // temporary object we created (and, potentially, for which we extended
386 // the lifetime) to the subobject we're binding the reference to.
387 for (unsigned I = Adjustments.size(); I != 0; --I) {
388 SubobjectAdjustment &Adjustment = Adjustments[I-1];
389 switch (Adjustment.Kind) {
390 case SubobjectAdjustment::DerivedToBaseAdjustment:
391 Object =
392 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
393 Adjustment.DerivedToBase.BasePath->path_begin(),
394 Adjustment.DerivedToBase.BasePath->path_end(),
395 /*NullCheckValue=*/ false, E->getExprLoc());
396 break;
397
398 case SubobjectAdjustment::FieldAdjustment: {
399 LValue LV = MakeAddrLValue(Object, E->getType());
400 LV = EmitLValueForField(LV, Adjustment.Field);
401 assert(LV.isSimple() &&
402 "materialized temporary field is not a simple lvalue");
403 Object = LV.getAddress();
404 break;
405 }
406
407 case SubobjectAdjustment::MemberPointerAdjustment: {
408 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
409 Object = CGM.getCXXABI().EmitMemberDataPointerAddress(
410 *this, E, Object, Ptr, Adjustment.Ptr.MPT);
411 break;
412 }
413 }
414 }
415
416 return MakeAddrLValue(Object, M->getType());
417 }
418
419 RValue
EmitReferenceBindingToExpr(const Expr * E)420 CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
421 // Emit the expression as an lvalue.
422 LValue LV = EmitLValue(E);
423 assert(LV.isSimple());
424 llvm::Value *Value = LV.getAddress();
425
426 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
427 // C++11 [dcl.ref]p5 (as amended by core issue 453):
428 // If a glvalue to which a reference is directly bound designates neither
429 // an existing object or function of an appropriate type nor a region of
430 // storage of suitable size and alignment to contain an object of the
431 // reference's type, the behavior is undefined.
432 QualType Ty = E->getType();
433 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
434 }
435
436 return RValue::get(Value);
437 }
438
439
440 /// getAccessedFieldNo - Given an encoded value and a result number, return the
441 /// input field number being accessed.
getAccessedFieldNo(unsigned Idx,const llvm::Constant * Elts)442 unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
443 const llvm::Constant *Elts) {
444 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
445 ->getZExtValue();
446 }
447
448 /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
emitHash16Bytes(CGBuilderTy & Builder,llvm::Value * Low,llvm::Value * High)449 static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
450 llvm::Value *High) {
451 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
452 llvm::Value *K47 = Builder.getInt64(47);
453 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
454 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
455 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
456 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
457 return Builder.CreateMul(B1, KMul);
458 }
459
sanitizePerformTypeCheck() const460 bool CodeGenFunction::sanitizePerformTypeCheck() const {
461 return SanOpts.has(SanitizerKind::Null) |
462 SanOpts.has(SanitizerKind::Alignment) |
463 SanOpts.has(SanitizerKind::ObjectSize) |
464 SanOpts.has(SanitizerKind::Vptr);
465 }
466
EmitTypeCheck(TypeCheckKind TCK,SourceLocation Loc,llvm::Value * Address,QualType Ty,CharUnits Alignment,bool SkipNullCheck)467 void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
468 llvm::Value *Address, QualType Ty,
469 CharUnits Alignment, bool SkipNullCheck) {
470 if (!sanitizePerformTypeCheck())
471 return;
472
473 // Don't check pointers outside the default address space. The null check
474 // isn't correct, the object-size check isn't supported by LLVM, and we can't
475 // communicate the addresses to the runtime handler for the vptr check.
476 if (Address->getType()->getPointerAddressSpace())
477 return;
478
479 SanitizerScope SanScope(this);
480
481 SmallVector<std::pair<llvm::Value *, SanitizerKind>, 3> Checks;
482 llvm::BasicBlock *Done = nullptr;
483
484 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
485 TCK == TCK_UpcastToVirtualBase;
486 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
487 !SkipNullCheck) {
488 // The glvalue must not be an empty glvalue.
489 llvm::Value *IsNonNull = Builder.CreateICmpNE(
490 Address, llvm::Constant::getNullValue(Address->getType()));
491
492 if (AllowNullPointers) {
493 // When performing pointer casts, it's OK if the value is null.
494 // Skip the remaining checks in that case.
495 Done = createBasicBlock("null");
496 llvm::BasicBlock *Rest = createBasicBlock("not.null");
497 Builder.CreateCondBr(IsNonNull, Rest, Done);
498 EmitBlock(Rest);
499 } else {
500 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
501 }
502 }
503
504 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
505 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
506
507 // The glvalue must refer to a large enough storage region.
508 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
509 // to check this.
510 // FIXME: Get object address space
511 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
512 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
513 llvm::Value *Min = Builder.getFalse();
514 llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
515 llvm::Value *LargeEnough =
516 Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
517 llvm::ConstantInt::get(IntPtrTy, Size));
518 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
519 }
520
521 uint64_t AlignVal = 0;
522
523 if (SanOpts.has(SanitizerKind::Alignment)) {
524 AlignVal = Alignment.getQuantity();
525 if (!Ty->isIncompleteType() && !AlignVal)
526 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
527
528 // The glvalue must be suitably aligned.
529 if (AlignVal) {
530 llvm::Value *Align =
531 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
532 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
533 llvm::Value *Aligned =
534 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
535 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
536 }
537 }
538
539 if (Checks.size() > 0) {
540 llvm::Constant *StaticData[] = {
541 EmitCheckSourceLocation(Loc),
542 EmitCheckTypeDescriptor(Ty),
543 llvm::ConstantInt::get(SizeTy, AlignVal),
544 llvm::ConstantInt::get(Int8Ty, TCK)
545 };
546 EmitCheck(Checks, "type_mismatch", StaticData, Address);
547 }
548
549 // If possible, check that the vptr indicates that there is a subobject of
550 // type Ty at offset zero within this object.
551 //
552 // C++11 [basic.life]p5,6:
553 // [For storage which does not refer to an object within its lifetime]
554 // The program has undefined behavior if:
555 // -- the [pointer or glvalue] is used to access a non-static data member
556 // or call a non-static member function
557 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
558 if (SanOpts.has(SanitizerKind::Vptr) &&
559 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
560 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
561 TCK == TCK_UpcastToVirtualBase) &&
562 RD && RD->hasDefinition() && RD->isDynamicClass()) {
563 // Compute a hash of the mangled name of the type.
564 //
565 // FIXME: This is not guaranteed to be deterministic! Move to a
566 // fingerprinting mechanism once LLVM provides one. For the time
567 // being the implementation happens to be deterministic.
568 SmallString<64> MangledName;
569 llvm::raw_svector_ostream Out(MangledName);
570 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
571 Out);
572
573 // Blacklist based on the mangled type.
574 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
575 Out.str())) {
576 llvm::hash_code TypeHash = hash_value(Out.str());
577
578 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
579 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
580 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
581 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
582 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
583 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
584
585 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
586 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
587
588 // Look the hash up in our cache.
589 const int CacheSize = 128;
590 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
591 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
592 "__ubsan_vptr_type_cache");
593 llvm::Value *Slot = Builder.CreateAnd(Hash,
594 llvm::ConstantInt::get(IntPtrTy,
595 CacheSize-1));
596 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
597 llvm::Value *CacheVal =
598 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
599
600 // If the hash isn't in the cache, call a runtime handler to perform the
601 // hard work of checking whether the vptr is for an object of the right
602 // type. This will either fill in the cache and return, or produce a
603 // diagnostic.
604 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
605 llvm::Constant *StaticData[] = {
606 EmitCheckSourceLocation(Loc),
607 EmitCheckTypeDescriptor(Ty),
608 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
609 llvm::ConstantInt::get(Int8Ty, TCK)
610 };
611 llvm::Value *DynamicData[] = { Address, Hash };
612 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
613 "dynamic_type_cache_miss", StaticData, DynamicData);
614 }
615 }
616
617 if (Done) {
618 Builder.CreateBr(Done);
619 EmitBlock(Done);
620 }
621 }
622
623 /// Determine whether this expression refers to a flexible array member in a
624 /// struct. We disable array bounds checks for such members.
isFlexibleArrayMemberExpr(const Expr * E)625 static bool isFlexibleArrayMemberExpr(const Expr *E) {
626 // For compatibility with existing code, we treat arrays of length 0 or
627 // 1 as flexible array members.
628 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
629 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
630 if (CAT->getSize().ugt(1))
631 return false;
632 } else if (!isa<IncompleteArrayType>(AT))
633 return false;
634
635 E = E->IgnoreParens();
636
637 // A flexible array member must be the last member in the class.
638 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
639 // FIXME: If the base type of the member expr is not FD->getParent(),
640 // this should not be treated as a flexible array member access.
641 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
642 RecordDecl::field_iterator FI(
643 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
644 return ++FI == FD->getParent()->field_end();
645 }
646 }
647
648 return false;
649 }
650
651 /// If Base is known to point to the start of an array, return the length of
652 /// that array. Return 0 if the length cannot be determined.
getArrayIndexingBound(CodeGenFunction & CGF,const Expr * Base,QualType & IndexedType)653 static llvm::Value *getArrayIndexingBound(
654 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
655 // For the vector indexing extension, the bound is the number of elements.
656 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
657 IndexedType = Base->getType();
658 return CGF.Builder.getInt32(VT->getNumElements());
659 }
660
661 Base = Base->IgnoreParens();
662
663 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
664 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
665 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
666 IndexedType = CE->getSubExpr()->getType();
667 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
668 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
669 return CGF.Builder.getInt(CAT->getSize());
670 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
671 return CGF.getVLASize(VAT).first;
672 }
673 }
674
675 return nullptr;
676 }
677
EmitBoundsCheck(const Expr * E,const Expr * Base,llvm::Value * Index,QualType IndexType,bool Accessed)678 void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
679 llvm::Value *Index, QualType IndexType,
680 bool Accessed) {
681 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
682 "should not be called unless adding bounds checks");
683 SanitizerScope SanScope(this);
684
685 QualType IndexedType;
686 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
687 if (!Bound)
688 return;
689
690 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
691 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
692 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
693
694 llvm::Constant *StaticData[] = {
695 EmitCheckSourceLocation(E->getExprLoc()),
696 EmitCheckTypeDescriptor(IndexedType),
697 EmitCheckTypeDescriptor(IndexType)
698 };
699 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
700 : Builder.CreateICmpULE(IndexVal, BoundVal);
701 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
702 StaticData, Index);
703 }
704
705
706 CodeGenFunction::ComplexPairTy CodeGenFunction::
EmitComplexPrePostIncDec(const UnaryOperator * E,LValue LV,bool isInc,bool isPre)707 EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
708 bool isInc, bool isPre) {
709 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
710
711 llvm::Value *NextVal;
712 if (isa<llvm::IntegerType>(InVal.first->getType())) {
713 uint64_t AmountVal = isInc ? 1 : -1;
714 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
715
716 // Add the inc/dec to the real part.
717 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
718 } else {
719 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
720 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
721 if (!isInc)
722 FVal.changeSign();
723 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
724
725 // Add the inc/dec to the real part.
726 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
727 }
728
729 ComplexPairTy IncVal(NextVal, InVal.second);
730
731 // Store the updated result through the lvalue.
732 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
733
734 // If this is a postinc, return the value read from memory, otherwise use the
735 // updated value.
736 return isPre ? IncVal : InVal;
737 }
738
739 //===----------------------------------------------------------------------===//
740 // LValue Expression Emission
741 //===----------------------------------------------------------------------===//
742
GetUndefRValue(QualType Ty)743 RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
744 if (Ty->isVoidType())
745 return RValue::get(nullptr);
746
747 switch (getEvaluationKind(Ty)) {
748 case TEK_Complex: {
749 llvm::Type *EltTy =
750 ConvertType(Ty->castAs<ComplexType>()->getElementType());
751 llvm::Value *U = llvm::UndefValue::get(EltTy);
752 return RValue::getComplex(std::make_pair(U, U));
753 }
754
755 // If this is a use of an undefined aggregate type, the aggregate must have an
756 // identifiable address. Just because the contents of the value are undefined
757 // doesn't mean that the address can't be taken and compared.
758 case TEK_Aggregate: {
759 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
760 return RValue::getAggregate(DestPtr);
761 }
762
763 case TEK_Scalar:
764 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
765 }
766 llvm_unreachable("bad evaluation kind");
767 }
768
EmitUnsupportedRValue(const Expr * E,const char * Name)769 RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
770 const char *Name) {
771 ErrorUnsupported(E, Name);
772 return GetUndefRValue(E->getType());
773 }
774
EmitUnsupportedLValue(const Expr * E,const char * Name)775 LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
776 const char *Name) {
777 ErrorUnsupported(E, Name);
778 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
779 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
780 }
781
EmitCheckedLValue(const Expr * E,TypeCheckKind TCK)782 LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
783 LValue LV;
784 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
785 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
786 else
787 LV = EmitLValue(E);
788 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
789 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
790 E->getType(), LV.getAlignment());
791 return LV;
792 }
793
794 /// EmitLValue - Emit code to compute a designator that specifies the location
795 /// of the expression.
796 ///
797 /// This can return one of two things: a simple address or a bitfield reference.
798 /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
799 /// an LLVM pointer type.
800 ///
801 /// If this returns a bitfield reference, nothing about the pointee type of the
802 /// LLVM value is known: For example, it may not be a pointer to an integer.
803 ///
804 /// If this returns a normal address, and if the lvalue's C type is fixed size,
805 /// this method guarantees that the returned pointer type will point to an LLVM
806 /// type of the same size of the lvalue's type. If the lvalue has a variable
807 /// length type, this is not possible.
808 ///
EmitLValue(const Expr * E)809 LValue CodeGenFunction::EmitLValue(const Expr *E) {
810 switch (E->getStmtClass()) {
811 default: return EmitUnsupportedLValue(E, "l-value expression");
812
813 case Expr::ObjCPropertyRefExprClass:
814 llvm_unreachable("cannot emit a property reference directly");
815
816 case Expr::ObjCSelectorExprClass:
817 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
818 case Expr::ObjCIsaExprClass:
819 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
820 case Expr::BinaryOperatorClass:
821 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
822 case Expr::CompoundAssignOperatorClass:
823 if (!E->getType()->isAnyComplexType())
824 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
825 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
826 case Expr::CallExprClass:
827 case Expr::CXXMemberCallExprClass:
828 case Expr::CXXOperatorCallExprClass:
829 case Expr::UserDefinedLiteralClass:
830 return EmitCallExprLValue(cast<CallExpr>(E));
831 case Expr::VAArgExprClass:
832 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
833 case Expr::DeclRefExprClass:
834 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
835 case Expr::ParenExprClass:
836 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
837 case Expr::GenericSelectionExprClass:
838 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
839 case Expr::PredefinedExprClass:
840 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
841 case Expr::StringLiteralClass:
842 return EmitStringLiteralLValue(cast<StringLiteral>(E));
843 case Expr::ObjCEncodeExprClass:
844 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
845 case Expr::PseudoObjectExprClass:
846 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
847 case Expr::InitListExprClass:
848 return EmitInitListLValue(cast<InitListExpr>(E));
849 case Expr::CXXTemporaryObjectExprClass:
850 case Expr::CXXConstructExprClass:
851 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
852 case Expr::CXXBindTemporaryExprClass:
853 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
854 case Expr::CXXUuidofExprClass:
855 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
856 case Expr::LambdaExprClass:
857 return EmitLambdaLValue(cast<LambdaExpr>(E));
858
859 case Expr::ExprWithCleanupsClass: {
860 const auto *cleanups = cast<ExprWithCleanups>(E);
861 enterFullExpression(cleanups);
862 RunCleanupsScope Scope(*this);
863 return EmitLValue(cleanups->getSubExpr());
864 }
865
866 case Expr::CXXDefaultArgExprClass:
867 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
868 case Expr::CXXDefaultInitExprClass: {
869 CXXDefaultInitExprScope Scope(*this);
870 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
871 }
872 case Expr::CXXTypeidExprClass:
873 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
874
875 case Expr::ObjCMessageExprClass:
876 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
877 case Expr::ObjCIvarRefExprClass:
878 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
879 case Expr::StmtExprClass:
880 return EmitStmtExprLValue(cast<StmtExpr>(E));
881 case Expr::UnaryOperatorClass:
882 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
883 case Expr::ArraySubscriptExprClass:
884 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
885 case Expr::ExtVectorElementExprClass:
886 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
887 case Expr::MemberExprClass:
888 return EmitMemberExpr(cast<MemberExpr>(E));
889 case Expr::CompoundLiteralExprClass:
890 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
891 case Expr::ConditionalOperatorClass:
892 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
893 case Expr::BinaryConditionalOperatorClass:
894 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
895 case Expr::ChooseExprClass:
896 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
897 case Expr::OpaqueValueExprClass:
898 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
899 case Expr::SubstNonTypeTemplateParmExprClass:
900 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
901 case Expr::ImplicitCastExprClass:
902 case Expr::CStyleCastExprClass:
903 case Expr::CXXFunctionalCastExprClass:
904 case Expr::CXXStaticCastExprClass:
905 case Expr::CXXDynamicCastExprClass:
906 case Expr::CXXReinterpretCastExprClass:
907 case Expr::CXXConstCastExprClass:
908 case Expr::ObjCBridgedCastExprClass:
909 return EmitCastLValue(cast<CastExpr>(E));
910
911 case Expr::MaterializeTemporaryExprClass:
912 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
913 }
914 }
915
916 /// Given an object of the given canonical type, can we safely copy a
917 /// value out of it based on its initializer?
isConstantEmittableObjectType(QualType type)918 static bool isConstantEmittableObjectType(QualType type) {
919 assert(type.isCanonical());
920 assert(!type->isReferenceType());
921
922 // Must be const-qualified but non-volatile.
923 Qualifiers qs = type.getLocalQualifiers();
924 if (!qs.hasConst() || qs.hasVolatile()) return false;
925
926 // Otherwise, all object types satisfy this except C++ classes with
927 // mutable subobjects or non-trivial copy/destroy behavior.
928 if (const auto *RT = dyn_cast<RecordType>(type))
929 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
930 if (RD->hasMutableFields() || !RD->isTrivial())
931 return false;
932
933 return true;
934 }
935
936 /// Can we constant-emit a load of a reference to a variable of the
937 /// given type? This is different from predicates like
938 /// Decl::isUsableInConstantExpressions because we do want it to apply
939 /// in situations that don't necessarily satisfy the language's rules
940 /// for this (e.g. C++'s ODR-use rules). For example, we want to able
941 /// to do this with const float variables even if those variables
942 /// aren't marked 'constexpr'.
943 enum ConstantEmissionKind {
944 CEK_None,
945 CEK_AsReferenceOnly,
946 CEK_AsValueOrReference,
947 CEK_AsValueOnly
948 };
checkVarTypeForConstantEmission(QualType type)949 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
950 type = type.getCanonicalType();
951 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
952 if (isConstantEmittableObjectType(ref->getPointeeType()))
953 return CEK_AsValueOrReference;
954 return CEK_AsReferenceOnly;
955 }
956 if (isConstantEmittableObjectType(type))
957 return CEK_AsValueOnly;
958 return CEK_None;
959 }
960
961 /// Try to emit a reference to the given value without producing it as
962 /// an l-value. This is actually more than an optimization: we can't
963 /// produce an l-value for variables that we never actually captured
964 /// in a block or lambda, which means const int variables or constexpr
965 /// literals or similar.
966 CodeGenFunction::ConstantEmission
tryEmitAsConstant(DeclRefExpr * refExpr)967 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
968 ValueDecl *value = refExpr->getDecl();
969
970 // The value needs to be an enum constant or a constant variable.
971 ConstantEmissionKind CEK;
972 if (isa<ParmVarDecl>(value)) {
973 CEK = CEK_None;
974 } else if (auto *var = dyn_cast<VarDecl>(value)) {
975 CEK = checkVarTypeForConstantEmission(var->getType());
976 } else if (isa<EnumConstantDecl>(value)) {
977 CEK = CEK_AsValueOnly;
978 } else {
979 CEK = CEK_None;
980 }
981 if (CEK == CEK_None) return ConstantEmission();
982
983 Expr::EvalResult result;
984 bool resultIsReference;
985 QualType resultType;
986
987 // It's best to evaluate all the way as an r-value if that's permitted.
988 if (CEK != CEK_AsReferenceOnly &&
989 refExpr->EvaluateAsRValue(result, getContext())) {
990 resultIsReference = false;
991 resultType = refExpr->getType();
992
993 // Otherwise, try to evaluate as an l-value.
994 } else if (CEK != CEK_AsValueOnly &&
995 refExpr->EvaluateAsLValue(result, getContext())) {
996 resultIsReference = true;
997 resultType = value->getType();
998
999 // Failure.
1000 } else {
1001 return ConstantEmission();
1002 }
1003
1004 // In any case, if the initializer has side-effects, abandon ship.
1005 if (result.HasSideEffects)
1006 return ConstantEmission();
1007
1008 // Emit as a constant.
1009 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1010
1011 // Make sure we emit a debug reference to the global variable.
1012 // This should probably fire even for
1013 if (isa<VarDecl>(value)) {
1014 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1015 EmitDeclRefExprDbgValue(refExpr, C);
1016 } else {
1017 assert(isa<EnumConstantDecl>(value));
1018 EmitDeclRefExprDbgValue(refExpr, C);
1019 }
1020
1021 // If we emitted a reference constant, we need to dereference that.
1022 if (resultIsReference)
1023 return ConstantEmission::forReference(C);
1024
1025 return ConstantEmission::forValue(C);
1026 }
1027
EmitLoadOfScalar(LValue lvalue,SourceLocation Loc)1028 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1029 SourceLocation Loc) {
1030 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1031 lvalue.getAlignment().getQuantity(),
1032 lvalue.getType(), Loc, lvalue.getTBAAInfo(),
1033 lvalue.getTBAABaseType(), lvalue.getTBAAOffset());
1034 }
1035
hasBooleanRepresentation(QualType Ty)1036 static bool hasBooleanRepresentation(QualType Ty) {
1037 if (Ty->isBooleanType())
1038 return true;
1039
1040 if (const EnumType *ET = Ty->getAs<EnumType>())
1041 return ET->getDecl()->getIntegerType()->isBooleanType();
1042
1043 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1044 return hasBooleanRepresentation(AT->getValueType());
1045
1046 return false;
1047 }
1048
getRangeForType(CodeGenFunction & CGF,QualType Ty,llvm::APInt & Min,llvm::APInt & End,bool StrictEnums)1049 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1050 llvm::APInt &Min, llvm::APInt &End,
1051 bool StrictEnums) {
1052 const EnumType *ET = Ty->getAs<EnumType>();
1053 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1054 ET && !ET->getDecl()->isFixed();
1055 bool IsBool = hasBooleanRepresentation(Ty);
1056 if (!IsBool && !IsRegularCPlusPlusEnum)
1057 return false;
1058
1059 if (IsBool) {
1060 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1061 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1062 } else {
1063 const EnumDecl *ED = ET->getDecl();
1064 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1065 unsigned Bitwidth = LTy->getScalarSizeInBits();
1066 unsigned NumNegativeBits = ED->getNumNegativeBits();
1067 unsigned NumPositiveBits = ED->getNumPositiveBits();
1068
1069 if (NumNegativeBits) {
1070 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1071 assert(NumBits <= Bitwidth);
1072 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1073 Min = -End;
1074 } else {
1075 assert(NumPositiveBits <= Bitwidth);
1076 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1077 Min = llvm::APInt(Bitwidth, 0);
1078 }
1079 }
1080 return true;
1081 }
1082
getRangeForLoadFromType(QualType Ty)1083 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1084 llvm::APInt Min, End;
1085 if (!getRangeForType(*this, Ty, Min, End,
1086 CGM.getCodeGenOpts().StrictEnums))
1087 return nullptr;
1088
1089 llvm::MDBuilder MDHelper(getLLVMContext());
1090 return MDHelper.createRange(Min, End);
1091 }
1092
EmitLoadOfScalar(llvm::Value * Addr,bool Volatile,unsigned Alignment,QualType Ty,SourceLocation Loc,llvm::MDNode * TBAAInfo,QualType TBAABaseType,uint64_t TBAAOffset)1093 llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
1094 unsigned Alignment, QualType Ty,
1095 SourceLocation Loc,
1096 llvm::MDNode *TBAAInfo,
1097 QualType TBAABaseType,
1098 uint64_t TBAAOffset) {
1099 // For better performance, handle vector loads differently.
1100 if (Ty->isVectorType()) {
1101 llvm::Value *V;
1102 const llvm::Type *EltTy =
1103 cast<llvm::PointerType>(Addr->getType())->getElementType();
1104
1105 const auto *VTy = cast<llvm::VectorType>(EltTy);
1106
1107 // Handle vectors of size 3, like size 4 for better performance.
1108 if (VTy->getNumElements() == 3) {
1109
1110 // Bitcast to vec4 type.
1111 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1112 4);
1113 llvm::PointerType *ptVec4Ty =
1114 llvm::PointerType::get(vec4Ty,
1115 (cast<llvm::PointerType>(
1116 Addr->getType()))->getAddressSpace());
1117 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1118 "castToVec4");
1119 // Now load value.
1120 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1121
1122 // Shuffle vector to get vec3.
1123 llvm::Constant *Mask[] = {
1124 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
1125 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
1126 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
1127 };
1128
1129 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1130 V = Builder.CreateShuffleVector(LoadVal,
1131 llvm::UndefValue::get(vec4Ty),
1132 MaskV, "extractVec");
1133 return EmitFromMemory(V, Ty);
1134 }
1135 }
1136
1137 // Atomic operations have to be done on integral types.
1138 if (Ty->isAtomicType()) {
1139 LValue lvalue = LValue::MakeAddr(Addr, Ty,
1140 CharUnits::fromQuantity(Alignment),
1141 getContext(), TBAAInfo);
1142 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
1143 }
1144
1145 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
1146 if (Volatile)
1147 Load->setVolatile(true);
1148 if (Alignment)
1149 Load->setAlignment(Alignment);
1150 if (TBAAInfo) {
1151 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1152 TBAAOffset);
1153 if (TBAAPath)
1154 CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
1155 }
1156
1157 bool NeedsBoolCheck =
1158 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1159 bool NeedsEnumCheck =
1160 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1161 if (NeedsBoolCheck || NeedsEnumCheck) {
1162 SanitizerScope SanScope(this);
1163 llvm::APInt Min, End;
1164 if (getRangeForType(*this, Ty, Min, End, true)) {
1165 --End;
1166 llvm::Value *Check;
1167 if (!Min)
1168 Check = Builder.CreateICmpULE(
1169 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1170 else {
1171 llvm::Value *Upper = Builder.CreateICmpSLE(
1172 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1173 llvm::Value *Lower = Builder.CreateICmpSGE(
1174 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1175 Check = Builder.CreateAnd(Upper, Lower);
1176 }
1177 llvm::Constant *StaticArgs[] = {
1178 EmitCheckSourceLocation(Loc),
1179 EmitCheckTypeDescriptor(Ty)
1180 };
1181 SanitizerKind Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1182 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1183 EmitCheckValue(Load));
1184 }
1185 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1186 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1187 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1188
1189 return EmitFromMemory(Load, Ty);
1190 }
1191
EmitToMemory(llvm::Value * Value,QualType Ty)1192 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1193 // Bool has a different representation in memory than in registers.
1194 if (hasBooleanRepresentation(Ty)) {
1195 // This should really always be an i1, but sometimes it's already
1196 // an i8, and it's awkward to track those cases down.
1197 if (Value->getType()->isIntegerTy(1))
1198 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1199 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1200 "wrong value rep of bool");
1201 }
1202
1203 return Value;
1204 }
1205
EmitFromMemory(llvm::Value * Value,QualType Ty)1206 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1207 // Bool has a different representation in memory than in registers.
1208 if (hasBooleanRepresentation(Ty)) {
1209 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1210 "wrong value rep of bool");
1211 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1212 }
1213
1214 return Value;
1215 }
1216
EmitStoreOfScalar(llvm::Value * Value,llvm::Value * Addr,bool Volatile,unsigned Alignment,QualType Ty,llvm::MDNode * TBAAInfo,bool isInit,QualType TBAABaseType,uint64_t TBAAOffset)1217 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
1218 bool Volatile, unsigned Alignment,
1219 QualType Ty, llvm::MDNode *TBAAInfo,
1220 bool isInit, QualType TBAABaseType,
1221 uint64_t TBAAOffset) {
1222
1223 // Handle vectors differently to get better performance.
1224 if (Ty->isVectorType()) {
1225 llvm::Type *SrcTy = Value->getType();
1226 auto *VecTy = cast<llvm::VectorType>(SrcTy);
1227 // Handle vec3 special.
1228 if (VecTy->getNumElements() == 3) {
1229 llvm::LLVMContext &VMContext = getLLVMContext();
1230
1231 // Our source is a vec3, do a shuffle vector to make it a vec4.
1232 SmallVector<llvm::Constant*, 4> Mask;
1233 Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1234 0));
1235 Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1236 1));
1237 Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
1238 2));
1239 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1240
1241 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1242 Value = Builder.CreateShuffleVector(Value,
1243 llvm::UndefValue::get(VecTy),
1244 MaskV, "extractVec");
1245 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1246 }
1247 auto *DstPtr = cast<llvm::PointerType>(Addr->getType());
1248 if (DstPtr->getElementType() != SrcTy) {
1249 llvm::Type *MemTy =
1250 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1251 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1252 }
1253 }
1254
1255 Value = EmitToMemory(Value, Ty);
1256
1257 if (Ty->isAtomicType()) {
1258 EmitAtomicStore(RValue::get(Value),
1259 LValue::MakeAddr(Addr, Ty,
1260 CharUnits::fromQuantity(Alignment),
1261 getContext(), TBAAInfo),
1262 isInit);
1263 return;
1264 }
1265
1266 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1267 if (Alignment)
1268 Store->setAlignment(Alignment);
1269 if (TBAAInfo) {
1270 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1271 TBAAOffset);
1272 if (TBAAPath)
1273 CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
1274 }
1275 }
1276
EmitStoreOfScalar(llvm::Value * value,LValue lvalue,bool isInit)1277 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1278 bool isInit) {
1279 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1280 lvalue.getAlignment().getQuantity(), lvalue.getType(),
1281 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1282 lvalue.getTBAAOffset());
1283 }
1284
1285 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1286 /// method emits the address of the lvalue, then loads the result as an rvalue,
1287 /// returning the rvalue.
EmitLoadOfLValue(LValue LV,SourceLocation Loc)1288 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1289 if (LV.isObjCWeak()) {
1290 // load of a __weak object.
1291 llvm::Value *AddrWeakObj = LV.getAddress();
1292 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1293 AddrWeakObj));
1294 }
1295 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1296 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1297 Object = EmitObjCConsumeObject(LV.getType(), Object);
1298 return RValue::get(Object);
1299 }
1300
1301 if (LV.isSimple()) {
1302 assert(!LV.getType()->isFunctionType());
1303
1304 // Everything needs a load.
1305 return RValue::get(EmitLoadOfScalar(LV, Loc));
1306 }
1307
1308 if (LV.isVectorElt()) {
1309 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1310 LV.isVolatileQualified());
1311 Load->setAlignment(LV.getAlignment().getQuantity());
1312 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1313 "vecext"));
1314 }
1315
1316 // If this is a reference to a subset of the elements of a vector, either
1317 // shuffle the input or extract/insert them as appropriate.
1318 if (LV.isExtVectorElt())
1319 return EmitLoadOfExtVectorElementLValue(LV);
1320
1321 // Global Register variables always invoke intrinsics
1322 if (LV.isGlobalReg())
1323 return EmitLoadOfGlobalRegLValue(LV);
1324
1325 assert(LV.isBitField() && "Unknown LValue type!");
1326 return EmitLoadOfBitfieldLValue(LV);
1327 }
1328
EmitLoadOfBitfieldLValue(LValue LV)1329 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
1330 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1331
1332 // Get the output type.
1333 llvm::Type *ResLTy = ConvertType(LV.getType());
1334
1335 llvm::Value *Ptr = LV.getBitFieldAddr();
1336 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1337 "bf.load");
1338 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1339
1340 if (Info.IsSigned) {
1341 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1342 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1343 if (HighBits)
1344 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1345 if (Info.Offset + HighBits)
1346 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1347 } else {
1348 if (Info.Offset)
1349 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1350 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1351 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1352 Info.Size),
1353 "bf.clear");
1354 }
1355 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1356
1357 return RValue::get(Val);
1358 }
1359
1360 // If this is a reference to a subset of the elements of a vector, create an
1361 // appropriate shufflevector.
EmitLoadOfExtVectorElementLValue(LValue LV)1362 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1363 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1364 LV.isVolatileQualified());
1365 Load->setAlignment(LV.getAlignment().getQuantity());
1366 llvm::Value *Vec = Load;
1367
1368 const llvm::Constant *Elts = LV.getExtVectorElts();
1369
1370 // If the result of the expression is a non-vector type, we must be extracting
1371 // a single element. Just codegen as an extractelement.
1372 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1373 if (!ExprVT) {
1374 unsigned InIdx = getAccessedFieldNo(0, Elts);
1375 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1376 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1377 }
1378
1379 // Always use shuffle vector to try to retain the original program structure
1380 unsigned NumResultElts = ExprVT->getNumElements();
1381
1382 SmallVector<llvm::Constant*, 4> Mask;
1383 for (unsigned i = 0; i != NumResultElts; ++i)
1384 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1385
1386 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1387 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1388 MaskV);
1389 return RValue::get(Vec);
1390 }
1391
1392 /// @brief Generates lvalue for partial ext_vector access.
EmitExtVectorElementLValue(LValue LV)1393 llvm::Value *CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1394 llvm::Value *VectorAddress = LV.getExtVectorAddr();
1395 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1396 QualType EQT = ExprVT->getElementType();
1397 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1398 llvm::Type *VectorElementPtrToTy = VectorElementTy->getPointerTo();
1399
1400 llvm::Value *CastToPointerElement =
1401 Builder.CreateBitCast(VectorAddress,
1402 VectorElementPtrToTy, "conv.ptr.element");
1403
1404 const llvm::Constant *Elts = LV.getExtVectorElts();
1405 unsigned ix = getAccessedFieldNo(0, Elts);
1406
1407 llvm::Value *VectorBasePtrPlusIx =
1408 Builder.CreateInBoundsGEP(CastToPointerElement,
1409 llvm::ConstantInt::get(SizeTy, ix), "add.ptr");
1410
1411 return VectorBasePtrPlusIx;
1412 }
1413
1414 /// @brief Load of global gamed gegisters are always calls to intrinsics.
EmitLoadOfGlobalRegLValue(LValue LV)1415 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1416 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1417 "Bad type for register variable");
1418 llvm::MDNode *RegName = cast<llvm::MDNode>(
1419 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1420
1421 // We accept integer and pointer types only
1422 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1423 llvm::Type *Ty = OrigTy;
1424 if (OrigTy->isPointerTy())
1425 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1426 llvm::Type *Types[] = { Ty };
1427
1428 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1429 llvm::Value *Call = Builder.CreateCall(
1430 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1431 if (OrigTy->isPointerTy())
1432 Call = Builder.CreateIntToPtr(Call, OrigTy);
1433 return RValue::get(Call);
1434 }
1435
1436
1437 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1438 /// lvalue, where both are guaranteed to the have the same type, and that type
1439 /// is 'Ty'.
EmitStoreThroughLValue(RValue Src,LValue Dst,bool isInit)1440 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1441 bool isInit) {
1442 if (!Dst.isSimple()) {
1443 if (Dst.isVectorElt()) {
1444 // Read/modify/write the vector, inserting the new element.
1445 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1446 Dst.isVolatileQualified());
1447 Load->setAlignment(Dst.getAlignment().getQuantity());
1448 llvm::Value *Vec = Load;
1449 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1450 Dst.getVectorIdx(), "vecins");
1451 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1452 Dst.isVolatileQualified());
1453 Store->setAlignment(Dst.getAlignment().getQuantity());
1454 return;
1455 }
1456
1457 // If this is an update of extended vector elements, insert them as
1458 // appropriate.
1459 if (Dst.isExtVectorElt())
1460 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1461
1462 if (Dst.isGlobalReg())
1463 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1464
1465 assert(Dst.isBitField() && "Unknown LValue type");
1466 return EmitStoreThroughBitfieldLValue(Src, Dst);
1467 }
1468
1469 // There's special magic for assigning into an ARC-qualified l-value.
1470 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1471 switch (Lifetime) {
1472 case Qualifiers::OCL_None:
1473 llvm_unreachable("present but none");
1474
1475 case Qualifiers::OCL_ExplicitNone:
1476 // nothing special
1477 break;
1478
1479 case Qualifiers::OCL_Strong:
1480 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1481 return;
1482
1483 case Qualifiers::OCL_Weak:
1484 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1485 return;
1486
1487 case Qualifiers::OCL_Autoreleasing:
1488 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1489 Src.getScalarVal()));
1490 // fall into the normal path
1491 break;
1492 }
1493 }
1494
1495 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1496 // load of a __weak object.
1497 llvm::Value *LvalueDst = Dst.getAddress();
1498 llvm::Value *src = Src.getScalarVal();
1499 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1500 return;
1501 }
1502
1503 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1504 // load of a __strong object.
1505 llvm::Value *LvalueDst = Dst.getAddress();
1506 llvm::Value *src = Src.getScalarVal();
1507 if (Dst.isObjCIvar()) {
1508 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1509 llvm::Type *ResultType = ConvertType(getContext().LongTy);
1510 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
1511 llvm::Value *dst = RHS;
1512 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1513 llvm::Value *LHS =
1514 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1515 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1516 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1517 BytesBetween);
1518 } else if (Dst.isGlobalObjCRef()) {
1519 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1520 Dst.isThreadLocalRef());
1521 }
1522 else
1523 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1524 return;
1525 }
1526
1527 assert(Src.isScalar() && "Can't emit an agg store with this method");
1528 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1529 }
1530
EmitStoreThroughBitfieldLValue(RValue Src,LValue Dst,llvm::Value ** Result)1531 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1532 llvm::Value **Result) {
1533 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1534 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1535 llvm::Value *Ptr = Dst.getBitFieldAddr();
1536
1537 // Get the source value, truncated to the width of the bit-field.
1538 llvm::Value *SrcVal = Src.getScalarVal();
1539
1540 // Cast the source to the storage type and shift it into place.
1541 SrcVal = Builder.CreateIntCast(SrcVal,
1542 Ptr->getType()->getPointerElementType(),
1543 /*IsSigned=*/false);
1544 llvm::Value *MaskedVal = SrcVal;
1545
1546 // See if there are other bits in the bitfield's storage we'll need to load
1547 // and mask together with source before storing.
1548 if (Info.StorageSize != Info.Size) {
1549 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1550 llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1551 "bf.load");
1552 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1553
1554 // Mask the source value as needed.
1555 if (!hasBooleanRepresentation(Dst.getType()))
1556 SrcVal = Builder.CreateAnd(SrcVal,
1557 llvm::APInt::getLowBitsSet(Info.StorageSize,
1558 Info.Size),
1559 "bf.value");
1560 MaskedVal = SrcVal;
1561 if (Info.Offset)
1562 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1563
1564 // Mask out the original value.
1565 Val = Builder.CreateAnd(Val,
1566 ~llvm::APInt::getBitsSet(Info.StorageSize,
1567 Info.Offset,
1568 Info.Offset + Info.Size),
1569 "bf.clear");
1570
1571 // Or together the unchanged values and the source value.
1572 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1573 } else {
1574 assert(Info.Offset == 0);
1575 }
1576
1577 // Write the new value back out.
1578 llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1579 Dst.isVolatileQualified());
1580 Store->setAlignment(Info.StorageAlignment);
1581
1582 // Return the new value of the bit-field, if requested.
1583 if (Result) {
1584 llvm::Value *ResultVal = MaskedVal;
1585
1586 // Sign extend the value if needed.
1587 if (Info.IsSigned) {
1588 assert(Info.Size <= Info.StorageSize);
1589 unsigned HighBits = Info.StorageSize - Info.Size;
1590 if (HighBits) {
1591 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1592 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1593 }
1594 }
1595
1596 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1597 "bf.result.cast");
1598 *Result = EmitFromMemory(ResultVal, Dst.getType());
1599 }
1600 }
1601
EmitStoreThroughExtVectorComponentLValue(RValue Src,LValue Dst)1602 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1603 LValue Dst) {
1604 // This access turns into a read/modify/write of the vector. Load the input
1605 // value now.
1606 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1607 Dst.isVolatileQualified());
1608 Load->setAlignment(Dst.getAlignment().getQuantity());
1609 llvm::Value *Vec = Load;
1610 const llvm::Constant *Elts = Dst.getExtVectorElts();
1611
1612 llvm::Value *SrcVal = Src.getScalarVal();
1613
1614 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1615 unsigned NumSrcElts = VTy->getNumElements();
1616 unsigned NumDstElts =
1617 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1618 if (NumDstElts == NumSrcElts) {
1619 // Use shuffle vector is the src and destination are the same number of
1620 // elements and restore the vector mask since it is on the side it will be
1621 // stored.
1622 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1623 for (unsigned i = 0; i != NumSrcElts; ++i)
1624 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1625
1626 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1627 Vec = Builder.CreateShuffleVector(SrcVal,
1628 llvm::UndefValue::get(Vec->getType()),
1629 MaskV);
1630 } else if (NumDstElts > NumSrcElts) {
1631 // Extended the source vector to the same length and then shuffle it
1632 // into the destination.
1633 // FIXME: since we're shuffling with undef, can we just use the indices
1634 // into that? This could be simpler.
1635 SmallVector<llvm::Constant*, 4> ExtMask;
1636 for (unsigned i = 0; i != NumSrcElts; ++i)
1637 ExtMask.push_back(Builder.getInt32(i));
1638 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1639 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1640 llvm::Value *ExtSrcVal =
1641 Builder.CreateShuffleVector(SrcVal,
1642 llvm::UndefValue::get(SrcVal->getType()),
1643 ExtMaskV);
1644 // build identity
1645 SmallVector<llvm::Constant*, 4> Mask;
1646 for (unsigned i = 0; i != NumDstElts; ++i)
1647 Mask.push_back(Builder.getInt32(i));
1648
1649 // When the vector size is odd and .odd or .hi is used, the last element
1650 // of the Elts constant array will be one past the size of the vector.
1651 // Ignore the last element here, if it is greater than the mask size.
1652 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1653 NumSrcElts--;
1654
1655 // modify when what gets shuffled in
1656 for (unsigned i = 0; i != NumSrcElts; ++i)
1657 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1658 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1659 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
1660 } else {
1661 // We should never shorten the vector
1662 llvm_unreachable("unexpected shorten vector length");
1663 }
1664 } else {
1665 // If the Src is a scalar (not a vector) it must be updating one element.
1666 unsigned InIdx = getAccessedFieldNo(0, Elts);
1667 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1668 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
1669 }
1670
1671 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1672 Dst.isVolatileQualified());
1673 Store->setAlignment(Dst.getAlignment().getQuantity());
1674 }
1675
1676 /// @brief Store of global named registers are always calls to intrinsics.
EmitStoreThroughGlobalRegLValue(RValue Src,LValue Dst)1677 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
1678 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1679 "Bad type for register variable");
1680 llvm::MDNode *RegName = cast<llvm::MDNode>(
1681 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
1682 assert(RegName && "Register LValue is not metadata");
1683
1684 // We accept integer and pointer types only
1685 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1686 llvm::Type *Ty = OrigTy;
1687 if (OrigTy->isPointerTy())
1688 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1689 llvm::Type *Types[] = { Ty };
1690
1691 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1692 llvm::Value *Value = Src.getScalarVal();
1693 if (OrigTy->isPointerTy())
1694 Value = Builder.CreatePtrToInt(Value, Ty);
1695 Builder.CreateCall2(F, llvm::MetadataAsValue::get(Ty->getContext(), RegName),
1696 Value);
1697 }
1698
1699 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
1700 // generating write-barries API. It is currently a global, ivar,
1701 // or neither.
setObjCGCLValueClass(const ASTContext & Ctx,const Expr * E,LValue & LV,bool IsMemberAccess=false)1702 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
1703 LValue &LV,
1704 bool IsMemberAccess=false) {
1705 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
1706 return;
1707
1708 if (isa<ObjCIvarRefExpr>(E)) {
1709 QualType ExpTy = E->getType();
1710 if (IsMemberAccess && ExpTy->isPointerType()) {
1711 // If ivar is a structure pointer, assigning to field of
1712 // this struct follows gcc's behavior and makes it a non-ivar
1713 // writer-barrier conservatively.
1714 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1715 if (ExpTy->isRecordType()) {
1716 LV.setObjCIvar(false);
1717 return;
1718 }
1719 }
1720 LV.setObjCIvar(true);
1721 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
1722 LV.setBaseIvarExp(Exp->getBase());
1723 LV.setObjCArray(E->getType()->isArrayType());
1724 return;
1725 }
1726
1727 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1728 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
1729 if (VD->hasGlobalStorage()) {
1730 LV.setGlobalObjCRef(true);
1731 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
1732 }
1733 }
1734 LV.setObjCArray(E->getType()->isArrayType());
1735 return;
1736 }
1737
1738 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
1739 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1740 return;
1741 }
1742
1743 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
1744 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1745 if (LV.isObjCIvar()) {
1746 // If cast is to a structure pointer, follow gcc's behavior and make it
1747 // a non-ivar write-barrier.
1748 QualType ExpTy = E->getType();
1749 if (ExpTy->isPointerType())
1750 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1751 if (ExpTy->isRecordType())
1752 LV.setObjCIvar(false);
1753 }
1754 return;
1755 }
1756
1757 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1758 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1759 return;
1760 }
1761
1762 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
1763 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1764 return;
1765 }
1766
1767 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
1768 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1769 return;
1770 }
1771
1772 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
1773 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
1774 return;
1775 }
1776
1777 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
1778 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
1779 if (LV.isObjCIvar() && !LV.isObjCArray())
1780 // Using array syntax to assigning to what an ivar points to is not
1781 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
1782 LV.setObjCIvar(false);
1783 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1784 // Using array syntax to assigning to what global points to is not
1785 // same as assigning to the global itself. {id *G;} G[i] = 0;
1786 LV.setGlobalObjCRef(false);
1787 return;
1788 }
1789
1790 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
1791 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
1792 // We don't know if member is an 'ivar', but this flag is looked at
1793 // only in the context of LV.isObjCIvar().
1794 LV.setObjCArray(E->getType()->isArrayType());
1795 return;
1796 }
1797 }
1798
1799 static llvm::Value *
EmitBitCastOfLValueToProperType(CodeGenFunction & CGF,llvm::Value * V,llvm::Type * IRType,StringRef Name=StringRef ())1800 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
1801 llvm::Value *V, llvm::Type *IRType,
1802 StringRef Name = StringRef()) {
1803 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
1804 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
1805 }
1806
EmitThreadPrivateVarDeclLValue(CodeGenFunction & CGF,const VarDecl * VD,QualType T,llvm::Value * V,llvm::Type * RealVarTy,CharUnits Alignment,SourceLocation Loc)1807 static LValue EmitThreadPrivateVarDeclLValue(
1808 CodeGenFunction &CGF, const VarDecl *VD, QualType T, llvm::Value *V,
1809 llvm::Type *RealVarTy, CharUnits Alignment, SourceLocation Loc) {
1810 V = CGF.CGM.getOpenMPRuntime().getOMPAddrOfThreadPrivate(CGF, VD, V, Loc);
1811 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
1812 return CGF.MakeAddrLValue(V, T, Alignment);
1813 }
1814
EmitGlobalVarDeclLValue(CodeGenFunction & CGF,const Expr * E,const VarDecl * VD)1815 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1816 const Expr *E, const VarDecl *VD) {
1817 QualType T = E->getType();
1818
1819 // If it's thread_local, emit a call to its wrapper function instead.
1820 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1821 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
1822 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1823
1824 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
1825 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1826 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
1827 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
1828 LValue LV;
1829 // Emit reference to the private copy of the variable if it is an OpenMP
1830 // threadprivate variable.
1831 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
1832 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, V, RealVarTy, Alignment,
1833 E->getExprLoc());
1834 if (VD->getType()->isReferenceType()) {
1835 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
1836 LI->setAlignment(Alignment.getQuantity());
1837 V = LI;
1838 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1839 } else {
1840 LV = CGF.MakeAddrLValue(V, T, Alignment);
1841 }
1842 setObjCGCLValueClass(CGF.getContext(), E, LV);
1843 return LV;
1844 }
1845
EmitFunctionDeclLValue(CodeGenFunction & CGF,const Expr * E,const FunctionDecl * FD)1846 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
1847 const Expr *E, const FunctionDecl *FD) {
1848 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
1849 if (!FD->hasPrototype()) {
1850 if (const FunctionProtoType *Proto =
1851 FD->getType()->getAs<FunctionProtoType>()) {
1852 // Ugly case: for a K&R-style definition, the type of the definition
1853 // isn't the same as the type of a use. Correct for this with a
1854 // bitcast.
1855 QualType NoProtoType =
1856 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
1857 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
1858 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
1859 }
1860 }
1861 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
1862 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
1863 }
1864
EmitCapturedFieldLValue(CodeGenFunction & CGF,const FieldDecl * FD,llvm::Value * ThisValue)1865 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
1866 llvm::Value *ThisValue) {
1867 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
1868 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
1869 return CGF.EmitLValueForField(LV, FD);
1870 }
1871
1872 /// Named Registers are named metadata pointing to the register name
1873 /// which will be read from/written to as an argument to the intrinsic
1874 /// @llvm.read/write_register.
1875 /// So far, only the name is being passed down, but other options such as
1876 /// register type, allocation type or even optimization options could be
1877 /// passed down via the metadata node.
EmitGlobalNamedRegister(const VarDecl * VD,CodeGenModule & CGM,CharUnits Alignment)1878 static LValue EmitGlobalNamedRegister(const VarDecl *VD,
1879 CodeGenModule &CGM,
1880 CharUnits Alignment) {
1881 SmallString<64> Name("llvm.named.register.");
1882 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
1883 assert(Asm->getLabel().size() < 64-Name.size() &&
1884 "Register name too big");
1885 Name.append(Asm->getLabel());
1886 llvm::NamedMDNode *M =
1887 CGM.getModule().getOrInsertNamedMetadata(Name);
1888 if (M->getNumOperands() == 0) {
1889 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
1890 Asm->getLabel());
1891 llvm::Metadata *Ops[] = {Str};
1892 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1893 }
1894 return LValue::MakeGlobalReg(
1895 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)),
1896 VD->getType(), Alignment);
1897 }
1898
EmitDeclRefLValue(const DeclRefExpr * E)1899 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
1900 const NamedDecl *ND = E->getDecl();
1901 CharUnits Alignment = getContext().getDeclAlign(ND);
1902 QualType T = E->getType();
1903
1904 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
1905 // Global Named registers access via intrinsics only
1906 if (VD->getStorageClass() == SC_Register &&
1907 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
1908 return EmitGlobalNamedRegister(VD, CGM, Alignment);
1909
1910 // A DeclRefExpr for a reference initialized by a constant expression can
1911 // appear without being odr-used. Directly emit the constant initializer.
1912 const Expr *Init = VD->getAnyInitializer(VD);
1913 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1914 VD->isUsableInConstantExpressions(getContext()) &&
1915 VD->checkInitIsICE()) {
1916 llvm::Constant *Val =
1917 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1918 assert(Val && "failed to emit reference constant expression");
1919 // FIXME: Eventually we will want to emit vector element references.
1920 return MakeAddrLValue(Val, T, Alignment);
1921 }
1922
1923 // Check for captured variables.
1924 if (E->refersToEnclosingVariableOrCapture()) {
1925 if (auto *FD = LambdaCaptureFields.lookup(VD))
1926 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
1927 else if (CapturedStmtInfo) {
1928 if (auto *V = LocalDeclMap.lookup(VD))
1929 return MakeAddrLValue(V, T, Alignment);
1930 else
1931 return EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
1932 CapturedStmtInfo->getContextValue());
1933 }
1934 assert(isa<BlockDecl>(CurCodeDecl));
1935 return MakeAddrLValue(GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()),
1936 T, Alignment);
1937 }
1938 }
1939
1940 // FIXME: We should be able to assert this for FunctionDecls as well!
1941 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1942 // those with a valid source location.
1943 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1944 !E->getLocation().isValid()) &&
1945 "Should not use decl without marking it used!");
1946
1947 if (ND->hasAttr<WeakRefAttr>()) {
1948 const auto *VD = cast<ValueDecl>(ND);
1949 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
1950 return MakeAddrLValue(Aliasee, T, Alignment);
1951 }
1952
1953 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
1954 // Check if this is a global variable.
1955 if (VD->hasLinkage() || VD->isStaticDataMember())
1956 return EmitGlobalVarDeclLValue(*this, E, VD);
1957
1958 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1959
1960 llvm::Value *V = LocalDeclMap.lookup(VD);
1961 if (!V && VD->isStaticLocal())
1962 V = CGM.getOrCreateStaticVarDecl(
1963 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1964
1965 // Check if variable is threadprivate.
1966 if (V && getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
1967 return EmitThreadPrivateVarDeclLValue(
1968 *this, VD, T, V, getTypes().ConvertTypeForMem(VD->getType()),
1969 Alignment, E->getExprLoc());
1970
1971 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1972
1973 if (isBlockVariable)
1974 V = BuildBlockByrefAddress(V, VD);
1975
1976 LValue LV;
1977 if (VD->getType()->isReferenceType()) {
1978 llvm::LoadInst *LI = Builder.CreateLoad(V);
1979 LI->setAlignment(Alignment.getQuantity());
1980 V = LI;
1981 LV = MakeNaturalAlignAddrLValue(V, T);
1982 } else {
1983 LV = MakeAddrLValue(V, T, Alignment);
1984 }
1985
1986 bool isLocalStorage = VD->hasLocalStorage();
1987
1988 bool NonGCable = isLocalStorage &&
1989 !VD->getType()->isReferenceType() &&
1990 !isBlockVariable;
1991 if (NonGCable) {
1992 LV.getQuals().removeObjCGCAttr();
1993 LV.setNonGC(true);
1994 }
1995
1996 bool isImpreciseLifetime =
1997 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
1998 if (isImpreciseLifetime)
1999 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2000 setObjCGCLValueClass(getContext(), E, LV);
2001 return LV;
2002 }
2003
2004 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2005 return EmitFunctionDeclLValue(*this, E, FD);
2006
2007 llvm_unreachable("Unhandled DeclRefExpr");
2008 }
2009
EmitUnaryOpLValue(const UnaryOperator * E)2010 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2011 // __extension__ doesn't affect lvalue-ness.
2012 if (E->getOpcode() == UO_Extension)
2013 return EmitLValue(E->getSubExpr());
2014
2015 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2016 switch (E->getOpcode()) {
2017 default: llvm_unreachable("Unknown unary operator lvalue!");
2018 case UO_Deref: {
2019 QualType T = E->getSubExpr()->getType()->getPointeeType();
2020 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2021
2022 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
2023 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2024
2025 // We should not generate __weak write barrier on indirect reference
2026 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2027 // But, we continue to generate __strong write barrier on indirect write
2028 // into a pointer to object.
2029 if (getLangOpts().ObjC1 &&
2030 getLangOpts().getGC() != LangOptions::NonGC &&
2031 LV.isObjCWeak())
2032 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2033 return LV;
2034 }
2035 case UO_Real:
2036 case UO_Imag: {
2037 LValue LV = EmitLValue(E->getSubExpr());
2038 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2039 llvm::Value *Addr = LV.getAddress();
2040
2041 // __real is valid on scalars. This is a faster way of testing that.
2042 // __imag can only produce an rvalue on scalars.
2043 if (E->getOpcode() == UO_Real &&
2044 !cast<llvm::PointerType>(Addr->getType())
2045 ->getElementType()->isStructTy()) {
2046 assert(E->getSubExpr()->getType()->isArithmeticType());
2047 return LV;
2048 }
2049
2050 assert(E->getSubExpr()->getType()->isAnyComplexType());
2051
2052 unsigned Idx = E->getOpcode() == UO_Imag;
2053 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
2054 Idx, "idx"),
2055 ExprTy);
2056 }
2057 case UO_PreInc:
2058 case UO_PreDec: {
2059 LValue LV = EmitLValue(E->getSubExpr());
2060 bool isInc = E->getOpcode() == UO_PreInc;
2061
2062 if (E->getType()->isAnyComplexType())
2063 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2064 else
2065 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2066 return LV;
2067 }
2068 }
2069 }
2070
EmitStringLiteralLValue(const StringLiteral * E)2071 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2072 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2073 E->getType());
2074 }
2075
EmitObjCEncodeExprLValue(const ObjCEncodeExpr * E)2076 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2077 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2078 E->getType());
2079 }
2080
EmitPredefinedLValue(const PredefinedExpr * E)2081 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2082 auto SL = E->getFunctionName();
2083 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2084 StringRef FnName = CurFn->getName();
2085 if (FnName.startswith("\01"))
2086 FnName = FnName.substr(1);
2087 StringRef NameItems[] = {
2088 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2089 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2090 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
2091 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str(), 1);
2092 return MakeAddrLValue(C, E->getType());
2093 }
2094 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2095 return MakeAddrLValue(C, E->getType());
2096 }
2097
2098 /// Emit a type description suitable for use by a runtime sanitizer library. The
2099 /// format of a type descriptor is
2100 ///
2101 /// \code
2102 /// { i16 TypeKind, i16 TypeInfo }
2103 /// \endcode
2104 ///
2105 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2106 /// integer, 1 for a floating point value, and -1 for anything else.
EmitCheckTypeDescriptor(QualType T)2107 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2108 // Only emit each type's descriptor once.
2109 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2110 return C;
2111
2112 uint16_t TypeKind = -1;
2113 uint16_t TypeInfo = 0;
2114
2115 if (T->isIntegerType()) {
2116 TypeKind = 0;
2117 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2118 (T->isSignedIntegerType() ? 1 : 0);
2119 } else if (T->isFloatingType()) {
2120 TypeKind = 1;
2121 TypeInfo = getContext().getTypeSize(T);
2122 }
2123
2124 // Format the type name as if for a diagnostic, including quotes and
2125 // optionally an 'aka'.
2126 SmallString<32> Buffer;
2127 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2128 (intptr_t)T.getAsOpaquePtr(),
2129 StringRef(), StringRef(), None, Buffer,
2130 None);
2131
2132 llvm::Constant *Components[] = {
2133 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2134 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2135 };
2136 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2137
2138 auto *GV = new llvm::GlobalVariable(
2139 CGM.getModule(), Descriptor->getType(),
2140 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2141 GV->setUnnamedAddr(true);
2142 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2143
2144 // Remember the descriptor for this type.
2145 CGM.setTypeDescriptorInMap(T, GV);
2146
2147 return GV;
2148 }
2149
EmitCheckValue(llvm::Value * V)2150 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2151 llvm::Type *TargetTy = IntPtrTy;
2152
2153 // Floating-point types which fit into intptr_t are bitcast to integers
2154 // and then passed directly (after zero-extension, if necessary).
2155 if (V->getType()->isFloatingPointTy()) {
2156 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2157 if (Bits <= TargetTy->getIntegerBitWidth())
2158 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2159 Bits));
2160 }
2161
2162 // Integers which fit in intptr_t are zero-extended and passed directly.
2163 if (V->getType()->isIntegerTy() &&
2164 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2165 return Builder.CreateZExt(V, TargetTy);
2166
2167 // Pointers are passed directly, everything else is passed by address.
2168 if (!V->getType()->isPointerTy()) {
2169 llvm::Value *Ptr = CreateTempAlloca(V->getType());
2170 Builder.CreateStore(V, Ptr);
2171 V = Ptr;
2172 }
2173 return Builder.CreatePtrToInt(V, TargetTy);
2174 }
2175
2176 /// \brief Emit a representation of a SourceLocation for passing to a handler
2177 /// in a sanitizer runtime library. The format for this data is:
2178 /// \code
2179 /// struct SourceLocation {
2180 /// const char *Filename;
2181 /// int32_t Line, Column;
2182 /// };
2183 /// \endcode
2184 /// For an invalid SourceLocation, the Filename pointer is null.
EmitCheckSourceLocation(SourceLocation Loc)2185 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2186 llvm::Constant *Filename;
2187 int Line, Column;
2188
2189 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2190 if (PLoc.isValid()) {
2191 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
2192 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(FilenameGV);
2193 Filename = FilenameGV;
2194 Line = PLoc.getLine();
2195 Column = PLoc.getColumn();
2196 } else {
2197 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2198 Line = Column = 0;
2199 }
2200
2201 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2202 Builder.getInt32(Column)};
2203
2204 return llvm::ConstantStruct::getAnon(Data);
2205 }
2206
2207 namespace {
2208 /// \brief Specify under what conditions this check can be recovered
2209 enum class CheckRecoverableKind {
2210 /// Always terminate program execution if this check fails.
2211 Unrecoverable,
2212 /// Check supports recovering, runtime has both fatal (noreturn) and
2213 /// non-fatal handlers for this check.
2214 Recoverable,
2215 /// Runtime conditionally aborts, always need to support recovery.
2216 AlwaysRecoverable
2217 };
2218 }
2219
getRecoverableKind(SanitizerKind Kind)2220 static CheckRecoverableKind getRecoverableKind(SanitizerKind Kind) {
2221 switch (Kind) {
2222 case SanitizerKind::Vptr:
2223 return CheckRecoverableKind::AlwaysRecoverable;
2224 case SanitizerKind::Return:
2225 case SanitizerKind::Unreachable:
2226 return CheckRecoverableKind::Unrecoverable;
2227 default:
2228 return CheckRecoverableKind::Recoverable;
2229 }
2230 }
2231
emitCheckHandlerCall(CodeGenFunction & CGF,llvm::FunctionType * FnType,ArrayRef<llvm::Value * > FnArgs,StringRef CheckName,CheckRecoverableKind RecoverKind,bool IsFatal,llvm::BasicBlock * ContBB)2232 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2233 llvm::FunctionType *FnType,
2234 ArrayRef<llvm::Value *> FnArgs,
2235 StringRef CheckName,
2236 CheckRecoverableKind RecoverKind, bool IsFatal,
2237 llvm::BasicBlock *ContBB) {
2238 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2239 bool NeedsAbortSuffix =
2240 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2241 std::string FnName = ("__ubsan_handle_" + CheckName +
2242 (NeedsAbortSuffix ? "_abort" : "")).str();
2243 bool MayReturn =
2244 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2245
2246 llvm::AttrBuilder B;
2247 if (!MayReturn) {
2248 B.addAttribute(llvm::Attribute::NoReturn)
2249 .addAttribute(llvm::Attribute::NoUnwind);
2250 }
2251 B.addAttribute(llvm::Attribute::UWTable);
2252
2253 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2254 FnType, FnName,
2255 llvm::AttributeSet::get(CGF.getLLVMContext(),
2256 llvm::AttributeSet::FunctionIndex, B));
2257 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2258 if (!MayReturn) {
2259 HandlerCall->setDoesNotReturn();
2260 CGF.Builder.CreateUnreachable();
2261 } else {
2262 CGF.Builder.CreateBr(ContBB);
2263 }
2264 }
2265
EmitCheck(ArrayRef<std::pair<llvm::Value *,SanitizerKind>> Checked,StringRef CheckName,ArrayRef<llvm::Constant * > StaticArgs,ArrayRef<llvm::Value * > DynamicArgs)2266 void CodeGenFunction::EmitCheck(
2267 ArrayRef<std::pair<llvm::Value *, SanitizerKind>> Checked,
2268 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2269 ArrayRef<llvm::Value *> DynamicArgs) {
2270 assert(IsSanitizerScope);
2271 assert(Checked.size() > 0);
2272
2273 llvm::Value *FatalCond = nullptr;
2274 llvm::Value *RecoverableCond = nullptr;
2275 for (int i = 0, n = Checked.size(); i < n; ++i) {
2276 llvm::Value *Check = Checked[i].first;
2277 llvm::Value *&Cond =
2278 CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2279 ? RecoverableCond
2280 : FatalCond;
2281 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2282 }
2283
2284 llvm::Value *JointCond;
2285 if (FatalCond && RecoverableCond)
2286 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2287 else
2288 JointCond = FatalCond ? FatalCond : RecoverableCond;
2289 assert(JointCond);
2290
2291 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2292 assert(SanOpts.has(Checked[0].second));
2293 #ifndef NDEBUG
2294 for (int i = 1, n = Checked.size(); i < n; ++i) {
2295 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2296 "All recoverable kinds in a single check must be same!");
2297 assert(SanOpts.has(Checked[i].second));
2298 }
2299 #endif
2300
2301 if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
2302 assert(RecoverKind != CheckRecoverableKind::AlwaysRecoverable &&
2303 "Runtime call required for AlwaysRecoverable kind!");
2304 // Assume that -fsanitize-undefined-trap-on-error overrides
2305 // -fsanitize-recover= options, as we can only print meaningful error
2306 // message and recover if we have a runtime support.
2307 return EmitTrapCheck(JointCond);
2308 }
2309
2310 llvm::BasicBlock *Cont = createBasicBlock("cont");
2311 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2312 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2313 // Give hint that we very much don't expect to execute the handler
2314 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2315 llvm::MDBuilder MDHelper(getLLVMContext());
2316 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2317 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2318 EmitBlock(Handlers);
2319
2320 // Emit handler arguments and create handler function type.
2321 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2322 auto *InfoPtr =
2323 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2324 llvm::GlobalVariable::PrivateLinkage, Info);
2325 InfoPtr->setUnnamedAddr(true);
2326 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2327
2328 SmallVector<llvm::Value *, 4> Args;
2329 SmallVector<llvm::Type *, 4> ArgTypes;
2330 Args.reserve(DynamicArgs.size() + 1);
2331 ArgTypes.reserve(DynamicArgs.size() + 1);
2332
2333 // Handler functions take an i8* pointing to the (handler-specific) static
2334 // information block, followed by a sequence of intptr_t arguments
2335 // representing operand values.
2336 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2337 ArgTypes.push_back(Int8PtrTy);
2338 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2339 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2340 ArgTypes.push_back(IntPtrTy);
2341 }
2342
2343 llvm::FunctionType *FnType =
2344 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2345
2346 if (!FatalCond || !RecoverableCond) {
2347 // Simple case: we need to generate a single handler call, either
2348 // fatal, or non-fatal.
2349 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2350 (FatalCond != nullptr), Cont);
2351 } else {
2352 // Emit two handler calls: first one for set of unrecoverable checks,
2353 // another one for recoverable.
2354 llvm::BasicBlock *NonFatalHandlerBB =
2355 createBasicBlock("non_fatal." + CheckName);
2356 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2357 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2358 EmitBlock(FatalHandlerBB);
2359 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2360 NonFatalHandlerBB);
2361 EmitBlock(NonFatalHandlerBB);
2362 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2363 Cont);
2364 }
2365
2366 EmitBlock(Cont);
2367 }
2368
EmitTrapCheck(llvm::Value * Checked)2369 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
2370 llvm::BasicBlock *Cont = createBasicBlock("cont");
2371
2372 // If we're optimizing, collapse all calls to trap down to just one per
2373 // function to save on code size.
2374 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2375 TrapBB = createBasicBlock("trap");
2376 Builder.CreateCondBr(Checked, Cont, TrapBB);
2377 EmitBlock(TrapBB);
2378 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2379 llvm::CallInst *TrapCall = Builder.CreateCall(F);
2380 TrapCall->setDoesNotReturn();
2381 TrapCall->setDoesNotThrow();
2382 Builder.CreateUnreachable();
2383 } else {
2384 Builder.CreateCondBr(Checked, Cont, TrapBB);
2385 }
2386
2387 EmitBlock(Cont);
2388 }
2389
2390 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2391 /// array to pointer, return the array subexpression.
isSimpleArrayDecayOperand(const Expr * E)2392 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2393 // If this isn't just an array->pointer decay, bail out.
2394 const auto *CE = dyn_cast<CastExpr>(E);
2395 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
2396 return nullptr;
2397
2398 // If this is a decay from variable width array, bail out.
2399 const Expr *SubExpr = CE->getSubExpr();
2400 if (SubExpr->getType()->isVariableArrayType())
2401 return nullptr;
2402
2403 return SubExpr;
2404 }
2405
EmitArraySubscriptExpr(const ArraySubscriptExpr * E,bool Accessed)2406 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2407 bool Accessed) {
2408 // The index must always be an integer, which is not an aggregate. Emit it.
2409 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
2410 QualType IdxTy = E->getIdx()->getType();
2411 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2412
2413 if (SanOpts.has(SanitizerKind::ArrayBounds))
2414 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2415
2416 // If the base is a vector type, then we are forming a vector element lvalue
2417 // with this subscript.
2418 if (E->getBase()->getType()->isVectorType() &&
2419 !isa<ExtVectorElementExpr>(E->getBase())) {
2420 // Emit the vector as an lvalue to get its address.
2421 LValue LHS = EmitLValue(E->getBase());
2422 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
2423 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
2424 E->getBase()->getType(), LHS.getAlignment());
2425 }
2426
2427 // Extend or truncate the index type to 32 or 64-bits.
2428 if (Idx->getType() != IntPtrTy)
2429 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2430
2431 // We know that the pointer points to a type of the correct size, unless the
2432 // size is a VLA or Objective-C interface.
2433 llvm::Value *Address = nullptr;
2434 CharUnits ArrayAlignment;
2435 if (isa<ExtVectorElementExpr>(E->getBase())) {
2436 LValue LV = EmitLValue(E->getBase());
2437 Address = EmitExtVectorElementLValue(LV);
2438 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
2439 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2440 QualType EQT = ExprVT->getElementType();
2441 return MakeAddrLValue(Address, EQT,
2442 getContext().getTypeAlignInChars(EQT));
2443 }
2444 else if (const VariableArrayType *vla =
2445 getContext().getAsVariableArrayType(E->getType())) {
2446 // The base must be a pointer, which is not an aggregate. Emit
2447 // it. It needs to be emitted first in case it's what captures
2448 // the VLA bounds.
2449 Address = EmitScalarExpr(E->getBase());
2450
2451 // The element count here is the total number of non-VLA elements.
2452 llvm::Value *numElements = getVLASize(vla).first;
2453
2454 // Effectively, the multiply by the VLA size is part of the GEP.
2455 // GEP indexes are signed, and scaling an index isn't permitted to
2456 // signed-overflow, so we use the same semantics for our explicit
2457 // multiply. We suppress this if overflow is not undefined behavior.
2458 if (getLangOpts().isSignedOverflowDefined()) {
2459 Idx = Builder.CreateMul(Idx, numElements);
2460 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2461 } else {
2462 Idx = Builder.CreateNSWMul(Idx, numElements);
2463 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
2464 }
2465 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2466 // Indexing over an interface, as in "NSString *P; P[4];"
2467 llvm::Value *InterfaceSize =
2468 llvm::ConstantInt::get(Idx->getType(),
2469 getContext().getTypeSizeInChars(OIT).getQuantity());
2470
2471 Idx = Builder.CreateMul(Idx, InterfaceSize);
2472
2473 // The base must be a pointer, which is not an aggregate. Emit it.
2474 llvm::Value *Base = EmitScalarExpr(E->getBase());
2475 Address = EmitCastToVoidPtr(Base);
2476 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
2477 Address = Builder.CreateBitCast(Address, Base->getType());
2478 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2479 // If this is A[i] where A is an array, the frontend will have decayed the
2480 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2481 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2482 // "gep x, i" here. Emit one "gep A, 0, i".
2483 assert(Array->getType()->isArrayType() &&
2484 "Array to pointer decay must have array source type!");
2485 LValue ArrayLV;
2486 // For simple multidimensional array indexing, set the 'accessed' flag for
2487 // better bounds-checking of the base expression.
2488 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
2489 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2490 else
2491 ArrayLV = EmitLValue(Array);
2492 llvm::Value *ArrayPtr = ArrayLV.getAddress();
2493 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2494 llvm::Value *Args[] = { Zero, Idx };
2495
2496 // Propagate the alignment from the array itself to the result.
2497 ArrayAlignment = ArrayLV.getAlignment();
2498
2499 if (getLangOpts().isSignedOverflowDefined())
2500 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
2501 else
2502 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
2503 } else {
2504 // The base must be a pointer, which is not an aggregate. Emit it.
2505 llvm::Value *Base = EmitScalarExpr(E->getBase());
2506 if (getLangOpts().isSignedOverflowDefined())
2507 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2508 else
2509 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
2510 }
2511
2512 QualType T = E->getBase()->getType()->getPointeeType();
2513 assert(!T.isNull() &&
2514 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
2515
2516
2517 // Limit the alignment to that of the result type.
2518 LValue LV;
2519 if (!ArrayAlignment.isZero()) {
2520 CharUnits Align = getContext().getTypeAlignInChars(T);
2521 ArrayAlignment = std::min(Align, ArrayAlignment);
2522 LV = MakeAddrLValue(Address, T, ArrayAlignment);
2523 } else {
2524 LV = MakeNaturalAlignAddrLValue(Address, T);
2525 }
2526
2527 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
2528
2529 if (getLangOpts().ObjC1 &&
2530 getLangOpts().getGC() != LangOptions::NonGC) {
2531 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2532 setObjCGCLValueClass(getContext(), E, LV);
2533 }
2534 return LV;
2535 }
2536
2537 static
GenerateConstantVector(CGBuilderTy & Builder,SmallVectorImpl<unsigned> & Elts)2538 llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
2539 SmallVectorImpl<unsigned> &Elts) {
2540 SmallVector<llvm::Constant*, 4> CElts;
2541 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
2542 CElts.push_back(Builder.getInt32(Elts[i]));
2543
2544 return llvm::ConstantVector::get(CElts);
2545 }
2546
2547 LValue CodeGenFunction::
EmitExtVectorElementExpr(const ExtVectorElementExpr * E)2548 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
2549 // Emit the base vector as an l-value.
2550 LValue Base;
2551
2552 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
2553 if (E->isArrow()) {
2554 // If it is a pointer to a vector, emit the address and form an lvalue with
2555 // it.
2556 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
2557 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
2558 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2559 Base.getQuals().removeObjCGCAttr();
2560 } else if (E->getBase()->isGLValue()) {
2561 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2562 // emit the base as an lvalue.
2563 assert(E->getBase()->getType()->isVectorType());
2564 Base = EmitLValue(E->getBase());
2565 } else {
2566 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
2567 assert(E->getBase()->getType()->isVectorType() &&
2568 "Result must be a vector");
2569 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2570
2571 // Store the vector to memory (because LValue wants an address).
2572 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
2573 Builder.CreateStore(Vec, VecMem);
2574 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
2575 }
2576
2577 QualType type =
2578 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
2579
2580 // Encode the element access list into a vector of unsigned indices.
2581 SmallVector<unsigned, 4> Indices;
2582 E->getEncodedElementAccess(Indices);
2583
2584 if (Base.isSimple()) {
2585 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
2586 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2587 Base.getAlignment());
2588 }
2589 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2590
2591 llvm::Constant *BaseElts = Base.getExtVectorElts();
2592 SmallVector<llvm::Constant *, 4> CElts;
2593
2594 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2595 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
2596 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2597 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2598 Base.getAlignment());
2599 }
2600
EmitMemberExpr(const MemberExpr * E)2601 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
2602 Expr *BaseExpr = E->getBase();
2603
2604 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
2605 LValue BaseLV;
2606 if (E->isArrow()) {
2607 llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2608 QualType PtrTy = BaseExpr->getType()->getPointeeType();
2609 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
2610 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2611 } else
2612 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
2613
2614 NamedDecl *ND = E->getMemberDecl();
2615 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
2616 LValue LV = EmitLValueForField(BaseLV, Field);
2617 setObjCGCLValueClass(getContext(), E, LV);
2618 return LV;
2619 }
2620
2621 if (auto *VD = dyn_cast<VarDecl>(ND))
2622 return EmitGlobalVarDeclLValue(*this, E, VD);
2623
2624 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2625 return EmitFunctionDeclLValue(*this, E, FD);
2626
2627 llvm_unreachable("Unhandled member declaration!");
2628 }
2629
2630 /// Given that we are currently emitting a lambda, emit an l-value for
2631 /// one of its members.
EmitLValueForLambdaField(const FieldDecl * Field)2632 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
2633 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
2634 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
2635 QualType LambdaTagType =
2636 getContext().getTagDeclType(Field->getParent());
2637 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
2638 return EmitLValueForField(LambdaLV, Field);
2639 }
2640
EmitLValueForField(LValue base,const FieldDecl * field)2641 LValue CodeGenFunction::EmitLValueForField(LValue base,
2642 const FieldDecl *field) {
2643 if (field->isBitField()) {
2644 const CGRecordLayout &RL =
2645 CGM.getTypes().getCGRecordLayout(field->getParent());
2646 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
2647 llvm::Value *Addr = base.getAddress();
2648 unsigned Idx = RL.getLLVMFieldNo(field);
2649 if (Idx != 0)
2650 // For structs, we GEP to the field that the record layout suggests.
2651 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2652 // Get the access type.
2653 llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2654 getLLVMContext(), Info.StorageSize,
2655 CGM.getContext().getTargetAddressSpace(base.getType()));
2656 if (Addr->getType() != PtrTy)
2657 Addr = Builder.CreateBitCast(Addr, PtrTy);
2658
2659 QualType fieldType =
2660 field->getType().withCVRQualifiers(base.getVRQualifiers());
2661 return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
2662 }
2663
2664 const RecordDecl *rec = field->getParent();
2665 QualType type = field->getType();
2666 CharUnits alignment = getContext().getDeclAlign(field);
2667
2668 // FIXME: It should be impossible to have an LValue without alignment for a
2669 // complete type.
2670 if (!base.getAlignment().isZero())
2671 alignment = std::min(alignment, base.getAlignment());
2672
2673 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2674
2675 llvm::Value *addr = base.getAddress();
2676 unsigned cvr = base.getVRQualifiers();
2677 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
2678 if (rec->isUnion()) {
2679 // For unions, there is no pointer adjustment.
2680 assert(!type->isReferenceType() && "union has reference member");
2681 // TODO: handle path-aware TBAA for union.
2682 TBAAPath = false;
2683 } else {
2684 // For structs, we GEP to the field that the record layout suggests.
2685 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
2686 addr = Builder.CreateStructGEP(addr, idx, field->getName());
2687
2688 // If this is a reference field, load the reference right now.
2689 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2690 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2691 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
2692 load->setAlignment(alignment.getQuantity());
2693
2694 // Loading the reference will disable path-aware TBAA.
2695 TBAAPath = false;
2696 if (CGM.shouldUseTBAA()) {
2697 llvm::MDNode *tbaa;
2698 if (mayAlias)
2699 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2700 else
2701 tbaa = CGM.getTBAAInfo(type);
2702 if (tbaa)
2703 CGM.DecorateInstruction(load, tbaa);
2704 }
2705
2706 addr = load;
2707 mayAlias = false;
2708 type = refType->getPointeeType();
2709 if (type->isIncompleteType())
2710 alignment = CharUnits();
2711 else
2712 alignment = getContext().getTypeAlignInChars(type);
2713 cvr = 0; // qualifiers don't recursively apply to referencee
2714 }
2715 }
2716
2717 // Make sure that the address is pointing to the right type. This is critical
2718 // for both unions and structs. A union needs a bitcast, a struct element
2719 // will need a bitcast if the LLVM type laid out doesn't match the desired
2720 // type.
2721 addr = EmitBitCastOfLValueToProperType(*this, addr,
2722 CGM.getTypes().ConvertTypeForMem(type),
2723 field->getName());
2724
2725 if (field->hasAttr<AnnotateAttr>())
2726 addr = EmitFieldAnnotations(field, addr);
2727
2728 LValue LV = MakeAddrLValue(addr, type, alignment);
2729 LV.getQuals().addCVRQualifiers(cvr);
2730 if (TBAAPath) {
2731 const ASTRecordLayout &Layout =
2732 getContext().getASTRecordLayout(field->getParent());
2733 // Set the base type to be the base type of the base LValue and
2734 // update offset to be relative to the base type.
2735 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
2736 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
2737 Layout.getFieldOffset(field->getFieldIndex()) /
2738 getContext().getCharWidth());
2739 }
2740
2741 // __weak attribute on a field is ignored.
2742 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2743 LV.getQuals().removeObjCGCAttr();
2744
2745 // Fields of may_alias structs act like 'char' for TBAA purposes.
2746 // FIXME: this should get propagated down through anonymous structs
2747 // and unions.
2748 if (mayAlias && LV.getTBAAInfo())
2749 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2750
2751 return LV;
2752 }
2753
2754 LValue
EmitLValueForFieldInitialization(LValue Base,const FieldDecl * Field)2755 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2756 const FieldDecl *Field) {
2757 QualType FieldType = Field->getType();
2758
2759 if (!FieldType->isReferenceType())
2760 return EmitLValueForField(Base, Field);
2761
2762 const CGRecordLayout &RL =
2763 CGM.getTypes().getCGRecordLayout(Field->getParent());
2764 unsigned idx = RL.getLLVMFieldNo(Field);
2765 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
2766 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2767
2768 // Make sure that the address is pointing to the right type. This is critical
2769 // for both unions and structs. A union needs a bitcast, a struct element
2770 // will need a bitcast if the LLVM type laid out doesn't match the desired
2771 // type.
2772 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
2773 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2774
2775 CharUnits Alignment = getContext().getDeclAlign(Field);
2776
2777 // FIXME: It should be impossible to have an LValue without alignment for a
2778 // complete type.
2779 if (!Base.getAlignment().isZero())
2780 Alignment = std::min(Alignment, Base.getAlignment());
2781
2782 return MakeAddrLValue(V, FieldType, Alignment);
2783 }
2784
EmitCompoundLiteralLValue(const CompoundLiteralExpr * E)2785 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
2786 if (E->isFileScope()) {
2787 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2788 return MakeAddrLValue(GlobalPtr, E->getType());
2789 }
2790 if (E->getType()->isVariablyModifiedType())
2791 // make sure to emit the VLA size.
2792 EmitVariablyModifiedType(E->getType());
2793
2794 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
2795 const Expr *InitExpr = E->getInitializer();
2796 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
2797
2798 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2799 /*Init*/ true);
2800
2801 return Result;
2802 }
2803
EmitInitListLValue(const InitListExpr * E)2804 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2805 if (!E->isGLValue())
2806 // Initializing an aggregate temporary in C++11: T{...}.
2807 return EmitAggExprToLValue(E);
2808
2809 // An lvalue initializer list must be initializing a reference.
2810 assert(E->getNumInits() == 1 && "reference init with multiple values");
2811 return EmitLValue(E->getInit(0));
2812 }
2813
2814 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
2815 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
2816 /// LValue is returned and the current block has been terminated.
EmitLValueOrThrowExpression(CodeGenFunction & CGF,const Expr * Operand)2817 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
2818 const Expr *Operand) {
2819 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
2820 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
2821 return None;
2822 }
2823
2824 return CGF.EmitLValue(Operand);
2825 }
2826
2827 LValue CodeGenFunction::
EmitConditionalOperatorLValue(const AbstractConditionalOperator * expr)2828 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2829 if (!expr->isGLValue()) {
2830 // ?: here should be an aggregate.
2831 assert(hasAggregateEvaluationKind(expr->getType()) &&
2832 "Unexpected conditional operator!");
2833 return EmitAggExprToLValue(expr);
2834 }
2835
2836 OpaqueValueMapping binding(*this, expr);
2837 RegionCounter Cnt = getPGORegionCounter(expr);
2838
2839 const Expr *condExpr = expr->getCond();
2840 bool CondExprBool;
2841 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2842 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
2843 if (!CondExprBool) std::swap(live, dead);
2844
2845 if (!ContainsLabel(dead)) {
2846 // If the true case is live, we need to track its region.
2847 if (CondExprBool)
2848 Cnt.beginRegion(Builder);
2849 return EmitLValue(live);
2850 }
2851 }
2852
2853 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2854 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2855 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
2856
2857 ConditionalEvaluation eval(*this);
2858 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, Cnt.getCount());
2859
2860 // Any temporaries created here are conditional.
2861 EmitBlock(lhsBlock);
2862 Cnt.beginRegion(Builder);
2863 eval.begin(*this);
2864 Optional<LValue> lhs =
2865 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
2866 eval.end(*this);
2867
2868 if (lhs && !lhs->isSimple())
2869 return EmitUnsupportedLValue(expr, "conditional operator");
2870
2871 lhsBlock = Builder.GetInsertBlock();
2872 if (lhs)
2873 Builder.CreateBr(contBlock);
2874
2875 // Any temporaries created here are conditional.
2876 EmitBlock(rhsBlock);
2877 eval.begin(*this);
2878 Optional<LValue> rhs =
2879 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
2880 eval.end(*this);
2881 if (rhs && !rhs->isSimple())
2882 return EmitUnsupportedLValue(expr, "conditional operator");
2883 rhsBlock = Builder.GetInsertBlock();
2884
2885 EmitBlock(contBlock);
2886
2887 if (lhs && rhs) {
2888 llvm::PHINode *phi = Builder.CreatePHI(lhs->getAddress()->getType(),
2889 2, "cond-lvalue");
2890 phi->addIncoming(lhs->getAddress(), lhsBlock);
2891 phi->addIncoming(rhs->getAddress(), rhsBlock);
2892 return MakeAddrLValue(phi, expr->getType());
2893 } else {
2894 assert((lhs || rhs) &&
2895 "both operands of glvalue conditional are throw-expressions?");
2896 return lhs ? *lhs : *rhs;
2897 }
2898 }
2899
2900 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2901 /// type. If the cast is to a reference, we can have the usual lvalue result,
2902 /// otherwise if a cast is needed by the code generator in an lvalue context,
2903 /// then it must mean that we need the address of an aggregate in order to
2904 /// access one of its members. This can happen for all the reasons that casts
2905 /// are permitted with aggregate result, including noop aggregate casts, and
2906 /// cast from scalar to union.
EmitCastLValue(const CastExpr * E)2907 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
2908 switch (E->getCastKind()) {
2909 case CK_ToVoid:
2910 case CK_BitCast:
2911 case CK_ArrayToPointerDecay:
2912 case CK_FunctionToPointerDecay:
2913 case CK_NullToMemberPointer:
2914 case CK_NullToPointer:
2915 case CK_IntegralToPointer:
2916 case CK_PointerToIntegral:
2917 case CK_PointerToBoolean:
2918 case CK_VectorSplat:
2919 case CK_IntegralCast:
2920 case CK_IntegralToBoolean:
2921 case CK_IntegralToFloating:
2922 case CK_FloatingToIntegral:
2923 case CK_FloatingToBoolean:
2924 case CK_FloatingCast:
2925 case CK_FloatingRealToComplex:
2926 case CK_FloatingComplexToReal:
2927 case CK_FloatingComplexToBoolean:
2928 case CK_FloatingComplexCast:
2929 case CK_FloatingComplexToIntegralComplex:
2930 case CK_IntegralRealToComplex:
2931 case CK_IntegralComplexToReal:
2932 case CK_IntegralComplexToBoolean:
2933 case CK_IntegralComplexCast:
2934 case CK_IntegralComplexToFloatingComplex:
2935 case CK_DerivedToBaseMemberPointer:
2936 case CK_BaseToDerivedMemberPointer:
2937 case CK_MemberPointerToBoolean:
2938 case CK_ReinterpretMemberPointer:
2939 case CK_AnyPointerToBlockPointerCast:
2940 case CK_ARCProduceObject:
2941 case CK_ARCConsumeObject:
2942 case CK_ARCReclaimReturnedObject:
2943 case CK_ARCExtendBlockObject:
2944 case CK_CopyAndAutoreleaseBlockObject:
2945 case CK_AddressSpaceConversion:
2946 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
2947
2948 case CK_Dependent:
2949 llvm_unreachable("dependent cast kind in IR gen!");
2950
2951 case CK_BuiltinFnToFnPtr:
2952 llvm_unreachable("builtin functions are handled elsewhere");
2953
2954 // These are never l-values; just use the aggregate emission code.
2955 case CK_NonAtomicToAtomic:
2956 case CK_AtomicToNonAtomic:
2957 return EmitAggExprToLValue(E);
2958
2959 case CK_Dynamic: {
2960 LValue LV = EmitLValue(E->getSubExpr());
2961 llvm::Value *V = LV.getAddress();
2962 const auto *DCE = cast<CXXDynamicCastExpr>(E);
2963 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
2964 }
2965
2966 case CK_ConstructorConversion:
2967 case CK_UserDefinedConversion:
2968 case CK_CPointerToObjCPointerCast:
2969 case CK_BlockPointerToObjCPointerCast:
2970 case CK_NoOp:
2971 case CK_LValueToRValue:
2972 return EmitLValue(E->getSubExpr());
2973
2974 case CK_UncheckedDerivedToBase:
2975 case CK_DerivedToBase: {
2976 const RecordType *DerivedClassTy =
2977 E->getSubExpr()->getType()->getAs<RecordType>();
2978 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2979
2980 LValue LV = EmitLValue(E->getSubExpr());
2981 llvm::Value *This = LV.getAddress();
2982
2983 // Perform the derived-to-base conversion
2984 llvm::Value *Base = GetAddressOfBaseClass(
2985 This, DerivedClassDecl, E->path_begin(), E->path_end(),
2986 /*NullCheckValue=*/false, E->getExprLoc());
2987
2988 return MakeAddrLValue(Base, E->getType());
2989 }
2990 case CK_ToUnion:
2991 return EmitAggExprToLValue(E);
2992 case CK_BaseToDerived: {
2993 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2994 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2995
2996 LValue LV = EmitLValue(E->getSubExpr());
2997
2998 // Perform the base-to-derived conversion
2999 llvm::Value *Derived =
3000 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
3001 E->path_begin(), E->path_end(),
3002 /*NullCheckValue=*/false);
3003
3004 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3005 // performed and the object is not of the derived type.
3006 if (sanitizePerformTypeCheck())
3007 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
3008 Derived, E->getType());
3009
3010 return MakeAddrLValue(Derived, E->getType());
3011 }
3012 case CK_LValueBitCast: {
3013 // This must be a reinterpret_cast (or c-style equivalent).
3014 const auto *CE = cast<ExplicitCastExpr>(E);
3015
3016 LValue LV = EmitLValue(E->getSubExpr());
3017 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
3018 ConvertType(CE->getTypeAsWritten()));
3019 return MakeAddrLValue(V, E->getType());
3020 }
3021 case CK_ObjCObjectLValueCast: {
3022 LValue LV = EmitLValue(E->getSubExpr());
3023 QualType ToType = getContext().getLValueReferenceType(E->getType());
3024 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
3025 ConvertType(ToType));
3026 return MakeAddrLValue(V, E->getType());
3027 }
3028 case CK_ZeroToOCLEvent:
3029 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
3030 }
3031
3032 llvm_unreachable("Unhandled lvalue cast kind?");
3033 }
3034
EmitOpaqueValueLValue(const OpaqueValueExpr * e)3035 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
3036 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
3037 return getOpaqueLValueMapping(e);
3038 }
3039
EmitRValueForField(LValue LV,const FieldDecl * FD,SourceLocation Loc)3040 RValue CodeGenFunction::EmitRValueForField(LValue LV,
3041 const FieldDecl *FD,
3042 SourceLocation Loc) {
3043 QualType FT = FD->getType();
3044 LValue FieldLV = EmitLValueForField(LV, FD);
3045 switch (getEvaluationKind(FT)) {
3046 case TEK_Complex:
3047 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
3048 case TEK_Aggregate:
3049 return FieldLV.asAggregateRValue();
3050 case TEK_Scalar:
3051 return EmitLoadOfLValue(FieldLV, Loc);
3052 }
3053 llvm_unreachable("bad evaluation kind");
3054 }
3055
3056 //===--------------------------------------------------------------------===//
3057 // Expression Emission
3058 //===--------------------------------------------------------------------===//
3059
EmitCallExpr(const CallExpr * E,ReturnValueSlot ReturnValue)3060 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
3061 ReturnValueSlot ReturnValue) {
3062 // Force column info to be generated so we can differentiate
3063 // multiple call sites on the same line in the debug info.
3064 // FIXME: This is insufficient. Two calls coming from the same macro
3065 // expansion will still get the same line/column and break debug info. It's
3066 // possible that LLVM can be fixed to not rely on this uniqueness, at which
3067 // point this workaround can be removed.
3068 ApplyDebugLocation DL(*this, E->getLocStart(),
3069 E->getDirectCallee() &&
3070 E->getDirectCallee()->isInlineSpecified());
3071
3072 // Builtins never have block type.
3073 if (E->getCallee()->getType()->isBlockPointerType())
3074 return EmitBlockCallExpr(E, ReturnValue);
3075
3076 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
3077 return EmitCXXMemberCallExpr(CE, ReturnValue);
3078
3079 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
3080 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3081
3082 const Decl *TargetDecl = E->getCalleeDecl();
3083 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3084 if (unsigned builtinID = FD->getBuiltinID())
3085 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
3086 }
3087
3088 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
3089 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
3090 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
3091
3092 if (const auto *PseudoDtor =
3093 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
3094 QualType DestroyedType = PseudoDtor->getDestroyedType();
3095 if (getLangOpts().ObjCAutoRefCount &&
3096 DestroyedType->isObjCLifetimeType() &&
3097 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
3098 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
3099 // Automatic Reference Counting:
3100 // If the pseudo-expression names a retainable object with weak or
3101 // strong lifetime, the object shall be released.
3102 Expr *BaseExpr = PseudoDtor->getBase();
3103 llvm::Value *BaseValue = nullptr;
3104 Qualifiers BaseQuals;
3105
3106 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
3107 if (PseudoDtor->isArrow()) {
3108 BaseValue = EmitScalarExpr(BaseExpr);
3109 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3110 BaseQuals = PTy->getPointeeType().getQualifiers();
3111 } else {
3112 LValue BaseLV = EmitLValue(BaseExpr);
3113 BaseValue = BaseLV.getAddress();
3114 QualType BaseTy = BaseExpr->getType();
3115 BaseQuals = BaseTy.getQualifiers();
3116 }
3117
3118 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
3119 case Qualifiers::OCL_None:
3120 case Qualifiers::OCL_ExplicitNone:
3121 case Qualifiers::OCL_Autoreleasing:
3122 break;
3123
3124 case Qualifiers::OCL_Strong:
3125 EmitARCRelease(Builder.CreateLoad(BaseValue,
3126 PseudoDtor->getDestroyedType().isVolatileQualified()),
3127 ARCPreciseLifetime);
3128 break;
3129
3130 case Qualifiers::OCL_Weak:
3131 EmitARCDestroyWeak(BaseValue);
3132 break;
3133 }
3134 } else {
3135 // C++ [expr.pseudo]p1:
3136 // The result shall only be used as the operand for the function call
3137 // operator (), and the result of such a call has type void. The only
3138 // effect is the evaluation of the postfix-expression before the dot or
3139 // arrow.
3140 EmitScalarExpr(E->getCallee());
3141 }
3142
3143 return RValue::get(nullptr);
3144 }
3145
3146 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
3147 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3148 TargetDecl);
3149 }
3150
EmitBinaryOperatorLValue(const BinaryOperator * E)3151 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
3152 // Comma expressions just emit their LHS then their RHS as an l-value.
3153 if (E->getOpcode() == BO_Comma) {
3154 EmitIgnoredExpr(E->getLHS());
3155 EnsureInsertPoint();
3156 return EmitLValue(E->getRHS());
3157 }
3158
3159 if (E->getOpcode() == BO_PtrMemD ||
3160 E->getOpcode() == BO_PtrMemI)
3161 return EmitPointerToDataMemberBinaryExpr(E);
3162
3163 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
3164
3165 // Note that in all of these cases, __block variables need the RHS
3166 // evaluated first just in case the variable gets moved by the RHS.
3167
3168 switch (getEvaluationKind(E->getType())) {
3169 case TEK_Scalar: {
3170 switch (E->getLHS()->getType().getObjCLifetime()) {
3171 case Qualifiers::OCL_Strong:
3172 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3173
3174 case Qualifiers::OCL_Autoreleasing:
3175 return EmitARCStoreAutoreleasing(E).first;
3176
3177 // No reason to do any of these differently.
3178 case Qualifiers::OCL_None:
3179 case Qualifiers::OCL_ExplicitNone:
3180 case Qualifiers::OCL_Weak:
3181 break;
3182 }
3183
3184 RValue RV = EmitAnyExpr(E->getRHS());
3185 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
3186 EmitStoreThroughLValue(RV, LV);
3187 return LV;
3188 }
3189
3190 case TEK_Complex:
3191 return EmitComplexAssignmentLValue(E);
3192
3193 case TEK_Aggregate:
3194 return EmitAggExprToLValue(E);
3195 }
3196 llvm_unreachable("bad evaluation kind");
3197 }
3198
EmitCallExprLValue(const CallExpr * E)3199 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
3200 RValue RV = EmitCallExpr(E);
3201
3202 if (!RV.isScalar())
3203 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
3204
3205 assert(E->getCallReturnType()->isReferenceType() &&
3206 "Can't have a scalar return unless the return type is a "
3207 "reference type!");
3208
3209 return MakeAddrLValue(RV.getScalarVal(), E->getType());
3210 }
3211
EmitVAArgExprLValue(const VAArgExpr * E)3212 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3213 // FIXME: This shouldn't require another copy.
3214 return EmitAggExprToLValue(E);
3215 }
3216
EmitCXXConstructLValue(const CXXConstructExpr * E)3217 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
3218 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3219 && "binding l-value to type which needs a temporary");
3220 AggValueSlot Slot = CreateAggTemp(E->getType());
3221 EmitCXXConstructExpr(E, Slot);
3222 return MakeAddrLValue(Slot.getAddr(), E->getType());
3223 }
3224
3225 LValue
EmitCXXTypeidLValue(const CXXTypeidExpr * E)3226 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
3227 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
3228 }
3229
EmitCXXUuidofExpr(const CXXUuidofExpr * E)3230 llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3231 return Builder.CreateBitCast(CGM.GetAddrOfUuidDescriptor(E),
3232 ConvertType(E->getType())->getPointerTo());
3233 }
3234
EmitCXXUuidofLValue(const CXXUuidofExpr * E)3235 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
3236 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
3237 }
3238
3239 LValue
EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr * E)3240 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
3241 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
3242 Slot.setExternallyDestructed();
3243 EmitAggExpr(E->getSubExpr(), Slot);
3244 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
3245 return MakeAddrLValue(Slot.getAddr(), E->getType());
3246 }
3247
3248 LValue
EmitLambdaLValue(const LambdaExpr * E)3249 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
3250 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
3251 EmitLambdaExpr(E, Slot);
3252 return MakeAddrLValue(Slot.getAddr(), E->getType());
3253 }
3254
EmitObjCMessageExprLValue(const ObjCMessageExpr * E)3255 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
3256 RValue RV = EmitObjCMessageExpr(E);
3257
3258 if (!RV.isScalar())
3259 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
3260
3261 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
3262 "Can't have a scalar return unless the return type is a "
3263 "reference type!");
3264
3265 return MakeAddrLValue(RV.getScalarVal(), E->getType());
3266 }
3267
EmitObjCSelectorLValue(const ObjCSelectorExpr * E)3268 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
3269 llvm::Value *V =
3270 CGM.getObjCRuntime().GetSelector(*this, E->getSelector(), true);
3271 return MakeAddrLValue(V, E->getType());
3272 }
3273
EmitIvarOffset(const ObjCInterfaceDecl * Interface,const ObjCIvarDecl * Ivar)3274 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
3275 const ObjCIvarDecl *Ivar) {
3276 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
3277 }
3278
EmitLValueForIvar(QualType ObjectTy,llvm::Value * BaseValue,const ObjCIvarDecl * Ivar,unsigned CVRQualifiers)3279 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3280 llvm::Value *BaseValue,
3281 const ObjCIvarDecl *Ivar,
3282 unsigned CVRQualifiers) {
3283 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
3284 Ivar, CVRQualifiers);
3285 }
3286
EmitObjCIvarRefLValue(const ObjCIvarRefExpr * E)3287 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
3288 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
3289 llvm::Value *BaseValue = nullptr;
3290 const Expr *BaseExpr = E->getBase();
3291 Qualifiers BaseQuals;
3292 QualType ObjectTy;
3293 if (E->isArrow()) {
3294 BaseValue = EmitScalarExpr(BaseExpr);
3295 ObjectTy = BaseExpr->getType()->getPointeeType();
3296 BaseQuals = ObjectTy.getQualifiers();
3297 } else {
3298 LValue BaseLV = EmitLValue(BaseExpr);
3299 // FIXME: this isn't right for bitfields.
3300 BaseValue = BaseLV.getAddress();
3301 ObjectTy = BaseExpr->getType();
3302 BaseQuals = ObjectTy.getQualifiers();
3303 }
3304
3305 LValue LV =
3306 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3307 BaseQuals.getCVRQualifiers());
3308 setObjCGCLValueClass(getContext(), E, LV);
3309 return LV;
3310 }
3311
EmitStmtExprLValue(const StmtExpr * E)3312 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
3313 // Can only get l-value for message expression returning aggregate type
3314 RValue RV = EmitAnyExprToTemp(E);
3315 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
3316 }
3317
EmitCall(QualType CalleeType,llvm::Value * Callee,const CallExpr * E,ReturnValueSlot ReturnValue,const Decl * TargetDecl,llvm::Value * Chain)3318 RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
3319 const CallExpr *E, ReturnValueSlot ReturnValue,
3320 const Decl *TargetDecl, llvm::Value *Chain) {
3321 // Get the actual function type. The callee type will always be a pointer to
3322 // function type or a block pointer type.
3323 assert(CalleeType->isFunctionPointerType() &&
3324 "Call must have function pointer type!");
3325
3326 CalleeType = getContext().getCanonicalType(CalleeType);
3327
3328 const auto *FnType =
3329 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
3330
3331 // Force column info to differentiate multiple inlined call sites on
3332 // the same line, analoguous to EmitCallExpr.
3333 // FIXME: This is insufficient. Two calls coming from the same macro expansion
3334 // will still get the same line/column and break debug info. It's possible
3335 // that LLVM can be fixed to not rely on this uniqueness, at which point this
3336 // workaround can be removed.
3337 bool ForceColumnInfo = false;
3338 if (const FunctionDecl* FD = dyn_cast_or_null<const FunctionDecl>(TargetDecl))
3339 ForceColumnInfo = FD->isInlineSpecified();
3340
3341 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
3342 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3343 if (llvm::Constant *PrefixSig =
3344 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
3345 SanitizerScope SanScope(this);
3346 llvm::Constant *FTRTTIConst =
3347 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3348 llvm::Type *PrefixStructTyElems[] = {
3349 PrefixSig->getType(),
3350 FTRTTIConst->getType()
3351 };
3352 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3353 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3354
3355 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3356 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3357 llvm::Value *CalleeSigPtr =
3358 Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 0);
3359 llvm::Value *CalleeSig = Builder.CreateLoad(CalleeSigPtr);
3360 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3361
3362 llvm::BasicBlock *Cont = createBasicBlock("cont");
3363 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3364 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3365
3366 EmitBlock(TypeCheck);
3367 llvm::Value *CalleeRTTIPtr =
3368 Builder.CreateConstGEP2_32(CalleePrefixStruct, 0, 1);
3369 llvm::Value *CalleeRTTI = Builder.CreateLoad(CalleeRTTIPtr);
3370 llvm::Value *CalleeRTTIMatch =
3371 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3372 llvm::Constant *StaticData[] = {
3373 EmitCheckSourceLocation(E->getLocStart()),
3374 EmitCheckTypeDescriptor(CalleeType)
3375 };
3376 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
3377 "function_type_mismatch", StaticData, Callee);
3378
3379 Builder.CreateBr(Cont);
3380 EmitBlock(Cont);
3381 }
3382 }
3383
3384 CallArgList Args;
3385 if (Chain)
3386 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
3387 CGM.getContext().VoidPtrTy);
3388 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arg_begin(),
3389 E->arg_end(), E->getDirectCallee(), /*ParamsToSkip*/ 0,
3390 ForceColumnInfo);
3391
3392 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
3393 Args, FnType, /*isChainCall=*/Chain);
3394
3395 // C99 6.5.2.2p6:
3396 // If the expression that denotes the called function has a type
3397 // that does not include a prototype, [the default argument
3398 // promotions are performed]. If the number of arguments does not
3399 // equal the number of parameters, the behavior is undefined. If
3400 // the function is defined with a type that includes a prototype,
3401 // and either the prototype ends with an ellipsis (, ...) or the
3402 // types of the arguments after promotion are not compatible with
3403 // the types of the parameters, the behavior is undefined. If the
3404 // function is defined with a type that does not include a
3405 // prototype, and the types of the arguments after promotion are
3406 // not compatible with those of the parameters after promotion,
3407 // the behavior is undefined [except in some trivial cases].
3408 // That is, in the general case, we should assume that a call
3409 // through an unprototyped function type works like a *non-variadic*
3410 // call. The way we make this work is to cast to the exact type
3411 // of the promoted arguments.
3412 //
3413 // Chain calls use this same code path to add the invisible chain parameter
3414 // to the function type.
3415 if (isa<FunctionNoProtoType>(FnType) || Chain) {
3416 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
3417 CalleeTy = CalleeTy->getPointerTo();
3418 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3419 }
3420
3421 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
3422 }
3423
3424 LValue CodeGenFunction::
EmitPointerToDataMemberBinaryExpr(const BinaryOperator * E)3425 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
3426 llvm::Value *BaseV;
3427 if (E->getOpcode() == BO_PtrMemI)
3428 BaseV = EmitScalarExpr(E->getLHS());
3429 else
3430 BaseV = EmitLValue(E->getLHS()).getAddress();
3431
3432 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3433
3434 const MemberPointerType *MPT
3435 = E->getRHS()->getType()->getAs<MemberPointerType>();
3436
3437 llvm::Value *AddV = CGM.getCXXABI().EmitMemberDataPointerAddress(
3438 *this, E, BaseV, OffsetV, MPT);
3439
3440 return MakeAddrLValue(AddV, MPT->getPointeeType());
3441 }
3442
3443 /// Given the address of a temporary variable, produce an r-value of
3444 /// its type.
convertTempToRValue(llvm::Value * addr,QualType type,SourceLocation loc)3445 RValue CodeGenFunction::convertTempToRValue(llvm::Value *addr,
3446 QualType type,
3447 SourceLocation loc) {
3448 LValue lvalue = MakeNaturalAlignAddrLValue(addr, type);
3449 switch (getEvaluationKind(type)) {
3450 case TEK_Complex:
3451 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
3452 case TEK_Aggregate:
3453 return lvalue.asAggregateRValue();
3454 case TEK_Scalar:
3455 return RValue::get(EmitLoadOfScalar(lvalue, loc));
3456 }
3457 llvm_unreachable("bad evaluation kind");
3458 }
3459
SetFPAccuracy(llvm::Value * Val,float Accuracy)3460 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
3461 assert(Val->getType()->isFPOrFPVectorTy());
3462 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
3463 return;
3464
3465 llvm::MDBuilder MDHelper(getLLVMContext());
3466 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
3467
3468 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
3469 }
3470
3471 namespace {
3472 struct LValueOrRValue {
3473 LValue LV;
3474 RValue RV;
3475 };
3476 }
3477
emitPseudoObjectExpr(CodeGenFunction & CGF,const PseudoObjectExpr * E,bool forLValue,AggValueSlot slot)3478 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3479 const PseudoObjectExpr *E,
3480 bool forLValue,
3481 AggValueSlot slot) {
3482 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3483
3484 // Find the result expression, if any.
3485 const Expr *resultExpr = E->getResultExpr();
3486 LValueOrRValue result;
3487
3488 for (PseudoObjectExpr::const_semantics_iterator
3489 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3490 const Expr *semantic = *i;
3491
3492 // If this semantic expression is an opaque value, bind it
3493 // to the result of its source expression.
3494 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3495
3496 // If this is the result expression, we may need to evaluate
3497 // directly into the slot.
3498 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3499 OVMA opaqueData;
3500 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3501 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
3502 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3503
3504 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3505 opaqueData = OVMA::bind(CGF, ov, LV);
3506 result.RV = slot.asRValue();
3507
3508 // Otherwise, emit as normal.
3509 } else {
3510 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3511
3512 // If this is the result, also evaluate the result now.
3513 if (ov == resultExpr) {
3514 if (forLValue)
3515 result.LV = CGF.EmitLValue(ov);
3516 else
3517 result.RV = CGF.EmitAnyExpr(ov, slot);
3518 }
3519 }
3520
3521 opaques.push_back(opaqueData);
3522
3523 // Otherwise, if the expression is the result, evaluate it
3524 // and remember the result.
3525 } else if (semantic == resultExpr) {
3526 if (forLValue)
3527 result.LV = CGF.EmitLValue(semantic);
3528 else
3529 result.RV = CGF.EmitAnyExpr(semantic, slot);
3530
3531 // Otherwise, evaluate the expression in an ignored context.
3532 } else {
3533 CGF.EmitIgnoredExpr(semantic);
3534 }
3535 }
3536
3537 // Unbind all the opaques now.
3538 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3539 opaques[i].unbind(CGF);
3540
3541 return result;
3542 }
3543
EmitPseudoObjectRValue(const PseudoObjectExpr * E,AggValueSlot slot)3544 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3545 AggValueSlot slot) {
3546 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3547 }
3548
EmitPseudoObjectLValue(const PseudoObjectExpr * E)3549 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3550 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3551 }
3552