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