Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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 Decl nodes as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGBlocks.h"
14
#include "CGCXXABI.h"
15
#include "CGCleanup.h"
16
#include "CGDebugInfo.h"
17
#include "CGOpenCLRuntime.h"
18
#include "CGOpenMPRuntime.h"
19
#include "CodeGenFunction.h"
20
#include "CodeGenModule.h"
21
#include "ConstantEmitter.h"
22
#include "PatternInit.h"
23
#include "TargetInfo.h"
24
#include "clang/AST/ASTContext.h"
25
#include "clang/AST/Attr.h"
26
#include "clang/AST/CharUnits.h"
27
#include "clang/AST/Decl.h"
28
#include "clang/AST/DeclObjC.h"
29
#include "clang/AST/DeclOpenMP.h"
30
#include "clang/Basic/CodeGenOptions.h"
31
#include "clang/Basic/SourceManager.h"
32
#include "clang/Basic/TargetInfo.h"
33
#include "clang/CodeGen/CGFunctionInfo.h"
34
#include "clang/Sema/Sema.h"
35
#include "llvm/Analysis/ValueTracking.h"
36
#include "llvm/IR/DataLayout.h"
37
#include "llvm/IR/GlobalVariable.h"
38
#include "llvm/IR/Intrinsics.h"
39
#include "llvm/IR/Type.h"
40
41
using namespace clang;
42
using namespace CodeGen;
43
44
static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
45
              "Clang max alignment greater than what LLVM supports?");
46
47
159k
void CodeGenFunction::EmitDecl(const Decl &D) {
48
159k
  switch (D.getKind()) {
49
0
  case Decl::BuiltinTemplate:
50
0
  case Decl::TranslationUnit:
51
0
  case Decl::ExternCContext:
52
0
  case Decl::Namespace:
53
0
  case Decl::UnresolvedUsingTypename:
54
0
  case Decl::ClassTemplateSpecialization:
55
0
  case Decl::ClassTemplatePartialSpecialization:
56
0
  case Decl::VarTemplateSpecialization:
57
0
  case Decl::VarTemplatePartialSpecialization:
58
0
  case Decl::TemplateTypeParm:
59
0
  case Decl::UnresolvedUsingValue:
60
0
  case Decl::NonTypeTemplateParm:
61
0
  case Decl::CXXDeductionGuide:
62
0
  case Decl::CXXMethod:
63
0
  case Decl::CXXConstructor:
64
0
  case Decl::CXXDestructor:
65
0
  case Decl::CXXConversion:
66
0
  case Decl::Field:
67
0
  case Decl::MSProperty:
68
0
  case Decl::IndirectField:
69
0
  case Decl::ObjCIvar:
70
0
  case Decl::ObjCAtDefsField:
71
0
  case Decl::ParmVar:
72
0
  case Decl::ImplicitParam:
73
0
  case Decl::ClassTemplate:
74
0
  case Decl::VarTemplate:
75
0
  case Decl::FunctionTemplate:
76
0
  case Decl::TypeAliasTemplate:
77
0
  case Decl::TemplateTemplateParm:
78
0
  case Decl::ObjCMethod:
79
0
  case Decl::ObjCCategory:
80
0
  case Decl::ObjCProtocol:
81
0
  case Decl::ObjCInterface:
82
0
  case Decl::ObjCCategoryImpl:
83
0
  case Decl::ObjCImplementation:
84
0
  case Decl::ObjCProperty:
85
0
  case Decl::ObjCCompatibleAlias:
86
0
  case Decl::PragmaComment:
87
0
  case Decl::PragmaDetectMismatch:
88
0
  case Decl::AccessSpec:
89
0
  case Decl::LinkageSpec:
90
0
  case Decl::Export:
91
0
  case Decl::ObjCPropertyImpl:
92
0
  case Decl::FileScopeAsm:
93
0
  case Decl::Friend:
94
0
  case Decl::FriendTemplate:
95
0
  case Decl::Block:
96
0
  case Decl::Captured:
97
0
  case Decl::ClassScopeFunctionSpecialization:
98
0
  case Decl::UsingShadow:
99
0
  case Decl::ConstructorUsingShadow:
100
0
  case Decl::ObjCTypeParam:
101
0
  case Decl::Binding:
102
0
    llvm_unreachable("Declaration should not be in declstmts!");
103
2.42k
  case Decl::Record:    // struct/union/class X;
104
2.42k
  case Decl::CXXRecord: // struct/union/class X; [C++]
105
2.42k
    if (CGDebugInfo *DI = getDebugInfo())
106
1.72k
      if (cast<RecordDecl>(D).getDefinition())
107
1.72k
        DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
108
2.42k
    return;
109
81
  case Decl::Enum:      // enum X;
110
81
    if (CGDebugInfo *DI = getDebugInfo())
111
33
      if (cast<EnumDecl>(D).getDefinition())
112
31
        DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
113
81
    return;
114
3.07k
  case Decl::Function:     // void X();
115
3.07k
  case Decl::EnumConstant: // enum ? { X = ? }
116
3.07k
  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
117
3.07k
  case Decl::Label:        // __label__ x;
118
3.07k
  case Decl::Import:
119
3.07k
  case Decl::MSGuid:    // __declspec(uuid("..."))
120
3.07k
  case Decl::TemplateParamObject:
121
3.07k
  case Decl::OMPThreadPrivate:
122
3.07k
  case Decl::OMPAllocate:
123
3.07k
  case Decl::OMPCapturedExpr:
124
3.07k
  case Decl::OMPRequires:
125
3.07k
  case Decl::Empty:
126
3.07k
  case Decl::Concept:
127
3.07k
  case Decl::LifetimeExtendedTemporary:
128
3.07k
  case Decl::RequiresExprBody:
129
    // None of these decls require codegen support.
130
3.07k
    return;
131
132
9
  case Decl::NamespaceAlias:
133
9
    if (CGDebugInfo *DI = getDebugInfo())
134
8
        DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
135
9
    return;
136
7.68k
  case Decl::Using:          // using X; [C++]
137
7.68k
    if (CGDebugInfo *DI = getDebugInfo())
138
84
        DI->EmitUsingDecl(cast<UsingDecl>(D));
139
7.68k
    return;
140
0
  case Decl::UsingPack:
141
0
    for (auto *Using : cast<UsingPackDecl>(D).expansions())
142
0
      EmitDecl(*Using);
143
0
    return;
144
236
  case Decl::UsingDirective: // using namespace X; [C++]
145
236
    if (CGDebugInfo *DI = getDebugInfo())
146
233
      DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
147
236
    return;
148
141k
  case Decl::Var:
149
141k
  case Decl::Decomposition: {
150
141k
    const VarDecl &VD = cast<VarDecl>(D);
151
141k
    assert(VD.isLocalVarDecl() &&
152
141k
           "Should not see file-scope variables inside a function!");
153
141k
    EmitVarDecl(VD);
154
141k
    if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
155
7
      for (auto *B : DD->bindings())
156
17
        if (auto *HD = B->getHoldingVar())
157
4
          EmitVarDecl(*HD);
158
141k
    return;
159
141k
  }
160
161
70
  case Decl::OMPDeclareReduction:
162
70
    return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
163
164
0
  case Decl::OMPDeclareMapper:
165
0
    return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
166
167
4.44k
  case Decl::Typedef:      // typedef int X;
168
4.44k
  case Decl::TypeAlias: {  // using X = int; [C++0x]
169
4.44k
    QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
170
4.44k
    if (CGDebugInfo *DI = getDebugInfo())
171
3.91k
      DI->EmitAndRetainType(Ty);
172
4.44k
    if (Ty->isVariablyModifiedType())
173
21
      EmitVariablyModifiedType(Ty);
174
4.44k
    return;
175
4.44k
  }
176
159k
  }
177
159k
}
178
179
/// EmitVarDecl - This method handles emission of any variable declaration
180
/// inside a function, including static vars etc.
181
206k
void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
182
206k
  if (D.hasExternalStorage())
183
    // Don't emit it now, allow it to be emitted lazily on its first use.
184
133
    return;
185
186
  // Some function-scope variable does not have static storage but still
187
  // needs to be emitted like a static variable, e.g. a function-scope
188
  // variable in constant address space in OpenCL.
189
206k
  if (D.getStorageDuration() != SD_Automatic) {
190
    // Static sampler variables translated to function calls.
191
10.8k
    if (D.getType()->isSamplerT())
192
3
      return;
193
194
10.8k
    llvm::GlobalValue::LinkageTypes Linkage =
195
10.8k
        CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
196
197
    // FIXME: We need to force the emission/use of a guard variable for
198
    // some variables even if we can constant-evaluate them because
199
    // we can't guarantee every translation unit will constant-evaluate them.
200
201
10.8k
    return EmitStaticVarDecl(D, Linkage);
202
10.8k
  }
203
204
195k
  if (D.getType().getAddressSpace() == LangAS::opencl_local)
205
122
    return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
206
207
195k
  assert(D.hasLocalStorage());
208
195k
  return EmitAutoVarDecl(D);
209
195k
}
210
211
10.9k
static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
212
10.9k
  if (CGM.getLangOpts().CPlusPlus)
213
10.3k
    return CGM.getMangledName(&D).str();
214
215
  // If this isn't C++, we don't need a mangled name, just a pretty one.
216
545
  assert(!D.isExternallyVisible() && "name shouldn't matter");
217
545
  std::string ContextName;
218
545
  const DeclContext *DC = D.getDeclContext();
219
545
  if (auto *CD = dyn_cast<CapturedDecl>(DC))
220
1
    DC = cast<DeclContext>(CD->getNonClosureContext());
221
545
  if (const auto *FD = dyn_cast<FunctionDecl>(DC))
222
537
    ContextName = std::string(CGM.getMangledName(FD));
223
8
  else if (const auto *BD = dyn_cast<BlockDecl>(DC))
224
5
    ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
225
3
  else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
226
3
    ContextName = OMD->getSelector().getAsString();
227
3
  else
228
0
    llvm_unreachable("Unknown context for static var decl");
229
230
545
  ContextName += "." + D.getNameAsString();
231
545
  return ContextName;
232
545
}
233
234
llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
235
11.5k
    const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
236
  // In general, we don't always emit static var decls once before we reference
237
  // them. It is possible to reference them before emitting the function that
238
  // contains them, and it is possible to emit the containing function multiple
239
  // times.
240
11.5k
  if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
241
667
    return ExistingGV;
242
243
10.9k
  QualType Ty = D.getType();
244
10.9k
  assert(Ty->isConstantSizeType() && "VLAs can't be static");
245
246
  // Use the label if the variable is renamed with the asm-label extension.
247
10.9k
  std::string Name;
248
10.9k
  if (D.hasAttr<AsmLabelAttr>())
249
2
    Name = std::string(getMangledName(&D));
250
10.9k
  else
251
10.9k
    Name = getStaticDeclName(*this, D);
252
253
10.9k
  llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
254
10.9k
  LangAS AS = GetGlobalVarAddressSpace(&D);
255
10.9k
  unsigned TargetAS = getContext().getTargetAddressSpace(AS);
256
257
  // OpenCL variables in local address space and CUDA shared
258
  // variables cannot have an initializer.
259
10.9k
  llvm::Constant *Init = nullptr;
260
10.9k
  if (Ty.getAddressSpace() == LangAS::opencl_local ||
261
10.7k
      D.hasAttr<CUDASharedAttr>() || 
D.hasAttr<LoaderUninitializedAttr>()10.7k
)
262
147
    Init = llvm::UndefValue::get(LTy);
263
10.7k
  else
264
10.7k
    Init = EmitNullConstant(Ty);
265
266
10.9k
  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
267
10.9k
      getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
268
10.9k
      nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
269
10.9k
  GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
270
271
10.9k
  if (supportsCOMDAT() && 
GV->isWeakForLinker()2.57k
)
272
250
    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
273
274
10.9k
  if (D.getTLSKind())
275
118
    setTLSMode(GV, D);
276
277
10.9k
  setGVProperties(GV, &D);
278
279
  // Make sure the result is of the correct type.
280
10.9k
  LangAS ExpectedAS = Ty.getAddressSpace();
281
10.9k
  llvm::Constant *Addr = GV;
