Coverage Report

Created: 2022-01-18 06:27

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