clang 21.0.0git
CGDecl.cpp
Go to the documentation of this file.
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 "EHScopeStack.h"
23#include "PatternInit.h"
24#include "TargetInfo.h"
26#include "clang/AST/Attr.h"
27#include "clang/AST/CharUnits.h"
28#include "clang/AST/Decl.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/Analysis/ConstantFolding.h"
36#include "llvm/Analysis/ValueTracking.h"
37#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/Type.h"
42#include <optional>
43
44using namespace clang;
45using namespace CodeGen;
46
47static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
48 "Clang max alignment greater than what LLVM supports?");
49
50void CodeGenFunction::EmitDecl(const Decl &D) {
51 switch (D.getKind()) {
52 case Decl::BuiltinTemplate:
53 case Decl::TranslationUnit:
54 case Decl::ExternCContext:
55 case Decl::Namespace:
56 case Decl::UnresolvedUsingTypename:
57 case Decl::ClassTemplateSpecialization:
58 case Decl::ClassTemplatePartialSpecialization:
59 case Decl::VarTemplateSpecialization:
60 case Decl::VarTemplatePartialSpecialization:
61 case Decl::TemplateTypeParm:
62 case Decl::UnresolvedUsingValue:
63 case Decl::NonTypeTemplateParm:
64 case Decl::CXXDeductionGuide:
65 case Decl::CXXMethod:
66 case Decl::CXXConstructor:
67 case Decl::CXXDestructor:
68 case Decl::CXXConversion:
69 case Decl::Field:
70 case Decl::MSProperty:
71 case Decl::IndirectField:
72 case Decl::ObjCIvar:
73 case Decl::ObjCAtDefsField:
74 case Decl::ParmVar:
75 case Decl::ImplicitParam:
76 case Decl::ClassTemplate:
77 case Decl::VarTemplate:
78 case Decl::FunctionTemplate:
79 case Decl::TypeAliasTemplate:
80 case Decl::TemplateTemplateParm:
81 case Decl::ObjCMethod:
82 case Decl::ObjCCategory:
83 case Decl::ObjCProtocol:
84 case Decl::ObjCInterface:
85 case Decl::ObjCCategoryImpl:
86 case Decl::ObjCImplementation:
87 case Decl::ObjCProperty:
88 case Decl::ObjCCompatibleAlias:
89 case Decl::PragmaComment:
90 case Decl::PragmaDetectMismatch:
91 case Decl::AccessSpec:
92 case Decl::LinkageSpec:
93 case Decl::Export:
94 case Decl::ObjCPropertyImpl:
95 case Decl::FileScopeAsm:
96 case Decl::TopLevelStmt:
97 case Decl::Friend:
98 case Decl::FriendTemplate:
99 case Decl::Block:
100 case Decl::OutlinedFunction:
101 case Decl::Captured:
102 case Decl::UsingShadow:
103 case Decl::ConstructorUsingShadow:
104 case Decl::ObjCTypeParam:
105 case Decl::Binding:
106 case Decl::UnresolvedUsingIfExists:
107 case Decl::HLSLBuffer:
108 llvm_unreachable("Declaration should not be in declstmts!");
109 case Decl::Record: // struct/union/class X;
110 case Decl::CXXRecord: // struct/union/class X; [C++]
111 if (CGDebugInfo *DI = getDebugInfo())
112 if (cast<RecordDecl>(D).getDefinition())
113 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
114 return;
115 case Decl::Enum: // enum X;
116 if (CGDebugInfo *DI = getDebugInfo())
117 if (cast<EnumDecl>(D).getDefinition())
118 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
119 return;
120 case Decl::Function: // void X();
121 case Decl::EnumConstant: // enum ? { X = ? }
122 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
123 case Decl::Label: // __label__ x;
124 case Decl::Import:
125 case Decl::MSGuid: // __declspec(uuid("..."))
126 case Decl::UnnamedGlobalConstant:
127 case Decl::TemplateParamObject:
128 case Decl::OMPThreadPrivate:
129 case Decl::OMPAllocate:
130 case Decl::OMPCapturedExpr:
131 case Decl::OMPRequires:
132 case Decl::Empty:
133 case Decl::Concept:
134 case Decl::ImplicitConceptSpecialization:
135 case Decl::LifetimeExtendedTemporary:
136 case Decl::RequiresExprBody:
137 // None of these decls require codegen support.
138 return;
139
140 case Decl::NamespaceAlias:
141 if (CGDebugInfo *DI = getDebugInfo())
142 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
143 return;
144 case Decl::Using: // using X; [C++]
145 if (CGDebugInfo *DI = getDebugInfo())
146 DI->EmitUsingDecl(cast<UsingDecl>(D));
147 return;
148 case Decl::UsingEnum: // using enum X; [C++]
149 if (CGDebugInfo *DI = getDebugInfo())
150 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
151 return;
152 case Decl::UsingPack:
153 for (auto *Using : cast<UsingPackDecl>(D).expansions())
154 EmitDecl(*Using);
155 return;
156 case Decl::UsingDirective: // using namespace X; [C++]
157 if (CGDebugInfo *DI = getDebugInfo())
158 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
159 return;
160 case Decl::Var:
161 case Decl::Decomposition: {
162 const VarDecl &VD = cast<VarDecl>(D);
163 assert(VD.isLocalVarDecl() &&
164 "Should not see file-scope variables inside a function!");
165 EmitVarDecl(VD);
166 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
167 for (auto *B : DD->flat_bindings())
168 if (auto *HD = B->getHoldingVar())
169 EmitVarDecl(*HD);
170
171 return;
172 }
173
174 case Decl::OMPDeclareReduction:
175 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
176
177 case Decl::OMPDeclareMapper:
178 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
179
180 case Decl::Typedef: // typedef int X;
181 case Decl::TypeAlias: { // using X = int; [C++0x]
182 QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
183 if (CGDebugInfo *DI = getDebugInfo())
184 DI->EmitAndRetainType(Ty);
185 if (Ty->isVariablyModifiedType())
187 return;
188 }
189 }
190}
191
192/// EmitVarDecl - This method handles emission of any variable declaration
193/// inside a function, including static vars etc.
195 if (D.hasExternalStorage())
196 // Don't emit it now, allow it to be emitted lazily on its first use.
197 return;
198
199 // Some function-scope variable does not have static storage but still
200 // needs to be emitted like a static variable, e.g. a function-scope
201 // variable in constant address space in OpenCL.
202 if (D.getStorageDuration() != SD_Automatic) {
203 // Static sampler variables translated to function calls.
204 if (D.getType()->isSamplerT())
205 return;
206
207 llvm::GlobalValue::LinkageTypes Linkage =
209
210 // FIXME: We need to force the emission/use of a guard variable for
211 // some variables even if we can constant-evaluate them because
212 // we can't guarantee every translation unit will constant-evaluate them.
213
214 return EmitStaticVarDecl(D, Linkage);
215 }
216
217 if (D.getType().getAddressSpace() == LangAS::opencl_local)
219
220 assert(D.hasLocalStorage());
221 return EmitAutoVarDecl(D);
222}
223
224static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
225 if (CGM.getLangOpts().CPlusPlus)
226 return CGM.getMangledName(&D).str();
227
228 // If this isn't C++, we don't need a mangled name, just a pretty one.
229 assert(!D.isExternallyVisible() && "name shouldn't matter");
230 std::string ContextName;
231 const DeclContext *DC = D.getDeclContext();
232 if (auto *CD = dyn_cast<CapturedDecl>(DC))
233 DC = cast<DeclContext>(CD->getNonClosureContext());
234 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
235 ContextName = std::string(CGM.getMangledName(FD));
236 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
237 ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
238 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
239 ContextName = OMD->getSelector().getAsString();
240 else
241 llvm_unreachable("Unknown context for static var decl");
242
243 ContextName += "." + D.getNameAsString();
244 return ContextName;
245}
246
248 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
249 // In general, we don't always emit static var decls once before we reference
250 // them. It is possible to reference them before emitting the function that
251 // contains them, and it is possible to emit the containing function multiple
252 // times.
253 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
254 return ExistingGV;
255
256 QualType Ty = D.getType();
257 assert(Ty->isConstantSizeType() && "VLAs can't be static");
258
259 // Use the label if the variable is renamed with the asm-label extension.
260 std::string Name;
261 if (D.hasAttr<AsmLabelAttr>())
262 Name = std::string(getMangledName(&D));
263 else
264 Name = getStaticDeclName(*this, D);
265
266 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
268 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
269
270 // OpenCL variables in local address space and CUDA shared
271 // variables cannot have an initializer.
272 llvm::Constant *Init = nullptr;
274 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
275 Init = llvm::UndefValue::get(LTy);
276 else
278
279 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
280 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
281 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
282 GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
283
284 if (supportsCOMDAT() && GV->isWeakForLinker())
285 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
286
287 if (D.getTLSKind())
288 setTLSMode(GV, D);
289
290 setGVProperties(GV, &D);
291 getTargetCodeGenInfo().setTargetAttributes(cast<Decl>(&D), GV, *this);
292
293 // Make sure the result is of the correct type.
294 LangAS ExpectedAS = Ty.getAddressSpace();
295 llvm::Constant *Addr = GV;
296 if (AS != ExpectedAS) {
298 *this, GV, AS, ExpectedAS,
299 llvm::PointerType::get(getLLVMContext(),
300 getContext().getTargetAddressSpace(ExpectedAS)));
301 }
302
304
305 // Ensure that the static local gets initialized by making sure the parent
306 // function gets emitted eventually.
307 const Decl *DC = cast<Decl>(D.getDeclContext());
308
309 // We can't name blocks or captured statements directly, so try to emit their
310 // parents.
311 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
312 DC = DC->getNonClosureContext();
313 // FIXME: Ensure that global blocks get emitted.
314 if (!DC)
315 return Addr;
316 }
317
318 GlobalDecl GD;
319 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
320 GD = GlobalDecl(CD, Ctor_Base);
321 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
322 GD = GlobalDecl(DD, Dtor_Base);
323 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
324 GD = GlobalDecl(FD);
325 else {
326 // Don't do anything for Obj-C method decls or global closures. We should
327 // never defer them.
328 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
329 }
330 if (GD.getDecl()) {
331 // Disable emission of the parent function for the OpenMP device codegen.
333 (void)GetAddrOfGlobal(GD);
334 }
335
336 return Addr;
337}
338
339/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
340/// global variable that has already been created for it. If the initializer
341/// has a different type than GV does, this may free GV and return a different
342/// one. Otherwise it just returns GV.
343llvm::GlobalVariable *
345 llvm::GlobalVariable *GV) {
346 ConstantEmitter emitter(*this);
347 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
348
349 // If constant emission failed, then this should be a C++ static
350 // initializer.
351 if (!Init) {
352 if (!getLangOpts().CPlusPlus)
353 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
354 else if (D.hasFlexibleArrayInit(getContext()))
355 CGM.ErrorUnsupported(D.getInit(), "flexible array initializer");
356 else if (HaveInsertPoint()) {
357 // Since we have a static initializer, this global variable can't
358 // be constant.
359 GV->setConstant(false);
360
361 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
362 }
363 return GV;
364 }
365
366 PGO.markStmtMaybeUsed(D.getInit()); // FIXME: Too lazy
367
368#ifndef NDEBUG
369 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(D.getType()) +
370 D.getFlexibleArrayInitChars(getContext());
372 CGM.getDataLayout().getTypeAllocSize(Init->getType()));
373 assert(VarSize == CstSize && "Emitted constant has unexpected size");
374#endif
375
376 bool NeedsDtor =
377 D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
378
379 GV->setConstant(
380 D.getType().isConstantStorage(getContext(), true, !NeedsDtor));
381 GV->replaceInitializer(Init);
382
383 emitter.finalize(GV);
384
385 if (NeedsDtor && HaveInsertPoint()) {
386 // We have a constant initializer, but a nontrivial destructor. We still
387 // need to perform a guarded "initialization" in order to register the
388 // destructor.
389 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
390 }
391
392 return GV;
393}
394
396 llvm::GlobalValue::LinkageTypes Linkage) {
397 // Check to see if we already have a global variable for this
398 // declaration. This can happen when double-emitting function
399 // bodies, e.g. with complete and base constructors.
400 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
401 CharUnits alignment = getContext().getDeclAlign(&D);
402
403 // Store into LocalDeclMap before generating initializer to handle
404 // circular references.
405 llvm::Type *elemTy = ConvertTypeForMem(D.getType());
406 setAddrOfLocalVar(&D, Address(addr, elemTy, alignment));
407
408 // We can't have a VLA here, but we can have a pointer to a VLA,
409 // even though that doesn't really make any sense.
410 // Make sure to evaluate VLA bounds now so that we have them for later.
411 if (D.getType()->isVariablyModifiedType())
412 EmitVariablyModifiedType(D.getType());
413
414 // Save the type in case adding the initializer forces a type change.
415 llvm::Type *expectedType = addr->getType();
416
417 llvm::GlobalVariable *var =
418 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
419
420 // CUDA's local and local static __shared__ variables should not
421 // have any non-empty initializers. This is ensured by Sema.
422 // Whatever initializer such variable may have when it gets here is
423 // a no-op and should not be emitted.
424 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
425 D.hasAttr<CUDASharedAttr>();
426 // If this value has an initializer, emit it.
427 if (D.getInit() && !isCudaSharedVar)
429
430 var->setAlignment(alignment.getAsAlign());
431
432 if (D.hasAttr<AnnotateAttr>())
434
435 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
436 var->addAttribute("bss-section", SA->getName());
437 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
438 var->addAttribute("data-section", SA->getName());
439 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
440 var->addAttribute("rodata-section", SA->getName());
441 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
442 var->addAttribute("relro-section", SA->getName());
443
444 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
445 var->setSection(SA->getName());
446
447 if (D.hasAttr<RetainAttr>())
448 CGM.addUsedGlobal(var);
449 else if (D.hasAttr<UsedAttr>())
451
452 if (CGM.getCodeGenOpts().KeepPersistentStorageVariables)
454
455 // We may have to cast the constant because of the initializer
456 // mismatch above.
457 //
458 // FIXME: It is really dangerous to store this in the map; if anyone
459 // RAUW's the GV uses of this constant will be invalid.
460 llvm::Constant *castedAddr =
461 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
462 LocalDeclMap.find(&D)->second = Address(castedAddr, elemTy, alignment);
463 CGM.setStaticLocalDeclAddress(&D, castedAddr);
464
466
467 // Emit global variable debug descriptor for static vars.
469 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
471 DI->EmitGlobalVariable(var, &D);
472 }
473}
474
475namespace {
476 struct DestroyObject final : EHScopeStack::Cleanup {
477 DestroyObject(Address addr, QualType type,
478 CodeGenFunction::Destroyer *destroyer,
479 bool useEHCleanupForArray)
480 : addr(addr), type(type), destroyer(destroyer),
481 useEHCleanupForArray(useEHCleanupForArray) {}
482
483 Address addr;
485 CodeGenFunction::Destroyer *destroyer;
486 bool useEHCleanupForArray;
487
488 void Emit(CodeGenFunction &CGF, Flags flags) override {
489 // Don't use an EH cleanup recursively from an EH cleanup.
490 bool useEHCleanupForArray =
491 flags.isForNormalCleanup() && this->useEHCleanupForArray;
492
493 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
494 }
495 };
496
497 template <class Derived>
498 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
499 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
500 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
501
502 llvm::Value *NRVOFlag;
503 Address Loc;
504 QualType Ty;
505
506 void Emit(CodeGenFunction &CGF, Flags flags) override {
507 // Along the exceptions path we always execute the dtor.
508 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
509
510 llvm::BasicBlock *SkipDtorBB = nullptr;
511 if (NRVO) {
512 // If we exited via NRVO, we skip the destructor call.
513 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
514 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
515 llvm::Value *DidNRVO =
516 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
517 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
518 CGF.EmitBlock(RunDtorBB);
519 }
520
521 static_cast<Derived *>(this)->emitDestructorCall(CGF);
522
523 if (NRVO) CGF.EmitBlock(SkipDtorBB);
524 }
525
526 virtual ~DestroyNRVOVariable() = default;
527 };
528
529 struct DestroyNRVOVariableCXX final
530 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
531 DestroyNRVOVariableCXX(Address addr, QualType type,
532 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
533 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
534 Dtor(Dtor) {}
535
536 const CXXDestructorDecl *Dtor;
537
538 void emitDestructorCall(CodeGenFunction &CGF) {
540 /*ForVirtualBase=*/false,
541 /*Delegating=*/false, Loc, Ty);
542 }
543 };
544
545 struct DestroyNRVOVariableC final
546 : DestroyNRVOVariable<DestroyNRVOVariableC> {
547 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
548 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
549
550 void emitDestructorCall(CodeGenFunction &CGF) {
551 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
552 }
553 };
554
555 struct CallStackRestore final : EHScopeStack::Cleanup {
556 Address Stack;
557 CallStackRestore(Address Stack) : Stack(Stack) {}
558 bool isRedundantBeforeReturn() override { return true; }
559 void Emit(CodeGenFunction &CGF, Flags flags) override {
560 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
561 CGF.Builder.CreateStackRestore(V);
562 }
563 };
564
565 struct KmpcAllocFree final : EHScopeStack::Cleanup {
566 std::pair<llvm::Value *, llvm::Value *> AddrSizePair;
567 KmpcAllocFree(const std::pair<llvm::Value *, llvm::Value *> &AddrSizePair)
568 : AddrSizePair(AddrSizePair) {}
569 void Emit(CodeGenFunction &CGF, Flags EmissionFlags) override {
570 auto &RT = CGF.CGM.getOpenMPRuntime();
571 RT.getKmpcFreeShared(CGF, AddrSizePair);
572 }
573 };
574
575 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
576 const VarDecl &Var;
577 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
578
579 void Emit(CodeGenFunction &CGF, Flags flags) override {
580 // Compute the address of the local variable, in case it's a
581 // byref or something.
582 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
584 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
586 CGF.EmitExtendGCLifetime(value);
587 }
588 };
589
590 struct CallCleanupFunction final : EHScopeStack::Cleanup {
591 llvm::Constant *CleanupFn;
592 const CGFunctionInfo &FnInfo;
593 const VarDecl &Var;
594
595 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
596 const VarDecl *Var)
597 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
598
599 void Emit(CodeGenFunction &CGF, Flags flags) override {
600 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
602 // Compute the address of the local variable, in case it's a byref
603 // or something.
604 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
605
606 // In some cases, the type of the function argument will be different from
607 // the type of the pointer. An example of this is
608 // void f(void* arg);
609 // __attribute__((cleanup(f))) void *g;
610 //
611 // To fix this we insert a bitcast here.
612 QualType ArgTy = FnInfo.arg_begin()->type;
613 llvm::Value *Arg =
614 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
615
616 CallArgList Args;
617 Args.add(RValue::get(Arg),
618 CGF.getContext().getPointerType(Var.getType()));
619 auto Callee = CGCallee::forDirect(CleanupFn);
620 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
621 }
622 };
623} // end anonymous namespace
624
625/// EmitAutoVarWithLifetime - Does the setup required for an automatic
626/// variable with lifetime.
628 Address addr,
629 Qualifiers::ObjCLifetime lifetime) {
630 switch (lifetime) {
632 llvm_unreachable("present but none");
633
635 // nothing to do
636 break;
637
639 CodeGenFunction::Destroyer *destroyer =
640 (var.hasAttr<ObjCPreciseLifetimeAttr>()
643
644 CleanupKind cleanupKind = CGF.getARCCleanupKind();
645 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
646 cleanupKind & EHCleanup);
647 break;
648 }
650 // nothing to do
651 break;
652
654 // __weak objects always get EH cleanups; otherwise, exceptions
655 // could cause really nasty crashes instead of mere leaks.
656 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
658 /*useEHCleanup*/ true);
659 break;
660 }
661}
662
663static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
664 if (const Expr *e = dyn_cast<Expr>(s)) {
665 // Skip the most common kinds of expressions that make
666 // hierarchy-walking expensive.
667 s = e = e->IgnoreParenCasts();
668
669 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
670 return (ref->getDecl() == &var);
671 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
672 const BlockDecl *block = be->getBlockDecl();
673 for (const auto &I : block->captures()) {
674 if (I.getVariable() == &var)
675 return true;
676 }
677 }
678 }
679
680 for (const Stmt *SubStmt : s->children())
681 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
682 if (SubStmt && isAccessedBy(var, SubStmt))
683 return true;
684
685 return false;
686}
687
688static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
689 if (!decl) return false;
690 if (!isa<VarDecl>(decl)) return false;
691 const VarDecl *var = cast<VarDecl>(decl);
692 return isAccessedBy(*var, e);
693}
694
696 const LValue &destLV, const Expr *init) {
697 bool needsCast = false;
698
699 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
700 switch (castExpr->getCastKind()) {
701 // Look through casts that don't require representation changes.
702 case CK_NoOp:
703 case CK_BitCast:
704 case CK_BlockPointerToObjCPointerCast:
705 needsCast = true;
706 break;
707
708 // If we find an l-value to r-value cast from a __weak variable,
709 // emit this operation as a copy or move.
710 case CK_LValueToRValue: {
711 const Expr *srcExpr = castExpr->getSubExpr();
712 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
713 return false;
714
715 // Emit the source l-value.
716 LValue srcLV = CGF.EmitLValue(srcExpr);
717
718 // Handle a formal type change to avoid asserting.
719 auto srcAddr = srcLV.getAddress();
720 if (needsCast) {
721 srcAddr = srcAddr.withElementType(destLV.getAddress().getElementType());
722 }
723
724 // If it was an l-value, use objc_copyWeak.
725 if (srcExpr->isLValue()) {
726 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
727 } else {
728 assert(srcExpr->isXValue());
729 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
730 }
731 return true;
732 }
733
734 // Stop at anything else.
735 default:
736 return false;
737 }
738
739 init = castExpr->getSubExpr();
740 }
741 return false;
742}
743
745 LValue &lvalue,
746 const VarDecl *var) {
747 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
748}
749
750void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
752 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
753 return;
754
755 auto Nullability = LHS.getType()->getNullability();
756 if (!Nullability || *Nullability != NullabilityKind::NonNull)
757 return;
758
759 // Check if the right hand side of the assignment is nonnull, if the left
760 // hand side must be nonnull.
761 SanitizerScope SanScope(this);
762 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
763 llvm::Constant *StaticData[] = {
765 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
766 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
767 EmitCheck({{IsNotNull, SanitizerKind::SO_NullabilityAssign}},
768 SanitizerHandler::TypeMismatch, StaticData, RHS);
769}
770
771void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
772 LValue lvalue, bool capturedByInit) {
773 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
774 if (!lifetime) {
775 llvm::Value *value = EmitScalarExpr(init);
776 if (capturedByInit)
777 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
778 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
779 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
780 return;
781 }
782
783 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
784 init = DIE->getExpr();
785
786 // If we're emitting a value with lifetime, we have to do the
787 // initialization *before* we leave the cleanup scopes.
788 if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
789 CodeGenFunction::RunCleanupsScope Scope(*this);
790 return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
791 }
792
793 // We have to maintain the illusion that the variable is
794 // zero-initialized. If the variable might be accessed in its
795 // initializer, zero-initialize before running the initializer, then
796 // actually perform the initialization with an assign.
797 bool accessedByInit = false;
798 if (lifetime != Qualifiers::OCL_ExplicitNone)
799 accessedByInit = (capturedByInit || isAccessedBy(D, init));
800 if (accessedByInit) {
801 LValue tempLV = lvalue;
802 // Drill down to the __block object if necessary.
803 if (capturedByInit) {
804 // We can use a simple GEP for this because it can't have been
805 // moved yet.
807 cast<VarDecl>(D),
808 /*follow*/ false));
809 }
810
811 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
812 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
813
814 // If __weak, we want to use a barrier under certain conditions.
815 if (lifetime == Qualifiers::OCL_Weak)
816 EmitARCInitWeak(tempLV.getAddress(), zero);
817
818 // Otherwise just do a simple store.
819 else
820 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
821 }
822
823 // Emit the initializer.
824 llvm::Value *value = nullptr;
825
826 switch (lifetime) {
828 llvm_unreachable("present but none");
829
831 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
832 value = EmitARCRetainScalarExpr(init);
833 break;
834 }
835 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
836 // that we omit the retain, and causes non-autoreleased return values to be
837 // immediately released.
838 [[fallthrough]];
839 }
840
843 break;
844
846 // If it's not accessed by the initializer, try to emit the
847 // initialization with a copy or move.
848 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
849 return;
850 }
851
852 // No way to optimize a producing initializer into this. It's not
853 // worth optimizing for, because the value will immediately
854 // disappear in the common case.
855 value = EmitScalarExpr(init);
856
857 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
858 if (accessedByInit)
859 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
860 else
861 EmitARCInitWeak(lvalue.getAddress(), value);
862 return;
863 }
864
867 break;
868 }
869
870 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
871
872 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
873
874 // If the variable might have been accessed by its initializer, we
875 // might have to initialize with a barrier. We have to do this for
876 // both __weak and __strong, but __weak got filtered out above.
877 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
878 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
879 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
881 return;
882 }
883
884 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
885}
886
887/// Decide whether we can emit the non-zero parts of the specified initializer
888/// with equal or fewer than NumStores scalar stores.
889static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
890 unsigned &NumStores) {
891 // Zero and Undef never requires any extra stores.
892 if (isa<llvm::ConstantAggregateZero>(Init) ||
893 isa<llvm::ConstantPointerNull>(Init) ||
894 isa<llvm::UndefValue>(Init))
895 return true;
896 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
897 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
898 isa<llvm::ConstantExpr>(Init))
899 return Init->isNullValue() || NumStores--;
900
901 // See if we can emit each element.
902 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
903 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
904 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
905 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
906 return false;
907 }
908 return true;
909 }
910
911 if (llvm::ConstantDataSequential *CDS =
912 dyn_cast<llvm::ConstantDataSequential>(Init)) {
913 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
914 llvm::Constant *Elt = CDS->getElementAsConstant(i);
915 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
916 return false;
917 }
918 return true;
919 }
920
921 // Anything else is hard and scary.
922 return false;
923}
924
925/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
926/// the scalar stores that would be required.
928 llvm::Constant *Init, Address Loc,
929 bool isVolatile, CGBuilderTy &Builder,
930 bool IsAutoInit) {
931 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
932 "called emitStoresForInitAfterBZero for zero or undef value.");
933
934 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
935 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
936 isa<llvm::ConstantExpr>(Init)) {
937 auto *I = Builder.CreateStore(Init, Loc, isVolatile);
938 if (IsAutoInit)
939 I->addAnnotationMetadata("auto-init");
940 return;
941 }
942
943 if (llvm::ConstantDataSequential *CDS =
944 dyn_cast<llvm::ConstantDataSequential>(Init)) {
945 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
946 llvm::Constant *Elt = CDS->getElementAsConstant(i);
947
948 // If necessary, get a pointer to the element and emit it.
949 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
951 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
952 Builder, IsAutoInit);
953 }
954 return;
955 }
956
957 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
958 "Unknown value type!");
959
960 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
961 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
962
963 // If necessary, get a pointer to the element and emit it.
964 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
966 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
967 isVolatile, Builder, IsAutoInit);
968 }
969}
970
971/// Decide whether we should use bzero plus some stores to initialize a local
972/// variable instead of using a memcpy from a constant global. It is beneficial
973/// to use bzero if the global is all zeros, or mostly zeros and large.
974static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
975 uint64_t GlobalSize) {
976 // If a global is all zeros, always use a bzero.
977 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
978
979 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
980 // do it if it will require 6 or fewer scalar stores.
981 // TODO: Should budget depends on the size? Avoiding a large global warrants
982 // plopping in more stores.
983 unsigned StoreBudget = 6;
984 uint64_t SizeLimit = 32;
985
986 return GlobalSize > SizeLimit &&
988}
989
990/// Decide whether we should use memset to initialize a local variable instead
991/// of using a memcpy from a constant global. Assumes we've already decided to
992/// not user bzero.
993/// FIXME We could be more clever, as we are for bzero above, and generate
994/// memset followed by stores. It's unclear that's worth the effort.
995static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
996 uint64_t GlobalSize,
997 const llvm::DataLayout &DL) {
998 uint64_t SizeLimit = 32;
999 if (GlobalSize <= SizeLimit)
1000 return nullptr;
1001 return llvm::isBytewiseValue(Init, DL);
1002}
1003
1004/// Decide whether we want to split a constant structure or array store into a
1005/// sequence of its fields' stores. This may cost us code size and compilation
1006/// speed, but plays better with store optimizations.
1008 uint64_t GlobalByteSize) {
1009 // Don't break things that occupy more than one cacheline.
1010 uint64_t ByteSizeLimit = 64;
1011 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1012 return false;
1013 if (GlobalByteSize <= ByteSizeLimit)
1014 return true;
1015 return false;
1016}
1017
1018enum class IsPattern { No, Yes };
1019
1020/// Generate a constant filled with either a pattern or zeroes.
1021static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1022 llvm::Type *Ty) {
1023 if (isPattern == IsPattern::Yes)
1024 return initializationPatternFor(CGM, Ty);
1025 else
1026 return llvm::Constant::getNullValue(Ty);
1027}
1028
1029static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1030 llvm::Constant *constant);
1031
1032/// Helper function for constWithPadding() to deal with padding in structures.
1033static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1034 IsPattern isPattern,
1035 llvm::StructType *STy,
1036 llvm::Constant *constant) {
1037 const llvm::DataLayout &DL = CGM.getDataLayout();
1038 const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1039 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1040 unsigned SizeSoFar = 0;
1042 bool NestedIntact = true;
1043 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1044 unsigned CurOff = Layout->getElementOffset(i);
1045 if (SizeSoFar < CurOff) {
1046 assert(!STy->isPacked());
1047 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1048 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1049 }
1050 llvm::Constant *CurOp;
1051 if (constant->isZeroValue())
1052 CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1053 else
1054 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1055 auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1056 if (CurOp != NewOp)
1057 NestedIntact = false;
1058 Values.push_back(NewOp);
1059 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1060 }
1061 unsigned TotalSize = Layout->getSizeInBytes();
1062 if (SizeSoFar < TotalSize) {
1063 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1064 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1065 }
1066 if (NestedIntact && Values.size() == STy->getNumElements())
1067 return constant;
1068 return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1069}
1070
1071/// Replace all padding bytes in a given constant with either a pattern byte or
1072/// 0x00.
1073static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1074 llvm::Constant *constant) {
1075 llvm::Type *OrigTy = constant->getType();
1076 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1077 return constStructWithPadding(CGM, isPattern, STy, constant);
1078 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1080 uint64_t Size = ArrayTy->getNumElements();
1081 if (!Size)
1082 return constant;
1083 llvm::Type *ElemTy = ArrayTy->getElementType();
1084 bool ZeroInitializer = constant->isNullValue();
1085 llvm::Constant *OpValue, *PaddedOp;
1086 if (ZeroInitializer) {
1087 OpValue = llvm::Constant::getNullValue(ElemTy);
1088 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1089 }
1090 for (unsigned Op = 0; Op != Size; ++Op) {
1091 if (!ZeroInitializer) {
1092 OpValue = constant->getAggregateElement(Op);
1093 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1094 }
1095 Values.push_back(PaddedOp);
1096 }
1097 auto *NewElemTy = Values[0]->getType();
1098 if (NewElemTy == ElemTy)
1099 return constant;
1100 auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1101 return llvm::ConstantArray::get(NewArrayTy, Values);
1102 }
1103 // FIXME: Add handling for tail padding in vectors. Vectors don't
1104 // have padding between or inside elements, but the total amount of
1105 // data can be less than the allocated size.
1106 return constant;
1107}
1108
1110 llvm::Constant *Constant,
1111 CharUnits Align) {
1112 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1113 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1114 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1115 return CC->getNameAsString();
1116 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1117 return CD->getNameAsString();
1118 return std::string(getMangledName(FD));
1119 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1120 return OM->getNameAsString();
1121 } else if (isa<BlockDecl>(DC)) {
1122 return "<block>";
1123 } else if (isa<CapturedDecl>(DC)) {
1124 return "<captured>";
1125 } else {
1126 llvm_unreachable("expected a function or method");
1127 }
1128 };
1129
1130 // Form a simple per-variable cache of these values in case we find we
1131 // want to reuse them.
1132 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1133 if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1134 auto *Ty = Constant->getType();
1135 bool isConstant = true;
1136 llvm::GlobalVariable *InsertBefore = nullptr;
1137 unsigned AS =
1139 std::string Name;
1140 if (D.hasGlobalStorage())
1141 Name = getMangledName(&D).str() + ".const";
1142 else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1143 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1144 else
1145 llvm_unreachable("local variable has no parent function or method");
1146 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1147 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1148 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1149 GV->setAlignment(Align.getAsAlign());
1150 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1151 CacheEntry = GV;
1152 } else if (CacheEntry->getAlignment() < uint64_t(Align.getQuantity())) {
1153 CacheEntry->setAlignment(Align.getAsAlign());
1154 }
1155
1156 return Address(CacheEntry, CacheEntry->getValueType(), Align);
1157}
1158
1160 const VarDecl &D,
1161 CGBuilderTy &Builder,
1162 llvm::Constant *Constant,
1163 CharUnits Align) {
1164 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1165 return SrcPtr.withElementType(CGM.Int8Ty);
1166}
1167
1169 Address Loc, bool isVolatile,
1170 CGBuilderTy &Builder,
1171 llvm::Constant *constant, bool IsAutoInit) {
1172 auto *Ty = constant->getType();
1173 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1174 if (!ConstantSize)
1175 return;
1176
1177 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1178 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1179 if (canDoSingleStore) {
1180 auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1181 if (IsAutoInit)
1182 I->addAnnotationMetadata("auto-init");
1183 return;
1184 }
1185
1186 auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1187
1188 // If the initializer is all or mostly the same, codegen with bzero / memset
1189 // then do a few stores afterward.
1190 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1191 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1192 SizeVal, isVolatile);
1193 if (IsAutoInit)
1194 I->addAnnotationMetadata("auto-init");
1195
1196 bool valueAlreadyCorrect =
1197 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1198 if (!valueAlreadyCorrect) {
1199 Loc = Loc.withElementType(Ty);
1200 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1201 IsAutoInit);
1202 }
1203 return;
1204 }
1205
1206 // If the initializer is a repeated byte pattern, use memset.
1207 llvm::Value *Pattern =
1208 shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1209 if (Pattern) {
1210 uint64_t Value = 0x00;
1211 if (!isa<llvm::UndefValue>(Pattern)) {
1212 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1213 assert(AP.getBitWidth() <= 8);
1214 Value = AP.getLimitedValue();
1215 }
1216 auto *I = Builder.CreateMemSet(
1217 Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1218 if (IsAutoInit)
1219 I->addAnnotationMetadata("auto-init");
1220 return;
1221 }
1222
1223 // If the initializer is small or trivialAutoVarInit is set, use a handful of
1224 // stores.
1225 bool IsTrivialAutoVarInitPattern =
1226 CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==
1228 if (shouldSplitConstantStore(CGM, ConstantSize)) {
1229 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1230 if (STy == Loc.getElementType() ||
1231 (STy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
1232 const llvm::StructLayout *Layout =
1233 CGM.getDataLayout().getStructLayout(STy);
1234 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1235 CharUnits CurOff =
1236 CharUnits::fromQuantity(Layout->getElementOffset(i));
1237 Address EltPtr = Builder.CreateConstInBoundsByteGEP(
1238 Loc.withElementType(CGM.Int8Ty), CurOff);
1239 emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1240 constant->getAggregateElement(i), IsAutoInit);
1241 }
1242 return;
1243 }
1244 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1245 if (ATy == Loc.getElementType() ||
1246 (ATy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
1247 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1248 Address EltPtr = Builder.CreateConstGEP(
1249 Loc.withElementType(ATy->getElementType()), i);
1250 emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
1251 constant->getAggregateElement(i), IsAutoInit);
1252 }
1253 return;
1254 }
1255 }
1256 }
1257
1258 // Copy from a global.
1259 auto *I =
1260 Builder.CreateMemCpy(Loc,
1262 CGM, D, Builder, constant, Loc.getAlignment()),
1263 SizeVal, isVolatile);
1264 if (IsAutoInit)
1265 I->addAnnotationMetadata("auto-init");
1266}
1267
1269 Address Loc, bool isVolatile,
1270 CGBuilderTy &Builder) {
1271 llvm::Type *ElTy = Loc.getElementType();
1272 llvm::Constant *constant =
1273 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1274 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1275 /*IsAutoInit=*/true);
1276}
1277
1279 Address Loc, bool isVolatile,
1280 CGBuilderTy &Builder) {
1281 llvm::Type *ElTy = Loc.getElementType();
1282 llvm::Constant *constant = constWithPadding(
1283 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1284 assert(!isa<llvm::UndefValue>(constant));
1285 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1286 /*IsAutoInit=*/true);
1287}
1288
1289static bool containsUndef(llvm::Constant *constant) {
1290 auto *Ty = constant->getType();
1291 if (isa<llvm::UndefValue>(constant))
1292 return true;
1293 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1294 for (llvm::Use &Op : constant->operands())
1295 if (containsUndef(cast<llvm::Constant>(Op)))
1296 return true;
1297 return false;
1298}
1299
1300static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1301 llvm::Constant *constant) {
1302 auto *Ty = constant->getType();
1303 if (isa<llvm::UndefValue>(constant))
1304 return patternOrZeroFor(CGM, isPattern, Ty);
1305 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1306 return constant;
1307 if (!containsUndef(constant))
1308 return constant;
1309 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1310 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1311 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1312 Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1313 }
1314 if (Ty->isStructTy())
1315 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1316 if (Ty->isArrayTy())
1317 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1318 assert(Ty->isVectorTy());
1319 return llvm::ConstantVector::get(Values);
1320}
1321
1322/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1323/// variable declaration with auto, register, or no storage class specifier.
1324/// These turn into simple stack objects, or GlobalValues depending on target.
1326 AutoVarEmission emission = EmitAutoVarAlloca(D);
1327 EmitAutoVarInit(emission);
1328 EmitAutoVarCleanups(emission);
1329}
1330
1331/// Emit a lifetime.begin marker if some criteria are satisfied.
1332/// \return a pointer to the temporary size Value if a marker was emitted, null
1333/// otherwise
1334llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
1335 llvm::Value *Addr) {
1336 if (!ShouldEmitLifetimeMarkers)
1337 return nullptr;
1338
1339 assert(Addr->getType()->getPointerAddressSpace() ==
1340 CGM.getDataLayout().getAllocaAddrSpace() &&
1341 "Pointer should be in alloca address space");
1342 llvm::Value *SizeV = llvm::ConstantInt::get(
1343 Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
1344 llvm::CallInst *C =
1345 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1346 C->setDoesNotThrow();
1347 return SizeV;
1348}
1349
1350void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1351 assert(Addr->getType()->getPointerAddressSpace() ==
1352 CGM.getDataLayout().getAllocaAddrSpace() &&
1353 "Pointer should be in alloca address space");
1354 llvm::CallInst *C =
1355 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1356 C->setDoesNotThrow();
1357}
1358
1360 auto NL = ApplyDebugLocation::CreateEmpty(*this);
1361 llvm::Value *V = Builder.CreateLoad(Addr, "fake.use");
1362 llvm::CallInst *C = Builder.CreateCall(CGM.getLLVMFakeUseFn(), {V});
1363 C->setDoesNotThrow();
1364 C->setTailCallKind(llvm::CallInst::TCK_NoTail);
1365}
1366
1368 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1369 // For each dimension stores its QualType and corresponding
1370 // size-expression Value.
1373
1374 // Break down the array into individual dimensions.
1375 QualType Type1D = D.getType();
1376 while (getContext().getAsVariableArrayType(Type1D)) {
1377 auto VlaSize = getVLAElements1D(Type1D);
1378 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1379 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1380 else {
1381 // Generate a locally unique name for the size expression.
1382 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1383 SmallString<12> Buffer;
1384 StringRef NameRef = Name.toStringRef(Buffer);
1385 auto &Ident = getContext().Idents.getOwn(NameRef);
1386 VLAExprNames.push_back(&Ident);
1387 auto SizeExprAddr =
1388 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1389 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1390 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1391 Type1D.getUnqualifiedType());
1392 }
1393 Type1D = VlaSize.Type;
1394 }
1395
1396 if (!EmitDebugInfo)
1397 return;
1398
1399 // Register each dimension's size-expression with a DILocalVariable,
1400 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1401 // to describe this array.
1402 unsigned NameIdx = 0;
1403 for (auto &VlaSize : Dimensions) {
1404 llvm::Metadata *MD;
1405 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1406 MD = llvm::ConstantAsMetadata::get(C);
1407 else {
1408 // Create an artificial VarDecl to generate debug info for.
1409 const IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1411 SizeTy->getScalarSizeInBits(), false);
1412 auto *ArtificialDecl = VarDecl::Create(
1413 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1414 D.getLocation(), D.getLocation(), NameIdent, QT,
1415 getContext().CreateTypeSourceInfo(QT), SC_Auto);
1416 ArtificialDecl->setImplicit();
1417
1418 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1419 Builder);
1420 }
1421 assert(MD && "No Size expression debug node created");
1422 DI->registerVLASizeExpression(VlaSize.Type, MD);
1423 }
1424}
1425
1426/// Return the maximum size of an aggregate for which we generate a fake use
1427/// intrinsic when -fextend-variable-liveness is in effect.
1428static uint64_t maxFakeUseAggregateSize(const ASTContext &C) {
1429 return 4 * C.getTypeSize(C.UnsignedIntTy);
1430}
1431
1432// Helper function to determine whether a variable's or parameter's lifetime
1433// should be extended.
1434static bool shouldExtendLifetime(const ASTContext &Context,
1435 const Decl *FuncDecl, const VarDecl &D,
1436 ImplicitParamDecl *CXXABIThisDecl) {
1437 // When we're not inside a valid function it is unlikely that any
1438 // lifetime extension is useful.
1439 if (!FuncDecl)
1440 return false;
1441 if (FuncDecl->isImplicit())
1442 return false;
1443 // Do not extend compiler-created variables except for the this pointer.
1444 if (D.isImplicit() && &D != CXXABIThisDecl)
1445 return false;
1446 QualType Ty = D.getType();
1447 // No need to extend volatiles, they have a memory location.
1448 if (Ty.isVolatileQualified())
1449 return false;
1450 // Don't extend variables that exceed a certain size.
1451 if (Context.getTypeSize(Ty) > maxFakeUseAggregateSize(Context))
1452 return false;
1453 // Do not extend variables in nodebug or optnone functions.
1454 if (FuncDecl->hasAttr<NoDebugAttr>() || FuncDecl->hasAttr<OptimizeNoneAttr>())
1455 return false;
1456 return true;
1457}
1458
1459/// EmitAutoVarAlloca - Emit the alloca and debug information for a
1460/// local variable. Does not emit initialization or destruction.
1461CodeGenFunction::AutoVarEmission
1463 QualType Ty = D.getType();
1464 assert(
1467
1468 AutoVarEmission emission(D);
1469
1470 bool isEscapingByRef = D.isEscapingByref();
1471 emission.IsEscapingByRef = isEscapingByRef;
1472
1473 CharUnits alignment = getContext().getDeclAlign(&D);
1474
1475 // If the type is variably-modified, emit all the VLA sizes for it.
1476 if (Ty->isVariablyModifiedType())
1478
1479 auto *DI = getDebugInfo();
1480 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1481
1482 Address address = Address::invalid();
1483 RawAddress AllocaAddr = RawAddress::invalid();
1484 Address OpenMPLocalAddr = Address::invalid();
1485 if (CGM.getLangOpts().OpenMPIRBuilder)
1486 OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1487 else
1488 OpenMPLocalAddr =
1489 getLangOpts().OpenMP
1491 : Address::invalid();
1492
1493 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1494
1495 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1496 address = OpenMPLocalAddr;
1497 AllocaAddr = OpenMPLocalAddr;
1498 } else if (Ty->isConstantSizeType()) {
1499 // If this value is an array or struct with a statically determinable
1500 // constant initializer, there are optimizations we can do.
1501 //
1502 // TODO: We should constant-evaluate the initializer of any variable,
1503 // as long as it is initialized by a constant expression. Currently,
1504 // isConstantInitializer produces wrong answers for structs with
1505 // reference or bitfield members, and a few other cases, and checking
1506 // for POD-ness protects us from some of these.
1507 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1508 (D.isConstexpr() ||
1509 ((Ty.isPODType(getContext()) ||
1510 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1511 D.getInit()->isConstantInitializer(getContext(), false)))) {
1512
1513 // If the variable's a const type, and it's neither an NRVO
1514 // candidate nor a __block variable and has no mutable members,
1515 // emit it as a global instead.
1516 // Exception is if a variable is located in non-constant address space
1517 // in OpenCL.
1518 bool NeedsDtor =
1519 D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
1520 if ((!getLangOpts().OpenCL ||
1522 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1523 !isEscapingByRef &&
1524 Ty.isConstantStorage(getContext(), true, !NeedsDtor))) {
1525 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1526
1527 // Signal this condition to later callbacks.
1528 emission.Addr = Address::invalid();
1529 assert(emission.wasEmittedAsGlobal());
1530 return emission;
1531 }
1532
1533 // Otherwise, tell the initialization code that we're in this case.
1534 emission.IsConstantAggregate = true;
1535 }
1536
1537 // A normal fixed sized variable becomes an alloca in the entry block,
1538 // unless:
1539 // - it's an NRVO variable.
1540 // - we are compiling OpenMP and it's an OpenMP local variable.
1541 if (NRVO) {
1542 // The named return value optimization: allocate this variable in the
1543 // return slot, so that we can elide the copy when returning this
1544 // variable (C++0x [class.copy]p34).
1545 address = ReturnValue;
1546 AllocaAddr =
1549 ;
1550
1551 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1552 const auto *RD = RecordTy->getDecl();
1553 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1554 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1555 RD->isNonTrivialToPrimitiveDestroy()) {
1556 // Create a flag that is used to indicate when the NRVO was applied
1557 // to this variable. Set it to zero to indicate that NRVO was not
1558 // applied.
1559 llvm::Value *Zero = Builder.getFalse();
1560 RawAddress NRVOFlag =
1561 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1563 Builder.CreateStore(Zero, NRVOFlag);
1564
1565 // Record the NRVO flag for this variable.
1566 NRVOFlags[&D] = NRVOFlag.getPointer();
1567 emission.NRVOFlag = NRVOFlag.getPointer();
1568 }
1569 }
1570 } else {
1571 CharUnits allocaAlignment;
1572 llvm::Type *allocaTy;
1573 if (isEscapingByRef) {
1574 auto &byrefInfo = getBlockByrefInfo(&D);
1575 allocaTy = byrefInfo.Type;
1576 allocaAlignment = byrefInfo.ByrefAlignment;
1577 } else {
1578 allocaTy = ConvertTypeForMem(Ty);
1579 allocaAlignment = alignment;
1580 }
1581
1582 // Create the alloca. Note that we set the name separately from
1583 // building the instruction so that it's there even in no-asserts
1584 // builds.
1585 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1586 /*ArraySize=*/nullptr, &AllocaAddr);
1587
1588 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1589 // the catch parameter starts in the catchpad instruction, and we can't
1590 // insert code in those basic blocks.
1591 bool IsMSCatchParam =
1592 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1593
1594 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1595 // if we don't have a valid insertion point (?).
1596 if (HaveInsertPoint() && !IsMSCatchParam) {
1597 // If there's a jump into the lifetime of this variable, its lifetime
1598 // gets broken up into several regions in IR, which requires more work
1599 // to handle correctly. For now, just omit the intrinsics; this is a
1600 // rare case, and it's better to just be conservatively correct.
1601 // PR28267.
1602 //
1603 // We have to do this in all language modes if there's a jump past the
1604 // declaration. We also have to do it in C if there's a jump to an
1605 // earlier point in the current block because non-VLA lifetimes begin as
1606 // soon as the containing block is entered, not when its variables
1607 // actually come into scope; suppressing the lifetime annotations
1608 // completely in this case is unnecessarily pessimistic, but again, this
1609 // is rare.
1610 if (!Bypasses.IsBypassed(&D) &&
1612 llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1613 emission.SizeForLifetimeMarkers =
1614 EmitLifetimeStart(Size, AllocaAddr.getPointer());
1615 }
1616 } else {
1617 assert(!emission.useLifetimeMarkers());
1618 }
1619 }
1620 } else {
1622
1623 // Delayed globalization for variable length declarations. This ensures that
1624 // the expression representing the length has been emitted and can be used
1625 // by the definition of the VLA. Since this is an escaped declaration, in
1626 // OpenMP we have to use a call to __kmpc_alloc_shared(). The matching
1627 // deallocation call to __kmpc_free_shared() is emitted later.
1628 bool VarAllocated = false;
1629 if (getLangOpts().OpenMPIsTargetDevice) {
1630 auto &RT = CGM.getOpenMPRuntime();
1631 if (RT.isDelayedVariableLengthDecl(*this, &D)) {
1632 // Emit call to __kmpc_alloc_shared() instead of the alloca.
1633 std::pair<llvm::Value *, llvm::Value *> AddrSizePair =
1634 RT.getKmpcAllocShared(*this, &D);
1635
1636 // Save the address of the allocation:
1637 LValue Base = MakeAddrLValue(AddrSizePair.first, D.getType(),
1640 address = Base.getAddress();
1641
1642 // Push a cleanup block to emit the call to __kmpc_free_shared in the
1643 // appropriate location at the end of the scope of the
1644 // __kmpc_alloc_shared functions:
1645 pushKmpcAllocFree(NormalCleanup, AddrSizePair);
1646
1647 // Mark variable as allocated:
1648 VarAllocated = true;
1649 }
1650 }
1651
1652 if (!VarAllocated) {
1653 if (!DidCallStackSave) {
1654 // Save the stack.
1655 Address Stack =
1657
1658 llvm::Value *V = Builder.CreateStackSave();
1659 assert(V->getType() == AllocaInt8PtrTy);
1660 Builder.CreateStore(V, Stack);
1661
1662 DidCallStackSave = true;
1663
1664 // Push a cleanup block and restore the stack there.
1665 // FIXME: in general circumstances, this should be an EH cleanup.
1667 }
1668
1669 auto VlaSize = getVLASize(Ty);
1670 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1671
1672 // Allocate memory for the array.
1673 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1674 &AllocaAddr);
1675 }
1676
1677 // If we have debug info enabled, properly describe the VLA dimensions for
1678 // this type by registering the vla size expression for each of the
1679 // dimensions.
1680 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1681 }
1682
1683 setAddrOfLocalVar(&D, address);
1684 emission.Addr = address;
1685 emission.AllocaAddr = AllocaAddr;
1686
1687 // Emit debug info for local var declaration.
1688 if (EmitDebugInfo && HaveInsertPoint()) {
1689 Address DebugAddr = address;
1690 bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1691 DI->setLocation(D.getLocation());
1692
1693 // If NRVO, use a pointer to the return address.
1694 if (UsePointerValue) {
1695 DebugAddr = ReturnValuePointer;
1696 AllocaAddr = ReturnValuePointer;
1697 }
1698 (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
1699 UsePointerValue);
1700 }
1701
1702 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1703 EmitVarAnnotations(&D, address.emitRawPointer(*this));
1704
1705 // Make sure we call @llvm.lifetime.end.
1706 if (emission.useLifetimeMarkers())
1707 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1708 emission.getOriginalAllocatedAddress(),
1709 emission.getSizeForLifetimeMarkers());
1710
1711 // Analogous to lifetime markers, we use a 'cleanup' to emit fake.use
1712 // calls for local variables. We are exempting volatile variables and
1713 // non-scalars larger than 4 times the size of an unsigned int. Larger
1714 // non-scalars are often allocated in memory and may create unnecessary
1715 // overhead.
1716 if (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
1718 if (shouldExtendLifetime(getContext(), CurCodeDecl, D, CXXABIThisDecl))
1719 EHStack.pushCleanup<FakeUse>(NormalFakeUse,
1720 emission.getAllocatedAddress());
1721 }
1722
1723 return emission;
1724}
1725
1726static bool isCapturedBy(const VarDecl &, const Expr *);
1727
1728/// Determines whether the given __block variable is potentially
1729/// captured by the given statement.
1730static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1731 if (const Expr *E = dyn_cast<Expr>(S))
1732 return isCapturedBy(Var, E);
1733 for (const Stmt *SubStmt : S->children())
1734 if (isCapturedBy(Var, SubStmt))
1735 return true;
1736 return false;
1737}
1738
1739/// Determines whether the given __block variable is potentially
1740/// captured by the given expression.
1741static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1742 // Skip the most common kinds of expressions that make
1743 // hierarchy-walking expensive.
1744 E = E->IgnoreParenCasts();
1745
1746 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1747 const BlockDecl *Block = BE->getBlockDecl();
1748 for (const auto &I : Block->captures()) {
1749 if (I.getVariable() == &Var)
1750 return true;
1751 }
1752
1753 // No need to walk into the subexpressions.
1754 return false;
1755 }
1756
1757 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1758 const CompoundStmt *CS = SE->getSubStmt();
1759 for (const auto *BI : CS->body())
1760 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1761 if (isCapturedBy(Var, BIE))
1762 return true;
1763 }
1764 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1765 // special case declarations
1766 for (const auto *I : DS->decls()) {
1767 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1768 const Expr *Init = VD->getInit();
1769 if (Init && isCapturedBy(Var, Init))
1770 return true;
1771 }
1772 }
1773 }
1774 else
1775 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1776 // Later, provide code to poke into statements for capture analysis.
1777 return true;
1778 return false;
1779 }
1780
1781 for (const Stmt *SubStmt : E->children())
1782 if (isCapturedBy(Var, SubStmt))
1783 return true;
1784
1785 return false;
1786}
1787
1788/// Determine whether the given initializer is trivial in the sense
1789/// that it requires no code to be generated.
1791 if (!Init)
1792 return true;
1793
1794 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1795 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1796 if (Constructor->isTrivial() &&
1797 Constructor->isDefaultConstructor() &&
1798 !Construct->requiresZeroInitialization())
1799 return true;
1800
1801 return false;
1802}
1803
1804void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1805 const VarDecl &D,
1806 Address Loc) {
1807 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1808 auto trivialAutoVarInitMaxSize =
1809 getContext().getLangOpts().TrivialAutoVarInitMaxSize;
1811 bool isVolatile = type.isVolatileQualified();
1812 if (!Size.isZero()) {
1813 // We skip auto-init variables by their alloc size. Take this as an example:
1814 // "struct Foo {int x; char buff[1024];}" Assume the max-size flag is 1023.
1815 // All Foo type variables will be skipped. Ideally, we only skip the buff
1816 // array and still auto-init X in this example.
1817 // TODO: Improve the size filtering to by member size.
1818 auto allocSize = CGM.getDataLayout().getTypeAllocSize(Loc.getElementType());
1819 switch (trivialAutoVarInit) {
1821 llvm_unreachable("Uninitialized handled by caller");
1823 if (CGM.stopAutoInit())
1824 return;
1825 if (trivialAutoVarInitMaxSize > 0 &&
1826 allocSize > trivialAutoVarInitMaxSize)
1827 return;
1828 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1829 break;
1831 if (CGM.stopAutoInit())
1832 return;
1833 if (trivialAutoVarInitMaxSize > 0 &&
1834 allocSize > trivialAutoVarInitMaxSize)
1835 return;
1836 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1837 break;
1838 }
1839 return;
1840 }
1841
1842 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1843 // them, so emit a memcpy with the VLA size to initialize each element.
1844 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1845 // will catch that code, but there exists code which generates zero-sized
1846 // VLAs. Be nice and initialize whatever they requested.
1847 const auto *VlaType = getContext().getAsVariableArrayType(type);
1848 if (!VlaType)
1849 return;
1850 auto VlaSize = getVLASize(VlaType);
1851 auto SizeVal = VlaSize.NumElts;
1852 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1853 switch (trivialAutoVarInit) {
1855 llvm_unreachable("Uninitialized handled by caller");
1856
1858 if (CGM.stopAutoInit())
1859 return;
1860 if (!EltSize.isOne())
1861 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1862 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1863 SizeVal, isVolatile);
1864 I->addAnnotationMetadata("auto-init");
1865 break;
1866 }
1867
1869 if (CGM.stopAutoInit())
1870 return;
1871 llvm::Type *ElTy = Loc.getElementType();
1872 llvm::Constant *Constant = constWithPadding(
1873 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1874 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1875 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1876 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1877 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1878 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1879 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1880 "vla.iszerosized");
1881 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1882 EmitBlock(SetupBB);
1883 if (!EltSize.isOne())
1884 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1885 llvm::Value *BaseSizeInChars =
1886 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1887 Address Begin = Loc.withElementType(Int8Ty);
1888 llvm::Value *End = Builder.CreateInBoundsGEP(Begin.getElementType(),
1889 Begin.emitRawPointer(*this),
1890 SizeVal, "vla.end");
1891 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1892 EmitBlock(LoopBB);
1893 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1894 Cur->addIncoming(Begin.emitRawPointer(*this), OriginBB);
1895 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1896 auto *I =
1897 Builder.CreateMemCpy(Address(Cur, Int8Ty, CurAlign),
1899 CGM, D, Builder, Constant, ConstantAlign),
1900 BaseSizeInChars, isVolatile);
1901 I->addAnnotationMetadata("auto-init");
1902 llvm::Value *Next =
1903 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1904 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1905 Builder.CreateCondBr(Done, ContBB, LoopBB);
1906 Cur->addIncoming(Next, LoopBB);
1907 EmitBlock(ContBB);
1908 } break;
1909 }
1910}
1911
1912void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1913 assert(emission.Variable && "emission was not valid!");
1914
1915 // If this was emitted as a global constant, we're done.
1916 if (emission.wasEmittedAsGlobal()) return;
1917
1918 const VarDecl &D = *emission.Variable;
1920 QualType type = D.getType();
1921
1922 // If this local has an initializer, emit it now.
1923 const Expr *Init = D.getInit();
1924
1925 // If we are at an unreachable point, we don't need to emit the initializer
1926 // unless it contains a label.
1927 if (!HaveInsertPoint()) {
1928 if (!Init || !ContainsLabel(Init)) {
1930 return;
1931 }
1933 }
1934
1935 // Initialize the structure of a __block variable.
1936 if (emission.IsEscapingByRef)
1937 emitByrefStructureInit(emission);
1938
1939 // Initialize the variable here if it doesn't have a initializer and it is a
1940 // C struct that is non-trivial to initialize or an array containing such a
1941 // struct.
1942 if (!Init &&
1943 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1945 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1946 if (emission.IsEscapingByRef)
1947 drillIntoBlockVariable(*this, Dst, &D);
1949 return;
1950 }
1951
1952 // Check whether this is a byref variable that's potentially
1953 // captured and moved by its own initializer. If so, we'll need to
1954 // emit the initializer first, then copy into the variable.
1955 bool capturedByInit =
1956 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1957
1958 bool locIsByrefHeader = !capturedByInit;
1959 const Address Loc =
1960 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1961
1962 auto hasNoTrivialAutoVarInitAttr = [&](const Decl *D) {
1963 return D && D->hasAttr<NoTrivialAutoVarInitAttr>();
1964 };
1965 // Note: constexpr already initializes everything correctly.
1966 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1967 ((D.isConstexpr() || D.getAttr<UninitializedAttr>() ||
1968 hasNoTrivialAutoVarInitAttr(type->getAsTagDecl()) ||
1969 hasNoTrivialAutoVarInitAttr(CurFuncDecl))
1971 : getContext().getLangOpts().getTrivialAutoVarInit());
1972
1973 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1974 if (trivialAutoVarInit ==
1976 return;
1977
1978 // Only initialize a __block's storage: we always initialize the header.
1979 if (emission.IsEscapingByRef && !locIsByrefHeader)
1980 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1981
1982 return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1983 };
1984
1986 return initializeWhatIsTechnicallyUninitialized(Loc);
1987
1988 llvm::Constant *constant = nullptr;
1989 if (emission.IsConstantAggregate ||
1990 D.mightBeUsableInConstantExpressions(getContext())) {
1991 assert(!capturedByInit && "constant init contains a capturing block?");
1993 if (constant && !constant->isZeroValue() &&
1994 (trivialAutoVarInit !=
1996 IsPattern isPattern =
1997 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1998 ? IsPattern::Yes
1999 : IsPattern::No;
2000 // C guarantees that brace-init with fewer initializers than members in
2001 // the aggregate will initialize the rest of the aggregate as-if it were
2002 // static initialization. In turn static initialization guarantees that
2003 // padding is initialized to zero bits. We could instead pattern-init if D
2004 // has any ImplicitValueInitExpr, but that seems to be unintuitive
2005 // behavior.
2006 constant = constWithPadding(CGM, IsPattern::No,
2007 replaceUndef(CGM, isPattern, constant));
2008 }
2009
2010 if (constant && type->isBitIntType() &&
2012 // Constants for long _BitInt types are split into individual bytes.
2013 // Try to fold these back into an integer constant so it can be stored
2014 // properly.
2015 llvm::Type *LoadType =
2016 CGM.getTypes().convertTypeForLoadStore(type, constant->getType());
2017 constant = llvm::ConstantFoldLoadFromConst(
2018 constant, LoadType, llvm::APInt::getZero(32), CGM.getDataLayout());
2019 }
2020 }
2021
2022 if (!constant) {
2023 if (trivialAutoVarInit !=
2025 // At this point, we know D has an Init expression, but isn't a constant.
2026 // - If D is not a scalar, auto-var-init conservatively (members may be
2027 // left uninitialized by constructor Init expressions for example).
2028 // - If D is a scalar, we only need to auto-var-init if there is a
2029 // self-reference. Otherwise, the Init expression should be sufficient.
2030 // It may be that the Init expression uses other uninitialized memory,
2031 // but auto-var-init here would not help, as auto-init would get
2032 // overwritten by Init.
2033 if (!type->isScalarType() || capturedByInit || isAccessedBy(D, Init)) {
2034 initializeWhatIsTechnicallyUninitialized(Loc);
2035 }
2036 }
2038 lv.setNonGC(true);
2039 return EmitExprAsInit(Init, &D, lv, capturedByInit);
2040 }
2041
2043
2044 if (!emission.IsConstantAggregate) {
2045 // For simple scalar/complex initialization, store the value directly.
2047 lv.setNonGC(true);
2048 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
2049 }
2050
2051 emitStoresForConstant(CGM, D, Loc.withElementType(CGM.Int8Ty),
2052 type.isVolatileQualified(), Builder, constant,
2053 /*IsAutoInit=*/false);
2054}
2055
2056/// Emit an expression as an initializer for an object (variable, field, etc.)
2057/// at the given location. The expression is not necessarily the normal
2058/// initializer for the object, and the address is not necessarily
2059/// its normal location.
2060///
2061/// \param init the initializing expression
2062/// \param D the object to act as if we're initializing
2063/// \param lvalue the lvalue to initialize
2064/// \param capturedByInit true if \p D is a __block variable
2065/// whose address is potentially changed by the initializer
2066void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
2067 LValue lvalue, bool capturedByInit) {
2068 QualType type = D->getType();
2069
2070 if (type->isReferenceType()) {
2071 RValue rvalue = EmitReferenceBindingToExpr(init);
2072 if (capturedByInit)
2073 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
2074 EmitStoreThroughLValue(rvalue, lvalue, true);
2075 return;
2076 }
2077 switch (getEvaluationKind(type)) {
2078 case TEK_Scalar:
2079 EmitScalarInit(init, D, lvalue, capturedByInit);
2080 return;
2081 case TEK_Complex: {
2082 ComplexPairTy complex = EmitComplexExpr(init);
2083 if (capturedByInit)
2084 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
2085 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
2086 return;
2087 }
2088 case TEK_Aggregate:
2089 if (type->isAtomicType()) {
2090 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
2091 } else {
2093 if (isa<VarDecl>(D))
2095 else if (auto *FD = dyn_cast<FieldDecl>(D))
2096 Overlap = getOverlapForFieldInit(FD);
2097 // TODO: how can we delay here if D is captured by its initializer?
2098 EmitAggExpr(init,
2101 AggValueSlot::IsNotAliased, Overlap));
2102 }
2103 return;
2104 }
2105 llvm_unreachable("bad evaluation kind");
2106}
2107
2108/// Enter a destroy cleanup for the given local variable.
2110 const CodeGenFunction::AutoVarEmission &emission,
2111 QualType::DestructionKind dtorKind) {
2112 assert(dtorKind != QualType::DK_none);
2113
2114 // Note that for __block variables, we want to destroy the
2115 // original stack object, not the possibly forwarded object.
2116 Address addr = emission.getObjectAddress(*this);
2117
2118 const VarDecl *var = emission.Variable;
2119 QualType type = var->getType();
2120
2121 CleanupKind cleanupKind = NormalAndEHCleanup;
2122 CodeGenFunction::Destroyer *destroyer = nullptr;
2123
2124 switch (dtorKind) {
2125 case QualType::DK_none:
2126 llvm_unreachable("no cleanup for trivially-destructible variable");
2127
2129 // If there's an NRVO flag on the emission, we need a different
2130 // cleanup.
2131 if (emission.NRVOFlag) {
2132 assert(!type->isArrayType());
2133 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
2134 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
2135 emission.NRVOFlag);
2136 return;
2137 }
2138 break;
2139
2141 // Suppress cleanups for pseudo-strong variables.
2142 if (var->isARCPseudoStrong()) return;
2143
2144 // Otherwise, consider whether to use an EH cleanup or not.
2145 cleanupKind = getARCCleanupKind();
2146
2147 // Use the imprecise destroyer by default.
2148 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2150 break;
2151
2153 break;
2154
2157 if (emission.NRVOFlag) {
2158 assert(!type->isArrayType());
2159 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2160 emission.NRVOFlag, type);
2161 return;
2162 }
2163 break;
2164 }
2165
2166 // If we haven't chosen a more specific destroyer, use the default.
2167 if (!destroyer) destroyer = getDestroyer(dtorKind);
2168
2169 // Use an EH cleanup in array destructors iff the destructor itself
2170 // is being pushed as an EH cleanup.
2171 bool useEHCleanup = (cleanupKind & EHCleanup);
2172 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2173 useEHCleanup);
2174}
2175
2176void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2177 assert(emission.Variable && "emission was not valid!");
2178
2179 // If this was emitted as a global constant, we're done.
2180 if (emission.wasEmittedAsGlobal()) return;
2181
2182 // If we don't have an insertion point, we're done. Sema prevents
2183 // us from jumping into any of these scopes anyway.
2184 if (!HaveInsertPoint()) return;
2185
2186 const VarDecl &D = *emission.Variable;
2187
2188 // Check the type for a cleanup.
2189 if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2190 emitAutoVarTypeCleanup(emission, dtorKind);
2191
2192 // In GC mode, honor objc_precise_lifetime.
2193 if (getLangOpts().getGC() != LangOptions::NonGC &&
2194 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2195 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2196 }
2197
2198 // Handle the cleanup attribute.
2199 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2200 const FunctionDecl *FD = CA->getFunctionDecl();
2201
2202 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2203 assert(F && "Could not find function!");
2204
2206 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2207 }
2208
2209 // If this is a block variable, call _Block_object_destroy
2210 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2211 // mode.
2212 if (emission.IsEscapingByRef &&
2213 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2215 if (emission.Variable->getType().isObjCGCWeak())
2216 Flags |= BLOCK_FIELD_IS_WEAK;
2217 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2218 /*LoadBlockVarAddr*/ false,
2219 cxxDestructorCanThrow(emission.Variable->getType()));
2220 }
2221}
2222
2225 switch (kind) {
2226 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2228 return destroyCXXObject;
2232 return destroyARCWeak;
2235 }
2236 llvm_unreachable("Unknown DestructionKind");
2237}
2238
2239/// pushEHDestroy - Push the standard destructor for the given type as
2240/// an EH-only cleanup.
2242 Address addr, QualType type) {
2243 assert(dtorKind && "cannot push destructor for trivial type");
2244 assert(needsEHCleanup(dtorKind));
2245
2246 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2247}
2248
2249/// pushDestroy - Push the standard destructor for the given type as
2250/// at least a normal cleanup.
2252 Address addr, QualType type) {
2253 assert(dtorKind && "cannot push destructor for trivial type");
2254
2255 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2256 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2257 cleanupKind & EHCleanup);
2258}
2259
2260void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2261 QualType type, Destroyer *destroyer,
2262 bool useEHCleanupForArray) {
2263 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2264 destroyer, useEHCleanupForArray);
2265}
2266
2267// Pushes a destroy and defers its deactivation until its
2268// CleanupDeactivationScope is exited.
2271 assert(dtorKind && "cannot push destructor for trivial type");
2272
2273 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2275 cleanupKind, addr, type, getDestroyer(dtorKind), cleanupKind & EHCleanup);
2276}
2277
2279 CleanupKind cleanupKind, Address addr, QualType type, Destroyer *destroyer,
2280 bool useEHCleanupForArray) {
2281 llvm::Instruction *DominatingIP =
2282 Builder.CreateFlagLoad(llvm::Constant::getNullValue(Int8PtrTy));
2283 pushDestroy(cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2285 {EHStack.stable_begin(), DominatingIP});
2286}
2287
2289 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2290}
2291
2293 CleanupKind Kind, std::pair<llvm::Value *, llvm::Value *> AddrSizePair) {
2294 EHStack.pushCleanup<KmpcAllocFree>(Kind, AddrSizePair);
2295}
2296
2298 Address addr, QualType type,
2299 Destroyer *destroyer,
2300 bool useEHCleanupForArray) {
2301 // If we're not in a conditional branch, we don't need to bother generating a
2302 // conditional cleanup.
2303 if (!isInConditionalBranch()) {
2304 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2305 // around in case a temporary's destructor throws an exception.
2306
2307 // Add the cleanup to the EHStack. After the full-expr, this would be
2308 // deactivated before being popped from the stack.
2309 pushDestroyAndDeferDeactivation(cleanupKind, addr, type, destroyer,
2310 useEHCleanupForArray);
2311
2312 // Since this is lifetime-extended, push it once again to the EHStack after
2313 // the full expression.
2314 return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2315 cleanupKind, Address::invalid(), addr, type, destroyer,
2316 useEHCleanupForArray);
2317 }
2318
2319 // Otherwise, we should only destroy the object if it's been initialized.
2320
2321 using ConditionalCleanupType =
2323 Destroyer *, bool>;
2325
2326 // Remember to emit cleanup if we branch-out before end of full-expression
2327 // (eg: through stmt-expr or coro suspensions).
2328 AllocaTrackerRAII DeactivationAllocas(*this);
2329 Address ActiveFlagForDeactivation = createCleanupActiveFlag();
2330
2331 pushCleanupAndDeferDeactivation<ConditionalCleanupType>(
2332 cleanupKind, SavedAddr, type, destroyer, useEHCleanupForArray);
2333 initFullExprCleanupWithFlag(ActiveFlagForDeactivation);
2334 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
2335 // Erase the active flag if the cleanup was not emitted.
2336 cleanup.AddAuxAllocas(std::move(DeactivationAllocas).Take());
2337
2338 // Since this is lifetime-extended, push it once again to the EHStack after
2339 // the full expression.
2340 // The previous active flag would always be 'false' due to forced deferred
2341 // deactivation. Use a separate flag for lifetime-extension to correctly
2342 // remember if this branch was taken and the object was initialized.
2343 Address ActiveFlagForLifetimeExt = createCleanupActiveFlag();
2344 pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2345 cleanupKind, ActiveFlagForLifetimeExt, SavedAddr, type, destroyer,
2346 useEHCleanupForArray);
2347}
2348
2349/// emitDestroy - Immediately perform the destruction of the given
2350/// object.
2351///
2352/// \param addr - the address of the object; a type*
2353/// \param type - the type of the object; if an array type, all
2354/// objects are destroyed in reverse order
2355/// \param destroyer - the function to call to destroy individual
2356/// elements
2357/// \param useEHCleanupForArray - whether an EH cleanup should be
2358/// used when destroying array elements, in case one of the
2359/// destructions throws an exception
2361 Destroyer *destroyer,
2362 bool useEHCleanupForArray) {
2364 if (!arrayType)
2365 return destroyer(*this, addr, type);
2366
2367 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2368
2369 CharUnits elementAlign =
2370 addr.getAlignment()
2371 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2372
2373 // Normally we have to check whether the array is zero-length.
2374 bool checkZeroLength = true;
2375
2376 // But if the array length is constant, we can suppress that.
2377 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2378 // ...and if it's constant zero, we can just skip the entire thing.
2379 if (constLength->isZero()) return;
2380 checkZeroLength = false;
2381 }
2382
2383 llvm::Value *begin = addr.emitRawPointer(*this);
2384 llvm::Value *end =
2386 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2387 checkZeroLength, useEHCleanupForArray);
2388}
2389
2390/// emitArrayDestroy - Destroys all the elements of the given array,
2391/// beginning from last to first. The array cannot be zero-length.
2392///
2393/// \param begin - a type* denoting the first element of the array
2394/// \param end - a type* denoting one past the end of the array
2395/// \param elementType - the element type of the array
2396/// \param destroyer - the function to call to destroy elements
2397/// \param useEHCleanup - whether to push an EH cleanup to destroy
2398/// the remaining elements in case the destruction of a single
2399/// element throws
2400void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2401 llvm::Value *end,
2402 QualType elementType,
2403 CharUnits elementAlign,
2404 Destroyer *destroyer,
2405 bool checkZeroLength,
2406 bool useEHCleanup) {
2407 assert(!elementType->isArrayType());
2408
2409 // The basic structure here is a do-while loop, because we don't
2410 // need to check for the zero-element case.
2411 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2412 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2413
2414 if (checkZeroLength) {
2415 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2416 "arraydestroy.isempty");
2417 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2418 }
2419
2420 // Enter the loop body, making that address the current address.
2421 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2422 EmitBlock(bodyBB);
2423 llvm::PHINode *elementPast =
2424 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2425 elementPast->addIncoming(end, entryBB);
2426
2427 // Shift the address back by one element.
2428 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2429 llvm::Type *llvmElementType = ConvertTypeForMem(elementType);
2430 llvm::Value *element = Builder.CreateInBoundsGEP(
2431 llvmElementType, elementPast, negativeOne, "arraydestroy.element");
2432
2433 if (useEHCleanup)
2434 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2435 destroyer);
2436
2437 // Perform the actual destruction there.
2438 destroyer(*this, Address(element, llvmElementType, elementAlign),
2439 elementType);
2440
2441 if (useEHCleanup)
2443
2444 // Check whether we've reached the end.
2445 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2446 Builder.CreateCondBr(done, doneBB, bodyBB);
2447 elementPast->addIncoming(element, Builder.GetInsertBlock());
2448
2449 // Done.
2450 EmitBlock(doneBB);
2451}
2452
2453/// Perform partial array destruction as if in an EH cleanup. Unlike
2454/// emitArrayDestroy, the element type here may still be an array type.
2456 llvm::Value *begin, llvm::Value *end,
2457 QualType type, CharUnits elementAlign,
2458 CodeGenFunction::Destroyer *destroyer) {
2459 llvm::Type *elemTy = CGF.ConvertTypeForMem(type);
2460
2461 // If the element type is itself an array, drill down.
2462 unsigned arrayDepth = 0;
2463 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2464 // VLAs don't require a GEP index to walk into.
2465 if (!isa<VariableArrayType>(arrayType))
2466 arrayDepth++;
2467 type = arrayType->getElementType();
2468 }
2469
2470 if (arrayDepth) {
2471 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2472
2473 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2474 begin = CGF.Builder.CreateInBoundsGEP(
2475 elemTy, begin, gepIndices, "pad.arraybegin");
2476 end = CGF.Builder.CreateInBoundsGEP(
2477 elemTy, end, gepIndices, "pad.arrayend");
2478 }
2479
2480 // Destroy the array. We don't ever need an EH cleanup because we
2481 // assume that we're in an EH cleanup ourselves, so a throwing
2482 // destructor causes an immediate terminate.
2483 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2484 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2485}
2486
2487namespace {
2488 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2489 /// array destroy where the end pointer is regularly determined and
2490 /// does not need to be loaded from a local.
2491 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2492 llvm::Value *ArrayBegin;
2493 llvm::Value *ArrayEnd;
2494 QualType ElementType;
2495 CodeGenFunction::Destroyer *Destroyer;
2496 CharUnits ElementAlign;
2497 public:
2498 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2499 QualType elementType, CharUnits elementAlign,
2500 CodeGenFunction::Destroyer *destroyer)
2501 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2502 ElementType(elementType), Destroyer(destroyer),
2503 ElementAlign(elementAlign) {}
2504
2505 void Emit(CodeGenFunction &CGF, Flags flags) override {
2506 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2507 ElementType, ElementAlign, Destroyer);
2508 }
2509 };
2510
2511 /// IrregularPartialArrayDestroy - a cleanup which performs a
2512 /// partial array destroy where the end pointer is irregularly
2513 /// determined and must be loaded from a local.
2514 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2515 llvm::Value *ArrayBegin;
2516 Address ArrayEndPointer;
2517 QualType ElementType;
2518 CodeGenFunction::Destroyer *Destroyer;
2519 CharUnits ElementAlign;
2520 public:
2521 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2522 Address arrayEndPointer,
2523 QualType elementType,
2524 CharUnits elementAlign,
2525 CodeGenFunction::Destroyer *destroyer)
2526 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2527 ElementType(elementType), Destroyer(destroyer),
2528 ElementAlign(elementAlign) {}
2529
2530 void Emit(CodeGenFunction &CGF, Flags flags) override {
2531 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2532 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2533 ElementType, ElementAlign, Destroyer);
2534 }
2535 };
2536} // end anonymous namespace
2537
2538/// pushIrregularPartialArrayCleanup - Push a NormalAndEHCleanup to
2539/// destroy already-constructed elements of the given array. The cleanup may be
2540/// popped with DeactivateCleanupBlock or PopCleanupBlock.
2541///
2542/// \param elementType - the immediate element type of the array;
2543/// possibly still an array type
2544void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2545 Address arrayEndPointer,
2546 QualType elementType,
2547 CharUnits elementAlign,
2548 Destroyer *destroyer) {
2549 pushFullExprCleanup<IrregularPartialArrayDestroy>(
2550 NormalAndEHCleanup, arrayBegin, arrayEndPointer, elementType,
2551 elementAlign, destroyer);
2552}
2553
2554/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2555/// already-constructed elements of the given array. The cleanup
2556/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2557///
2558/// \param elementType - the immediate element type of the array;
2559/// possibly still an array type
2560void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2561 llvm::Value *arrayEnd,
2562 QualType elementType,
2563 CharUnits elementAlign,
2564 Destroyer *destroyer) {
2565 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2566 arrayBegin, arrayEnd,
2567 elementType, elementAlign,
2568 destroyer);
2569}
2570
2571/// Lazily declare the @llvm.lifetime.start intrinsic.
2573 if (LifetimeStartFn)
2574 return LifetimeStartFn;
2575 LifetimeStartFn = llvm::Intrinsic::getOrInsertDeclaration(
2576 &getModule(), llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2577 return LifetimeStartFn;
2578}
2579
2580/// Lazily declare the @llvm.lifetime.end intrinsic.
2582 if (LifetimeEndFn)
2583 return LifetimeEndFn;
2584 LifetimeEndFn = llvm::Intrinsic::getOrInsertDeclaration(
2585 &getModule(), llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2586 return LifetimeEndFn;
2587}
2588
2589/// Lazily declare the @llvm.fake.use intrinsic.
2591 if (FakeUseFn)
2592 return FakeUseFn;
2593 FakeUseFn = llvm::Intrinsic::getOrInsertDeclaration(
2594 &getModule(), llvm::Intrinsic::fake_use);
2595 return FakeUseFn;
2596}
2597
2598namespace {
2599 /// A cleanup to perform a release of an object at the end of a
2600 /// function. This is used to balance out the incoming +1 of a
2601 /// ns_consumed argument when we can't reasonably do that just by
2602 /// not doing the initial retain for a __block argument.
2603 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2604 ConsumeARCParameter(llvm::Value *param,
2605 ARCPreciseLifetime_t precise)
2606 : Param(param), Precise(precise) {}
2607
2608 llvm::Value *Param;
2609 ARCPreciseLifetime_t Precise;
2610
2611 void Emit(CodeGenFunction &CGF, Flags flags) override {
2612 CGF.EmitARCRelease(Param, Precise);
2613 }
2614 };
2615} // end anonymous namespace
2616
2617/// Emit an alloca (or GlobalValue depending on target)
2618/// for the specified parameter and set up LocalDeclMap.
2619void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2620 unsigned ArgNo) {
2621 bool NoDebugInfo = false;
2622 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2623 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2624 "Invalid argument to EmitParmDecl");
2625
2626 // Set the name of the parameter's initial value to make IR easier to
2627 // read. Don't modify the names of globals.
2628 if (!isa<llvm::GlobalValue>(Arg.getAnyValue()))
2629 Arg.getAnyValue()->setName(D.getName());
2630
2631 QualType Ty = D.getType();
2632
2633 // Use better IR generation for certain implicit parameters.
2634 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2635 // The only implicit argument a block has is its literal.
2636 // This may be passed as an inalloca'ed value on Windows x86.
2637 if (BlockInfo) {
2638 llvm::Value *V = Arg.isIndirect()
2639 ? Builder.CreateLoad(Arg.getIndirectAddress())
2640 : Arg.getDirectValue();
2641 setBlockContextParameter(IPD, ArgNo, V);
2642 return;
2643 }
2644 // Suppressing debug info for ThreadPrivateVar parameters, else it hides
2645 // debug info of TLS variables.
2646 NoDebugInfo =
2647 (IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);
2648 }
2649
2650 Address DeclPtr = Address::invalid();
2651 RawAddress AllocaPtr = Address::invalid();
2652 bool DoStore = false;
2653 bool IsScalar = hasScalarEvaluationKind(Ty);
2654 bool UseIndirectDebugAddress = false;
2655
2656 // If we already have a pointer to the argument, reuse the input pointer.
2657 if (Arg.isIndirect()) {
2658 DeclPtr = Arg.getIndirectAddress();
2659 DeclPtr = DeclPtr.withElementType(ConvertTypeForMem(Ty));
2660 // Indirect argument is in alloca address space, which may be different
2661 // from the default address space.
2662 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2663 auto *V = DeclPtr.emitRawPointer(*this);
2664 AllocaPtr = RawAddress(V, DeclPtr.getElementType(), DeclPtr.getAlignment());
2665
2666 // For truly ABI indirect arguments -- those that are not `byval` -- store
2667 // the address of the argument on the stack to preserve debug information.
2668 ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
2669 if (ArgInfo.isIndirect())
2670 UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
2671 if (UseIndirectDebugAddress) {
2672 auto PtrTy = getContext().getPointerType(Ty);
2673 AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),
2674 D.getName() + ".indirect_addr");
2675 EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);
2676 }
2677
2678 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2679 auto DestLangAS =
2681 if (SrcLangAS != DestLangAS) {
2682 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2683 CGM.getDataLayout().getAllocaAddrSpace());
2684 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2685 auto *T = llvm::PointerType::get(getLLVMContext(), DestAS);
2686 DeclPtr =
2687 DeclPtr.withPointer(getTargetHooks().performAddrSpaceCast(
2688 *this, V, SrcLangAS, DestLangAS, T, true),
2689 DeclPtr.isKnownNonNull());
2690 }
2691
2692 // Push a destructor cleanup for this parameter if the ABI requires it.
2693 // Don't push a cleanup in a thunk for a method that will also emit a
2694 // cleanup.
2695 if (Ty->isRecordType() && !CurFuncIsThunk &&
2697 if (QualType::DestructionKind DtorKind =
2698 D.needsDestruction(getContext())) {
2699 assert((DtorKind == QualType::DK_cxx_destructor ||
2700 DtorKind == QualType::DK_nontrivial_c_struct) &&
2701 "unexpected destructor type");
2702 pushDestroy(DtorKind, DeclPtr, Ty);
2703 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2705 }
2706 }
2707 } else {
2708 // Check if the parameter address is controlled by OpenMP runtime.
2709 Address OpenMPLocalAddr =
2710 getLangOpts().OpenMP
2712 : Address::invalid();
2713 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2714 DeclPtr = OpenMPLocalAddr;
2715 AllocaPtr = DeclPtr;
2716 } else {
2717 // Otherwise, create a temporary to hold the value.
2718 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2719 D.getName() + ".addr", &AllocaPtr);
2720 }
2721 DoStore = true;
2722 }
2723
2724 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2725
2726 LValue lv = MakeAddrLValue(DeclPtr, Ty);
2727 if (IsScalar) {
2728 Qualifiers qs = Ty.getQualifiers();
2730 // We honor __attribute__((ns_consumed)) for types with lifetime.
2731 // For __strong, it's handled by just skipping the initial retain;
2732 // otherwise we have to balance out the initial +1 with an extra
2733 // cleanup to do the release at the end of the function.
2734 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2735
2736 // If a parameter is pseudo-strong then we can omit the implicit retain.
2737 if (D.isARCPseudoStrong()) {
2738 assert(lt == Qualifiers::OCL_Strong &&
2739 "pseudo-strong variable isn't strong?");
2740 assert(qs.hasConst() && "pseudo-strong variable should be const!");
2742 }
2743
2744 // Load objects passed indirectly.
2745 if (Arg.isIndirect() && !ArgVal)
2746 ArgVal = Builder.CreateLoad(DeclPtr);
2747
2748 if (lt == Qualifiers::OCL_Strong) {
2749 if (!isConsumed) {
2750 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2751 // use objc_storeStrong(&dest, value) for retaining the
2752 // object. But first, store a null into 'dest' because
2753 // objc_storeStrong attempts to release its old value.
2754 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2755 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2756 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
2757 DoStore = false;
2758 }
2759 else
2760 // Don't use objc_retainBlock for block pointers, because we
2761 // don't want to Block_copy something just because we got it
2762 // as a parameter.
2763 ArgVal = EmitARCRetainNonBlock(ArgVal);
2764 }
2765 } else {
2766 // Push the cleanup for a consumed parameter.
2767 if (isConsumed) {
2768 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2770 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2771 precise);
2772 }
2773
2774 if (lt == Qualifiers::OCL_Weak) {
2775 EmitARCInitWeak(DeclPtr, ArgVal);
2776 DoStore = false; // The weak init is a store, no need to do two.
2777 }
2778 }
2779
2780 // Enter the cleanup scope.
2781 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2782 }
2783 }
2784
2785 // Store the initial value into the alloca.
2786 if (DoStore)
2787 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2788
2789 setAddrOfLocalVar(&D, DeclPtr);
2790
2791 // Push a FakeUse 'cleanup' object onto the EHStack for the parameter,
2792 // which may be the 'this' pointer. This causes the emission of a fake.use
2793 // call with the parameter as argument at the end of the function.
2794 if (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
2796 (CGM.getCodeGenOpts().getExtendVariableLiveness() ==
2798 &D == CXXABIThisDecl)) {
2799 if (shouldExtendLifetime(getContext(), CurCodeDecl, D, CXXABIThisDecl))
2800 EHStack.pushCleanup<FakeUse>(NormalFakeUse, DeclPtr);
2801 }
2802
2803 // Emit debug info for param declarations in non-thunk functions.
2804 if (CGDebugInfo *DI = getDebugInfo()) {
2806 !NoDebugInfo) {
2807 llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2808 &D, AllocaPtr.getPointer(), ArgNo, Builder, UseIndirectDebugAddress);
2809 if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2810 DI->getParamDbgMappings().insert({Var, DILocalVar});
2811 }
2812 }
2813
2814 if (D.hasAttr<AnnotateAttr>())
2815 EmitVarAnnotations(&D, DeclPtr.emitRawPointer(*this));
2816
2817 // We can only check return value nullability if all arguments to the
2818 // function satisfy their nullability preconditions. This makes it necessary
2819 // to emit null checks for args in the function body itself.
2820 if (requiresReturnValueNullabilityCheck()) {
2821 auto Nullability = Ty->getNullability();
2822 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2823 SanitizerScope SanScope(this);
2824 RetValNullabilityPrecondition =
2825 Builder.CreateAnd(RetValNullabilityPrecondition,
2826 Builder.CreateIsNotNull(Arg.getAnyValue()));
2827 }
2828 }
2829}
2830
2832 CodeGenFunction *CGF) {
2833 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2834 return;
2836}
2837
2839 CodeGenFunction *CGF) {
2840 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2841 (!LangOpts.EmitAllDecls && !D->isUsed()))
2842 return;
2844}
2845
2848}
2849
2851 for (const Expr *E : D->varlist()) {
2852 const auto *DE = cast<DeclRefExpr>(E);
2853 const auto *VD = cast<VarDecl>(DE->getDecl());
2854
2855 // Skip all but globals.
2856 if (!VD->hasGlobalStorage())
2857 continue;
2858
2859 // Check if the global has been materialized yet or not. If not, we are done
2860 // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2861 // we already emitted the global we might have done so before the
2862 // OMPAllocateDeclAttr was attached, leading to the wrong address space
2863 // (potentially). While not pretty, common practise is to remove the old IR
2864 // global and generate a new one, so we do that here too. Uses are replaced
2865 // properly.
2866 StringRef MangledName = getMangledName(VD);
2867 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2868 if (!Entry)
2869 continue;
2870
2871 // We can also keep the existing global if the address space is what we
2872 // expect it to be, if not, it is replaced.
2873 QualType ASTTy = VD->getType();
2875 auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2876 if (Entry->getType()->getAddressSpace() == TargetAS)
2877 continue;
2878
2879 // Make a new global with the correct type / address space.
2880 llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2881 llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2882
2883 // Replace all uses of the old global with a cast. Since we mutate the type
2884 // in place we neeed an intermediate that takes the spot of the old entry
2885 // until we can create the cast.
2886 llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2887 getModule(), Entry->getValueType(), false,
2888 llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2889 llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2890 Entry->replaceAllUsesWith(DummyGV);
2891
2892 Entry->mutateType(PTy);
2893 llvm::Constant *NewPtrForOldDecl =
2894 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2895 Entry, DummyGV->getType());
2896
2897 // Now we have a casted version of the changed global, the dummy can be
2898 // replaced and deleted.
2899 DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2900 DummyGV->eraseFromParent();
2901 }
2902}
2903
2904std::optional<CharUnits>
2906 if (const auto *AA = VD->getAttr<OMPAllocateDeclAttr>()) {
2907 if (Expr *Alignment = AA->getAlignment()) {
2908 unsigned UserAlign =
2909 Alignment->EvaluateKnownConstInt(getContext()).getExtValue();
2910 CharUnits NaturalAlign =
2912
2913 // OpenMP5.1 pg 185 lines 7-10
2914 // Each item in the align modifier list must be aligned to the maximum
2915 // of the specified alignment and the type's natural alignment.
2917 std::max<unsigned>(UserAlign, NaturalAlign.getQuantity()));
2918 }
2919 }
2920 return std::nullopt;
2921}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
static void emitStoresForInitAfterBZero(CodeGenModule &CGM, llvm::Constant *Init, Address Loc, bool isVolatile, CGBuilderTy &Builder, bool IsAutoInit)
For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit the scalar stores that woul...
Definition: CGDecl.cpp:927
static bool isCapturedBy(const VarDecl &, const Expr *)
Determines whether the given __block variable is potentially captured by the given expression.
Definition: CGDecl.cpp:1741
static void emitPartialArrayDestroy(CodeGenFunction &CGF, llvm::Value *begin, llvm::Value *end, QualType type, CharUnits elementAlign, CodeGenFunction::Destroyer *destroyer)
Perform partial array destruction as if in an EH cleanup.
Definition: CGDecl.cpp:2455
static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D, Address Loc, bool isVolatile, CGBuilderTy &Builder)
Definition: CGDecl.cpp:1278
static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init, unsigned &NumStores)
Decide whether we can emit the non-zero parts of the specified initializer with equal or fewer than N...
Definition: CGDecl.cpp:889
static llvm::Constant * patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern, llvm::Type *Ty)
Generate a constant filled with either a pattern or zeroes.
Definition: CGDecl.cpp:1021
static llvm::Constant * constWithPadding(CodeGenModule &CGM, IsPattern isPattern, llvm::Constant *constant)
Replace all padding bytes in a given constant with either a pattern byte or 0x00.
Definition: CGDecl.cpp:1073
static llvm::Value * shouldUseMemSetToInitialize(llvm::Constant *Init, uint64_t GlobalSize, const llvm::DataLayout &DL)
Decide whether we should use memset to initialize a local variable instead of using a memcpy from a c...
Definition: CGDecl.cpp:995
IsPattern
Definition: CGDecl.cpp:1018
static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D)
Definition: CGDecl.cpp:224
static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D, Address Loc, bool isVolatile, CGBuilderTy &Builder, llvm::Constant *constant, bool IsAutoInit)
Definition: CGDecl.cpp:1168
static bool shouldSplitConstantStore(CodeGenModule &CGM, uint64_t GlobalByteSize)
Decide whether we want to split a constant structure or array store into a sequence of its fields' st...
Definition: CGDecl.cpp:1007
static llvm::Constant * replaceUndef(CodeGenModule &CGM, IsPattern isPattern, llvm::Constant *constant)
Definition: CGDecl.cpp:1300
static bool shouldExtendLifetime(const ASTContext &Context, const Decl *FuncDecl, const VarDecl &D, ImplicitParamDecl *CXXABIThisDecl)
Definition: CGDecl.cpp:1434
static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, const LValue &destLV, const Expr *init)
Definition: CGDecl.cpp:695
static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init, uint64_t GlobalSize)
Decide whether we should use bzero plus some stores to initialize a local variable instead of using a...
Definition: CGDecl.cpp:974
static llvm::Constant * constStructWithPadding(CodeGenModule &CGM, IsPattern isPattern, llvm::StructType *STy, llvm::Constant *constant)
Helper function for constWithPadding() to deal with padding in structures.
Definition: CGDecl.cpp:1033
static bool containsUndef(llvm::Constant *constant)
Definition: CGDecl.cpp:1289
static uint64_t maxFakeUseAggregateSize(const ASTContext &C)
Return the maximum size of an aggregate for which we generate a fake use intrinsic when -fextend-vari...
Definition: CGDecl.cpp:1428
static bool isAccessedBy(const VarDecl &var, const Stmt *s)
Definition: CGDecl.cpp:663
static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, Address addr, Qualifiers::ObjCLifetime lifetime)
EmitAutoVarWithLifetime - Does the setup required for an automatic variable with lifetime.
Definition: CGDecl.cpp:627
static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM, const VarDecl &D, CGBuilderTy &Builder, llvm::Constant *Constant, CharUnits Align)
Definition: CGDecl.cpp:1159
static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D, Address Loc, bool isVolatile, CGBuilderTy &Builder)
Definition: CGDecl.cpp:1268
static void drillIntoBlockVariable(CodeGenFunction &CGF, LValue &lvalue, const VarDecl *var)
Definition: CGDecl.cpp:744
CodeGenFunction::ComplexPairTy ComplexPairTy
const Decl * D
Expr * E
This file defines OpenMP nodes for declarative directives.
static const RecordType * getRecordType(QualType QT)
Checks that the passed in QualType either is of RecordType or points to RecordType.
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2892
SourceLocation Loc
Definition: SemaObjC.cpp:759
SourceLocation Begin
__device__ __2f16 float __ockl_bool s
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
IdentifierTable & Idents
Definition: ASTContext.h:680
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2489
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2925
unsigned getTargetAddressSpace(LangAS AS) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3578
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4503
ArrayRef< Capture > captures() const
Definition: Decl.h:4630
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2592
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2856
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition: CharUnits.h:214
bool isOne() const
isOne - Test whether the quantity equals one.
Definition: CharUnits.h:125
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:128
static Address invalid()
Definition: Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:251
CharUnits getAlignment() const
Definition: Address.h:189
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:207
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Definition: Address.h:259
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition: Address.h:274
KnownNonNull_t isKnownNonNull() const
Whether the pointer is known not to be null.
Definition: Address.h:231
bool isValid() const
Definition: Address.h:177
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition: CGValue.h:602
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
Definition: CGDebugInfo.h:905
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
Definition: CGDebugInfo.h:915
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:398
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:158
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition: CGBuilder.h:365
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition: CGBuilder.h:346
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition: CGCall.h:137
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:58
void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about a global variable.
Param2DILocTy & getParamDbgMappings()
Definition: CGDebugInfo.h:622
llvm::DILocalVariable * EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder, bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an argument variable declaration.
llvm::DILocalVariable * EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder, const bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an automatic variable declaration.
void setLocation(SourceLocation Loc)
Update the current source location.
void registerVLASizeExpression(QualType Ty, llvm::Metadata *SizeExpr)
Register VLA size expression debug node with the qualified type.
Definition: CGDebugInfo.h:427
CGFunctionInfo - Class to encapsulate the information about a function definition.
const_arg_iterator arg_begin() const
MutableArrayRef< ArgInfo > arguments()
virtual void EmitWorkGroupLocalVarDecl(CodeGenFunction &CGF, const VarDecl &D)
Emit the IR required for a work-group-local variable declaration, and add an entry to CGF's LocalDecl...
Allows to disable automatic handling of functions used in target regions as those marked as omp decla...
virtual void getKmpcFreeShared(CodeGenFunction &CGF, const std::pair< llvm::Value *, llvm::Value * > &AddrSizePair)
Get call to __kmpc_free_shared.
void emitUserDefinedMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit the function for the user defined mapper construct.
virtual void processRequiresDirective(const OMPRequiresDecl *D)
Perform check on requires decl to ensure that target architecture supports unified addressing.
virtual std::pair< llvm::Value *, llvm::Value * > getKmpcAllocShared(CodeGenFunction &CGF, const VarDecl *VD)
Get call to __kmpc_alloc_shared.
virtual void emitUserDefinedReduction(CodeGenFunction *CGF, const OMPDeclareReductionDecl *D)
Emit code for the specified user defined reduction construct.
virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD)
Gets the OpenMP-specific address of the local variable.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:274
void add(RValue rvalue, QualType type)
Definition: CGCall.h:305
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void emitAutoVarTypeCleanup(const AutoVarEmission &emission, QualType::DestructionKind dtorKind)
void enterByrefCleanup(CleanupKind Kind, Address Addr, BlockFieldFlags Flags, bool LoadBlockVarAddr, bool CanThrow)
Enter a cleanup to destroy a __block variable.
llvm::Value * EmitLifetimeStart(llvm::TypeSize Size, llvm::Value *Addr)
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
static Destroyer destroyNonTrivialCStruct
static bool cxxDestructorCanThrow(QualType T)
Check if T is a C++ class that has a destructor that can throw.
SanitizerSet SanOpts
Sanitizers enabled for this function.
llvm::DenseMap< const VarDecl *, llvm::Value * > NRVOFlags
A mapping from NRVO variables to the flags used to indicate when the NRVO has been applied to this va...
void EmitARCMoveWeak(Address dst, Address src)
void EmitAutoVarDecl(const VarDecl &D)
EmitAutoVarDecl - Emit an auto variable declaration.
void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
static bool hasScalarEvaluationKind(QualType T)
const BlockByrefInfo & getBlockByrefInfo(const VarDecl *var)
void EmitDecl(const Decl &D)
EmitDecl - Emit a declaration.
void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, Address arrayEndPointer, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
void EmitExtendGCLifetime(llvm::Value *object)
EmitExtendGCLifetime - Given a pointer to an Objective-C object, make sure it survives garbage collec...
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
void pushEHDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
void emitArrayDestroy(llvm::Value *begin, llvm::Value *end, QualType elementType, CharUnits elementAlign, Destroyer *destroyer, bool checkZeroLength, bool useEHCleanup)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
void pushDestroyAndDeferDeactivation(QualType::DestructionKind dtorKind, Address addr, QualType type)
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
const CodeGen::CGBlockInfo * BlockInfo
void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
EmitExprAsInit - Emits the code necessary to initialize a location in memory with the given initializ...
void emitByrefStructureInit(const AutoVarEmission &emission)
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
@ TCK_NonnullAssign
Checking the value assigned to a _Nonnull pointer. Must not be null.
llvm::Value * EmitARCStoreStrongCall(Address addr, llvm::Value *value, bool resultIgnored)
llvm::Type * ConvertTypeForMem(QualType T)
llvm::Value * EmitARCUnsafeUnretainedScalarExpr(const Expr *expr)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
void EmitAutoVarInit(const AutoVarEmission &emission)
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
DominatingValue< T >::saved_type saveValueInCond(T value)
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
void EmitStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
void EmitAtomicInit(Expr *E, LValue lvalue)
const TargetInfo & getTarget() const
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
void emitDestroy(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr, bool PerformInit)
Emit code in this function to perform a guarded variable initialization.
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
void initFullExprCleanupWithFlag(RawAddress ActiveFlag)
void EmitARCCopyWeak(Address dst, Address src)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
void setBlockContextParameter(const ImplicitParamDecl *D, unsigned argNum, llvm::Value *ptr)
void defaultInitNonTrivialCStructVar(LValue Dst)
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
bool isTrivialInitializer(const Expr *Init)
Determine whether the given initializer is trivial in the sense that it requires no code to be genera...
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
LValue EmitDeclRefLValue(const DeclRefExpr *E)
AggValueSlot::Overlap_t getOverlapForFieldInit(const FieldDecl *FD)
Determine whether a field initialization may overlap some other object.
llvm::Value * EmitARCRetainAutoreleaseScalarExpr(const Expr *expr)
const TargetCodeGenInfo & getTargetHooks() const
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
void EmitFakeUse(Address Addr)
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Address ReturnValuePointer
ReturnValuePointer - The temporary alloca to hold a pointer to sret.
void EmitAutoVarCleanups(const AutoVarEmission &emission)
llvm::GlobalVariable * AddInitializerToStaticVarDecl(const VarDecl &D, llvm::GlobalVariable *GV)
AddInitializerToStaticVarDecl - Add the initializer for 'D' to the global variable that has already b...
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
CleanupKind getCleanupKind(QualType::DestructionKind kind)
llvm::Type * ConvertType(QualType T)
void EmitARCInitWeak(Address addr, llvm::Value *value)
static Destroyer destroyARCStrongPrecise
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
void pushStackRestore(CleanupKind kind, Address SPMem)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const CGFunctionInfo * CurFnInfo
void pushKmpcAllocFree(CleanupKind Kind, std::pair< llvm::Value *, llvm::Value * > AddrSizePair)
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
static Destroyer destroyARCStrongImprecise
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
void EmitAndRegisterVariableArrayDimensions(CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo)
Emits the alloca and debug information for the size expressions for each dimension of an array.
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, llvm::Value *arrayEnd, QualType elementType, CharUnits elementAlignment, Destroyer *destroyer)
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
bool hasLabelBeenSeenInCurrentScope() const
Return true if a label was seen in the current scope.
This class organizes the cross-function state that is used while generating LLVM code.
StringRef getBlockMangledName(GlobalDecl GD, const BlockDecl *BD)
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
llvm::Module & getModule() const
void setStaticLocalDeclAddress(const VarDecl *D, llvm::Constant *C)
llvm::Function * getLLVMLifetimeStartFn()
Lazily declare the @llvm.lifetime.start intrinsic.
Definition: CGDecl.cpp:2572
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
Address createUnnamedGlobalFrom(const VarDecl &D, llvm::Constant *Constant, CharUnits Align)
Definition: CGDecl.cpp:1109
llvm::Constant * getNullPointer(llvm::PointerType *T, QualType QT)
Get target specific null pointer.
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
const LangOptions & getLangOpts() const
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CGOpenCLRuntime & getOpenCLRuntime()
Return a reference to the configured OpenCL runtime.
llvm::Function * getLLVMFakeUseFn()
Lazily declare the @llvm.fake.use intrinsic.
Definition: CGDecl.cpp:2590
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
void EmitOMPAllocateDecl(const OMPAllocateDecl *D)
Emit a code for the allocate directive.
Definition: CGDecl.cpp:2850
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
const llvm::DataLayout & getDataLayout() const
void addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
SanitizerMetadata * getSanitizerMetadata()
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:247
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
void AddGlobalAnnotations(const ValueDecl *D, llvm::GlobalValue *GV)
Add global annotations that are set on D, for the global GV.
void setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const
Set the TLS mode for the given LLVM GlobalValue for the thread-local variable declaration D.
ASTContext & getContext() const
void EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare mapper construct.
Definition: CGDecl.cpp:2838
llvm::Function * getLLVMLifetimeEndFn()
Lazily declare the @llvm.lifetime.end intrinsic.
Definition: CGDecl.cpp:2581
void EmitOMPRequiresDecl(const OMPRequiresDecl *D)
Emit a code for requires directive.
Definition: CGDecl.cpp:2846
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
std::optional< CharUnits > getOMPAllocateAlignment(const VarDecl *VD)
Return the alignment specified in an allocate directive, if present.
Definition: CGDecl.cpp:2905
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, CodeGenFunction *CGF=nullptr)
Emit a code for declare reduction construct.
Definition: CGDecl.cpp:2831
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
LangAS GetGlobalVarAddressSpace(const VarDecl *D)
Return the AST address space of the underlying global variable for D, as determined by its declaratio...
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void markStmtMaybeUsed(const Stmt *S)
Definition: CodeGenPGO.h:130
llvm::Type * convertTypeForLoadStore(QualType T, llvm::Type *LLVMTy=nullptr)
Given that T is a scalar type, return the IR type that should be used for load and store operations.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool typeRequiresSplitIntoByteArray(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
Check whether the given type needs to be laid out in memory using an opaque byte-array type because i...
const CGFunctionInfo & arrangeFunctionDeclaration(const FunctionDecl *FD)
Free functions are functions that are compatible with an ordinary C function pointer type.
Definition: CGCall.cpp:462
llvm::Constant * tryEmitAbstractForInitializer(const VarDecl &D)
Try to emit the initializer of the given declaration as an abstract constant.
A cleanup scope which generates the cleanup blocks lazily.
Definition: CGCleanup.h:247
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:146
ConditionalCleanup stores the saved form of its parameters, then restores them and performs the clean...
Definition: EHScopeStack.h:208
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:398
iterator begin() const
Returns an iterator pointing to the innermost EH scope.
Definition: CGCleanup.h:623
LValue - This represents an lvalue references.
Definition: CGValue.h:182
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition: CGValue.h:361
QualType getType() const
Definition: CGValue.h:291
void setNonGC(bool Value)
Definition: CGValue.h:304
void setAddress(Address address)
Definition: CGValue.h:363
Qualifiers::ObjCLifetime getObjCLifetime() const
Definition: CGValue.h:293
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:42
static RValue get(llvm::Value *V)
Definition: CGValue.h:98
An abstract representation of an aligned address.
Definition: Address.h:42
llvm::Value * getPointer() const
Definition: Address.h:66
static RawAddress invalid()
Definition: Address.h:61
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:386
void reportGlobal(llvm::GlobalVariable *GV, const VarDecl &D, bool IsDynInit=false)
Address performAddrSpaceCast(CodeGen::CodeGenFunction &CGF, Address Addr, LangAS SrcAddr, LangAS DestAddr, llvm::Type *DestTy, bool IsNonNull=false) const
virtual void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const
setTargetAttributes - Provides a convenient hook to handle extra target-specific attributes for the g...
Definition: TargetInfo.h:76
bool IsBypassed(const VarDecl *D) const
Returns true if the variable declaration was by bypassed by any goto or switch statement.
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
body_range body()
Definition: Stmt.h:1691
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:322
T * getAttr() const
Definition: DeclBase.h:576
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
Definition: DeclBase.cpp:1254
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:557
DeclContext * getDeclContext()
Definition: DeclBase.h:451
bool hasAttr() const
Definition: DeclBase.h:580
Kind getKind() const
Definition: DeclBase.h:445
This represents one expression.
Definition: Expr.h:110
bool isXValue() const
Definition: Expr.h:279
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3101
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3092
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
QualType getType() const
Definition: Expr.h:142
Represents a function declaration or definition.
Definition: Decl.h:1935
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
const Decl * getDecl() const
Definition: GlobalDecl.h:103
One of these records is kept for each identifier that is lexed.
IdentifierInfo & getOwn(StringRef Name)
Gets an IdentifierInfo for the given name without consulting external sources.
This represents '#pragma omp allocate ...' directive.
Definition: DeclOpenMP.h:474
This represents '#pragma omp declare mapper ...' directive.
Definition: DeclOpenMP.h:287
This represents '#pragma omp declare reduction ...' directive.
Definition: DeclOpenMP.h:177
This represents '#pragma omp requires...' directive.
Definition: DeclOpenMP.h:417
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8021
@ DK_cxx_destructor
Definition: Type.h:1521
@ DK_nontrivial_c_struct
Definition: Type.h:1524
@ DK_objc_weak_lifetime
Definition: Type.h:1523
@ DK_objc_strong_lifetime
Definition: Type.h:1522
@ PDIK_Struct
The type is a struct containing a field whose type is not PCK_Trivial.
Definition: Type.h:1467
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8063
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1089
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7977
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8140
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8031
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
Definition: Type.h:1028
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2639
The collection of all-type qualifiers we support.
Definition: Type.h:324
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasConst() const
Definition: Type.h:450
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
bool isParamDestroyedInCallee() const
Definition: Decl.h:4319
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
RecordDecl * getDecl() const
Definition: Type.h:6088
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
static const uint64_t MaximumAlignment
Definition: Sema.h:842
Encodes a location in the source.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4466
Stmt - This represents one statement.
Definition: Stmt.h:84
child_range children()
Definition: Stmt.cpp:295
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8264
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8810
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2725
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
bool isRecordType() const
Definition: Type.h:8292
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4761
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:886
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2140
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1181
const Expr * getInit() const
Definition: Decl.h:1323
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1208
Defines the clang::TargetInfo interface.
@ BLOCK_FIELD_IS_BYREF
Definition: CGBlocks.h:92
@ BLOCK_FIELD_IS_WEAK
Definition: CGBlocks.h:94
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
llvm::Constant * initializationPatternFor(CodeGenModule &, llvm::Type *)
Definition: PatternInit.cpp:15
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
Definition: EHScopeStack.h:84
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
ARCPreciseLifetime_t
Does an ARC strong l-value have precise lifetime?
Definition: CGValue.h:135
@ ARCPreciseLifetime
Definition: CGValue.h:136
@ ARCImpreciseLifetime
Definition: CGValue.h:136
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
constexpr Variable var(Literal L)
Returns the variable of L.
Definition: CNFFormula.h:64
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:3893
bool Null(InterpState &S, CodePtr OpPC, uint64_t Value, const Descriptor *Desc)
Definition: Interp.h:2366
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2350
The JSON file list parser is used to communicate input to InstallAPI.
@ Ctor_Base
Base object ctor.
Definition: ABI.h:26
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus
Definition: LangStandard.h:55
@ NonNull
Values of this type can never be null.
@ SC_Auto
Definition: Specifiers.h:256
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:329
@ Dtor_Base
Base object dtor.
Definition: ABI.h:36
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
@ ThreadPrivateVar
Parameter for Thread private variable.
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
static Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD)
Gets the OpenMP-specific address of the local variable /p VD.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::PointerType * AllocaInt8PtrTy
A metaprogramming class for ensuring that a value will dominate an arbitrary position in a function.
Definition: EHScopeStack.h:65
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
Definition: Sanitizers.h:169