282
10.9k
  if (AS != ExpectedAS) {
283
34
    Addr = getTargetCodeGenInfo().performAddrSpaceCast(
284
34
        *this, GV, AS, ExpectedAS,
285
34
        LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
286
34
  }
287
288
10.9k
  setStaticLocalDeclAddress(&D, Addr);
289
290
  // Ensure that the static local gets initialized by making sure the parent
291
  // function gets emitted eventually.
292
10.9k
  const Decl *DC = cast<Decl>(D.getDeclContext());
293
294
  // We can't name blocks or captured statements directly, so try to emit their
295
  // parents.
296
10.9k
  if (isa<BlockDecl>(DC) || 
isa<CapturedDecl>(DC)10.8k
) {
297
296
    DC = DC->getNonClosureContext();
298
    // FIXME: Ensure that global blocks get emitted.
299
296
    if (!DC)
300
21
      return Addr;
301
10.8k
  }
302
303
10.8k
  GlobalDecl GD;
304
10.8k
  if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
305
11
    GD = GlobalDecl(CD, Ctor_Base);
306
10.8k
  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
307
4
    GD = GlobalDecl(DD, Dtor_Base);
308
10.8k
  else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
309
10.7k
    GD = GlobalDecl(FD);
310
116
  else {
311
    // Don't do anything for Obj-C method decls or global closures. We should
312
    // never defer them.
313
116
    assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
314
116
  }
315
10.8k
  if (GD.getDecl()) {
316
    // Disable emission of the parent function for the OpenMP device codegen.
317
10.7k
    CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
318
10.7k
    (void)GetAddrOfGlobal(GD);
319
10.7k
  }
320
321
10.8k
  return Addr;
322
10.8k
}
323
324
/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
325
/// global variable that has already been created for it.  If the initializer
326
/// has a different type than GV does, this may free GV and return a different
327
/// one.  Otherwise it just returns GV.
328
llvm::GlobalVariable *
329
CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
330
8.92k
                                               llvm::GlobalVariable *GV) {
331
8.92k
  ConstantEmitter emitter(*this);
332
8.92k
  llvm::Constant *Init = emitter.tryEmitForInitializer(D);
333
334
  // If constant emission failed, then this should be a C++ static
335
  // initializer.
336
8.92k
  if (!Init) {
337
7.55k
    if (!getLangOpts().CPlusPlus)
338
0
      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
339
7.55k
    else if (HaveInsertPoint()) {
340
      // Since we have a static initializer, this global variable can't
341
      // be constant.
342
7.55k
      GV->setConstant(false);
343
344
7.55k
      EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
345
7.55k
    }
346
7.55k
    return GV;
347
7.55k
  }
348
349
  // The initializer may differ in type from the global. Rewrite
350
  // the global to match the initializer.  (We have to do this
351
  // because some types, like unions, can't be completely represented
352
  // in the LLVM type system.)
353
1.37k
  if (GV->getValueType() != Init->getType()) {
354
89
    llvm::GlobalVariable *OldGV = GV;
355
356
89
    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
357
89
                                  OldGV->isConstant(),
358
89
                                  OldGV->getLinkage(), Init, "",
359
89
                                  /*InsertBefore*/ OldGV,
360
89
                                  OldGV->getThreadLocalMode(),
361
89
                           CGM.getContext().getTargetAddressSpace(D.getType()));
362
89
    GV->setVisibility(OldGV->getVisibility());
363
89
    GV->setDSOLocal(OldGV->isDSOLocal());
364
89
    GV->setComdat(OldGV->getComdat());
365
366
    // Steal the name of the old global
367
89
    GV->takeName(OldGV);
368
369
    // Replace all uses of the old global with the new global
370
89
    llvm::Constant *NewPtrForOldDecl =
371
89
    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
372
89
    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
373
374
    // Erase the old global, since it is no longer used.
375
89
    OldGV->eraseFromParent();
376
89
  }
377
378
1.37k
  GV->setConstant(CGM.isTypeConstant(D.getType(), true));
379
1.37k
  GV->setInitializer(Init);
380
381
1.37k
  emitter.finalize(GV);
382
383
1.37k
  if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
384
49
      HaveInsertPoint()) {
385
    // We have a constant initializer, but a nontrivial destructor. We still
386
    // need to perform a guarded "initialization" in order to register the
387
    // destructor.
388
48
    EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
389
48
  }
390
391
1.37k
  return GV;
392
1.37k
}
393
394
void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
395
10.9k
                                      llvm::GlobalValue::LinkageTypes Linkage) {
396
  // Check to see if we already have a global variable for this
397
  // declaration.  This can happen when double-emitting function
398
  // bodies, e.g. with complete and base constructors.
399
10.9k
  llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
400
10.9k
  CharUnits alignment = getContext().getDeclAlign(&D);
401
402
  // Store into LocalDeclMap before generating initializer to handle
403
  // circular references.
404
10.9k
  setAddrOfLocalVar(&D, Address(addr, alignment));
405
406
  // We can't have a VLA here, but we can have a pointer to a VLA,
407
  // even though that doesn't really make any sense.
408
  // Make sure to evaluate VLA bounds now so that we have them for later.
409
10.9k
  if (D.getType()->isVariablyModifiedType())
410
1
    EmitVariablyModifiedType(D.getType());
411
412
  // Save the type in case adding the initializer forces a type change.
413
10.9k
  llvm::Type *expectedType = addr->getType();
414
415
10.9k
  llvm::GlobalVariable *var =
416
10.9k
    cast<llvm::GlobalVariable>(addr->stripPointerCasts());
417
418
  // CUDA's local and local static __shared__ variables should not
419
  // have any non-empty initializers. This is ensured by Sema.
420
  // Whatever initializer such variable may have when it gets here is
421
  // a no-op and should not be emitted.
422
10.9k
  bool isCudaSharedVar = getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice32
&&
423
32
                         D.hasAttr<CUDASharedAttr>();
424
  // If this value has an initializer, emit it.
425
10.9k
  if (D.getInit() && 
!isCudaSharedVar8.93k
)
426
8.92k
    var = AddInitializerToStaticVarDecl(D, var);
427
428
10.9k
  var->setAlignment(alignment.getAsAlign());
429
430
10.9k
  if (D.hasAttr<AnnotateAttr>())
431
3
    CGM.AddGlobalAnnotations(&D, var);
432
433
10.9k
  if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
434
1
    var->addAttribute("bss-section", SA->getName());
435
10.9k
  if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
436
0
    var->addAttribute("data-section", SA->getName());
437
10.9k
  if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
438
1
    var->addAttribute("rodata-section", SA->getName());
439
10.9k
  if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
440
0
    var->addAttribute("relro-section", SA->getName());
441
442
10.9k
  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
443
1
    var->setSection(SA->getName());
444
445
10.9k
  if (D.hasAttr<UsedAttr>())
446
1
    CGM.addUsedGlobal(var);
447
448
  // We may have to cast the constant because of the initializer
449
  // mismatch above.
450
  //
451
  // FIXME: It is really dangerous to store this in the map; if anyone
452
  // RAUW's the GV uses of this constant will be invalid.
453
10.9k
  llvm::Constant *castedAddr =
454
10.9k
    llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
455
10.9k
  if (var != castedAddr)
456
125
    LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
457
10.9k
  CGM.setStaticLocalDeclAddress(&D, castedAddr);
458
459
10.9k
  CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
460
461
  // Emit global variable debug descriptor for static vars.
462
10.9k
  CGDebugInfo *DI = getDebugInfo();
463
10.9k
  if (DI && 
CGM.getCodeGenOpts().hasReducedDebugInfo()225
) {
464
225
    DI->setLocation(D.getLocation());
465
225
    DI->EmitGlobalVariable(var, &D);
466
225
  }
467
10.9k
}
468
469
namespace {
470
  struct DestroyObject final : EHScopeStack::Cleanup {
471
    DestroyObject(Address addr, QualType type,
472
                  CodeGenFunction::Destroyer *destroyer,
473
                  bool useEHCleanupForArray)
474
      : addr(addr), type(type), destroyer(destroyer),
475
13.6k
        useEHCleanupForArray(useEHCleanupForArray) {}
476
477
    Address addr;
478
    QualType type;
479
    CodeGenFunction::Destroyer *destroyer;
480
    bool useEHCleanupForArray;
481
482
16.9k
    void Emit(CodeGenFunction &CGF, Flags flags) override {
483
      // Don't use an EH cleanup recursively from an EH cleanup.
484
16.9k
      bool useEHCleanupForArray =
485
16.9k
        flags.isForNormalCleanup() && 
this->useEHCleanupForArray12.5k
;
486
487
16.9k
      CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
488
16.9k
    }
489
  };
490
491
  template <class Derived>
492
  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
493
    DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
494
197
        : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableCXX>::DestroyNRVOVariable(clang::CodeGen::Address, clang::QualType, llvm::Value*)
Line
Count
Source
494
194
        : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableC>::DestroyNRVOVariable(clang::CodeGen::Address, clang::QualType, llvm::Value*)
Line
Count
Source
494
3
        : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
495
496
    llvm::Value *NRVOFlag;
497
    Address Loc;
498
    QualType Ty;
499
500
287
    void Emit(CodeGenFunction &CGF, Flags flags) override {
501
      // Along the exceptions path we always execute the dtor.
502
287
      bool NRVO = flags.isForNormalCleanup() && 
NRVOFlag197
;
503
504
287
      llvm::BasicBlock *SkipDtorBB = nullptr;
505
287
      if (NRVO) {
506
        // If we exited via NRVO, we skip the destructor call.
507
197
        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
508
197
        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
509
197
        llvm::Value *DidNRVO =
510
197
          CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
511
197
        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
512
197
        CGF.EmitBlock(RunDtorBB);
513
197
      }
514
515
287
      static_cast<Derived *>(this)->emitDestructorCall(CGF);
516
517
287
      if (NRVO) 
CGF.EmitBlock(SkipDtorBB)197
;
518
287
    }
CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableCXX>::Emit(clang::CodeGen::CodeGenFunction&, clang::CodeGen::EHScopeStack::Cleanup::Flags)
Line
Count
Source
500
284
    void Emit(CodeGenFunction &CGF, Flags flags) override {
501
      // Along the exceptions path we always execute the dtor.
502
284
      bool NRVO = flags.isForNormalCleanup() && 
NRVOFlag194
;
503
504
284
      llvm::BasicBlock *SkipDtorBB = nullptr;
505
284
      if (NRVO) {
506
        // If we exited via NRVO, we skip the destructor call.
507
194
        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
508
194
        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
509
194
        llvm::Value *DidNRVO =
510
194
          CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
511
194
        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
512
194
        CGF.EmitBlock(RunDtorBB);
513
194
      }
514
515
284
      static_cast<Derived *>(this)->emitDestructorCall(CGF);
516
517
284
      if (NRVO) 
CGF.EmitBlock(SkipDtorBB)194
;
518
284
    }
CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableC>::Emit(clang::CodeGen::CodeGenFunction&, clang::CodeGen::EHScopeStack::Cleanup::Flags)
Line
Count
Source
500
3
    void Emit(CodeGenFunction &CGF, Flags flags) override {
501
      // Along the exceptions path we always execute the dtor.
502
3
      bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
503
504
3
      llvm::BasicBlock *SkipDtorBB = nullptr;
505
3
      if (NRVO) {
506
        // If we exited via NRVO, we skip the destructor call.
507
3
        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
508
3
        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
509
3
        llvm::Value *DidNRVO =
510
3
          CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
511
3
        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
512
3
        CGF.EmitBlock(RunDtorBB);
513
3
      }
514
515
3
      static_cast<Derived *>(this)->emitDestructorCall(CGF);
516
517
3
      if (NRVO) CGF.EmitBlock(SkipDtorBB);
518
3
    }
519
520
0
    virtual ~DestroyNRVOVariable() = default;
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableCXX>::~DestroyNRVOVariable()
Unexecuted instantiation: CGDecl.cpp:(anonymous namespace)::DestroyNRVOVariable<(anonymous namespace)::DestroyNRVOVariableC>::~DestroyNRVOVariable()
521
  };
522
523
  struct DestroyNRVOVariableCXX final
524
      : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
525
    DestroyNRVOVariableCXX(Address addr, QualType type,
526
                           const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
527
        : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
528
194
          Dtor(Dtor) {}
529
530
    const CXXDestructorDecl *Dtor;
531
532
284
    void emitDestructorCall(CodeGenFunction &CGF) {
533
284
      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
534
284
                                /*ForVirtualBase=*/false,
535
284
                                /*Delegating=*/false, Loc, Ty);
536
284
    }
537
  };
538
539
  struct DestroyNRVOVariableC final
540
      : DestroyNRVOVariable<DestroyNRVOVariableC> {
541
    DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
542
3
        : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
543
544
3
    void emitDestructorCall(CodeGenFunction &CGF) {
545
3
      CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
546
3
    }
547
  };
548
549
  struct CallStackRestore final : EHScopeStack::Cleanup {
550
    Address Stack;
551
1.58k
    CallStackRestore(Address Stack) : Stack(Stack) {}
552
1.58k
    void Emit(CodeGenFunction &CGF, Flags flags) override {
553
1.58k
      llvm::Value *V = CGF.Builder.CreateLoad(Stack);
554
1.58k
      llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
555
1.58k
      CGF.Builder.CreateCall(F, V);
556
1.58k
    }
557
  };
558
559
  struct ExtendGCLifetime final : EHScopeStack::Cleanup {
560
    const VarDecl &Var;
561
1
    ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
562
563
1
    void Emit(CodeGenFunction &CGF, Flags flags) override {
564
      // Compute the address of the local variable, in case it's a
565
      // byref or something.
566
1
      DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
567
1
                      Var.getType(), VK_LValue, SourceLocation());
568
1
      llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
569
1
                                                SourceLocation());
570
1
      CGF.EmitExtendGCLifetime(value);
571
1
    }
572
  };
573
574
  struct CallCleanupFunction final : EHScopeStack::Cleanup {
575
    llvm::Constant *CleanupFn;
576
    const CGFunctionInfo &FnInfo;
577
    const VarDecl &Var;
578
579
    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
580
                        const VarDecl *Var)
581
8
      : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
582
583
10
    void Emit(CodeGenFunction &CGF, Flags flags) override {
584
10
      DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
585
10
                      Var.getType(), VK_LValue, SourceLocation());
586
      // Compute the address of the local variable, in case it's a byref
587
      // or something.
588
10
      llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
589
590
      // In some cases, the type of the function argument will be different from
591
      // the type of the pointer. An example of this is
592
      // void f(void* arg);
593
      // __attribute__((cleanup(f))) void *g;
594
      //
595
      // To fix this we insert a bitcast here.
596
10
      QualType ArgTy = FnInfo.arg_begin()->type;
597
10
      llvm::Value *Arg =
598
10
        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
599
600
10
      CallArgList Args;
601
10
      Args.add(RValue::get(Arg),
602
10
               CGF.getContext().getPointerType(Var.getType()));
603
10
      auto Callee = CGCallee::forDirect(CleanupFn);
604
10
      CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
605
10
    }
606
  };
607
} // end anonymous namespace
608
609
/// EmitAutoVarWithLifetime - Does the setup required for an automatic
610
/// variable with lifetime.
611
static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
612
                                    Address addr,
