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