Coverage Report

Created: 2019-07-24 05:18

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