613
526
                                    Qualifiers::ObjCLifetime lifetime) {
614
526
  switch (lifetime) {
615
0
  case Qualifiers::OCL_None:
616
0
    llvm_unreachable("present but none");
617
618
263
  case Qualifiers::OCL_ExplicitNone:
619
    // nothing to do
620
263
    break;
621
622
255
  case Qualifiers::OCL_Strong: {
623
255
    CodeGenFunction::Destroyer *destroyer =
624
255
      (var.hasAttr<ObjCPreciseLifetimeAttr>()
625
1
       ? CodeGenFunction::destroyARCStrongPrecise
626
254
       : CodeGenFunction::destroyARCStrongImprecise);
627
628
255
    CleanupKind cleanupKind = CGF.getARCCleanupKind();
629
255
    CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
630
255
                    cleanupKind & EHCleanup);
631
255
    break;
632
0
  }
633
1
  case Qualifiers::OCL_Autoreleasing:
634
    // nothing to do
635
1
    break;
636
637
7
  case Qualifiers::OCL_Weak:
638
    // __weak objects always get EH cleanups; otherwise, exceptions
639
    // could cause really nasty crashes instead of mere leaks.
640
7
    CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
641
7
                    CodeGenFunction::destroyARCWeak,
642
7
                    /*useEHCleanup*/ true);
643
7
    break;
644
526
  }
645
526
}
646
647
1.26k
static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
648
1.26k
  if (const Expr *e = dyn_cast<Expr>(s)) {
649
    // Skip the most common kinds of expressions that make
650
    // hierarchy-walking expensive.
651
1.25k
    s = e = e->IgnoreParenCasts();
652
653
1.25k
    if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
654
523
      return (ref->getDecl() == &var);
655
730
    if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
656
121
      const BlockDecl *block = be->getBlockDecl();
657
370
      for (const auto &I : block->captures()) {
658
370
        if (I.getVariable() == &var)
659
2
          return true;
660
370
      }
661
121
    }
662
730
  }
663
664
744
  for (const Stmt *SubStmt : s->children())
665
    // SubStmt might be null; as in missing decl or conditional of an if-stmt.
666
364
    if (SubStmt && isAccessedBy(var, SubStmt))
667
15
      return true;
668
669
729
  return false;
670
744
}
671
672
1.01k
static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
673
1.01k
  if (!decl) 
return false78
;
674
938
  if (!isa<VarDecl>(decl)) 
return false33
;
675
905
  const VarDecl *var = cast<VarDecl>(decl);
676
905
  return isAccessedBy(*var, e);
677
905
}
678
679
static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
680
321
                                   const LValue &destLV, const Expr *init) {
681
321
  bool needsCast = false;
682
683
332
  while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
684
192
    switch (castExpr->getCastKind()) {
685
    // Look through casts that don't require representation changes.
686
11
    case CK_NoOp:
687
11
    case CK_BitCast:
688
11
    case CK_BlockPointerToObjCPointerCast:
689
11
      needsCast = true;
690
11
      break;
691
692
    // If we find an l-value to r-value cast from a __weak variable,
693
    // emit this operation as a copy or move.
694
167
    case CK_LValueToRValue: {
695
167
      const Expr *srcExpr = castExpr->getSubExpr();
696
167
      if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
697
9
        return false;
698
699
      // Emit the source l-value.
700
158
      LValue srcLV = CGF.EmitLValue(srcExpr);
701
702
      // Handle a formal type change to avoid asserting.
703
158
      auto srcAddr = srcLV.getAddress(CGF);
704
158
      if (needsCast) {
705
3
        srcAddr = CGF.Builder.CreateElementBitCast(
706
3
            srcAddr, destLV.getAddress(CGF).getElementType());
707
3
      }
708
709
      // If it was an l-value, use objc_copyWeak.
710
158
      if (srcExpr->getValueKind() == VK_LValue) {
711
155
        CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
712
3
      } else {
713
3
        assert(srcExpr->getValueKind() == VK_XValue);
714
3
        CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
715
3
      }
716
158
      return true;
717
158
    }
718
719
    // Stop at anything else.
720
14
    default:
721
14
      return false;
722
11
    }
723
724
11
    init = castExpr->getSubExpr();
725
11
  }
726
140
  return false;
727
321
}
728
729
static void drillIntoBlockVariable(CodeGenFunction &CGF,
730
                                   LValue &lvalue,
731
15
                                   const VarDecl *var) {
732
15
  lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
733
15
}
734
735
void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
736
305k
                                           SourceLocation Loc) {
737
305k
  if (!SanOpts.has(SanitizerKind::NullabilityAssign))
738
305k
    return;
739
740
18
  auto Nullability = LHS.getType()->getNullability(getContext());
741
18
  if (!Nullability || 
*Nullability != NullabilityKind::NonNull14
)
742
4
    return;
743
744
  // Check if the right hand side of the assignment is nonnull, if the left
745
  // hand side must be nonnull.
746
14
  SanitizerScope SanScope(this);
747
14
  llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
748
14
  llvm::Constant *StaticData[] = {
749
14
      EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
750
14
      llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
751
14
      llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
752
14
  EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
753
14
            SanitizerHandler::TypeMismatch, StaticData, RHS);
754
14
}
755
756
void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
757
157k
                                     LValue lvalue, bool capturedByInit) {
758
157k
  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
759
157k
  if (!lifetime) {
760
156k
    llvm::Value *value = EmitScalarExpr(init);
761
156k
    if (capturedByInit)
762
4
      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
763
156k
    EmitNullabilityCheck(lvalue, value, init->getExprLoc());
764
156k
    EmitStoreThroughLValue(RValue::get(value), lvalue, true);
765
156k
    return;
766
156k
  }
767
768
1.11k
  if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
769
1
    init = DIE->getExpr();
770
771
  // If we're emitting a value with lifetime, we have to do the
772
  // initialization *before* we leave the cleanup scopes.
773
1.11k
  if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(init))
774
342
    init = EWC->getSubExpr();
775
1.11k
  CodeGenFunction::RunCleanupsScope Scope(*this);
776
777
  // We have to maintain the illusion that the variable is
778
  // zero-initialized.  If the variable might be accessed in its
779
  // initializer, zero-initialize before running the initializer, then
780
  // actually perform the initialization with an assign.
781
1.11k
  bool accessedByInit = false;
782
1.11k
  if (lifetime != Qualifiers::OCL_ExplicitNone)
783
1.01k
    accessedByInit = (capturedByInit || 
isAccessedBy(D, init)1.01k
);
784
1.11k
  if (accessedByInit) {
785
19
    LValue tempLV = lvalue;
786
    // Drill down to the __block object if necessary.
787
19
    if (capturedByInit) {
788
      // We can use a simple GEP for this because it can't have been
789
      // moved yet.
790
2
      tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
791
2
                                              cast<VarDecl>(D),
792
2
                                              /*follow*/ false));
793
2
    }
794
795
19
    auto ty =
796
19
        cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
797
19
    llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
798
799
    // If __weak, we want to use a barrier under certain conditions.
800
19
    if (lifetime == Qualifiers::OCL_Weak)
801
4
      EmitARCInitWeak(tempLV.getAddress(*this), zero);
802
803
    // Otherwise just do a simple store.
804
15
    else
805
15
      EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
806
19
  }
807
808
  // Emit the initializer.
809
1.11k
  llvm::Value *value = nullptr;
810
811
1.11k
  switch (lifetime) {
812
0
  case Qualifiers::OCL_None:
813
0
    llvm_unreachable("present but none");
814
815
688
  case Qualifiers::OCL_Strong: {
816
688
    if (!D || 
!isa<VarDecl>(D)616
||
!cast<VarDecl>(D)->isARCPseudoStrong()591
) {
817
684
      value = EmitARCRetainScalarExpr(init);
818
684
      break;
819
684
    }
820
    // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
821
    // that we omit the retain, and causes non-autoreleased return values to be
822
    // immediately released.
823
4
    LLVM_FALLTHROUGH;
824
4
  }
825
826
101
  case Qualifiers::OCL_ExplicitNone:
827
101
    value = EmitARCUnsafeUnretainedScalarExpr(init);
828
101
    break;
829
830
325
  case Qualifiers::OCL_Weak: {
831
    // If it's not accessed by the initializer, try to emit the
832
    // initialization with a copy or move.
833
325
    if (!accessedByInit && 
tryEmitARCCopyWeakInit(*this, lvalue, init)321
) {
834
158
      return;
835
158
    }
836
837
    // No way to optimize a producing initializer into this.  It's not
838
    // worth optimizing for, because the value will immediately
839
    // disappear in the common case.
840
167
    value = EmitScalarExpr(init);
841
842
167
    if (capturedByInit) 
drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D))0
;
843
167
    if (accessedByInit)
844
4
      EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
845
163
    else
846
163
      EmitARCInitWeak(lvalue.getAddress(*this), value);
847
167
    return;
848
167
  }
849
850
5
  case Qualifiers::OCL_Autoreleasing:
851
5
    value = EmitARCRetainAutoreleaseScalarExpr(init);
852
5
    break;
853
790
  }
854
855
790
  if (capturedByInit) 
drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D))2
;
856
857
790
  EmitNullabilityCheck(lvalue, value, init->getExprLoc());
858
859
  // If the variable might have been accessed by its initializer, we
860
  // might have to initialize with a barrier.  We have to do this for
861
  // both __weak and __strong, but __weak got filtered out above.
862
790
  if (accessedByInit && 
lifetime == Qualifiers::OCL_Strong15
) {
863
11
    llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
864
11
    EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
865
11
    EmitARCRelease(oldValue, ARCImpreciseLifetime);
866
11
    return;
867
11
  }
868
869
779
  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
870
779
}
871
872
/// Decide whether we can emit the non-zero parts of the specified initializer
873
/// with equal or fewer than NumStores scalar stores.
874
static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
875
102k
                                               unsigned &NumStores) {
876
  // Zero and Undef never requires any extra stores.
877
102k
  if (isa<llvm::ConstantAggregateZero>(Init) ||
878
102k
      isa<llvm::ConstantPointerNull>(Init) ||
879
102k
      isa<llvm::UndefValue>(Init))
880
57
    return true;
881
102k
  if (isa<llvm::ConstantInt>(Init) || 
isa<llvm::ConstantFP>(Init)402
||
882
328
      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
883
323
      isa<llvm::ConstantExpr>(Init))
884
102k
    return Init->isNullValue() || 
NumStores--1.04k
;
885
886
  // See if we can emit each element.
887
308
  if (isa<llvm::ConstantArray>(Init) || 
isa<llvm::ConstantStruct>(Init)259
) {
888
685
    for (unsigned i = 0, e = Init->getNumOperands(); i != e; 
++i494
) {
889
573
      llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
890
573
      if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
891
79
        return false;
892
573
    }
893
112
    return true;
894
117
  }
895
896
117
  if (llvm::ConstantDataSequential *CDS =
897
117
        dyn_cast<llvm::ConstantDataSequential>(Init)) {
898
101k
    for (unsigned i = 0, e = CDS->getNumElements(); i != e; 
++i101k
) {
899
101k
      llvm::Constant *Elt = CDS->getElementAsConstant(i);
900
101k
      if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
901
81
        return false;
902
101k
    }
903
36
    return true;
904
0
  }
905
906
  // Anything else is hard and scary.
907
0
  return false;
908
0
}
909
910
/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
911
/// the scalar stores that would be required.
912
static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
913
                                        llvm::Constant *Init, Address Loc,
914
                                        bool isVolatile, CGBuilderTy &Builder,
915
247
                                        bool IsAutoInit) {
916
247
  assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
917
247
         "called emitStoresForInitAfterBZero for zero or undef value.");
918
919
247
  if (isa<llvm::ConstantInt>(Init) || 
isa<llvm::ConstantFP>(Init)111
||
920
79
      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
921
188
      
isa<llvm::ConstantExpr>(Init)74
) {
922
188
    auto *I = Builder.CreateStore(Init, Loc, isVolatile);
923
188
    if (IsAutoInit)
924
0
      I->addAnnotationMetadata("auto-init");
925
188
    return;
926
188
  }
927
928
59
  if (llvm::ConstantDataSequential *CDS =
929
24
          dyn_cast<llvm::ConstantDataSequential>(Init)) {
930
101k
    for (unsigned i = 0, e = CDS->getNumElements(); i != e; 
++i101k
) {
931
101k
      llvm::Constant *Elt = CDS->getElementAsConstant(i);
932
933
      // If necessary, get a pointer to the element and emit it.
934
101k
      if (!Elt->isNullValue() && 
!isa<llvm::UndefValue>(Elt)103
)
935
103
        emitStoresForInitAfterBZero(
936
103
            CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
937
103
            Builder, IsAutoInit);
938
101k
    }
939
24
    return;
940
24
  }
941
942
35
  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
943
35
         "Unknown value type!");
944
945
178
  for (unsigned i = 0, e = Init->getNumOperands(); i != e; 
++i143
) {
946
143
    llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
947
948
    // If necessary, get a pointer to the element and emit it.
949
143
    if (!Elt->isNullValue() && 
!isa<llvm::UndefValue>(Elt)90
)
950
88
      emitStoresForInitAfterBZero(CGM, Elt,
951
88
                                  Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
952
88
                                  isVolatile, Builder, IsAutoInit);
953
143
  }
954
35
}
955
956
/// Decide whether we should use bzero plus some stores to initialize a local
957
/// variable instead of using a memcpy from a constant global.  It is beneficial
958
/// to use bzero if the global is all zeros, or mostly zeros and large.
959
static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
960
4.86k
                                                 uint64_t GlobalSize) {
961
  // If a global is all zeros, always use a bzero.
962
4.86k
  if (isa<llvm::ConstantAggregateZero>(Init)) 
return true1.05k
;
963
964
  // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
965
  // do it if it will require 6 or fewer scalar stores.
966
  // TODO: Should budget depends on the size?  Avoiding a large global warrants
967
  // plopping in more stores.
968
3.81k
  unsigned StoreBudget = 6;
969
3.81k
  uint64_t SizeLimit = 32;
970
971
3.81k
  return GlobalSize > SizeLimit &&
972
178
         canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
973
3.81k
}
974
975
/// Decide whether we should use memset to initialize a local variable instead
976
/// of using a memcpy from a constant global. Assumes we've already decided to
977
/// not user bzero.
978
/// FIXME We could be more clever, as we are for bzero above, and generate
979
///       memset followed by stores. It's unclear that's worth the effort.
980
static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
981
                                                uint64_t GlobalSize,
