Coverage Report

Created: 2020-02-18 08:44

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