1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Decl nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
17 #include "CGCleanup.h"
18 #include "CGDebugInfo.h"
19 #include "CGOpenCLRuntime.h"
20 #include "CGOpenMPRuntime.h"
21 #include "CodeGenModule.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclOpenMP.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/CodeGen/CGFunctionInfo.h"
30 #include "clang/Frontend/CodeGenOptions.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Type.h"
36 using namespace clang;
37 using namespace CodeGen;
39 void CodeGenFunction::EmitDecl(const Decl &D) {
40 switch (D.getKind()) {
41 case Decl::BuiltinTemplate:
42 case Decl::TranslationUnit:
43 case Decl::ExternCContext:
45 case Decl::UnresolvedUsingTypename:
46 case Decl::ClassTemplateSpecialization:
47 case Decl::ClassTemplatePartialSpecialization:
48 case Decl::VarTemplateSpecialization:
49 case Decl::VarTemplatePartialSpecialization:
50 case Decl::TemplateTypeParm:
51 case Decl::UnresolvedUsingValue:
52 case Decl::NonTypeTemplateParm:
53 case Decl::CXXDeductionGuide:
55 case Decl::CXXConstructor:
56 case Decl::CXXDestructor:
57 case Decl::CXXConversion:
59 case Decl::MSProperty:
60 case Decl::IndirectField:
62 case Decl::ObjCAtDefsField:
64 case Decl::ImplicitParam:
65 case Decl::ClassTemplate:
66 case Decl::VarTemplate:
67 case Decl::FunctionTemplate:
68 case Decl::TypeAliasTemplate:
69 case Decl::TemplateTemplateParm:
70 case Decl::ObjCMethod:
71 case Decl::ObjCCategory:
72 case Decl::ObjCProtocol:
73 case Decl::ObjCInterface:
74 case Decl::ObjCCategoryImpl:
75 case Decl::ObjCImplementation:
76 case Decl::ObjCProperty:
77 case Decl::ObjCCompatibleAlias:
78 case Decl::PragmaComment:
79 case Decl::PragmaDetectMismatch:
80 case Decl::AccessSpec:
81 case Decl::LinkageSpec:
83 case Decl::ObjCPropertyImpl:
84 case Decl::FileScopeAsm:
86 case Decl::FriendTemplate:
89 case Decl::ClassScopeFunctionSpecialization:
90 case Decl::UsingShadow:
91 case Decl::ConstructorUsingShadow:
92 case Decl::ObjCTypeParam:
94 llvm_unreachable("Declaration should not be in declstmts!");
95 case Decl::Function: // void X();
96 case Decl::Record: // struct/union/class X;
97 case Decl::Enum: // enum X;
98 case Decl::EnumConstant: // enum ? { X = ? }
99 case Decl::CXXRecord: // struct/union/class X; [C++]
100 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
101 case Decl::Label: // __label__ x;
103 case Decl::OMPThreadPrivate:
104 case Decl::OMPCapturedExpr:
106 // None of these decls require codegen support.
109 case Decl::NamespaceAlias:
110 if (CGDebugInfo *DI = getDebugInfo())
111 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
113 case Decl::Using: // using X; [C++]
114 if (CGDebugInfo *DI = getDebugInfo())
115 DI->EmitUsingDecl(cast<UsingDecl>(D));
117 case Decl::UsingPack:
118 for (auto *Using : cast<UsingPackDecl>(D).expansions())
121 case Decl::UsingDirective: // using namespace X; [C++]
122 if (CGDebugInfo *DI = getDebugInfo())
123 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
126 case Decl::Decomposition: {
127 const VarDecl &VD = cast<VarDecl>(D);
128 assert(VD.isLocalVarDecl() &&
129 "Should not see file-scope variables inside a function!");
131 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
132 for (auto *B : DD->bindings())
133 if (auto *HD = B->getHoldingVar())
138 case Decl::OMPDeclareReduction:
139 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
141 case Decl::Typedef: // typedef int X;
142 case Decl::TypeAlias: { // using X = int; [C++0x]
143 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
144 QualType Ty = TD.getUnderlyingType();
146 if (Ty->isVariablyModifiedType())
147 EmitVariablyModifiedType(Ty);
152 /// EmitVarDecl - This method handles emission of any variable declaration
153 /// inside a function, including static vars etc.
154 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
155 if (D.hasExternalStorage())
156 // Don't emit it now, allow it to be emitted lazily on its first use.
159 // Some function-scope variable does not have static storage but still
160 // needs to be emitted like a static variable, e.g. a function-scope
161 // variable in constant address space in OpenCL.
162 if (D.getStorageDuration() != SD_Automatic) {
163 llvm::GlobalValue::LinkageTypes Linkage =
164 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
166 // FIXME: We need to force the emission/use of a guard variable for
167 // some variables even if we can constant-evaluate them because
168 // we can't guarantee every translation unit will constant-evaluate them.
170 return EmitStaticVarDecl(D, Linkage);
173 if (D.getType().getAddressSpace() == LangAS::opencl_local)
174 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
176 assert(D.hasLocalStorage());
177 return EmitAutoVarDecl(D);
180 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
181 if (CGM.getLangOpts().CPlusPlus)
182 return CGM.getMangledName(&D).str();
184 // If this isn't C++, we don't need a mangled name, just a pretty one.
185 assert(!D.isExternallyVisible() && "name shouldn't matter");
186 std::string ContextName;
187 const DeclContext *DC = D.getDeclContext();
188 if (auto *CD = dyn_cast<CapturedDecl>(DC))
189 DC = cast<DeclContext>(CD->getNonClosureContext());
190 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
191 ContextName = CGM.getMangledName(FD);
192 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
193 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
194 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
195 ContextName = OMD->getSelector().getAsString();
197 llvm_unreachable("Unknown context for static var decl");
199 ContextName += "." + D.getNameAsString();
203 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
204 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
205 // In general, we don't always emit static var decls once before we reference
206 // them. It is possible to reference them before emitting the function that
207 // contains them, and it is possible to emit the containing function multiple
209 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
212 QualType Ty = D.getType();
213 assert(Ty->isConstantSizeType() && "VLAs can't be static");
215 // Use the label if the variable is renamed with the asm-label extension.
217 if (D.hasAttr<AsmLabelAttr>())
218 Name = getMangledName(&D);
220 Name = getStaticDeclName(*this, D);
222 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
224 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
226 // Local address space cannot have an initializer.
227 llvm::Constant *Init = nullptr;
228 if (Ty.getAddressSpace() != LangAS::opencl_local)
229 Init = EmitNullConstant(Ty);
231 Init = llvm::UndefValue::get(LTy);
233 llvm::GlobalVariable *GV =
234 new llvm::GlobalVariable(getModule(), LTy,
235 Ty.isConstant(getContext()), Linkage,
237 llvm::GlobalVariable::NotThreadLocal,
239 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
240 setGlobalVisibility(GV, &D);
242 if (supportsCOMDAT() && GV->isWeakForLinker())
243 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
248 if (D.isExternallyVisible()) {
249 if (D.hasAttr<DLLImportAttr>())
250 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
251 else if (D.hasAttr<DLLExportAttr>())
252 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
255 // Make sure the result is of the correct type.
256 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
257 llvm::Constant *Addr = GV;
258 if (AddrSpace != ExpectedAddrSpace) {
259 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
260 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
263 setStaticLocalDeclAddress(&D, Addr);
265 // Ensure that the static local gets initialized by making sure the parent
266 // function gets emitted eventually.
267 const Decl *DC = cast<Decl>(D.getDeclContext());
269 // We can't name blocks or captured statements directly, so try to emit their
271 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
272 DC = DC->getNonClosureContext();
273 // FIXME: Ensure that global blocks get emitted.
279 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
280 GD = GlobalDecl(CD, Ctor_Base);
281 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
282 GD = GlobalDecl(DD, Dtor_Base);
283 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
286 // Don't do anything for Obj-C method decls or global closures. We should
288 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
291 (void)GetAddrOfGlobal(GD);
296 /// hasNontrivialDestruction - Determine whether a type's destruction is
297 /// non-trivial. If so, and the variable uses static initialization, we must
298 /// register its destructor to run on exit.
299 static bool hasNontrivialDestruction(QualType T) {
300 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
301 return RD && !RD->hasTrivialDestructor();
304 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
305 /// global variable that has already been created for it. If the initializer
306 /// has a different type than GV does, this may free GV and return a different
307 /// one. Otherwise it just returns GV.
308 llvm::GlobalVariable *
309 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
310 llvm::GlobalVariable *GV) {
311 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
313 // If constant emission failed, then this should be a C++ static
316 if (!getLangOpts().CPlusPlus)
317 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
318 else if (HaveInsertPoint()) {
319 // Since we have a static initializer, this global variable can't
321 GV->setConstant(false);
323 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
328 // The initializer may differ in type from the global. Rewrite
329 // the global to match the initializer. (We have to do this
330 // because some types, like unions, can't be completely represented
331 // in the LLVM type system.)
332 if (GV->getType()->getElementType() != Init->getType()) {
333 llvm::GlobalVariable *OldGV = GV;
335 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
337 OldGV->getLinkage(), Init, "",
338 /*InsertBefore*/ OldGV,
339 OldGV->getThreadLocalMode(),
340 CGM.getContext().getTargetAddressSpace(D.getType()));
341 GV->setVisibility(OldGV->getVisibility());
342 GV->setComdat(OldGV->getComdat());
344 // Steal the name of the old global
347 // Replace all uses of the old global with the new global
348 llvm::Constant *NewPtrForOldDecl =
349 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
350 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
352 // Erase the old global, since it is no longer used.
353 OldGV->eraseFromParent();
356 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
357 GV->setInitializer(Init);
359 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
360 // We have a constant initializer, but a nontrivial destructor. We still
361 // need to perform a guarded "initialization" in order to register the
363 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
369 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
370 llvm::GlobalValue::LinkageTypes Linkage) {
371 // Check to see if we already have a global variable for this
372 // declaration. This can happen when double-emitting function
373 // bodies, e.g. with complete and base constructors.
374 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
375 CharUnits alignment = getContext().getDeclAlign(&D);
377 // Store into LocalDeclMap before generating initializer to handle
378 // circular references.
379 setAddrOfLocalVar(&D, Address(addr, alignment));
381 // We can't have a VLA here, but we can have a pointer to a VLA,
382 // even though that doesn't really make any sense.
383 // Make sure to evaluate VLA bounds now so that we have them for later.
384 if (D.getType()->isVariablyModifiedType())
385 EmitVariablyModifiedType(D.getType());
387 // Save the type in case adding the initializer forces a type change.
388 llvm::Type *expectedType = addr->getType();
390 llvm::GlobalVariable *var =
391 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
393 // CUDA's local and local static __shared__ variables should not
394 // have any non-empty initializers. This is ensured by Sema.
395 // Whatever initializer such variable may have when it gets here is
396 // a no-op and should not be emitted.
397 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
398 D.hasAttr<CUDASharedAttr>();
399 // If this value has an initializer, emit it.
400 if (D.getInit() && !isCudaSharedVar)
401 var = AddInitializerToStaticVarDecl(D, var);
403 var->setAlignment(alignment.getQuantity());
405 if (D.hasAttr<AnnotateAttr>())
406 CGM.AddGlobalAnnotations(&D, var);
408 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
409 var->setSection(SA->getName());
411 if (D.hasAttr<UsedAttr>())
412 CGM.addUsedGlobal(var);
414 // We may have to cast the constant because of the initializer
417 // FIXME: It is really dangerous to store this in the map; if anyone
418 // RAUW's the GV uses of this constant will be invalid.
419 llvm::Constant *castedAddr =
420 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
421 if (var != castedAddr)
422 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
423 CGM.setStaticLocalDeclAddress(&D, castedAddr);
425 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
427 // Emit global variable debug descriptor for static vars.
428 CGDebugInfo *DI = getDebugInfo();
430 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
431 DI->setLocation(D.getLocation());
432 DI->EmitGlobalVariable(var, &D);
437 struct DestroyObject final : EHScopeStack::Cleanup {
438 DestroyObject(Address addr, QualType type,
439 CodeGenFunction::Destroyer *destroyer,
440 bool useEHCleanupForArray)
441 : addr(addr), type(type), destroyer(destroyer),
442 useEHCleanupForArray(useEHCleanupForArray) {}
446 CodeGenFunction::Destroyer *destroyer;
447 bool useEHCleanupForArray;
449 void Emit(CodeGenFunction &CGF, Flags flags) override {
450 // Don't use an EH cleanup recursively from an EH cleanup.
451 bool useEHCleanupForArray =
452 flags.isForNormalCleanup() && this->useEHCleanupForArray;
454 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
458 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
459 DestroyNRVOVariable(Address addr,
460 const CXXDestructorDecl *Dtor,
461 llvm::Value *NRVOFlag)
462 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
464 const CXXDestructorDecl *Dtor;
465 llvm::Value *NRVOFlag;
468 void Emit(CodeGenFunction &CGF, Flags flags) override {
469 // Along the exceptions path we always execute the dtor.
470 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
472 llvm::BasicBlock *SkipDtorBB = nullptr;
474 // If we exited via NRVO, we skip the destructor call.
475 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
476 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
477 llvm::Value *DidNRVO =
478 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
479 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
480 CGF.EmitBlock(RunDtorBB);
483 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
484 /*ForVirtualBase=*/false,
485 /*Delegating=*/false,
488 if (NRVO) CGF.EmitBlock(SkipDtorBB);
492 struct CallStackRestore final : EHScopeStack::Cleanup {
494 CallStackRestore(Address Stack) : Stack(Stack) {}
495 void Emit(CodeGenFunction &CGF, Flags flags) override {
496 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
497 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
498 CGF.Builder.CreateCall(F, V);
502 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
504 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
506 void Emit(CodeGenFunction &CGF, Flags flags) override {
507 // Compute the address of the local variable, in case it's a
508 // byref or something.
509 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
510 Var.getType(), VK_LValue, SourceLocation());
511 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
513 CGF.EmitExtendGCLifetime(value);
517 struct CallCleanupFunction final : EHScopeStack::Cleanup {
518 llvm::Constant *CleanupFn;
519 const CGFunctionInfo &FnInfo;
522 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
524 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
526 void Emit(CodeGenFunction &CGF, Flags flags) override {
527 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
528 Var.getType(), VK_LValue, SourceLocation());
529 // Compute the address of the local variable, in case it's a byref
531 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
533 // In some cases, the type of the function argument will be different from
534 // the type of the pointer. An example of this is
535 // void f(void* arg);
536 // __attribute__((cleanup(f))) void *g;
538 // To fix this we insert a bitcast here.
539 QualType ArgTy = FnInfo.arg_begin()->type;
541 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
544 Args.add(RValue::get(Arg),
545 CGF.getContext().getPointerType(Var.getType()));
546 auto Callee = CGCallee::forDirect(CleanupFn);
547 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
550 } // end anonymous namespace
552 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
553 /// variable with lifetime.
554 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
556 Qualifiers::ObjCLifetime lifetime) {
558 case Qualifiers::OCL_None:
559 llvm_unreachable("present but none");
561 case Qualifiers::OCL_ExplicitNone:
565 case Qualifiers::OCL_Strong: {
566 CodeGenFunction::Destroyer *destroyer =
567 (var.hasAttr<ObjCPreciseLifetimeAttr>()
568 ? CodeGenFunction::destroyARCStrongPrecise
569 : CodeGenFunction::destroyARCStrongImprecise);
571 CleanupKind cleanupKind = CGF.getARCCleanupKind();
572 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
573 cleanupKind & EHCleanup);
576 case Qualifiers::OCL_Autoreleasing:
580 case Qualifiers::OCL_Weak:
581 // __weak objects always get EH cleanups; otherwise, exceptions
582 // could cause really nasty crashes instead of mere leaks.
583 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
584 CodeGenFunction::destroyARCWeak,
585 /*useEHCleanup*/ true);
590 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
591 if (const Expr *e = dyn_cast<Expr>(s)) {
592 // Skip the most common kinds of expressions that make
593 // hierarchy-walking expensive.
594 s = e = e->IgnoreParenCasts();
596 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
597 return (ref->getDecl() == &var);
598 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
599 const BlockDecl *block = be->getBlockDecl();
600 for (const auto &I : block->captures()) {
601 if (I.getVariable() == &var)
607 for (const Stmt *SubStmt : s->children())
608 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
609 if (SubStmt && isAccessedBy(var, SubStmt))
615 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
616 if (!decl) return false;
617 if (!isa<VarDecl>(decl)) return false;
618 const VarDecl *var = cast<VarDecl>(decl);
619 return isAccessedBy(*var, e);
622 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
623 const LValue &destLV, const Expr *init) {
624 bool needsCast = false;
626 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
627 switch (castExpr->getCastKind()) {
628 // Look through casts that don't require representation changes.
631 case CK_BlockPointerToObjCPointerCast:
635 // If we find an l-value to r-value cast from a __weak variable,
636 // emit this operation as a copy or move.
637 case CK_LValueToRValue: {
638 const Expr *srcExpr = castExpr->getSubExpr();
639 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
642 // Emit the source l-value.
643 LValue srcLV = CGF.EmitLValue(srcExpr);
645 // Handle a formal type change to avoid asserting.
646 auto srcAddr = srcLV.getAddress();
648 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
649 destLV.getAddress().getElementType());
652 // If it was an l-value, use objc_copyWeak.
653 if (srcExpr->getValueKind() == VK_LValue) {
654 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
656 assert(srcExpr->getValueKind() == VK_XValue);
657 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
662 // Stop at anything else.
667 init = castExpr->getSubExpr();
672 static void drillIntoBlockVariable(CodeGenFunction &CGF,
674 const VarDecl *var) {
675 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
678 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
679 SourceLocation Loc) {
680 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
683 auto Nullability = LHS.getType()->getNullability(getContext());
684 if (!Nullability || *Nullability != NullabilityKind::NonNull)
687 // Check if the right hand side of the assignment is nonnull, if the left
688 // hand side must be nonnull.
689 SanitizerScope SanScope(this);
690 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
691 llvm::Constant *StaticData[] = {
692 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
693 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
694 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
695 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
696 SanitizerHandler::TypeMismatch, StaticData, RHS);
699 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
700 LValue lvalue, bool capturedByInit) {
701 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
703 llvm::Value *value = EmitScalarExpr(init);
705 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
706 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
707 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
711 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
712 init = DIE->getExpr();
714 // If we're emitting a value with lifetime, we have to do the
715 // initialization *before* we leave the cleanup scopes.
716 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
717 enterFullExpression(ewc);
718 init = ewc->getSubExpr();
720 CodeGenFunction::RunCleanupsScope Scope(*this);
722 // We have to maintain the illusion that the variable is
723 // zero-initialized. If the variable might be accessed in its
724 // initializer, zero-initialize before running the initializer, then
725 // actually perform the initialization with an assign.
726 bool accessedByInit = false;
727 if (lifetime != Qualifiers::OCL_ExplicitNone)
728 accessedByInit = (capturedByInit || isAccessedBy(D, init));
729 if (accessedByInit) {
730 LValue tempLV = lvalue;
731 // Drill down to the __block object if necessary.
732 if (capturedByInit) {
733 // We can use a simple GEP for this because it can't have been
735 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
740 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
741 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
743 // If __weak, we want to use a barrier under certain conditions.
744 if (lifetime == Qualifiers::OCL_Weak)
745 EmitARCInitWeak(tempLV.getAddress(), zero);
747 // Otherwise just do a simple store.
749 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
752 // Emit the initializer.
753 llvm::Value *value = nullptr;
756 case Qualifiers::OCL_None:
757 llvm_unreachable("present but none");
759 case Qualifiers::OCL_ExplicitNone:
760 value = EmitARCUnsafeUnretainedScalarExpr(init);
763 case Qualifiers::OCL_Strong: {
764 value = EmitARCRetainScalarExpr(init);
768 case Qualifiers::OCL_Weak: {
769 // If it's not accessed by the initializer, try to emit the
770 // initialization with a copy or move.
771 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
775 // No way to optimize a producing initializer into this. It's not
776 // worth optimizing for, because the value will immediately
777 // disappear in the common case.
778 value = EmitScalarExpr(init);
780 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
782 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
784 EmitARCInitWeak(lvalue.getAddress(), value);
788 case Qualifiers::OCL_Autoreleasing:
789 value = EmitARCRetainAutoreleaseScalarExpr(init);
793 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
795 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
797 // If the variable might have been accessed by its initializer, we
798 // might have to initialize with a barrier. We have to do this for
799 // both __weak and __strong, but __weak got filtered out above.
800 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
801 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
802 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
803 EmitARCRelease(oldValue, ARCImpreciseLifetime);
807 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
810 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
811 /// non-zero parts of the specified initializer with equal or fewer than
812 /// NumStores scalar stores.
813 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
814 unsigned &NumStores) {
815 // Zero and Undef never requires any extra stores.
816 if (isa<llvm::ConstantAggregateZero>(Init) ||
817 isa<llvm::ConstantPointerNull>(Init) ||
818 isa<llvm::UndefValue>(Init))
820 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
821 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
822 isa<llvm::ConstantExpr>(Init))
823 return Init->isNullValue() || NumStores--;
825 // See if we can emit each element.
826 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
827 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
828 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
829 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
835 if (llvm::ConstantDataSequential *CDS =
836 dyn_cast<llvm::ConstantDataSequential>(Init)) {
837 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
838 llvm::Constant *Elt = CDS->getElementAsConstant(i);
839 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
845 // Anything else is hard and scary.
849 /// emitStoresForInitAfterMemset - For inits that
850 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
851 /// stores that would be required.
852 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
853 bool isVolatile, CGBuilderTy &Builder) {
854 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
855 "called emitStoresForInitAfterMemset for zero or undef value.");
857 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
858 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
859 isa<llvm::ConstantExpr>(Init)) {
860 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
864 if (llvm::ConstantDataSequential *CDS =
865 dyn_cast<llvm::ConstantDataSequential>(Init)) {
866 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
867 llvm::Constant *Elt = CDS->getElementAsConstant(i);
869 // If necessary, get a pointer to the element and emit it.
870 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
871 emitStoresForInitAfterMemset(
872 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
873 isVolatile, Builder);
878 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
879 "Unknown value type!");
881 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
882 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
884 // If necessary, get a pointer to the element and emit it.
885 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
886 emitStoresForInitAfterMemset(
887 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
888 isVolatile, Builder);
892 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
893 /// plus some stores to initialize a local variable instead of using a memcpy
894 /// from a constant global. It is beneficial to use memset if the global is all
895 /// zeros, or mostly zeros and large.
896 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
897 uint64_t GlobalSize) {
898 // If a global is all zeros, always use a memset.
899 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
901 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
902 // do it if it will require 6 or fewer scalar stores.
903 // TODO: Should budget depends on the size? Avoiding a large global warrants
904 // plopping in more stores.
905 unsigned StoreBudget = 6;
906 uint64_t SizeLimit = 32;
908 return GlobalSize > SizeLimit &&
909 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
912 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
913 /// variable declaration with auto, register, or no storage class specifier.
914 /// These turn into simple stack objects, or GlobalValues depending on target.
915 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
916 AutoVarEmission emission = EmitAutoVarAlloca(D);
917 EmitAutoVarInit(emission);
918 EmitAutoVarCleanups(emission);
921 /// Emit a lifetime.begin marker if some criteria are satisfied.
922 /// \return a pointer to the temporary size Value if a marker was emitted, null
924 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
926 if (!ShouldEmitLifetimeMarkers)
929 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
930 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
932 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
933 C->setDoesNotThrow();
937 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
938 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
940 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
941 C->setDoesNotThrow();
944 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
945 /// local variable. Does not emit initialization or destruction.
946 CodeGenFunction::AutoVarEmission
947 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
948 QualType Ty = D.getType();
950 AutoVarEmission emission(D);
952 bool isByRef = D.hasAttr<BlocksAttr>();
953 emission.IsByRef = isByRef;
955 CharUnits alignment = getContext().getDeclAlign(&D);
957 // If the type is variably-modified, emit all the VLA sizes for it.
958 if (Ty->isVariablyModifiedType())
959 EmitVariablyModifiedType(Ty);
961 Address address = Address::invalid();
962 if (Ty->isConstantSizeType()) {
963 bool NRVO = getLangOpts().ElideConstructors &&
966 // If this value is an array or struct with a statically determinable
967 // constant initializer, there are optimizations we can do.
969 // TODO: We should constant-evaluate the initializer of any variable,
970 // as long as it is initialized by a constant expression. Currently,
971 // isConstantInitializer produces wrong answers for structs with
972 // reference or bitfield members, and a few other cases, and checking
973 // for POD-ness protects us from some of these.
974 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
976 ((Ty.isPODType(getContext()) ||
977 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
978 D.getInit()->isConstantInitializer(getContext(), false)))) {
980 // If the variable's a const type, and it's neither an NRVO
981 // candidate nor a __block variable and has no mutable members,
982 // emit it as a global instead.
983 // Exception is if a variable is located in non-constant address space
985 if ((!getLangOpts().OpenCL ||
986 Ty.getAddressSpace() == LangAS::opencl_constant) &&
987 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
988 CGM.isTypeConstant(Ty, true))) {
989 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
991 // Signal this condition to later callbacks.
992 emission.Addr = Address::invalid();
993 assert(emission.wasEmittedAsGlobal());
997 // Otherwise, tell the initialization code that we're in this case.
998 emission.IsConstantAggregate = true;
1001 // A normal fixed sized variable becomes an alloca in the entry block,
1002 // unless it's an NRVO variable.
1005 // The named return value optimization: allocate this variable in the
1006 // return slot, so that we can elide the copy when returning this
1007 // variable (C++0x [class.copy]p34).
1008 address = ReturnValue;
1010 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1011 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1012 // Create a flag that is used to indicate when the NRVO was applied
1013 // to this variable. Set it to zero to indicate that NRVO was not
1015 llvm::Value *Zero = Builder.getFalse();
1017 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1018 EnsureInsertPoint();
1019 Builder.CreateStore(Zero, NRVOFlag);
1021 // Record the NRVO flag for this variable.
1022 NRVOFlags[&D] = NRVOFlag.getPointer();
1023 emission.NRVOFlag = NRVOFlag.getPointer();
1027 CharUnits allocaAlignment;
1028 llvm::Type *allocaTy;
1030 auto &byrefInfo = getBlockByrefInfo(&D);
1031 allocaTy = byrefInfo.Type;
1032 allocaAlignment = byrefInfo.ByrefAlignment;
1034 allocaTy = ConvertTypeForMem(Ty);
1035 allocaAlignment = alignment;
1038 // Create the alloca. Note that we set the name separately from
1039 // building the instruction so that it's there even in no-asserts
1041 address = CreateTempAlloca(allocaTy, allocaAlignment);
1042 address.getPointer()->setName(D.getName());
1044 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1045 // the catch parameter starts in the catchpad instruction, and we can't
1046 // insert code in those basic blocks.
1047 bool IsMSCatchParam =
1048 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1050 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1051 // if we don't have a valid insertion point (?).
1052 if (HaveInsertPoint() && !IsMSCatchParam) {
1053 // If there's a jump into the lifetime of this variable, its lifetime
1054 // gets broken up into several regions in IR, which requires more work
1055 // to handle correctly. For now, just omit the intrinsics; this is a
1056 // rare case, and it's better to just be conservatively correct.
1059 // We have to do this in all language modes if there's a jump past the
1060 // declaration. We also have to do it in C if there's a jump to an
1061 // earlier point in the current block because non-VLA lifetimes begin as
1062 // soon as the containing block is entered, not when its variables
1063 // actually come into scope; suppressing the lifetime annotations
1064 // completely in this case is unnecessarily pessimistic, but again, this
1066 if (!Bypasses.IsBypassed(&D) &&
1067 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1068 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1069 emission.SizeForLifetimeMarkers =
1070 EmitLifetimeStart(size, address.getPointer());
1073 assert(!emission.useLifetimeMarkers());
1077 EnsureInsertPoint();
1079 if (!DidCallStackSave) {
1082 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1084 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1085 llvm::Value *V = Builder.CreateCall(F);
1086 Builder.CreateStore(V, Stack);
1088 DidCallStackSave = true;
1090 // Push a cleanup block and restore the stack there.
1091 // FIXME: in general circumstances, this should be an EH cleanup.
1092 pushStackRestore(NormalCleanup, Stack);
1095 llvm::Value *elementCount;
1096 QualType elementType;
1097 std::tie(elementCount, elementType) = getVLASize(Ty);
1099 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1101 // Allocate memory for the array.
1102 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1103 vla->setAlignment(alignment.getQuantity());
1105 address = Address(vla, alignment);
1108 setAddrOfLocalVar(&D, address);
1109 emission.Addr = address;
1111 // Emit debug info for local var declaration.
1112 if (HaveInsertPoint())
1113 if (CGDebugInfo *DI = getDebugInfo()) {
1114 if (CGM.getCodeGenOpts().getDebugInfo() >=
1115 codegenoptions::LimitedDebugInfo) {
1116 DI->setLocation(D.getLocation());
1117 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1121 if (D.hasAttr<AnnotateAttr>())
1122 EmitVarAnnotations(&D, address.getPointer());
1124 // Make sure we call @llvm.lifetime.end.
1125 if (emission.useLifetimeMarkers())
1126 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1127 emission.getAllocatedAddress(),
1128 emission.getSizeForLifetimeMarkers());
1133 /// Determines whether the given __block variable is potentially
1134 /// captured by the given expression.
1135 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1136 // Skip the most common kinds of expressions that make
1137 // hierarchy-walking expensive.
1138 e = e->IgnoreParenCasts();
1140 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1141 const BlockDecl *block = be->getBlockDecl();
1142 for (const auto &I : block->captures()) {
1143 if (I.getVariable() == &var)
1147 // No need to walk into the subexpressions.
1151 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1152 const CompoundStmt *CS = SE->getSubStmt();
1153 for (const auto *BI : CS->body())
1154 if (const auto *E = dyn_cast<Expr>(BI)) {
1155 if (isCapturedBy(var, E))
1158 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1159 // special case declarations
1160 for (const auto *I : DS->decls()) {
1161 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1162 const Expr *Init = VD->getInit();
1163 if (Init && isCapturedBy(var, Init))
1169 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1170 // Later, provide code to poke into statements for capture analysis.
1175 for (const Stmt *SubStmt : e->children())
1176 if (isCapturedBy(var, cast<Expr>(SubStmt)))
1182 /// \brief Determine whether the given initializer is trivial in the sense
1183 /// that it requires no code to be generated.
1184 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1188 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1189 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1190 if (Constructor->isTrivial() &&
1191 Constructor->isDefaultConstructor() &&
1192 !Construct->requiresZeroInitialization())
1198 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1199 assert(emission.Variable && "emission was not valid!");
1201 // If this was emitted as a global constant, we're done.
1202 if (emission.wasEmittedAsGlobal()) return;
1204 const VarDecl &D = *emission.Variable;
1205 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1206 QualType type = D.getType();
1208 // If this local has an initializer, emit it now.
1209 const Expr *Init = D.getInit();
1211 // If we are at an unreachable point, we don't need to emit the initializer
1212 // unless it contains a label.
1213 if (!HaveInsertPoint()) {
1214 if (!Init || !ContainsLabel(Init)) return;
1215 EnsureInsertPoint();
1218 // Initialize the structure of a __block variable.
1219 if (emission.IsByRef)
1220 emitByrefStructureInit(emission);
1222 if (isTrivialInitializer(Init))
1225 // Check whether this is a byref variable that's potentially
1226 // captured and moved by its own initializer. If so, we'll need to
1227 // emit the initializer first, then copy into the variable.
1228 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1231 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1233 llvm::Constant *constant = nullptr;
1234 if (emission.IsConstantAggregate || D.isConstexpr()) {
1235 assert(!capturedByInit && "constant init contains a capturing block?");
1236 constant = CGM.EmitConstantInit(D, this);
1240 LValue lv = MakeAddrLValue(Loc, type);
1242 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1245 if (!emission.IsConstantAggregate) {
1246 // For simple scalar/complex initialization, store the value directly.
1247 LValue lv = MakeAddrLValue(Loc, type);
1249 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1252 // If this is a simple aggregate initialization, we can optimize it
1254 bool isVolatile = type.isVolatileQualified();
1256 llvm::Value *SizeVal =
1257 llvm::ConstantInt::get(IntPtrTy,
1258 getContext().getTypeSizeInChars(type).getQuantity());
1260 llvm::Type *BP = Int8PtrTy;
1261 if (Loc.getType() != BP)
1262 Loc = Builder.CreateBitCast(Loc, BP);
1264 // If the initializer is all or mostly zeros, codegen with memset then do
1265 // a few stores afterward.
1266 if (shouldUseMemSetPlusStoresToInitialize(constant,
1267 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1268 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1270 // Zero and undef don't require a stores.
1271 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1272 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1273 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1274 isVolatile, Builder);
1277 // Otherwise, create a temporary global with the initializer then
1278 // memcpy from the global to the alloca.
1279 std::string Name = getStaticDeclName(CGM, D);
1281 if (getLangOpts().OpenCL) {
1282 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1283 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1285 llvm::GlobalVariable *GV =
1286 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1287 llvm::GlobalValue::PrivateLinkage,
1288 constant, Name, nullptr,
1289 llvm::GlobalValue::NotThreadLocal, AS);
1290 GV->setAlignment(Loc.getAlignment().getQuantity());
1291 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1293 Address SrcPtr = Address(GV, Loc.getAlignment());
1294 if (SrcPtr.getType() != BP)
1295 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1297 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1301 /// Emit an expression as an initializer for a variable at the given
1302 /// location. The expression is not necessarily the normal
1303 /// initializer for the variable, and the address is not necessarily
1304 /// its normal location.
1306 /// \param init the initializing expression
1307 /// \param var the variable to act as if we're initializing
1308 /// \param loc the address to initialize; its type is a pointer
1309 /// to the LLVM mapping of the variable's type
1310 /// \param alignment the alignment of the address
1311 /// \param capturedByInit true if the variable is a __block variable
1312 /// whose address is potentially changed by the initializer
1313 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1314 LValue lvalue, bool capturedByInit) {
1315 QualType type = D->getType();
1317 if (type->isReferenceType()) {
1318 RValue rvalue = EmitReferenceBindingToExpr(init);
1320 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1321 EmitStoreThroughLValue(rvalue, lvalue, true);
1324 switch (getEvaluationKind(type)) {
1326 EmitScalarInit(init, D, lvalue, capturedByInit);
1329 ComplexPairTy complex = EmitComplexExpr(init);
1331 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1332 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1336 if (type->isAtomicType()) {
1337 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1339 // TODO: how can we delay here if D is captured by its initializer?
1340 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1341 AggValueSlot::IsDestructed,
1342 AggValueSlot::DoesNotNeedGCBarriers,
1343 AggValueSlot::IsNotAliased));
1347 llvm_unreachable("bad evaluation kind");
1350 /// Enter a destroy cleanup for the given local variable.
1351 void CodeGenFunction::emitAutoVarTypeCleanup(
1352 const CodeGenFunction::AutoVarEmission &emission,
1353 QualType::DestructionKind dtorKind) {
1354 assert(dtorKind != QualType::DK_none);
1356 // Note that for __block variables, we want to destroy the
1357 // original stack object, not the possibly forwarded object.
1358 Address addr = emission.getObjectAddress(*this);
1360 const VarDecl *var = emission.Variable;
1361 QualType type = var->getType();
1363 CleanupKind cleanupKind = NormalAndEHCleanup;
1364 CodeGenFunction::Destroyer *destroyer = nullptr;
1367 case QualType::DK_none:
1368 llvm_unreachable("no cleanup for trivially-destructible variable");
1370 case QualType::DK_cxx_destructor:
1371 // If there's an NRVO flag on the emission, we need a different
1373 if (emission.NRVOFlag) {
1374 assert(!type->isArrayType());
1375 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1376 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1377 dtor, emission.NRVOFlag);
1382 case QualType::DK_objc_strong_lifetime:
1383 // Suppress cleanups for pseudo-strong variables.
1384 if (var->isARCPseudoStrong()) return;
1386 // Otherwise, consider whether to use an EH cleanup or not.
1387 cleanupKind = getARCCleanupKind();
1389 // Use the imprecise destroyer by default.
1390 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1391 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1394 case QualType::DK_objc_weak_lifetime:
1398 // If we haven't chosen a more specific destroyer, use the default.
1399 if (!destroyer) destroyer = getDestroyer(dtorKind);
1401 // Use an EH cleanup in array destructors iff the destructor itself
1402 // is being pushed as an EH cleanup.
1403 bool useEHCleanup = (cleanupKind & EHCleanup);
1404 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1408 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1409 assert(emission.Variable && "emission was not valid!");
1411 // If this was emitted as a global constant, we're done.
1412 if (emission.wasEmittedAsGlobal()) return;
1414 // If we don't have an insertion point, we're done. Sema prevents
1415 // us from jumping into any of these scopes anyway.
1416 if (!HaveInsertPoint()) return;
1418 const VarDecl &D = *emission.Variable;
1420 // Check the type for a cleanup.
1421 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1422 emitAutoVarTypeCleanup(emission, dtorKind);
1424 // In GC mode, honor objc_precise_lifetime.
1425 if (getLangOpts().getGC() != LangOptions::NonGC &&
1426 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1427 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1430 // Handle the cleanup attribute.
1431 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1432 const FunctionDecl *FD = CA->getFunctionDecl();
1434 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1435 assert(F && "Could not find function!");
1437 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1438 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1441 // If this is a block variable, call _Block_object_destroy
1442 // (on the unforwarded address).
1443 if (emission.IsByRef)
1444 enterByrefCleanup(emission);
1447 CodeGenFunction::Destroyer *
1448 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1450 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1451 case QualType::DK_cxx_destructor:
1452 return destroyCXXObject;
1453 case QualType::DK_objc_strong_lifetime:
1454 return destroyARCStrongPrecise;
1455 case QualType::DK_objc_weak_lifetime:
1456 return destroyARCWeak;
1458 llvm_unreachable("Unknown DestructionKind");
1461 /// pushEHDestroy - Push the standard destructor for the given type as
1462 /// an EH-only cleanup.
1463 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1464 Address addr, QualType type) {
1465 assert(dtorKind && "cannot push destructor for trivial type");
1466 assert(needsEHCleanup(dtorKind));
1468 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1471 /// pushDestroy - Push the standard destructor for the given type as
1472 /// at least a normal cleanup.
1473 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1474 Address addr, QualType type) {
1475 assert(dtorKind && "cannot push destructor for trivial type");
1477 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1478 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1479 cleanupKind & EHCleanup);
1482 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1483 QualType type, Destroyer *destroyer,
1484 bool useEHCleanupForArray) {
1485 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1486 destroyer, useEHCleanupForArray);
1489 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1490 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1493 void CodeGenFunction::pushLifetimeExtendedDestroy(
1494 CleanupKind cleanupKind, Address addr, QualType type,
1495 Destroyer *destroyer, bool useEHCleanupForArray) {
1496 assert(!isInConditionalBranch() &&
1497 "performing lifetime extension from within conditional");
1499 // Push an EH-only cleanup for the object now.
1500 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1501 // around in case a temporary's destructor throws an exception.
1502 if (cleanupKind & EHCleanup)
1503 EHStack.pushCleanup<DestroyObject>(
1504 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1505 destroyer, useEHCleanupForArray);
1507 // Remember that we need to push a full cleanup for the object at the
1508 // end of the full-expression.
1509 pushCleanupAfterFullExpr<DestroyObject>(
1510 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1513 /// emitDestroy - Immediately perform the destruction of the given
1516 /// \param addr - the address of the object; a type*
1517 /// \param type - the type of the object; if an array type, all
1518 /// objects are destroyed in reverse order
1519 /// \param destroyer - the function to call to destroy individual
1521 /// \param useEHCleanupForArray - whether an EH cleanup should be
1522 /// used when destroying array elements, in case one of the
1523 /// destructions throws an exception
1524 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1525 Destroyer *destroyer,
1526 bool useEHCleanupForArray) {
1527 const ArrayType *arrayType = getContext().getAsArrayType(type);
1529 return destroyer(*this, addr, type);
1531 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1533 CharUnits elementAlign =
1535 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1537 // Normally we have to check whether the array is zero-length.
1538 bool checkZeroLength = true;
1540 // But if the array length is constant, we can suppress that.
1541 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1542 // ...and if it's constant zero, we can just skip the entire thing.
1543 if (constLength->isZero()) return;
1544 checkZeroLength = false;
1547 llvm::Value *begin = addr.getPointer();
1548 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1549 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1550 checkZeroLength, useEHCleanupForArray);
1553 /// emitArrayDestroy - Destroys all the elements of the given array,
1554 /// beginning from last to first. The array cannot be zero-length.
1556 /// \param begin - a type* denoting the first element of the array
1557 /// \param end - a type* denoting one past the end of the array
1558 /// \param elementType - the element type of the array
1559 /// \param destroyer - the function to call to destroy elements
1560 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1561 /// the remaining elements in case the destruction of a single
1563 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1565 QualType elementType,
1566 CharUnits elementAlign,
1567 Destroyer *destroyer,
1568 bool checkZeroLength,
1569 bool useEHCleanup) {
1570 assert(!elementType->isArrayType());
1572 // The basic structure here is a do-while loop, because we don't
1573 // need to check for the zero-element case.
1574 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1575 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1577 if (checkZeroLength) {
1578 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1579 "arraydestroy.isempty");
1580 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1583 // Enter the loop body, making that address the current address.
1584 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1586 llvm::PHINode *elementPast =
1587 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1588 elementPast->addIncoming(end, entryBB);
1590 // Shift the address back by one element.
1591 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1592 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1593 "arraydestroy.element");
1596 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1599 // Perform the actual destruction there.
1600 destroyer(*this, Address(element, elementAlign), elementType);
1605 // Check whether we've reached the end.
1606 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1607 Builder.CreateCondBr(done, doneBB, bodyBB);
1608 elementPast->addIncoming(element, Builder.GetInsertBlock());
1614 /// Perform partial array destruction as if in an EH cleanup. Unlike
1615 /// emitArrayDestroy, the element type here may still be an array type.
1616 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1617 llvm::Value *begin, llvm::Value *end,
1618 QualType type, CharUnits elementAlign,
1619 CodeGenFunction::Destroyer *destroyer) {
1620 // If the element type is itself an array, drill down.
1621 unsigned arrayDepth = 0;
1622 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1623 // VLAs don't require a GEP index to walk into.
1624 if (!isa<VariableArrayType>(arrayType))
1626 type = arrayType->getElementType();
1630 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1632 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1633 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1634 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1637 // Destroy the array. We don't ever need an EH cleanup because we
1638 // assume that we're in an EH cleanup ourselves, so a throwing
1639 // destructor causes an immediate terminate.
1640 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1641 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1645 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1646 /// array destroy where the end pointer is regularly determined and
1647 /// does not need to be loaded from a local.
1648 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1649 llvm::Value *ArrayBegin;
1650 llvm::Value *ArrayEnd;
1651 QualType ElementType;
1652 CodeGenFunction::Destroyer *Destroyer;
1653 CharUnits ElementAlign;
1655 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1656 QualType elementType, CharUnits elementAlign,
1657 CodeGenFunction::Destroyer *destroyer)
1658 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1659 ElementType(elementType), Destroyer(destroyer),
1660 ElementAlign(elementAlign) {}
1662 void Emit(CodeGenFunction &CGF, Flags flags) override {
1663 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1664 ElementType, ElementAlign, Destroyer);
1668 /// IrregularPartialArrayDestroy - a cleanup which performs a
1669 /// partial array destroy where the end pointer is irregularly
1670 /// determined and must be loaded from a local.
1671 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1672 llvm::Value *ArrayBegin;
1673 Address ArrayEndPointer;
1674 QualType ElementType;
1675 CodeGenFunction::Destroyer *Destroyer;
1676 CharUnits ElementAlign;
1678 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1679 Address arrayEndPointer,
1680 QualType elementType,
1681 CharUnits elementAlign,
1682 CodeGenFunction::Destroyer *destroyer)
1683 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1684 ElementType(elementType), Destroyer(destroyer),
1685 ElementAlign(elementAlign) {}
1687 void Emit(CodeGenFunction &CGF, Flags flags) override {
1688 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1689 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1690 ElementType, ElementAlign, Destroyer);
1693 } // end anonymous namespace
1695 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1696 /// already-constructed elements of the given array. The cleanup
1697 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1699 /// \param elementType - the immediate element type of the array;
1700 /// possibly still an array type
1701 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1702 Address arrayEndPointer,
1703 QualType elementType,
1704 CharUnits elementAlign,
1705 Destroyer *destroyer) {
1706 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1707 arrayBegin, arrayEndPointer,
1708 elementType, elementAlign,
1712 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1713 /// already-constructed elements of the given array. The cleanup
1714 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1716 /// \param elementType - the immediate element type of the array;
1717 /// possibly still an array type
1718 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1719 llvm::Value *arrayEnd,
1720 QualType elementType,
1721 CharUnits elementAlign,
1722 Destroyer *destroyer) {
1723 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1724 arrayBegin, arrayEnd,
1725 elementType, elementAlign,
1729 /// Lazily declare the @llvm.lifetime.start intrinsic.
1730 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1731 if (LifetimeStartFn)
1732 return LifetimeStartFn;
1733 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1734 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
1735 return LifetimeStartFn;
1738 /// Lazily declare the @llvm.lifetime.end intrinsic.
1739 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1741 return LifetimeEndFn;
1742 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1743 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
1744 return LifetimeEndFn;
1748 /// A cleanup to perform a release of an object at the end of a
1749 /// function. This is used to balance out the incoming +1 of a
1750 /// ns_consumed argument when we can't reasonably do that just by
1751 /// not doing the initial retain for a __block argument.
1752 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1753 ConsumeARCParameter(llvm::Value *param,
1754 ARCPreciseLifetime_t precise)
1755 : Param(param), Precise(precise) {}
1758 ARCPreciseLifetime_t Precise;
1760 void Emit(CodeGenFunction &CGF, Flags flags) override {
1761 CGF.EmitARCRelease(Param, Precise);
1764 } // end anonymous namespace
1766 /// Emit an alloca (or GlobalValue depending on target)
1767 /// for the specified parameter and set up LocalDeclMap.
1768 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1770 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1771 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1772 "Invalid argument to EmitParmDecl");
1774 Arg.getAnyValue()->setName(D.getName());
1776 QualType Ty = D.getType();
1778 // Use better IR generation for certain implicit parameters.
1779 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1780 // The only implicit argument a block has is its literal.
1781 // We assume this is always passed directly.
1783 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1787 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1788 // handle the case where 'this' is passed indirectly as part of an inalloca
1790 if (const CXXMethodDecl *MD =
1791 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1792 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1793 llvm::Value *This = Arg.isIndirect()
1794 ? Builder.CreateLoad(Arg.getIndirectAddress())
1795 : Arg.getDirectValue();
1796 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1797 *this, CurGD, This);
1798 if (Arg.isIndirect())
1799 Builder.CreateStore(This, Arg.getIndirectAddress());
1801 Arg = ParamValue::forDirect(This);
1806 Address DeclPtr = Address::invalid();
1807 bool DoStore = false;
1808 bool IsScalar = hasScalarEvaluationKind(Ty);
1809 // If we already have a pointer to the argument, reuse the input pointer.
1810 if (Arg.isIndirect()) {
1811 DeclPtr = Arg.getIndirectAddress();
1812 // If we have a prettier pointer type at this point, bitcast to that.
1813 unsigned AS = DeclPtr.getType()->getAddressSpace();
1814 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1815 if (DeclPtr.getType() != IRTy)
1816 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1818 // Push a destructor cleanup for this parameter if the ABI requires it.
1819 // Don't push a cleanup in a thunk for a method that will also emit a
1821 if (!IsScalar && !CurFuncIsThunk &&
1822 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1823 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1824 if (RD && RD->hasNonTrivialDestructor())
1825 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1828 // Otherwise, create a temporary to hold the value.
1829 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1830 D.getName() + ".addr");
1834 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1836 LValue lv = MakeAddrLValue(DeclPtr, Ty);
1838 Qualifiers qs = Ty.getQualifiers();
1839 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1840 // We honor __attribute__((ns_consumed)) for types with lifetime.
1841 // For __strong, it's handled by just skipping the initial retain;
1842 // otherwise we have to balance out the initial +1 with an extra
1843 // cleanup to do the release at the end of the function.
1844 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1846 // 'self' is always formally __strong, but if this is not an
1847 // init method then we don't want to retain it.
1848 if (D.isARCPseudoStrong()) {
1849 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1850 assert(&D == method->getSelfDecl());
1851 assert(lt == Qualifiers::OCL_Strong);
1852 assert(qs.hasConst());
1853 assert(method->getMethodFamily() != OMF_init);
1855 lt = Qualifiers::OCL_ExplicitNone;
1858 if (lt == Qualifiers::OCL_Strong) {
1860 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1861 // use objc_storeStrong(&dest, value) for retaining the
1862 // object. But first, store a null into 'dest' because
1863 // objc_storeStrong attempts to release its old value.
1864 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1865 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1866 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1870 // Don't use objc_retainBlock for block pointers, because we
1871 // don't want to Block_copy something just because we got it
1873 ArgVal = EmitARCRetainNonBlock(ArgVal);
1876 // Push the cleanup for a consumed parameter.
1878 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1879 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1880 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1884 if (lt == Qualifiers::OCL_Weak) {
1885 EmitARCInitWeak(DeclPtr, ArgVal);
1886 DoStore = false; // The weak init is a store, no need to do two.
1890 // Enter the cleanup scope.
1891 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1895 // Store the initial value into the alloca.
1897 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1899 setAddrOfLocalVar(&D, DeclPtr);
1901 // Emit debug info for param declaration.
1902 if (CGDebugInfo *DI = getDebugInfo()) {
1903 if (CGM.getCodeGenOpts().getDebugInfo() >=
1904 codegenoptions::LimitedDebugInfo) {
1905 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1909 if (D.hasAttr<AnnotateAttr>())
1910 EmitVarAnnotations(&D, DeclPtr.getPointer());
1912 // We can only check return value nullability if all arguments to the
1913 // function satisfy their nullability preconditions. This makes it necessary
1914 // to emit null checks for args in the function body itself.
1915 if (requiresReturnValueNullabilityCheck()) {
1916 auto Nullability = Ty->getNullability(getContext());
1917 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1918 SanitizerScope SanScope(this);
1919 RetValNullabilityPrecondition =
1920 Builder.CreateAnd(RetValNullabilityPrecondition,
1921 Builder.CreateIsNotNull(Arg.getAnyValue()));
1926 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1927 CodeGenFunction *CGF) {
1928 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1930 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);