982
3.76k
                                                const llvm::DataLayout &DL) {
983
3.76k
  uint64_t SizeLimit = 32;
984
3.76k
  if (GlobalSize <= SizeLimit)
985
3.63k
    return nullptr;
986
122
  return llvm::isBytewiseValue(Init, DL);
987
122
}
988
989
/// Decide whether we want to split a constant structure or array store into a
990
/// sequence of its fields' stores. This may cost us code size and compilation
991
/// speed, but plays better with store optimizations.
992
static bool shouldSplitConstantStore(CodeGenModule &CGM,
993
3.71k
                                     uint64_t GlobalByteSize) {
994
  // Don't break things that occupy more than one cacheline.
995
3.71k
  uint64_t ByteSizeLimit = 64;
996
3.71k
  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
997
3.42k
    return false;
998
299
  if (GlobalByteSize <= ByteSizeLimit)
999
299
    return true;
1000
0
  return false;
1001
0
}
1002
1003
enum class IsPattern { No, Yes };
1004
1005
/// Generate a constant filled with either a pattern or zeroes.
1006
static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1007
355
                                        llvm::Type *Ty) {
1008
355
  if (isPattern == IsPattern::Yes)
1009
172
    return initializationPatternFor(CGM, Ty);
1010
183
  else
1011
183
    return llvm::Constant::getNullValue(Ty);
1012
355
}
1013
1014
static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1015
                                        llvm::Constant *constant);
1016
1017
/// Helper function for constWithPadding() to deal with padding in structures.
1018
static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1019
                                              IsPattern isPattern,
1020
                                              llvm::StructType *STy,
1021
832
                                              llvm::Constant *constant) {
1022
832
  const llvm::DataLayout &DL = CGM.getDataLayout();
1023
832
  const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1024
832
  llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1025
832
  unsigned SizeSoFar = 0;
1026
832
  SmallVector<llvm::Constant *, 8> Values;
1027
832
  bool NestedIntact = true;
1028
2.64k
  for (unsigned i = 0, e = STy->getNumElements(); i != e; 
i++1.81k
) {
1029
1.81k
    unsigned CurOff = Layout->getElementOffset(i);
1030
1.81k
    if (SizeSoFar < CurOff) {
1031
82
      assert(!STy->isPacked());
1032
82
      auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1033
82
      Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1034
82
    }
1035
1.81k
    llvm::Constant *CurOp;
1036
1.81k
    if (constant->isZeroValue())
1037
422
      CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1038
1.38k
    else
1039
1.38k
      CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1040
1.81k
    auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1041
1.81k
    if (CurOp != NewOp)
1042
35
      NestedIntact = false;
1043
1.81k
    Values.push_back(NewOp);
1044
1.81k
    SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1045
1.81k
  }
1046
832
  unsigned TotalSize = Layout->getSizeInBytes();
1047
832
  if (SizeSoFar < TotalSize) {
1048
203
    auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1049
203
    Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1050
203
  }
1051
832
  if (NestedIntact && 
Values.size() == STy->getNumElements()811
)
1052
526
    return constant;
1053
306
  return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1054
306
}
1055
1056
/// Replace all padding bytes in a given constant with either a pattern byte or
1057
/// 0x00.
1058
static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1059
69.7k
                                        llvm::Constant *constant) {
1060
69.7k
  llvm::Type *OrigTy = constant->getType();
1061
69.7k
  if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1062
832
    return constStructWithPadding(CGM, isPattern, STy, constant);
1063
68.9k
  if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1064
219
    llvm::SmallVector<llvm::Constant *, 8> Values;
1065
219
    uint64_t Size = ArrayTy->getNumElements();
1066
219
    if (!Size)
1067
14
      return constant;
1068
205
    llvm::Type *ElemTy = ArrayTy->getElementType();
1069
205
    bool ZeroInitializer = constant->isNullValue();
1070
205
    llvm::Constant *OpValue, *PaddedOp;
1071
205
    if (ZeroInitializer) {
1072
69
      OpValue = llvm::Constant::getNullValue(ElemTy);
1073
69
      PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1074
69
    }
1075
395k
    for (unsigned Op = 0; Op != Size; 
++Op394k
) {
1076
394k
      if (!ZeroInitializer) {
1077
66.7k
        OpValue = constant->getAggregateElement(Op);
1078
66.7k
        PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1079
66.7k
      }
1080
394k
      Values.push_back(PaddedOp);
1081
394k
    }
1082
205
    auto *NewElemTy = Values[0]->getType();
1083
205
    if (NewElemTy == ElemTy)
1084
169
      return constant;
1085
36
    auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1086
36
    return llvm::ConstantArray::get(NewArrayTy, Values);
1087
36
  }
1088
  // FIXME: Add handling for tail padding in vectors. Vectors don't
1089
  // have padding between or inside elements, but the total amount of
1090
  // data can be less than the allocated size.
1091
68.7k
  return constant;
1092
68.7k
}
1093
1094
Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1095
                                               llvm::Constant *Constant,
1096
3.61k
                                               CharUnits Align) {
1097
3.60k
  auto FunctionName = [&](const DeclContext *DC) -> std::string {
1098
3.60k
    if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1099
3.59k
      if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1100
1
        return CC->getNameAsString();
1101
3.59k
      if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1102
0
        return CD->getNameAsString();
1103
3.59k
      return std::string(getMangledName(FD));
1104
14
    } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1105
7
      return OM->getNameAsString();
1106
7
    } else if (isa<BlockDecl>(DC)) {
1107
0
      return "<block>";
1108
7
    } else if (isa<CapturedDecl>(DC)) {
1109
7
      return "<captured>";
1110
0
    } else {
1111
0
      llvm_unreachable("expected a function or method");
1112
0
    }
1113
3.60k
  };
1114
1115
  // Form a simple per-variable cache of these values in case we find we
1116
  // want to reuse them.
1117
3.61k
  llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1118
3.61k
  if (!CacheEntry || 
CacheEntry->getInitializer() != Constant6
) {
1119
3.60k
    auto *Ty = Constant->getType();
1120
3.60k
    bool isConstant = true;
1121
3.60k
    llvm::GlobalVariable *InsertBefore = nullptr;
1122
3.60k
    unsigned AS =
1123
3.60k
        getContext().getTargetAddressSpace(getStringLiteralAddressSpace());
1124
3.60k
    std::string Name;
1125
3.60k
    if (D.hasGlobalStorage())
1126
2
      Name = getMangledName(&D).str() + ".const";
1127
3.60k
    else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1128
3.60k
      Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1129
3.60k
    else
1130
0
      llvm_unreachable("local variable has no parent function or method");
1131
3.60k
    llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1132
3.60k
        getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1133
3.60k
        Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1134
3.60k
    GV->setAlignment(Align.getAsAlign());
1135
3.60k
    GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1136
3.60k
    CacheEntry = GV;
1137
6
  } else if (CacheEntry->getAlignment() < Align.getQuantity()) {
1138
0
    CacheEntry->setAlignment(Align.getAsAlign());
1139
0
  }
1140
1141
3.61k
  return Address(CacheEntry, Align);
1142
3.61k
}
1143
1144
static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1145
                                                const VarDecl &D,
1146
                                                CGBuilderTy &Builder,
1147
                                                llvm::Constant *Constant,
1148
3.60k
                                                CharUnits Align) {
1149
3.60k
  Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1150
3.60k
  llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
1151
3.60k
                                                   SrcPtr.getAddressSpace());
1152
3.60k
  if (SrcPtr.getType() != BP)
1153
3.60k
    SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1154
3.60k
  return SrcPtr;
1155
3.60k
}
1156
1157
static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1158
                                  Address Loc, bool isVolatile,
1159
                                  CGBuilderTy &Builder,
1160
5.56k
                                  llvm::Constant *constant, bool IsAutoInit) {
1161
5.56k
  auto *Ty = constant->getType();
1162
5.56k
  uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1163
5.56k
  if (!ConstantSize)
1164
19
    return;
1165
1166
5.55k
  bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1167
5.10k
                          Ty->isPtrOrPtrVectorTy() || 
Ty->isFPOrFPVectorTy()5.01k
;
1168
5.55k
  if (canDoSingleStore) {
1169
683
    auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1170
683
    if (IsAutoInit)
1171
683
      I->addAnnotationMetadata("auto-init");
1172
683
    return;
1173
683
  }
1174
1175
4.86k
  auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1176
1177
  // If the initializer is all or mostly the same, codegen with bzero / memset
1178
  // then do a few stores afterward.
1179
4.86k
  if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1180
1.10k
    auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1181
1.10k
                                   SizeVal, isVolatile);
1182
1.10k
    if (IsAutoInit)
1183
167
      I->addAnnotationMetadata("auto-init");
1184
1185
1.10k
    bool valueAlreadyCorrect =
1186
1.10k
        constant->isNullValue() || 
isa<llvm::UndefValue>(constant)56
;
1187
1.10k
    if (!valueAlreadyCorrect) {
1188
56
      Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
1189
56
      emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1190
56
                                  IsAutoInit);
1191
56
    }
1192
1.10k
    return;
1193
1.10k
  }
1194
1195
  // If the initializer is a repeated byte pattern, use memset.
1196
3.76k
  llvm::Value *Pattern =
1197
3.76k
      shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1198
3.76k
  if (Pattern) {
1199
42
    uint64_t Value = 0x00;
1200
42
    if (!isa<llvm::UndefValue>(Pattern)) {
1201
42
      const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1202
42
      assert(AP.getBitWidth() <= 8);
1203
42
      Value = AP.getLimitedValue();
1204
42
    }
1205
42
    auto *I = Builder.CreateMemSet(
1206
42
        Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1207
42
    if (IsAutoInit)
1208
17
      I->addAnnotationMetadata("auto-init");
1209
42
    return;
1210
42
  }
1211
1212
  // If the initializer is small, use a handful of stores.
1213
3.71k
  if (shouldSplitConstantStore(CGM, ConstantSize)) {
1214
299
    if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1215
      // FIXME: handle the case when STy != Loc.getElementType().
1216
258
      if (STy == Loc.getElementType()) {
1217
256
        for (unsigned i = 0; i != constant->getNumOperands(); 
i++154
) {
1218
154
          Address EltPtr = Builder.CreateStructGEP(Loc, i);
1219
154
          emitStoresForConstant(
1220
154
              CGM, D, EltPtr, isVolatile, Builder,
1221
154
              cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1222
154
              IsAutoInit);
1223
154
        }
1224
102
        return;
1225
102
      }
1226
41
    } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1227
      // FIXME: handle the case when ATy != Loc.getElementType().
1228
41
      if (ATy == Loc.getElementType()) {
1229
64
        for (unsigned i = 0; i != ATy->getNumElements(); 
i++48
) {
1230
48
          Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1231
48
          emitStoresForConstant(
1232
48
              CGM, D, EltPtr, isVolatile, Builder,
1233
48
              cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1234
48
              IsAutoInit);
1235
48
        }
1236
16
        return;
1237
16
      }
1238
3.60k
    }
1239
299
  }
1240
1241
  // Copy from a global.
1242
3.60k
  auto *I =
1243
3.60k
      Builder.CreateMemCpy(Loc,
1244
3.60k
                           createUnnamedGlobalForMemcpyFrom(
1245
3.60k
                               CGM, D, Builder, constant, Loc.getAlignment()),
1246
3.60k
                           SizeVal, isVolatile);
1247
3.60k
  if (IsAutoInit)
1248
120
    I->addAnnotationMetadata("auto-init");
1249
3.60k
}
1250
1251
static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1252
                                  Address Loc, bool isVolatile,
1253
391
                                  CGBuilderTy &Builder) {
1254
391
  llvm::Type *ElTy = Loc.getElementType();
1255
391
  llvm::Constant *constant =
1256
391
      constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1257
391
  emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1258
391
                        /*IsAutoInit=*/true);
1259
391
}
1260
1261
static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1262
                                     Address Loc, bool isVolatile,
1263
514
                                     CGBuilderTy &Builder) {
1264
514
  llvm::Type *ElTy = Loc.getElementType();
1265
514
  llvm::Constant *constant = constWithPadding(
1266
514
      CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1267
514
  assert(!isa<llvm::UndefValue>(constant));
1268
514
  emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1269
514
                        /*IsAutoInit=*/true);
1270
514
}
1271
1272
1.01k
static bool containsUndef(llvm::Constant *constant) {
1273
1.01k
  auto *Ty = constant->getType();
1274
1.01k
  if (isa<llvm::UndefValue>(constant))
1275
49
    return true;
1276
968
  if (Ty->isStructTy() || 
Ty->isArrayTy()687
||
Ty->isVectorTy()625
)
1277
343
    for (llvm::Use &Op : constant->operands())
1278
827
      if (containsUndef(cast<llvm::Constant>(Op)))
1279
49
        return true;
1280
919
  return false;
1281
968
}
1282
1283
static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1284
323
                                    llvm::Constant *constant) {
1285
323
  auto *Ty = constant->getType();
1286
323
  if (isa<llvm::UndefValue>(constant))
1287
70
    return patternOrZeroFor(CGM, isPattern, Ty);
1288
253
  if (!(Ty->isStructTy() || 
Ty->isArrayTy()105
||
Ty->isVectorTy()63
))
1289
63
    return constant;
1290
190
  if (!containsUndef(constant))
1291
141
    return constant;
1292
49
  llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1293
175
  for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; 
++Op126
) {
1294
126
    auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1295
126
    Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1296
126
  }
