Coverage Report

Created: 2021-08-24 07:12

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