1297
49
  if (Ty->isStructTy())
1298
49
    return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1299
0
  if (Ty->isArrayTy())
1300
0
    return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1301
0
  assert(Ty->isVectorTy());
1302
0
  return llvm::ConstantVector::get(Values);
1303
0
}
1304
1305
/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1306
/// variable declaration with auto, register, or no storage class specifier.
1307
/// These turn into simple stack objects, or GlobalValues depending on target.
1308
196k
void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1309
196k
  AutoVarEmission emission = EmitAutoVarAlloca(D);
1310
196k
  EmitAutoVarInit(emission);
1311
196k
  EmitAutoVarCleanups(emission);
1312
196k
}
1313
1314
/// Emit a lifetime.begin marker if some criteria are satisfied.
1315
/// \return a pointer to the temporary size Value if a marker was emitted, null
1316
/// otherwise
1317
llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1318
212k
                                                llvm::Value *Addr) {
1319
212k
  if (!ShouldEmitLifetimeMarkers)
1320
206k
    return nullptr;
1321
1322
5.84k
  assert(Addr->getType()->getPointerAddressSpace() ==
1323
5.84k
             CGM.getDataLayout().getAllocaAddrSpace() &&
1324
5.84k
         "Pointer should be in alloca address space");
1325
5.84k
  llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
1326
5.84k
  Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1327
5.84k
  llvm::CallInst *C =
1328
5.84k
      Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1329
5.84k
  C->setDoesNotThrow();
1330
5.84k
  return SizeV;
1331
5.84k
}
1332
1333
6.13k
void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1334
6.13k
  assert(Addr->getType()->getPointerAddressSpace() ==
1335
6.13k
             CGM.getDataLayout().getAllocaAddrSpace() &&
1336
6.13k
         "Pointer should be in alloca address space");
1337
6.13k
  Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1338
6.13k
  llvm::CallInst *C =
1339
6.13k
      Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1340
6.13k
  C->setDoesNotThrow();
1341
6.13k
}
1342
1343
void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1344
2.14k
    CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1345
  // For each dimension stores its QualType and corresponding
1346
  // size-expression Value.
1347
2.14k
  SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1348
2.14k
  SmallVector<IdentifierInfo *, 4> VLAExprNames;
1349
1350
  // Break down the array into individual dimensions.
1351
2.14k
  QualType Type1D = D.getType();
1352
5.33k
  while (getContext().getAsVariableArrayType(Type1D)) {
1353
3.18k
    auto VlaSize = getVLAElements1D(Type1D);
1354
3.18k
    if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1355
889
      Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1356
2.29k
    else {
1357
      // Generate a locally unique name for the size expression.
1358
2.29k
      Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1359
2.29k
      SmallString<12> Buffer;
1360
2.29k
      StringRef NameRef = Name.toStringRef(Buffer);
1361
2.29k
      auto &Ident = getContext().Idents.getOwn(NameRef);
1362
2.29k
      VLAExprNames.push_back(&Ident);
1363
2.29k
      auto SizeExprAddr =
1364
2.29k
          CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1365
2.29k
      Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1366
2.29k
      Dimensions.emplace_back(SizeExprAddr.getPointer(),
1367
2.29k
                              Type1D.getUnqualifiedType());
1368
2.29k
    }
1369
3.18k
    Type1D = VlaSize.Type;
1370
3.18k
  }
1371
1372
2.14k
  if (!EmitDebugInfo)
1373
2.10k
    return;
1374
1375
  // Register each dimension's size-expression with a DILocalVariable,
1376
  // so that it can be used by CGDebugInfo when instantiating a DISubrange
1377
  // to describe this array.
1378
40
  unsigned NameIdx = 0;
1379
41
  for (auto &VlaSize : Dimensions) {
1380
41
    llvm::Metadata *MD;
1381
41
    if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1382
1
      MD = llvm::ConstantAsMetadata::get(C);
1383
40
    else {
1384
      // Create an artificial VarDecl to generate debug info for.
1385
40
      IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1386
40
      auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1387
40
      auto QT = getContext().getIntTypeForBitwidth(
1388
40
          VlaExprTy->getScalarSizeInBits(), false);
1389
40
      auto *ArtificialDecl = VarDecl::Create(
1390
40
          getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1391
40
          D.getLocation(), D.getLocation(), NameIdent, QT,
1392
40
          getContext().CreateTypeSourceInfo(QT), SC_Auto);
1393
40
      ArtificialDecl->setImplicit();
1394
1395
40
      MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1396
40
                                         Builder);
1397
40
    }
1398
41
    assert(MD && "No Size expression debug node created");
1399
41
    DI->registerVLASizeExpression(VlaSize.Type, MD);
1400
41
  }
1401
40
}
1402
1403
/// EmitAutoVarAlloca - Emit the alloca and debug information for a
1404
/// local variable.  Does not emit initialization or destruction.
1405
CodeGenFunction::AutoVarEmission
1406
215k
CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1407
215k
  QualType Ty = D.getType();
1408
215k
  assert(
1409
215k
      Ty.getAddressSpace() == LangAS::Default ||
1410
215k
      (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1411
1412
215k
  AutoVarEmission emission(D);
1413
1414
215k
  bool isEscapingByRef = D.isEscapingByref();
1415
215k
  emission.IsEscapingByRef = isEscapingByRef;
1416
1417
215k
  CharUnits alignment = getContext().getDeclAlign(&D);
1418
1419
  // If the type is variably-modified, emit all the VLA sizes for it.
1420
215k
  if (Ty->isVariablyModifiedType())
1421
2.22k
    EmitVariablyModifiedType(Ty);
1422
1423
215k
  auto *DI = getDebugInfo();
1424
215k
  bool EmitDebugInfo = DI && 
CGM.getCodeGenOpts().hasReducedDebugInfo()66.6k
;
1425
1426
215k
  Address address = Address::invalid();
1427
215k
  Address AllocaAddr = Address::invalid();
1428
215k
  Address OpenMPLocalAddr = Address::invalid();
1429
215k
  if (CGM.getLangOpts().OpenMPIRBuilder)
1430
222
    OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1431
214k
  else
1432
214k
    OpenMPLocalAddr =
1433
214k
        getLangOpts().OpenMP
1434
118k
            ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1435
96.6k
            : Address::invalid();
1436
1437
215k
  bool NRVO = getLangOpts().ElideConstructors && 
D.isNRVOVariable()215k
;
1438
1439
215k
  if (getLangOpts().OpenMP && 
OpenMPLocalAddr.isValid()118k
) {
1440
126
    address = OpenMPLocalAddr;
1441
214k
  } else if (Ty->isConstantSizeType()) {
1442
    // If this value is an array or struct with a statically determinable
1443
    // constant initializer, there are optimizations we can do.
1444
    //
1445
    // TODO: We should constant-evaluate the initializer of any variable,
1446
    // as long as it is initialized by a constant expression. Currently,
1447
    // isConstantInitializer produces wrong answers for structs with
1448
    // reference or bitfield members, and a few other cases, and checking
1449
    // for POD-ness protects us from some of these.
1450
212k
    if (D.getInit() && 
(159k
Ty->isArrayType()159k
||
Ty->isRecordType()154k
) &&
1451
21.0k
        (D.isConstexpr() ||
1452
20.8k
         ((Ty.isPODType(getContext()) ||
1453
11.5k
           getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1454
9.33k
          D.getInit()->isConstantInitializer(getContext(), false)))) {
1455
1456
      // If the variable's a const type, and it's neither an NRVO
1457
      // candidate nor a __block variable and has no mutable members,
1458
      // emit it as a global instead.
1459
      // Exception is if a variable is located in non-constant address space
1460
      // in OpenCL.
1461
7.84k
      if ((!getLangOpts().OpenCL ||
1462
84
           Ty.getAddressSpace() == LangAS::opencl_constant) &&
1463
7.76k
          (CGM.getCodeGenOpts().MergeAllConstants && 
!NRVO88
&&
1464
88
           !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
1465
6
        EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1466
1467
        // Signal this condition to later callbacks.
1468
6
        emission.Addr = Address::invalid();
1469
6
        assert(emission.wasEmittedAsGlobal());
1470
6
        return emission;
1471
6
      }
1472
1473
      // Otherwise, tell the initialization code that we're in this case.
1474
7.83k
      emission.IsConstantAggregate = true;
1475
7.83k
    }
1476
1477
    // A normal fixed sized variable becomes an alloca in the entry block,
1478
    // unless:
1479
    // - it's an NRVO variable.
1480
    // - we are compiling OpenMP and it's an OpenMP local variable.
1481
212k
    if (NRVO) {
1482
      // The named return value optimization: allocate this variable in the
1483
      // return slot, so that we can elide the copy when returning this
1484
      // variable (C++0x [class.copy]p34).
1485
1.28k
      address = ReturnValue;
1486
1487
1.28k
      if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1488
1.28k
        const auto *RD = RecordTy->getDecl();
1489
1.28k
        const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1490
1.28k
        if ((CXXRD && 
!CXXRD->hasTrivialDestructor()451
) ||
1491
1.09k
            RD->isNonTrivialToPrimitiveDestroy()) {
1492
          // Create a flag that is used to indicate when the NRVO was applied
1493
          // to this variable. Set it to zero to indicate that NRVO was not
1494
          // applied.
1495
197
          llvm::Value *Zero = Builder.getFalse();
1496
197
          Address NRVOFlag =
1497
197
            CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1498
197
          EnsureInsertPoint();
1499
197
          Builder.CreateStore(Zero, NRVOFlag);
1500
1501
          // Record the NRVO flag for this variable.
1502
197
          NRVOFlags[&D] = NRVOFlag.getPointer();
1503
197
          emission.NRVOFlag = NRVOFlag.getPointer();
1504
197
        }
1505
1.28k
      }
1506
211k
    } else {
1507
211k
      CharUnits allocaAlignment;
1508
211k
      llvm::Type *allocaTy;
1509
211k
      if (isEscapingByRef) {
1510
206
        auto &byrefInfo = getBlockByrefInfo(&D);
1511
206
        allocaTy = byrefInfo.Type;
1512
206
        allocaAlignment = byrefInfo.ByrefAlignment;
1513
211k
      } else {
1514
211k
        allocaTy = ConvertTypeForMem(Ty);
1515
211k
        allocaAlignment = alignment;
1516
211k
      }
1517
1518
      // Create the alloca.  Note that we set the name separately from
1519
      // building the instruction so that it's there even in no-asserts
1520
      // builds.
1521
211k
      address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1522
211k
                                 /*ArraySize=*/nullptr, &AllocaAddr);
1523
1524
      // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1525
      // the catch parameter starts in the catchpad instruction, and we can't
1526
      // insert code in those basic blocks.
1527
211k
      bool IsMSCatchParam =
1528
211k
          D.isExceptionVariable() && 
getTarget().getCXXABI().isMicrosoft()367
;
1529
1530
      // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1531
      // if we don't have a valid insertion point (?).
1532
211k
      if (HaveInsertPoint() && 
!IsMSCatchParam211k
) {
1533
        // If there's a jump into the lifetime of this variable, its lifetime
1534
        // gets broken up into several regions in IR, which requires more work
1535
        // to handle correctly. For now, just omit the intrinsics; this is a
1536
        // rare case, and it's better to just be conservatively correct.
1537
        // PR28267.
1538
        //
1539
        // We have to do this in all language modes if there's a jump past the
1540
        // declaration. We also have to do it in C if there's a jump to an
1541
        // earlier point in the current block because non-VLA lifetimes begin as
1542
        // soon as the containing block is entered, not when its variables
1543
        // actually come into scope; suppressing the lifetime annotations
1544
        // completely in this case is unnecessarily pessimistic, but again, this
1545
        // is rare.
1546
211k
        if (!Bypasses.IsBypassed(&D) &&
1547
211k
            !(!getLangOpts().CPlusPlus && 
hasLabelBeenSeenInCurrentScope()34.4k
)) {
1548
211k
          llvm::TypeSize size =
1549
211k
              CGM.getDataLayout().getTypeAllocSize(allocaTy);
1550
211k
          emission.SizeForLifetimeMarkers =
1551
126
              size.isScalable() ? EmitLifetimeStart(-1, AllocaAddr.getPointer())
1552
211k
                                : EmitLifetimeStart(size.getFixedSize(),
1553
211k
                                                    AllocaAddr.getPointer());
1554
211k
        }
1555
41
      } else {
1556
41
        assert(!emission.useLifetimeMarkers());
1557
41
      }
1558
211k
    }
1559
2.14k
  } else {
1560
2.14k
    EnsureInsertPoint();
1561
1562
2.14k
    if (!DidCallStackSave) {
1563
      // Save the stack.
1564
1.58k
      Address Stack =
1565
1.58k
        CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1566
1567
1.58k
      llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1568
1.58k
      llvm::Value *V = Builder.CreateCall(F);
1569
1.58k
      Builder.CreateStore(V, Stack);
1570
1571
1.58k
      DidCallStackSave = true;
1572
1573
      // Push a cleanup block and restore the stack there.
1574
      // FIXME: in general circumstances, this should be an EH cleanup.
1575
1.58k
      pushStackRestore(NormalCleanup, Stack);
1576
1.58k
    }
1577
1578
2.14k
    auto VlaSize = getVLASize(Ty);
1579
2.14k
    llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1580
1581
    // Allocate memory for the array.
1582
2.14k
    address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1583
2.14k
                               &AllocaAddr);
1584
1585
    // If we have debug info enabled, properly describe the VLA dimensions for
1586
    // this type by registering the vla size expression for each of the
1587
    // dimensions.
1588
2.14k
    EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1589
2.14k
  }
1590
1591
215k
  setAddrOfLocalVar(&D, address);
1592
215k
  emission.Addr = address;
1593
215k
  emission.AllocaAddr = AllocaAddr;
1594
1595
  // Emit debug info for local var declaration.
1596
215k
  if (EmitDebugInfo && 
HaveInsertPoint()65.0k
) {
1597
65.0k
    Address DebugAddr = address;
1598
65.0k
    bool UsePointerValue = NRVO && 
ReturnValuePointer.isValid()289
;
1599
65.0k
    DI->setLocation(D.getLocation());
1600
1601
    // If NRVO, use a pointer to the return address.
1602
65.0k
    if (UsePointerValue)
1603
139
      DebugAddr = ReturnValuePointer;
1604
1605
65.0k
    (void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder,
1606
65.0k
                                        UsePointerValue);
1607
65.0k
  }
1608
1609
215k
  if (D.hasAttr<AnnotateAttr>() && 
HaveInsertPoint()6
)
1610
5
    EmitVarAnnotations(&D, address.getPointer());
1611
1612
  // Make sure we call @llvm.lifetime.end.
1613
215k
  if (emission.useLifetimeMarkers())
1614
5.25k
    EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1615
5.25k
                                         emission.getOriginalAllocatedAddress(),
1616
5.25k
                                         emission.getSizeForLifetimeMarkers());
1617
1618
215k
  return emission;
1619
215k
}
1620
1621
static bool isCapturedBy(const VarDecl &, const Expr *);
1622
1623
/// Determines whether the given __block variable is potentially
1624
/// captured by the given statement.
1625
24
static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1626
24
  if (const Expr *E = dyn_cast<Expr>(S))
1627
22
    return isCapturedBy(Var, E);
1628
2
  for (const Stmt *SubStmt : S->children())
1629
2
    if (isCapturedBy(Var, SubStmt))
1630
0
      return true;
1631
2
  return false;
1632
2
}
1633
1634
/// Determines whether the given __block variable is potentially
1635
/// captured by the given expression.
1636
115
static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1637
  // Skip the most common kinds of expressions that make
1638
  // hierarchy-walking expensive.
1639
115
  E = E->IgnoreParenCasts();
1640
1641
115
  if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1642
6
    const BlockDecl *Block = BE->getBlockDecl();
1643
6
    for (const auto &I : Block->captures()) {
1644
6
      if (I.getVariable() == &Var)
1645
6
        return true;
1646
6
    }
1647
1648
    // No need to walk into the subexpressions.
1649
0
    return false;
1650
109
  }
1651
1652
109
  if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1653
0
    const CompoundStmt *CS = SE->getSubStmt();
1654
0
    for (const auto *BI : CS->body())
1655
0
      if (const auto *BIE = dyn_cast<Expr>(BI)) {
1656
0
        if (isCapturedBy(Var, BIE))
1657
0
          return true;
1658
0
      }
1659
0
      else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1660
          // special case declarations
1661
0
          for (const auto *I : DS->decls()) {
1662
0
              if (const auto *VD = dyn_cast<VarDecl>((I))) {
1663
0
                const Expr *Init = VD->getInit();
1664
0
                if (Init && isCapturedBy(Var, Init))
1665
0
                  return true;
1666
0
              }
1667
0
          }
1668
0
      }
1669
0
      else
1670
        // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1671
        // Later, provide code to poke into statements for capture analysis.
1672
0
        return true;
1673
0
    return false;
1674
109
  }
1675
1676
109
  for (const Stmt *SubStmt : E->children())
1677
22
    if (isCapturedBy(Var, SubStmt))
1678
3
      return true;
1679
1680
106
  return false;
1681
109
}
1682
1683
/// Determine whether the given initializer is trivial in the sense
1684
/// that it requires no code to be generated.
1685
197k
bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1686
197k
  if (!Init)
1687
38.2k
    return true;
1688
1689
159k
  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1690
12.3k
    if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1691
12.3k
      if (Constructor->isTrivial() &&
1692
4.08k
          Constructor->isDefaultConstructor() &&
1693
3.66k
          !Construct->requiresZeroInitialization())
1694
3.66k
        return true;
1695
1696
155k
  return false;
1697
155k
}
1698
1699
void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1700
                                                      const VarDecl &D,
1701
936
                                                      Address Loc) {
1702
936
  auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1703
936
  CharUnits Size = getContext().getTypeSizeInChars(type);
1704
936
  bool isVolatile = type.isVolatileQualified();
1705
936
  if (!Size.isZero()) {
1706
913
    switch (trivialAutoVarInit) {
1707
0
    case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1708
0
      llvm_unreachable("Uninitialized handled by caller");
1709
395
    case LangOptions::TrivialAutoVarInitKind::Zero:
1710
395
      if (CGM.stopAutoInit())
1711
4
        return;
1712
391
      emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1713
391
      break;
1714
518
    case LangOptions::TrivialAutoVarInitKind::Pattern:
1715
518
      if (CGM.stopAutoInit())
1716
4
        return;
1717
514
      emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1718
514
      break;
1719
905
    }
1720
905
    return;
1721
905
  }
1722
1723
  // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1724
  // them, so emit a memcpy with the VLA size to initialize each element.
1725
  // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1726
  // will catch that code, but there exists code which generates zero-sized
1727
  // VLAs. Be nice and initialize whatever they requested.
1728
23
  const auto *VlaType = getContext().getAsVariableArrayType(type);
1729
23
  if (!VlaType)
1730
9
    return;
1731
14
  auto VlaSize = getVLASize(VlaType);
1732
14
  auto SizeVal = VlaSize.NumElts;
1733
14
  CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1734
14
  switch (trivialAutoVarInit) {
1735
0
  case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1736
0
    llvm_unreachable("Uninitialized handled by caller");
1737
1738
7
  case LangOptions::TrivialAutoVarInitKind::Zero: {
1739
7
    if (CGM.stopAutoInit())
1740
2
      return;
1741
5
    if (!EltSize.isOne())
1742
5
      SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1743
5
    auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1744
5
                                   SizeVal, isVolatile);
1745
5
    I->addAnnotationMetadata("auto-init");
1746
5
    break;
1747
5
  }
1748
1749
7
  case LangOptions::TrivialAutoVarInitKind::Pattern: {
1750
7
    if (CGM.stopAutoInit())
1751
2
      return;
1752
5
    llvm::Type *ElTy = Loc.getElementType();
1753
5
    llvm::Constant *Constant = constWithPadding(
1754
5
        CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1755
5
    CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1756
5
    llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1757
5
    llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1758
5
    llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1759
5
    llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1760
5
        SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1761
5
        "vla.iszerosized");
1762
5
    Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1763
5
    EmitBlock(SetupBB);
1764
5
    if (!EltSize.isOne())
1765
5
      SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1766
5
    llvm::Value *BaseSizeInChars =
1767
5
        llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1768
5
    Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1769
5
    llvm::Value *End =
1770
5
        Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1771
5
    llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1772
5
    EmitBlock(LoopBB);
1773
5
    llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1774
5
    Cur->addIncoming(Begin.getPointer(), OriginBB);
1775
5
    CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1776
5
    auto *I =
1777
5
        Builder.CreateMemCpy(Address(Cur, CurAlign),
1778
5
                             createUnnamedGlobalForMemcpyFrom(
1779
5
                                 CGM, D, Builder, Constant, ConstantAlign),
1780
5
                             BaseSizeInChars, isVolatile);
1781
5
    I->addAnnotationMetadata("auto-init");
1782
5
    llvm::Value *Next =
1783
5
        Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1784
5
    llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1785
5
    Builder.CreateCondBr(Done, ContBB, LoopBB);
1786
5
    Cur->addIncoming(Next, LoopBB);
1787
5
    EmitBlock(ContBB);
1788
5
  } break;
1789
14
  }
1790
14
}
1791
1792
196k
void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1793
196k
  assert(emission.Variable && "emission was not valid!");
1794
1795
  // If this was emitted as a global constant, we're done.
1796
196k
  if (emission.wasEmittedAsGlobal()) 
return6
;
1797
1798
196k
  const VarDecl &D = *emission.Variable;
1799
196k
  auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1800
196k
  QualType type = D.getType();
1801
1802
  // If this local has an initializer, emit it now.
1803
196k
  const Expr *Init = D.getInit();
1804
1805
  // If we are at an unreachable point, we don't need to emit the initializer
1806
  // unless it contains a label.
1807
196k
  if (!HaveInsertPoint()) {
1808
19
    if (!Init || 
!ContainsLabel(Init)11
) return;
1809
0
    EnsureInsertPoint();
1810
0
  }
1811
1812
  // Initialize the structure of a __block variable.
1813
196k
  if (emission.IsEscapingByRef)
1814
206
    emitByrefStructureInit(emission);
1815
1816
  // Initialize the variable here if it doesn't have a initializer and it is a
1817
  // C struct that is non-trivial to initialize or an array containing such a
1818
  // struct.
1819
196k
  if (!Init &&
1820
38.2k
      type.isNonTrivialToPrimitiveDefaultInitialize() ==
1821
37
          QualType::PDIK_Struct) {
1822
37
    LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1823
37
    if (emission.IsEscapingByRef)
1824
9
      drillIntoBlockVariable(*this, Dst, &D);
1825
37
    defaultInitNonTrivialCStructVar(Dst);
1826
37
    return;
1827
37
  }
1828
1829
  // Check whether this is a byref variable that's potentially
1830
  // captured and moved by its own initializer.  If so, we'll need to
1831
  // emit the initializer first, then copy into the variable.
1832
196k
  bool capturedByInit =
1833
196k
      Init && 
emission.IsEscapingByRef158k
&&
isCapturedBy(D, Init)93
;
1834
1835
196k
  bool locIsByrefHeader = !capturedByInit;
1836
196k
  const Address Loc =
1837
196k
      locIsByrefHeader ? emission.getObjectAddress(*this) : 
emission.Addr6
;
1838
1839
  // Note: constexpr already initializes everything correctly.
1840
196k
  LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1841
196k
      (D.isConstexpr()
1842
350
           ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1843
196k
           : (D.getAttr<UninitializedAttr>()
1844
6
                  ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1845
196k
                  : getContext().getLangOpts().getTrivialAutoVarInit()));
1846
1847
191k
  auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1848
191k
    if (trivialAutoVarInit ==
1849
191k
        LangOptions::TrivialAutoVarInitKind::Uninitialized)
1850
190k
      return;
1851
1852
    // Only initialize a __block's storage: we always initialize the header.
1853
936
    if (emission.IsEscapingByRef && 
!locIsByrefHeader4
)
1854
2
      Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1855
1856
936
    return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1857
936
  };
1858
1859
196k
  if (isTrivialInitializer(Init))
1860
41.9k
    return initializeWhatIsTechnicallyUninitialized(Loc);
1861
1862
154k
  llvm::Constant *constant = nullptr;
1863
154k
  if (emission.IsConstantAggregate ||
1864
150k
      D.mightBeUsableInConstantExpressions(getContext())) {
1865
15.0k
    assert(!capturedByInit && "constant init contains a capturing block?");
1866
15.0k
    constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1867
15.0k
    if (constant && 
!constant->isZeroValue()4.97k
&&
1868
4.02k
        (trivialAutoVarInit !=
1869
197
         LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1870
197
      IsPattern isPattern =
1871
197
          (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1872
112
              ? IsPattern::Yes
1873
85
              : IsPattern::No;
1874
      // C guarantees that brace-init with fewer initializers than members in
1875
      // the aggregate will initialize the rest of the aggregate as-if it were
1876
      // static initialization. In turn static initialization guarantees that
1877
      // padding is initialized to zero bits. We could instead pattern-init if D
1878
      // has any ImplicitValueInitExpr, but that seems to be unintuitive
1879
      // behavior.
1880
197
      constant = constWithPadding(CGM, IsPattern::No,
1881
197
                                  replaceUndef(CGM, isPattern, constant));
1882
197
    }
1883
15.0k
  }
1884
1885
154k
  if (!constant) {
1886
149k
    initializeWhatIsTechnicallyUninitialized(Loc);
1887
149k
    LValue lv = MakeAddrLValue(Loc, type);
1888
149k
    lv.setNonGC(true);
1889
149k
    return EmitExprAsInit(Init, &D, lv, capturedByInit);
1890
149k
  }
1891
1892
4.97k
  if (!emission.IsConstantAggregate) {
1893
    // For simple scalar/complex initialization, store the value directly.
1894
512
    LValue lv = MakeAddrLValue(Loc, type);
1895
512
    lv.setNonGC(true);
1896
512
    return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1897
512
  }
1898
1899
4.46k
  llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
1900
4.46k
  emitStoresForConstant(
1901
4.46k
      CGM, D, (Loc.getType() == BP) ? 
Loc0
: Builder.CreateBitCast(Loc, BP),
1902
4.46k
      type.isVolatileQualified(), Builder, constant, /*IsAutoInit=*/false);
1903
4.46k
}
1904
1905
/// Emit an expression as an initializer for an object (variable, field, etc.)
1906
/// at the given location.  The expression is not necessarily the normal
1907
/// initializer for the object, and the address is not necessarily
1908
/// its normal location.
1909
///
1910
/// \param init the initializing expression
1911
/// \param D the object to act as if we're initializing
1912
/// \param lvalue the lvalue to initialize
1913
/// \param capturedByInit true if \p D is a __block variable
1914
///   whose address is potentially changed by the initializer
1915
void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1916
165k
                                     LValue lvalue, bool capturedByInit) {
1917
165k
  QualType type = D->getType();
1918
1919
165k
  if (type->isReferenceType()) {
1920
4.83k
    RValue rvalue = EmitReferenceBindingToExpr(init);
1921
4.83k
    if (capturedByInit)
1922
0
      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1923
4.83k
    EmitStoreThroughLValue(rvalue, lvalue, true);
1924
4.83k
    return;
1925
4.83k
  }
1926
160k
  switch (getEvaluationKind(type)) {
1927
147k
  case TEK_Scalar:
1928
147k
    EmitScalarInit(init, D, lvalue, capturedByInit);
1929
147k
    return;
1930
172
  case TEK_Complex: {
1931
172
    ComplexPairTy complex = EmitComplexExpr(init);
1932
172
    if (capturedByInit)
1933
0
      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1934
172
    EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1935
172
    return;
1936
0
  }
1937
12.8k
  case TEK_Aggregate:
1938
12.8k
    if (type->isAtomicType()) {
1939
4
      EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1940
12.8k
    } else {
1941
12.8k
      AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1942
12.8k
      if (isa<VarDecl>(D))
1943
12.8k
        Overlap = AggValueSlot::DoesNotOverlap;
1944
0
      else if (auto *FD = dyn_cast<FieldDecl>(D))
1945
0
        Overlap = getOverlapForFieldInit(FD);
1946
      // TODO: how can we delay here if D is captured by its initializer?
1947
12.8k
      EmitAggExpr(init, AggValueSlot::forLValue(
1948
12.8k
                            lvalue, *this, AggValueSlot::IsDestructed,
1949
12.8k
                            AggValueSlot::DoesNotNeedGCBarriers,
1950
12.8k
                            AggValueSlot::IsNotAliased, Overlap));
1951
12.8k
    }
1952
12.8k
    return;
1953
0
  }
1954
0
  llvm_unreachable("bad evaluation kind");
1955
0
}
1956
1957
/// Enter a destroy cleanup for the given local variable.
1958
void CodeGenFunction::emitAutoVarTypeCleanup(
1959
                            const CodeGenFunction::AutoVarEmission &emission,
1960
9.46k
                            QualType::DestructionKind dtorKind) {
1961
9.46k
  assert(dtorKind != QualType::DK_none);
1962
1963
  // Note that for __block variables, we want to destroy the
1964
  // original stack object, not the possibly forwarded object.
1965
9.46k
  Address addr = emission.getObjectAddress(*this);
1966
1967
9.46k
  const VarDecl *var = emission.Variable;
1968
9.46k
  QualType type = var->getType();
1969
1970
9.46k
  CleanupKind cleanupKind = NormalAndEHCleanup;
1971
9.46k
  CodeGenFunction::Destroyer *destroyer = nullptr;
1972
1973
9.46k
  switch (dtorKind) {
1974
0
  case QualType::DK_none:
1975
0
    llvm_unreachable("no cleanup for trivially-destructible variable");
1976
1977
8.74k
  case QualType::DK_cxx_destructor:
1978
    // If there's an NRVO flag on the emission, we need a different
1979
    // cleanup.
1980
8.74k
    if (emission.NRVOFlag) {
1981
194
      assert(!type->isArrayType());
1982
194
      CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1983
194
      EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
1984
194
                                                  emission.NRVOFlag);
1985
194
      return;
1986
194
    }
1987
8.54k
    break;
1988
1989
487
  case QualType::DK_objc_strong_lifetime:
1990
    // Suppress cleanups for pseudo-strong variables.
1991
487
    if (var->isARCPseudoStrong()) 
return13
;
1992
1993
    // Otherwise, consider whether to use an EH cleanup or not.
1994
474
    cleanupKind = getARCCleanupKind();
1995
1996
    // Use the imprecise destroyer by default.
1997
474
    if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1998
469
      destroyer = CodeGenFunction::destroyARCStrongImprecise;
1999
474
    break;
2000
2001
169
  case QualType::DK_objc_weak_lifetime:
2002
169
    break;
2003
2004
64
  case QualType::DK_nontrivial_c_struct:
2005
64
    destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2006
64
    if (emission.NRVOFlag) {
2007
3
      assert(!type->isArrayType());
2008
3
      EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2009
3
                                                emission.NRVOFlag, type);
2010
3
      return;
2011
3
    }
2012
61
    break;
2013
9.25k
  }
2014
2015
  // If we haven't chosen a more specific destroyer, use the default.
2016
9.25k
  if (!destroyer) 
destroyer = getDestroyer(dtorKind)8.72k
;
2017
2018
  // Use an EH cleanup in array destructors iff the destructor itself
2019
  // is being pushed as an EH cleanup.
2020
9.25k
  bool useEHCleanup = (cleanupKind & EHCleanup);
2021
9.25k
  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2022
9.25k
                                     useEHCleanup);
2023
9.25k
}
2024
2025
215k
void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2026
215k
  assert(emission.Variable && "emission was not valid!");
2027
2028
  // If this was emitted as a global constant, we're done.
2029
215k
  if (emission.wasEmittedAsGlobal()) 
return6
;
2030
2031
  // If we don't have an insertion point, we're done.  Sema prevents
2032
  // us from jumping into any of these scopes anyway.
2033
215k
  if (!HaveInsertPoint()) 
return19
;
2034
2035
215k
  const VarDecl &D = *emission.Variable;
2036
2037
  // Check the type for a cleanup.
2038
215k
  if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2039
9.46k
    emitAutoVarTypeCleanup(emission, dtorKind);
2040
2041
  // In GC mode, honor objc_precise_lifetime.
2042
215k
  if (getLangOpts().getGC() != LangOptions::NonGC &&
2043
126
      D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2044
1
    EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2045
1
  }
2046
2047
  // Handle the cleanup attribute.
2048
215k
  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2049
8
    const FunctionDecl *FD = CA->getFunctionDecl();
2050
2051
8
    llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2052
8
    assert(F && "Could not find function!");
2053
2054
8
    const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2055
8
    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2056
8
  }
2057
2058
  // If this is a block variable, call _Block_object_destroy
2059
  // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2060
  // mode.
2061
215k
  if (emission.IsEscapingByRef &&
2062
206
      CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2063
206
    BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2064
206
    if (emission.Variable->getType().isObjCGCWeak())
2065
7
      Flags |= BLOCK_FIELD_IS_WEAK;
2066
206
    enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2067
206
                      /*LoadBlockVarAddr*/ false,
2068
206
                      cxxDestructorCanThrow(emission.Variable->getType()));
2069
206
  }
2070
215k
}
2071
2072
CodeGenFunction::Destroyer *
2073
12.0k
CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2074
12.0k
  switch (kind) {
2075
0
  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2076
11.3k
  case QualType::DK_cxx_destructor:
2077
11.3k
    return destroyCXXObject;
2078
49
  case QualType::DK_objc_strong_lifetime:
2079
49
    return destroyARCStrongPrecise;
2080
500
  case QualType::DK_objc_weak_lifetime:
2081
500
    return destroyARCWeak;
2082
64
  case QualType::DK_nontrivial_c_struct:
2083
64
    return destroyNonTrivialCStruct;
2084
0
  }
2085
0
  llvm_unreachable("Unknown DestructionKind");
2086
0
}
2087
2088
/// pushEHDestroy - Push the standard destructor for the given type as
2089
/// an EH-only cleanup.
2090
void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2091
857
                                    Address addr, QualType type) {
2092
857
  assert(dtorKind && "cannot push destructor for trivial type");
2093
857
  assert(needsEHCleanup(dtorKind));
2094
2095
857
  pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2096
857
}
2097
2098
/// pushDestroy - Push the standard destructor for the given type as
2099
/// at least a normal cleanup.
2100
void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2101
345
                                  Address addr, QualType type) {
2102
345
  assert(dtorKind && "cannot push destructor for trivial type");
2103
2104
345
  CleanupKind cleanupKind = getCleanupKind(dtorKind);
2105
345
  pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2106
345
              cleanupKind & EHCleanup);
2107
345
}
2108
2109
void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2110
                                  QualType type, Destroyer *destroyer,
2111
3.66k
                                  bool useEHCleanupForArray) {
2112
3.66k
  pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2113
3.66k
                                     destroyer, useEHCleanupForArray);
2114
3.66k
}
2115
2116
1.58k
void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2117
1.58k
  EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2118
1.58k
}
2119
2120
void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2121
                                                  Address addr, QualType type,
2122
                                                  Destroyer *destroyer,
2123
517
                                                  bool useEHCleanupForArray) {
2124
  // If we're not in a conditional branch, we don't need to bother generating a
2125
  // conditional cleanup.
2126
517
  if (!isInConditionalBranch()) {
2127
    // Push an EH-only cleanup for the object now.
2128
    // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2129
    // around in case a temporary's destructor throws an exception.
2130
489
    if (cleanupKind & EHCleanup)
2131
201
      EHStack.pushCleanup<DestroyObject>(
2132
201
          static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2133
201
          destroyer, useEHCleanupForArray);
2134
2135
489
    return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2136
489
        cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
2137
489
  }
2138
2139
  // Otherwise, we should only destroy the object if it's been initialized.
2140
  // Re-use the active flag and saved address across both the EH and end of
2141
  // scope cleanups.
2142
2143
28
  using SavedType = typename DominatingValue<Address>::saved_type;
2144
28
  using ConditionalCleanupType =
2145
28
      EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2146
28
                                       Destroyer *, bool>;
2147
2148
28
  Address ActiveFlag = createCleanupActiveFlag();
2149
28
  SavedType SavedAddr = saveValueInCond(addr);
2150
2151
28
  if (cleanupKind & EHCleanup) {
2152
15
    EHStack.pushCleanup<ConditionalCleanupType>(
2153
15
        static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
2154
15
        destroyer, useEHCleanupForArray);
2155
15
    initFullExprCleanupWithFlag(ActiveFlag);
2156
15
  }
2157
2158
28
  pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2159
28
      cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
2160
28
      useEHCleanupForArray);
2161
28
}
2162
2163
/// emitDestroy - Immediately perform the destruction of the given
2164
/// object.
2165
///
2166
/// \param addr - the address of the object; a type*
2167
/// \param type - the type of the object; if an array type, all
2168
///   objects are destroyed in reverse order
2169
/// \param destroyer - the function to call to destroy individual
2170
///   elements
2171
/// \param useEHCleanupForArray - whether an EH cleanup should be
2172
///   used when destroying array elements, in case one of the
2173
///   destructions throws an exception
2174
void CodeGenFunction::emitDestroy(Address addr, QualType type,
2175
                                  Destroyer *destroyer,
2176
18.4k
                                  bool useEHCleanupForArray) {
2177
18.4k
  const ArrayType *arrayType = getContext().getAsArrayType(type);
2178
18.4k
  if (!arrayType)
2179
16.0k
    return destroyer(*this, addr, type);
2180
2181
2.37k
  llvm::Value *length = emitArrayLength(arrayType, type, addr);
2182
2183
2.37k
  CharUnits elementAlign =
2184
2.37k
    addr.getAlignment()
2185
2.37k
        .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2186
2187
  // Normally we have to check whether the array is zero-length.
2188
2.37k
  bool checkZeroLength = true;
2189
2190
  // But if the array length is constant, we can suppress that.
2191
2.37k
  if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2192
    // ...and if it's constant zero, we can just skip the entire thing.
2193
2.34k
    if (constLength->isZero()) 
return0
;
2194
2.34k
    checkZeroLength = false;
2195
2.34k
  }
2196
2197
2.37k
  llvm::Value *begin = addr.getPointer();
2198
2.37k
  llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
2199
2.37k
  emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2200
2.37k
                   checkZeroLength, useEHCleanupForArray);
2201
2.37k
}
2202
2203
/// emitArrayDestroy - Destroys all the elements of the given array,
2204
/// beginning from last to first.  The array cannot be zero-length.
2205
///
2206
/// \param begin - a type* denoting the first element of the array
2207
/// \param end - a type* denoting one past the end of the array
2208
/// \param elementType - the element type of the array
2209
/// \param destroyer - the function to call to destroy elements
2210
/// \param useEHCleanup - whether to push an EH cleanup to destroy
2211
///   the remaining elements in case the destruction of a single
2212
///   element throws
2213
void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2214
                                       llvm::Value *end,
2215
                                       QualType elementType,
2216
                                       CharUnits elementAlign,
2217
                                       Destroyer *destroyer,
2218
                                       bool checkZeroLength,
2219
2.53k
                                       bool useEHCleanup) {
2220
2.53k
  assert(!elementType->isArrayType());
2221
2222
  // The basic structure here is a do-while loop, because we don't
2223
  // need to check for the zero-element case.
2224
2.53k
  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2225
2.53k
  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2226
2227
2.53k
  if (checkZeroLength) {
2228
191
    llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2229
191
                                                "arraydestroy.isempty");
2230
191
    Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2231
191
  }
2232
2233
  // Enter the loop body, making that address the current address.
2234
2.53k
  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2235
2.53k
  EmitBlock(bodyBB);
2236
2.53k
  llvm::PHINode *elementPast =
2237
2.53k
    Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2238
2.53k
  elementPast->addIncoming(end, entryBB);
2239
2240
  // Shift the address back by one element.
2241
2.53k
  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2242
2.53k
  llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2243
2.53k
                                                   "arraydestroy.element");
2244
2245
2.53k
  if (useEHCleanup)
2246
1.84k
    pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2247
1.84k
                                   destroyer);
2248
2249
  // Perform the actual destruction there.
2250
2.53k
  destroyer(*this, Address(element, elementAlign), elementType);
2251
2252
2.53k
  if (useEHCleanup)
2253
1.84k
    PopCleanupBlock();
2254
2255
  // Check whether we've reached the end.
2256
2.53k
  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2257
2.53k
  Builder.CreateCondBr(done, doneBB, bodyBB);
2258
2.53k
  elementPast->addIncoming(element, Builder.GetInsertBlock());
2259
2260
  // Done.
2261
2.53k
  EmitBlock(doneBB);
2262
2.53k
}
2263
2264
/// Perform partial array destruction as if in an EH cleanup.  Unlike
2265
/// emitArrayDestroy, the element type here may still be an array type.
2266
static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2267
                                    llvm::Value *begin, llvm::Value *end,
2268
                                    QualType type, CharUnits elementAlign,
2269
118
                                    CodeGenFunction::Destroyer *destroyer) {
2270
  // If the element type is itself an array, drill down.
2271
118
  unsigned arrayDepth = 0;
2272
137
  while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2273
    // VLAs don't require a GEP index to walk into.
2274
19
    if (!isa<VariableArrayType>(arrayType))
2275
19
      arrayDepth++;
2276
19
    type = arrayType->getElementType();
2277
19
  }
2278
2279
118
  if (arrayDepth) {
2280
19
    llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2281
2282
19
    SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2283
19
    begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2284
19
    end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
2285
19
  }
2286
2287
  // Destroy the array.  We don't ever need an EH cleanup because we
2288
  // assume that we're in an EH cleanup ourselves, so a throwing
2289
  // destructor causes an immediate terminate.
2290
118
  CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2291
118
                       /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2292
118
}
2293
2294
namespace {
2295
  /// RegularPartialArrayDestroy - a cleanup which performs a partial
2296
  /// array destroy where the end pointer is regularly determined and
2297
  /// does not need to be loaded from a local.
2298
  class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2299
    llvm::Value *ArrayBegin;
2300
    llvm::Value *ArrayEnd;
2301
    QualType ElementType;
2302
    CodeGenFunction::Destroyer *Destroyer;
2303
    CharUnits ElementAlign;
2304
  public:
2305
    RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2306
                               QualType elementType, CharUnits elementAlign,
2307
                               CodeGenFunction::Destroyer *destroyer)
2308
      : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2309
        ElementType(elementType), Destroyer(destroyer),
2310
1.88k
        ElementAlign(elementAlign) {}
2311
2312
46
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2313
46
      emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2314
46
                              ElementType, ElementAlign, Destroyer);
2315
46
    }
2316
  };
2317
2318
  /// IrregularPartialArrayDestroy - a cleanup which performs a
2319
  /// partial array destroy where the end pointer is irregularly
2320
  /// determined and must be loaded from a local.
2321
  class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2322
    llvm::Value *ArrayBegin;
2323
    Address ArrayEndPointer;
2324
    QualType ElementType;
2325
    CodeGenFunction::Destroyer *Destroyer;
2326
    CharUnits ElementAlign;
2327
  public:
2328
    IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2329
                                 Address arrayEndPointer,
2330
                                 QualType elementType,
2331
                                 CharUnits elementAlign,
2332
                                 CodeGenFunction::Destroyer *destroyer)
2333
      : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2334
        ElementType(elementType), Destroyer(destroyer),
2335
72
        ElementAlign(elementAlign) {}
2336
2337
72
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2338
72
      llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2339
72
      emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2340
72
                              ElementType, ElementAlign, Destroyer);
2341
72
    }
2342
  };
2343
} // end anonymous namespace
2344
2345
/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2346
/// already-constructed elements of the given array.  The cleanup
2347
/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2348
///
2349
/// \param elementType - the immediate element type of the array;
2350
///   possibly still an array type
2351
void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2352
                                                       Address arrayEndPointer,
2353
                                                       QualType elementType,
2354
                                                       CharUnits elementAlign,
2355
72
                                                       Destroyer *destroyer) {
2356
72
  pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2357
72
                                                    arrayBegin, arrayEndPointer,
2358
72
                                                    elementType, elementAlign,
2359
72
                                                    destroyer);
2360
72
}
2361
2362
/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2363
/// already-constructed elements of the given array.  The cleanup
2364
/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2365
///
2366
/// \param elementType - the immediate element type of the array;
2367
///   possibly still an array type
2368
void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2369
                                                     llvm::Value *arrayEnd,
2370
                                                     QualType elementType,
2371
                                                     CharUnits elementAlign,
2372
1.88k
                                                     Destroyer *destroyer) {
2373
1.88k
  pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2374
1.88k
                                                  arrayBegin, arrayEnd,
2375
1.88k
                                                  elementType, elementAlign,
2376
1.88k
                                                  destroyer);
2377
1.88k
}
2378
2379
/// Lazily declare the @llvm.lifetime.start intrinsic.
2380
5.84k
llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2381
5.84k
  if (LifetimeStartFn)
2382
5.37k
    return LifetimeStartFn;
2383
470
  LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2384
470
    llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2385
470
  return LifetimeStartFn;
2386
470
}
2387
2388
/// Lazily declare the @llvm.lifetime.end intrinsic.
2389
6.13k
llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2390
6.13k
  if (LifetimeEndFn)
2391
5.66k
    return LifetimeEndFn;
2392
470
  LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2393
470
    llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2394
470
  return LifetimeEndFn;
2395
470
}
2396
2397
namespace {
2398
  /// A cleanup to perform a release of an object at the end of a
2399
  /// function.  This is used to balance out the incoming +1 of a
2400
  /// ns_consumed argument when we can't reasonably do that just by
2401
  /// not doing the initial retain for a __block argument.
2402
  struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2403
    ConsumeARCParameter(llvm::Value *param,
2404
                        ARCPreciseLifetime_t precise)
2405
0
      : Param(param), Precise(precise) {}
2406
2407
    llvm::Value *Param;
2408
    ARCPreciseLifetime_t Precise;
2409
2410
0
    void Emit(CodeGenFunction &CGF, Flags flags) override {
2411
0
      CGF.EmitARCRelease(Param, Precise);
2412
0
    }
2413
  };
2414
} // end anonymous namespace
2415
2416
/// Emit an alloca (or GlobalValue depending on target)
2417
/// for the specified parameter and set up LocalDeclMap.
2418
void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2419
483k
                                   unsigned ArgNo) {
2420
  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2421
483k
  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2422
483k
         "Invalid argument to EmitParmDecl");
2423
2424
483k
  Arg.getAnyValue()->setName(D.getName());
2425
2426
483k
  QualType Ty = D.getType();
2427
2428
  // Use better IR generation for certain implicit parameters.
2429
483k
  if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2430
    // The only implicit argument a block has is its literal.
2431
    // This may be passed as an inalloca'ed value on Windows x86.
2432
184k
    if (BlockInfo) {
2433
1.04k
      llvm::Value *V = Arg.isIndirect()
2434
1
                           ? Builder.CreateLoad(Arg.getIndirectAddress())
2435
1.04k
                           : Arg.getDirectValue();
2436
1.04k
      setBlockContextParameter(IPD, ArgNo, V);
2437
1.04k
      return;
2438
1.04k
    }
2439
482k
  }
2440
2441
482k
  Address DeclPtr = Address::invalid();
2442
482k
  bool DoStore = false;
2443
482k
  bool IsScalar = hasScalarEvaluationKind(Ty);
2444
  // If we already have a pointer to the argument, reuse the input pointer.
2445
482k
  if (Arg.isIndirect()) {
2446
15.0k
    DeclPtr = Arg.getIndirectAddress();
2447
    // If we have a prettier pointer type at this point, bitcast to that.
2448
15.0k
    unsigned AS = DeclPtr.getType()->getAddressSpace();
2449
15.0k
    llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
2450
15.0k
    if (DeclPtr.getType() != IRTy)
2451
2
      DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
2452
    // Indirect argument is in alloca address space, which may be different
2453
    // from the default address space.
2454
15.0k
    auto AllocaAS = CGM.getASTAllocaAddressSpace();
2455
15.0k
    auto *V = DeclPtr.getPointer();
2456
14.9k
    auto SrcLangAS = getLangOpts().OpenCL ? 
LangAS::opencl_private141
: AllocaAS;
2457
15.0k
    auto DestLangAS =
2458
14.9k
        getLangOpts().OpenCL ? 
LangAS::opencl_private141
: LangAS::Default;
2459
15.0k
    if (SrcLangAS != DestLangAS) {
2460
16
      assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2461
16
             CGM.getDataLayout().getAllocaAddrSpace());
2462
16
      auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2463
16
      auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2464
16
      DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2465
16
                            *this, V, SrcLangAS, DestLangAS, T, true),
2466
16
                        DeclPtr.getAlignment());
2467
16
    }
2468
2469
    // Push a destructor cleanup for this parameter if the ABI requires it.
2470
    // Don't push a cleanup in a thunk for a method that will also emit a
2471
    // cleanup.
2472
15.0k
    if (hasAggregateEvaluationKind(Ty) && 
!CurFuncIsThunk14.2k
&&
2473
14.2k
        Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2474
396
      if (QualType::DestructionKind DtorKind =
2475
121
              D.needsDestruction(getContext())) {
2476
121
        assert((DtorKind == QualType::DK_cxx_destructor ||
2477
121
                DtorKind == QualType::DK_nontrivial_c_struct) &&
2478
121
               "unexpected destructor type");
2479
121
        pushDestroy(DtorKind, DeclPtr, Ty);
2480
121
        CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2481
121
            EHStack.stable_begin();
2482
121
      }
2483
396
    }
2484
467k
  } else {
2485
    // Check if the parameter address is controlled by OpenMP runtime.
2486
467k
    Address OpenMPLocalAddr =
2487
467k
        getLangOpts().OpenMP
2488
114k
            ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2489
353k
            : Address::invalid();
2490
467k
    if (getLangOpts().OpenMP && 
OpenMPLocalAddr.isValid()114k
) {
2491
11
      DeclPtr = OpenMPLocalAddr;
2492
467k
    } else {
2493
      // Otherwise, create a temporary to hold the value.
2494
467k
      DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2495
467k
                              D.getName() + ".addr");
2496
467k
    }
2497
467k
    DoStore = true;
2498
467k
  }
2499
2500
467k
  llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : 
nullptr15.0k
);
2501
2502
482k
  LValue lv = MakeAddrLValue(DeclPtr, Ty);
2503
482k
  if (IsScalar) {
2504
467k
    Qualifiers qs = Ty.getQualifiers();
2505
467k
    if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2506
      // We honor __attribute__((ns_consumed)) for types with lifetime.
2507
      // For __strong, it's handled by just skipping the initial retain;
2508
      // otherwise we have to balance out the initial +1 with an extra
2509
      // cleanup to do the release at the end of the function.
2510
526
      bool isConsumed = D.hasAttr<NSConsumedAttr>();
2511
2512
      // If a parameter is pseudo-strong then we can omit the implicit retain.
2513
526
      if (D.isARCPseudoStrong()) {
2514
258
        assert(lt == Qualifiers::OCL_Strong &&
2515
258
               "pseudo-strong variable isn't strong?");
2516
258
        assert(qs.hasConst() && "pseudo-strong variable should be const!");
2517
258
        lt = Qualifiers::OCL_ExplicitNone;
2518
258
      }
2519
2520
      // Load objects passed indirectly.
2521
526
      if (Arg.isIndirect() && 
!ArgVal8
)
2522
8
        ArgVal = Builder.CreateLoad(DeclPtr);
2523
2524
526
      if (lt == Qualifiers::OCL_Strong) {
2525
255
        if (!isConsumed) {
2526
225
          if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2527
            // use objc_storeStrong(&dest, value) for retaining the
2528
            // object. But first, store a null into 'dest' because
2529
            // objc_storeStrong attempts to release its old value.
2530
166
            llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2531
166
            EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2532
166
            EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2533
166
            DoStore = false;
2534
166
          }
2535
59
          else
2536
          // Don't use objc_retainBlock for block pointers, because we
2537
          // don't want to Block_copy something just because we got it
2538
          // as a parameter.
2539
59
            ArgVal = EmitARCRetainNonBlock(ArgVal);
2540
225
        }
2541
271
      } else {
2542
        // Push the cleanup for a consumed parameter.
2543
271
        if (isConsumed) {
2544
0
          ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2545
0
                                ? ARCPreciseLifetime : ARCImpreciseLifetime);
2546
0
          EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2547
0
                                                   precise);
2548
0
        }
2549
2550
271
        if (lt == Qualifiers::OCL_Weak) {
2551
7
          EmitARCInitWeak(DeclPtr, ArgVal);
2552
7
          DoStore = false; // The weak init is a store, no need to do two.
2553
7
        }
2554
271
      }
2555
2556
      // Enter the cleanup scope.
2557
526
      EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2558
526
    }
2559
467k
  }
2560
2561
  // Store the initial value into the alloca.
2562
482k
  if (DoStore)
2563
467k
    EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2564
2565
482k
  setAddrOfLocalVar(&D, DeclPtr);
2566
2567
  // Emit debug info for param declarations in non-thunk functions.
2568
482k
  if (CGDebugInfo *DI = getDebugInfo()) {
2569
154k
    if (CGM.getCodeGenOpts().hasReducedDebugInfo() && 
!CurFuncIsThunk152k
) {
2570
152k
      DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
2571
152k
    }
2572
154k
  }
2573
2574
482k
  if (D.hasAttr<AnnotateAttr>())
2575
3
    EmitVarAnnotations(&D, DeclPtr.getPointer());
2576
2577
  // We can only check return value nullability if all arguments to the
2578
  // function satisfy their nullability preconditions. This makes it necessary
2579
  // to emit null checks for args in the function body itself.
2580
482k
  if (requiresReturnValueNullabilityCheck()) {
2581
28
    auto Nullability = Ty->getNullability(getContext());
2582
28
    if (Nullability && 
*Nullability == NullabilityKind::NonNull10
) {
2583
8
      SanitizerScope SanScope(this);
2584
8
      RetValNullabilityPrecondition =
2585
8
          Builder.CreateAnd(RetValNullabilityPrecondition,
2586
8
                            Builder.CreateIsNotNull(Arg.getAnyValue()));
2587
8
    }
2588
28
  }
2589
482k
}
2590
2591
void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2592
188
                                            CodeGenFunction *CGF) {
2593
188
  if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && 
!D->isUsed()84
))
2594
84
    return;
2595
104
  getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2596
104
}
2597
2598
void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2599
68
                                         CodeGenFunction *CGF) {
2600
68
  if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2601
34
      (!LangOpts.EmitAllDecls && 
!D->isUsed()10
))
2602
44
    return;
2603
24
  getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2604
24
}
2605
2606
34
void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2607
34
  getOpenMPRuntime().processRequiresDirective(D);
2608
34
}