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 //===----------------------------------------------------------------------===//
16 #include "CGCleanup.h"
17 #include "CGDebugInfo.h"
18 #include "CGOpenCLRuntime.h"
19 #include "CGOpenMPRuntime.h"
20 #include "CodeGenFunction.h"
21 #include "CodeGenModule.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclOpenMP.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/CodeGen/CGFunctionInfo.h"
31 #include "clang/Frontend/CodeGenOptions.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/Type.h"
37 using namespace clang;
38 using namespace CodeGen;
40 void CodeGenFunction::EmitDecl(const Decl &D) {
41 switch (D.getKind()) {
42 case Decl::BuiltinTemplate:
43 case Decl::TranslationUnit:
44 case Decl::ExternCContext:
46 case Decl::UnresolvedUsingTypename:
47 case Decl::ClassTemplateSpecialization:
48 case Decl::ClassTemplatePartialSpecialization:
49 case Decl::VarTemplateSpecialization:
50 case Decl::VarTemplatePartialSpecialization:
51 case Decl::TemplateTypeParm:
52 case Decl::UnresolvedUsingValue:
53 case Decl::NonTypeTemplateParm:
54 case Decl::CXXDeductionGuide:
56 case Decl::CXXConstructor:
57 case Decl::CXXDestructor:
58 case Decl::CXXConversion:
60 case Decl::MSProperty:
61 case Decl::IndirectField:
63 case Decl::ObjCAtDefsField:
65 case Decl::ImplicitParam:
66 case Decl::ClassTemplate:
67 case Decl::VarTemplate:
68 case Decl::FunctionTemplate:
69 case Decl::TypeAliasTemplate:
70 case Decl::TemplateTemplateParm:
71 case Decl::ObjCMethod:
72 case Decl::ObjCCategory:
73 case Decl::ObjCProtocol:
74 case Decl::ObjCInterface:
75 case Decl::ObjCCategoryImpl:
76 case Decl::ObjCImplementation:
77 case Decl::ObjCProperty:
78 case Decl::ObjCCompatibleAlias:
79 case Decl::PragmaComment:
80 case Decl::PragmaDetectMismatch:
81 case Decl::AccessSpec:
82 case Decl::LinkageSpec:
84 case Decl::ObjCPropertyImpl:
85 case Decl::FileScopeAsm:
87 case Decl::FriendTemplate:
90 case Decl::ClassScopeFunctionSpecialization:
91 case Decl::UsingShadow:
92 case Decl::ConstructorUsingShadow:
93 case Decl::ObjCTypeParam:
95 llvm_unreachable("Declaration should not be in declstmts!");
96 case Decl::Function: // void X();
97 case Decl::Record: // struct/union/class X;
98 case Decl::Enum: // enum X;
99 case Decl::EnumConstant: // enum ? { X = ? }
100 case Decl::CXXRecord: // struct/union/class X; [C++]
101 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
102 case Decl::Label: // __label__ x;
104 case Decl::OMPThreadPrivate:
105 case Decl::OMPCapturedExpr:
107 // None of these decls require codegen support.
110 case Decl::NamespaceAlias:
111 if (CGDebugInfo *DI = getDebugInfo())
112 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
114 case Decl::Using: // using X; [C++]
115 if (CGDebugInfo *DI = getDebugInfo())
116 DI->EmitUsingDecl(cast<UsingDecl>(D));
118 case Decl::UsingPack:
119 for (auto *Using : cast<UsingPackDecl>(D).expansions())
122 case Decl::UsingDirective: // using namespace X; [C++]
123 if (CGDebugInfo *DI = getDebugInfo())
124 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
127 case Decl::Decomposition: {
128 const VarDecl &VD = cast<VarDecl>(D);
129 assert(VD.isLocalVarDecl() &&
130 "Should not see file-scope variables inside a function!");
132 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
133 for (auto *B : DD->bindings())
134 if (auto *HD = B->getHoldingVar())
139 case Decl::OMPDeclareReduction:
140 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
142 case Decl::Typedef: // typedef int X;
143 case Decl::TypeAlias: { // using X = int; [C++0x]
144 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
145 QualType Ty = TD.getUnderlyingType();
147 if (Ty->isVariablyModifiedType())
148 EmitVariablyModifiedType(Ty);
153 /// EmitVarDecl - This method handles emission of any variable declaration
154 /// inside a function, including static vars etc.
155 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
156 if (D.hasExternalStorage())
157 // Don't emit it now, allow it to be emitted lazily on its first use.
160 // Some function-scope variable does not have static storage but still
161 // needs to be emitted like a static variable, e.g. a function-scope
162 // variable in constant address space in OpenCL.
163 if (D.getStorageDuration() != SD_Automatic) {
164 llvm::GlobalValue::LinkageTypes Linkage =
165 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
167 // FIXME: We need to force the emission/use of a guard variable for
168 // some variables even if we can constant-evaluate them because
169 // we can't guarantee every translation unit will constant-evaluate them.
171 return EmitStaticVarDecl(D, Linkage);
174 if (D.getType().getAddressSpace() == LangAS::opencl_local)
175 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
177 assert(D.hasLocalStorage());
178 return EmitAutoVarDecl(D);
181 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
182 if (CGM.getLangOpts().CPlusPlus)
183 return CGM.getMangledName(&D).str();
185 // If this isn't C++, we don't need a mangled name, just a pretty one.
186 assert(!D.isExternallyVisible() && "name shouldn't matter");
187 std::string ContextName;
188 const DeclContext *DC = D.getDeclContext();
189 if (auto *CD = dyn_cast<CapturedDecl>(DC))
190 DC = cast<DeclContext>(CD->getNonClosureContext());
191 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
192 ContextName = CGM.getMangledName(FD);
193 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
194 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
195 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
196 ContextName = OMD->getSelector().getAsString();
198 llvm_unreachable("Unknown context for static var decl");
200 ContextName += "." + D.getNameAsString();
204 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
205 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
206 // In general, we don't always emit static var decls once before we reference
207 // them. It is possible to reference them before emitting the function that
208 // contains them, and it is possible to emit the containing function multiple
210 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
213 QualType Ty = D.getType();
214 assert(Ty->isConstantSizeType() && "VLAs can't be static");
216 // Use the label if the variable is renamed with the asm-label extension.
218 if (D.hasAttr<AsmLabelAttr>())
219 Name = getMangledName(&D);
221 Name = getStaticDeclName(*this, D);
223 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
224 unsigned AS = GetGlobalVarAddressSpace(&D);
225 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
227 // Local address space cannot have an initializer.
228 llvm::Constant *Init = nullptr;
229 if (Ty.getAddressSpace() != LangAS::opencl_local)
230 Init = EmitNullConstant(Ty);
232 Init = llvm::UndefValue::get(LTy);
234 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
235 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
236 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
237 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
238 setGlobalVisibility(GV, &D);
240 if (supportsCOMDAT() && GV->isWeakForLinker())
241 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
246 if (D.isExternallyVisible()) {
247 if (D.hasAttr<DLLImportAttr>())
248 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
249 else if (D.hasAttr<DLLExportAttr>())
250 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
253 // Make sure the result is of the correct type.
254 unsigned ExpectedAS = Ty.getAddressSpace();
255 llvm::Constant *Addr = GV;
256 if (AS != ExpectedAS) {
257 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
258 *this, GV, AS, ExpectedAS,
259 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
262 setStaticLocalDeclAddress(&D, Addr);
264 // Ensure that the static local gets initialized by making sure the parent
265 // function gets emitted eventually.
266 const Decl *DC = cast<Decl>(D.getDeclContext());
268 // We can't name blocks or captured statements directly, so try to emit their
270 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
271 DC = DC->getNonClosureContext();
272 // FIXME: Ensure that global blocks get emitted.
278 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
279 GD = GlobalDecl(CD, Ctor_Base);
280 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
281 GD = GlobalDecl(DD, Dtor_Base);
282 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
285 // Don't do anything for Obj-C method decls or global closures. We should
287 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
290 (void)GetAddrOfGlobal(GD);
295 /// hasNontrivialDestruction - Determine whether a type's destruction is
296 /// non-trivial. If so, and the variable uses static initialization, we must
297 /// register its destructor to run on exit.
298 static bool hasNontrivialDestruction(QualType T) {
299 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
300 return RD && !RD->hasTrivialDestructor();
303 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
304 /// global variable that has already been created for it. If the initializer
305 /// has a different type than GV does, this may free GV and return a different
306 /// one. Otherwise it just returns GV.
307 llvm::GlobalVariable *
308 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
309 llvm::GlobalVariable *GV) {
310 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
312 // If constant emission failed, then this should be a C++ static
315 if (!getLangOpts().CPlusPlus)
316 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
317 else if (HaveInsertPoint()) {
318 // Since we have a static initializer, this global variable can't
320 GV->setConstant(false);
322 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
327 // The initializer may differ in type from the global. Rewrite
328 // the global to match the initializer. (We have to do this
329 // because some types, like unions, can't be completely represented
330 // in the LLVM type system.)
331 if (GV->getType()->getElementType() != Init->getType()) {
332 llvm::GlobalVariable *OldGV = GV;
334 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
336 OldGV->getLinkage(), Init, "",
337 /*InsertBefore*/ OldGV,
338 OldGV->getThreadLocalMode(),
339 CGM.getContext().getTargetAddressSpace(D.getType()));
340 GV->setVisibility(OldGV->getVisibility());
341 GV->setComdat(OldGV->getComdat());
343 // Steal the name of the old global
346 // Replace all uses of the old global with the new global
347 llvm::Constant *NewPtrForOldDecl =
348 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
349 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
351 // Erase the old global, since it is no longer used.
352 OldGV->eraseFromParent();
355 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
356 GV->setInitializer(Init);
358 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
359 // We have a constant initializer, but a nontrivial destructor. We still
360 // need to perform a guarded "initialization" in order to register the
362 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
368 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
369 llvm::GlobalValue::LinkageTypes Linkage) {
370 // Check to see if we already have a global variable for this
371 // declaration. This can happen when double-emitting function
372 // bodies, e.g. with complete and base constructors.
373 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
374 CharUnits alignment = getContext().getDeclAlign(&D);
376 // Store into LocalDeclMap before generating initializer to handle
377 // circular references.
378 setAddrOfLocalVar(&D, Address(addr, alignment));
380 // We can't have a VLA here, but we can have a pointer to a VLA,
381 // even though that doesn't really make any sense.
382 // Make sure to evaluate VLA bounds now so that we have them for later.
383 if (D.getType()->isVariablyModifiedType())
384 EmitVariablyModifiedType(D.getType());
386 // Save the type in case adding the initializer forces a type change.
387 llvm::Type *expectedType = addr->getType();
389 llvm::GlobalVariable *var =
390 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
392 // CUDA's local and local static __shared__ variables should not
393 // have any non-empty initializers. This is ensured by Sema.
394 // Whatever initializer such variable may have when it gets here is
395 // a no-op and should not be emitted.
396 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
397 D.hasAttr<CUDASharedAttr>();
398 // If this value has an initializer, emit it.
399 if (D.getInit() && !isCudaSharedVar)
400 var = AddInitializerToStaticVarDecl(D, var);
402 var->setAlignment(alignment.getQuantity());
404 if (D.hasAttr<AnnotateAttr>())
405 CGM.AddGlobalAnnotations(&D, var);
407 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
408 var->addAttribute("bss-section", SA->getName());
409 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
410 var->addAttribute("data-section", SA->getName());
411 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
412 var->addAttribute("rodata-section", SA->getName());
414 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
415 var->setSection(SA->getName());
417 if (D.hasAttr<UsedAttr>())
418 CGM.addUsedGlobal(var);
420 // We may have to cast the constant because of the initializer
423 // FIXME: It is really dangerous to store this in the map; if anyone
424 // RAUW's the GV uses of this constant will be invalid.
425 llvm::Constant *castedAddr =
426 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
427 if (var != castedAddr)
428 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
429 CGM.setStaticLocalDeclAddress(&D, castedAddr);
431 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
433 // Emit global variable debug descriptor for static vars.
434 CGDebugInfo *DI = getDebugInfo();
436 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
437 DI->setLocation(D.getLocation());
438 DI->EmitGlobalVariable(var, &D);
443 struct DestroyObject final : EHScopeStack::Cleanup {
444 DestroyObject(Address addr, QualType type,
445 CodeGenFunction::Destroyer *destroyer,
446 bool useEHCleanupForArray)
447 : addr(addr), type(type), destroyer(destroyer),
448 useEHCleanupForArray(useEHCleanupForArray) {}
452 CodeGenFunction::Destroyer *destroyer;
453 bool useEHCleanupForArray;
455 void Emit(CodeGenFunction &CGF, Flags flags) override {
456 // Don't use an EH cleanup recursively from an EH cleanup.
457 bool useEHCleanupForArray =
458 flags.isForNormalCleanup() && this->useEHCleanupForArray;
460 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
464 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
465 DestroyNRVOVariable(Address addr,
466 const CXXDestructorDecl *Dtor,
467 llvm::Value *NRVOFlag)
468 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
470 const CXXDestructorDecl *Dtor;
471 llvm::Value *NRVOFlag;
474 void Emit(CodeGenFunction &CGF, Flags flags) override {
475 // Along the exceptions path we always execute the dtor.
476 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
478 llvm::BasicBlock *SkipDtorBB = nullptr;
480 // If we exited via NRVO, we skip the destructor call.
481 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
482 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
483 llvm::Value *DidNRVO =
484 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
485 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
486 CGF.EmitBlock(RunDtorBB);
489 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
490 /*ForVirtualBase=*/false,
491 /*Delegating=*/false,
494 if (NRVO) CGF.EmitBlock(SkipDtorBB);
498 struct CallStackRestore final : EHScopeStack::Cleanup {
500 CallStackRestore(Address Stack) : Stack(Stack) {}
501 void Emit(CodeGenFunction &CGF, Flags flags) override {
502 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
503 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
504 CGF.Builder.CreateCall(F, V);
508 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
510 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
512 void Emit(CodeGenFunction &CGF, Flags flags) override {
513 // Compute the address of the local variable, in case it's a
514 // byref or something.
515 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
516 Var.getType(), VK_LValue, SourceLocation());
517 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
519 CGF.EmitExtendGCLifetime(value);
523 struct CallCleanupFunction final : EHScopeStack::Cleanup {
524 llvm::Constant *CleanupFn;
525 const CGFunctionInfo &FnInfo;
528 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
530 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
532 void Emit(CodeGenFunction &CGF, Flags flags) override {
533 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
534 Var.getType(), VK_LValue, SourceLocation());
535 // Compute the address of the local variable, in case it's a byref
537 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
539 // In some cases, the type of the function argument will be different from
540 // the type of the pointer. An example of this is
541 // void f(void* arg);
542 // __attribute__((cleanup(f))) void *g;
544 // To fix this we insert a bitcast here.
545 QualType ArgTy = FnInfo.arg_begin()->type;
547 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
550 Args.add(RValue::get(Arg),
551 CGF.getContext().getPointerType(Var.getType()));
552 auto Callee = CGCallee::forDirect(CleanupFn);
553 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
556 } // end anonymous namespace
558 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
559 /// variable with lifetime.
560 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
562 Qualifiers::ObjCLifetime lifetime) {
564 case Qualifiers::OCL_None:
565 llvm_unreachable("present but none");
567 case Qualifiers::OCL_ExplicitNone:
571 case Qualifiers::OCL_Strong: {
572 CodeGenFunction::Destroyer *destroyer =
573 (var.hasAttr<ObjCPreciseLifetimeAttr>()
574 ? CodeGenFunction::destroyARCStrongPrecise
575 : CodeGenFunction::destroyARCStrongImprecise);
577 CleanupKind cleanupKind = CGF.getARCCleanupKind();
578 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
579 cleanupKind & EHCleanup);
582 case Qualifiers::OCL_Autoreleasing:
586 case Qualifiers::OCL_Weak:
587 // __weak objects always get EH cleanups; otherwise, exceptions
588 // could cause really nasty crashes instead of mere leaks.
589 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
590 CodeGenFunction::destroyARCWeak,
591 /*useEHCleanup*/ true);
596 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
597 if (const Expr *e = dyn_cast<Expr>(s)) {
598 // Skip the most common kinds of expressions that make
599 // hierarchy-walking expensive.
600 s = e = e->IgnoreParenCasts();
602 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
603 return (ref->getDecl() == &var);
604 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
605 const BlockDecl *block = be->getBlockDecl();
606 for (const auto &I : block->captures()) {
607 if (I.getVariable() == &var)
613 for (const Stmt *SubStmt : s->children())
614 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
615 if (SubStmt && isAccessedBy(var, SubStmt))
621 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
622 if (!decl) return false;
623 if (!isa<VarDecl>(decl)) return false;
624 const VarDecl *var = cast<VarDecl>(decl);
625 return isAccessedBy(*var, e);
628 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
629 const LValue &destLV, const Expr *init) {
630 bool needsCast = false;
632 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
633 switch (castExpr->getCastKind()) {
634 // Look through casts that don't require representation changes.
637 case CK_BlockPointerToObjCPointerCast:
641 // If we find an l-value to r-value cast from a __weak variable,
642 // emit this operation as a copy or move.
643 case CK_LValueToRValue: {
644 const Expr *srcExpr = castExpr->getSubExpr();
645 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
648 // Emit the source l-value.
649 LValue srcLV = CGF.EmitLValue(srcExpr);
651 // Handle a formal type change to avoid asserting.
652 auto srcAddr = srcLV.getAddress();
654 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
655 destLV.getAddress().getElementType());
658 // If it was an l-value, use objc_copyWeak.
659 if (srcExpr->getValueKind() == VK_LValue) {
660 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
662 assert(srcExpr->getValueKind() == VK_XValue);
663 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
668 // Stop at anything else.
673 init = castExpr->getSubExpr();
678 static void drillIntoBlockVariable(CodeGenFunction &CGF,
680 const VarDecl *var) {
681 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
684 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
685 SourceLocation Loc) {
686 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
689 auto Nullability = LHS.getType()->getNullability(getContext());
690 if (!Nullability || *Nullability != NullabilityKind::NonNull)
693 // Check if the right hand side of the assignment is nonnull, if the left
694 // hand side must be nonnull.
695 SanitizerScope SanScope(this);
696 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
697 llvm::Constant *StaticData[] = {
698 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
699 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
700 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
701 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
702 SanitizerHandler::TypeMismatch, StaticData, RHS);
705 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
706 LValue lvalue, bool capturedByInit) {
707 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
709 llvm::Value *value = EmitScalarExpr(init);
711 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
712 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
713 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
717 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
718 init = DIE->getExpr();
720 // If we're emitting a value with lifetime, we have to do the
721 // initialization *before* we leave the cleanup scopes.
722 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
723 enterFullExpression(ewc);
724 init = ewc->getSubExpr();
726 CodeGenFunction::RunCleanupsScope Scope(*this);
728 // We have to maintain the illusion that the variable is
729 // zero-initialized. If the variable might be accessed in its
730 // initializer, zero-initialize before running the initializer, then
731 // actually perform the initialization with an assign.
732 bool accessedByInit = false;
733 if (lifetime != Qualifiers::OCL_ExplicitNone)
734 accessedByInit = (capturedByInit || isAccessedBy(D, init));
735 if (accessedByInit) {
736 LValue tempLV = lvalue;
737 // Drill down to the __block object if necessary.
738 if (capturedByInit) {
739 // We can use a simple GEP for this because it can't have been
741 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
746 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
747 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
749 // If __weak, we want to use a barrier under certain conditions.
750 if (lifetime == Qualifiers::OCL_Weak)
751 EmitARCInitWeak(tempLV.getAddress(), zero);
753 // Otherwise just do a simple store.
755 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
758 // Emit the initializer.
759 llvm::Value *value = nullptr;
762 case Qualifiers::OCL_None:
763 llvm_unreachable("present but none");
765 case Qualifiers::OCL_ExplicitNone:
766 value = EmitARCUnsafeUnretainedScalarExpr(init);
769 case Qualifiers::OCL_Strong: {
770 value = EmitARCRetainScalarExpr(init);
774 case Qualifiers::OCL_Weak: {
775 // If it's not accessed by the initializer, try to emit the
776 // initialization with a copy or move.
777 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
781 // No way to optimize a producing initializer into this. It's not
782 // worth optimizing for, because the value will immediately
783 // disappear in the common case.
784 value = EmitScalarExpr(init);
786 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
788 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
790 EmitARCInitWeak(lvalue.getAddress(), value);
794 case Qualifiers::OCL_Autoreleasing:
795 value = EmitARCRetainAutoreleaseScalarExpr(init);
799 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
801 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
803 // If the variable might have been accessed by its initializer, we
804 // might have to initialize with a barrier. We have to do this for
805 // both __weak and __strong, but __weak got filtered out above.
806 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
807 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
808 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
809 EmitARCRelease(oldValue, ARCImpreciseLifetime);
813 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
816 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
817 /// non-zero parts of the specified initializer with equal or fewer than
818 /// NumStores scalar stores.
819 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
820 unsigned &NumStores) {
821 // Zero and Undef never requires any extra stores.
822 if (isa<llvm::ConstantAggregateZero>(Init) ||
823 isa<llvm::ConstantPointerNull>(Init) ||
824 isa<llvm::UndefValue>(Init))
826 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
827 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
828 isa<llvm::ConstantExpr>(Init))
829 return Init->isNullValue() || NumStores--;
831 // See if we can emit each element.
832 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
833 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
834 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
835 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
841 if (llvm::ConstantDataSequential *CDS =
842 dyn_cast<llvm::ConstantDataSequential>(Init)) {
843 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
844 llvm::Constant *Elt = CDS->getElementAsConstant(i);
845 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
851 // Anything else is hard and scary.
855 /// emitStoresForInitAfterMemset - For inits that
856 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
857 /// stores that would be required.
858 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
859 bool isVolatile, CGBuilderTy &Builder) {
860 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
861 "called emitStoresForInitAfterMemset for zero or undef value.");
863 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
864 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
865 isa<llvm::ConstantExpr>(Init)) {
866 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
870 if (llvm::ConstantDataSequential *CDS =
871 dyn_cast<llvm::ConstantDataSequential>(Init)) {
872 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
873 llvm::Constant *Elt = CDS->getElementAsConstant(i);
875 // If necessary, get a pointer to the element and emit it.
876 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
877 emitStoresForInitAfterMemset(
878 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
879 isVolatile, Builder);
884 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
885 "Unknown value type!");
887 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
888 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
890 // If necessary, get a pointer to the element and emit it.
891 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
892 emitStoresForInitAfterMemset(
893 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
894 isVolatile, Builder);
898 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
899 /// plus some stores to initialize a local variable instead of using a memcpy
900 /// from a constant global. It is beneficial to use memset if the global is all
901 /// zeros, or mostly zeros and large.
902 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
903 uint64_t GlobalSize) {
904 // If a global is all zeros, always use a memset.
905 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
907 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
908 // do it if it will require 6 or fewer scalar stores.
909 // TODO: Should budget depends on the size? Avoiding a large global warrants
910 // plopping in more stores.
911 unsigned StoreBudget = 6;
912 uint64_t SizeLimit = 32;
914 return GlobalSize > SizeLimit &&
915 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
918 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
919 /// variable declaration with auto, register, or no storage class specifier.
920 /// These turn into simple stack objects, or GlobalValues depending on target.
921 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
922 AutoVarEmission emission = EmitAutoVarAlloca(D);
923 EmitAutoVarInit(emission);
924 EmitAutoVarCleanups(emission);
927 /// Emit a lifetime.begin marker if some criteria are satisfied.
928 /// \return a pointer to the temporary size Value if a marker was emitted, null
930 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
932 if (!ShouldEmitLifetimeMarkers)
935 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
936 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
938 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
939 C->setDoesNotThrow();
943 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
944 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
946 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
947 C->setDoesNotThrow();
950 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
951 /// local variable. Does not emit initialization or destruction.
952 CodeGenFunction::AutoVarEmission
953 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
954 QualType Ty = D.getType();
955 assert(Ty.getAddressSpace() == LangAS::Default);
957 AutoVarEmission emission(D);
959 bool isByRef = D.hasAttr<BlocksAttr>();
960 emission.IsByRef = isByRef;
962 CharUnits alignment = getContext().getDeclAlign(&D);
964 // If the type is variably-modified, emit all the VLA sizes for it.
965 if (Ty->isVariablyModifiedType())
966 EmitVariablyModifiedType(Ty);
968 Address address = Address::invalid();
969 if (Ty->isConstantSizeType()) {
970 bool NRVO = getLangOpts().ElideConstructors &&
973 // If this value is an array or struct with a statically determinable
974 // constant initializer, there are optimizations we can do.
976 // TODO: We should constant-evaluate the initializer of any variable,
977 // as long as it is initialized by a constant expression. Currently,
978 // isConstantInitializer produces wrong answers for structs with
979 // reference or bitfield members, and a few other cases, and checking
980 // for POD-ness protects us from some of these.
981 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
983 ((Ty.isPODType(getContext()) ||
984 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
985 D.getInit()->isConstantInitializer(getContext(), false)))) {
987 // If the variable's a const type, and it's neither an NRVO
988 // candidate nor a __block variable and has no mutable members,
989 // emit it as a global instead.
990 // Exception is if a variable is located in non-constant address space
992 if ((!getLangOpts().OpenCL ||
993 Ty.getAddressSpace() == LangAS::opencl_constant) &&
994 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
995 CGM.isTypeConstant(Ty, true))) {
996 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
998 // Signal this condition to later callbacks.
999 emission.Addr = Address::invalid();
1000 assert(emission.wasEmittedAsGlobal());
1004 // Otherwise, tell the initialization code that we're in this case.
1005 emission.IsConstantAggregate = true;
1008 // A normal fixed sized variable becomes an alloca in the entry block,
1009 // unless it's an NRVO variable.
1012 // The named return value optimization: allocate this variable in the
1013 // return slot, so that we can elide the copy when returning this
1014 // variable (C++0x [class.copy]p34).
1015 address = ReturnValue;
1017 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1018 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1019 // Create a flag that is used to indicate when the NRVO was applied
1020 // to this variable. Set it to zero to indicate that NRVO was not
1022 llvm::Value *Zero = Builder.getFalse();
1024 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1025 EnsureInsertPoint();
1026 Builder.CreateStore(Zero, NRVOFlag);
1028 // Record the NRVO flag for this variable.
1029 NRVOFlags[&D] = NRVOFlag.getPointer();
1030 emission.NRVOFlag = NRVOFlag.getPointer();
1034 CharUnits allocaAlignment;
1035 llvm::Type *allocaTy;
1037 auto &byrefInfo = getBlockByrefInfo(&D);
1038 allocaTy = byrefInfo.Type;
1039 allocaAlignment = byrefInfo.ByrefAlignment;
1041 allocaTy = ConvertTypeForMem(Ty);
1042 allocaAlignment = alignment;
1045 // Create the alloca. Note that we set the name separately from
1046 // building the instruction so that it's there even in no-asserts
1048 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName());
1050 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1051 // the catch parameter starts in the catchpad instruction, and we can't
1052 // insert code in those basic blocks.
1053 bool IsMSCatchParam =
1054 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1056 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1057 // if we don't have a valid insertion point (?).
1058 if (HaveInsertPoint() && !IsMSCatchParam) {
1059 // If there's a jump into the lifetime of this variable, its lifetime
1060 // gets broken up into several regions in IR, which requires more work
1061 // to handle correctly. For now, just omit the intrinsics; this is a
1062 // rare case, and it's better to just be conservatively correct.
1065 // We have to do this in all language modes if there's a jump past the
1066 // declaration. We also have to do it in C if there's a jump to an
1067 // earlier point in the current block because non-VLA lifetimes begin as
1068 // soon as the containing block is entered, not when its variables
1069 // actually come into scope; suppressing the lifetime annotations
1070 // completely in this case is unnecessarily pessimistic, but again, this
1072 if (!Bypasses.IsBypassed(&D) &&
1073 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1074 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1075 emission.SizeForLifetimeMarkers =
1076 EmitLifetimeStart(size, address.getPointer());
1079 assert(!emission.useLifetimeMarkers());
1083 EnsureInsertPoint();
1085 if (!DidCallStackSave) {
1088 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1090 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1091 llvm::Value *V = Builder.CreateCall(F);
1092 Builder.CreateStore(V, Stack);
1094 DidCallStackSave = true;
1096 // Push a cleanup block and restore the stack there.
1097 // FIXME: in general circumstances, this should be an EH cleanup.
1098 pushStackRestore(NormalCleanup, Stack);
1101 llvm::Value *elementCount;
1102 QualType elementType;
1103 std::tie(elementCount, elementType) = getVLASize(Ty);
1105 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1107 // Allocate memory for the array.
1108 address = CreateTempAlloca(llvmTy, alignment, "vla", elementCount);
1111 setAddrOfLocalVar(&D, address);
1112 emission.Addr = address;
1114 // Emit debug info for local var declaration.
1115 if (HaveInsertPoint())
1116 if (CGDebugInfo *DI = getDebugInfo()) {
1117 if (CGM.getCodeGenOpts().getDebugInfo() >=
1118 codegenoptions::LimitedDebugInfo) {
1119 DI->setLocation(D.getLocation());
1120 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1124 if (D.hasAttr<AnnotateAttr>())
1125 EmitVarAnnotations(&D, address.getPointer());
1127 // Make sure we call @llvm.lifetime.end.
1128 if (emission.useLifetimeMarkers())
1129 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1130 emission.getAllocatedAddress(),
1131 emission.getSizeForLifetimeMarkers());
1136 /// Determines whether the given __block variable is potentially
1137 /// captured by the given expression.
1138 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1139 // Skip the most common kinds of expressions that make
1140 // hierarchy-walking expensive.
1141 e = e->IgnoreParenCasts();
1143 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1144 const BlockDecl *block = be->getBlockDecl();
1145 for (const auto &I : block->captures()) {
1146 if (I.getVariable() == &var)
1150 // No need to walk into the subexpressions.
1154 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1155 const CompoundStmt *CS = SE->getSubStmt();
1156 for (const auto *BI : CS->body())
1157 if (const auto *E = dyn_cast<Expr>(BI)) {
1158 if (isCapturedBy(var, E))
1161 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1162 // special case declarations
1163 for (const auto *I : DS->decls()) {
1164 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1165 const Expr *Init = VD->getInit();
1166 if (Init && isCapturedBy(var, Init))
1172 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1173 // Later, provide code to poke into statements for capture analysis.
1178 for (const Stmt *SubStmt : e->children())
1179 if (isCapturedBy(var, cast<Expr>(SubStmt)))
1185 /// \brief Determine whether the given initializer is trivial in the sense
1186 /// that it requires no code to be generated.
1187 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1191 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1192 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1193 if (Constructor->isTrivial() &&
1194 Constructor->isDefaultConstructor() &&
1195 !Construct->requiresZeroInitialization())
1201 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1202 assert(emission.Variable && "emission was not valid!");
1204 // If this was emitted as a global constant, we're done.
1205 if (emission.wasEmittedAsGlobal()) return;
1207 const VarDecl &D = *emission.Variable;
1208 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1209 QualType type = D.getType();
1211 // If this local has an initializer, emit it now.
1212 const Expr *Init = D.getInit();
1214 // If we are at an unreachable point, we don't need to emit the initializer
1215 // unless it contains a label.
1216 if (!HaveInsertPoint()) {
1217 if (!Init || !ContainsLabel(Init)) return;
1218 EnsureInsertPoint();
1221 // Initialize the structure of a __block variable.
1222 if (emission.IsByRef)
1223 emitByrefStructureInit(emission);
1225 if (isTrivialInitializer(Init))
1228 // Check whether this is a byref variable that's potentially
1229 // captured and moved by its own initializer. If so, we'll need to
1230 // emit the initializer first, then copy into the variable.
1231 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1234 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1236 llvm::Constant *constant = nullptr;
1237 if (emission.IsConstantAggregate || D.isConstexpr()) {
1238 assert(!capturedByInit && "constant init contains a capturing block?");
1239 constant = CGM.EmitConstantInit(D, this);
1243 LValue lv = MakeAddrLValue(Loc, type);
1245 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1248 if (!emission.IsConstantAggregate) {
1249 // For simple scalar/complex initialization, store the value directly.
1250 LValue lv = MakeAddrLValue(Loc, type);
1252 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1255 // If this is a simple aggregate initialization, we can optimize it
1257 bool isVolatile = type.isVolatileQualified();
1259 llvm::Value *SizeVal =
1260 llvm::ConstantInt::get(IntPtrTy,
1261 getContext().getTypeSizeInChars(type).getQuantity());
1263 llvm::Type *BP = Int8PtrTy;
1264 if (Loc.getType() != BP)
1265 Loc = Builder.CreateBitCast(Loc, BP);
1267 // If the initializer is all or mostly zeros, codegen with memset then do
1268 // a few stores afterward.
1269 if (shouldUseMemSetPlusStoresToInitialize(constant,
1270 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1271 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1273 // Zero and undef don't require a stores.
1274 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1275 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1276 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1277 isVolatile, Builder);
1280 // Otherwise, create a temporary global with the initializer then
1281 // memcpy from the global to the alloca.
1282 std::string Name = getStaticDeclName(CGM, D);
1284 if (getLangOpts().OpenCL) {
1285 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1286 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1288 llvm::GlobalVariable *GV =
1289 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1290 llvm::GlobalValue::PrivateLinkage,
1291 constant, Name, nullptr,
1292 llvm::GlobalValue::NotThreadLocal, AS);
1293 GV->setAlignment(Loc.getAlignment().getQuantity());
1294 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1296 Address SrcPtr = Address(GV, Loc.getAlignment());
1297 if (SrcPtr.getType() != BP)
1298 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1300 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1304 /// Emit an expression as an initializer for a variable at the given
1305 /// location. The expression is not necessarily the normal
1306 /// initializer for the variable, and the address is not necessarily
1307 /// its normal location.
1309 /// \param init the initializing expression
1310 /// \param var the variable to act as if we're initializing
1311 /// \param loc the address to initialize; its type is a pointer
1312 /// to the LLVM mapping of the variable's type
1313 /// \param alignment the alignment of the address
1314 /// \param capturedByInit true if the variable is a __block variable
1315 /// whose address is potentially changed by the initializer
1316 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1317 LValue lvalue, bool capturedByInit) {
1318 QualType type = D->getType();
1320 if (type->isReferenceType()) {
1321 RValue rvalue = EmitReferenceBindingToExpr(init);
1323 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1324 EmitStoreThroughLValue(rvalue, lvalue, true);
1327 switch (getEvaluationKind(type)) {
1329 EmitScalarInit(init, D, lvalue, capturedByInit);
1332 ComplexPairTy complex = EmitComplexExpr(init);
1334 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1335 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1339 if (type->isAtomicType()) {
1340 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1342 // TODO: how can we delay here if D is captured by its initializer?
1343 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1344 AggValueSlot::IsDestructed,
1345 AggValueSlot::DoesNotNeedGCBarriers,
1346 AggValueSlot::IsNotAliased));
1350 llvm_unreachable("bad evaluation kind");
1353 /// Enter a destroy cleanup for the given local variable.
1354 void CodeGenFunction::emitAutoVarTypeCleanup(
1355 const CodeGenFunction::AutoVarEmission &emission,
1356 QualType::DestructionKind dtorKind) {
1357 assert(dtorKind != QualType::DK_none);
1359 // Note that for __block variables, we want to destroy the
1360 // original stack object, not the possibly forwarded object.
1361 Address addr = emission.getObjectAddress(*this);
1363 const VarDecl *var = emission.Variable;
1364 QualType type = var->getType();
1366 CleanupKind cleanupKind = NormalAndEHCleanup;
1367 CodeGenFunction::Destroyer *destroyer = nullptr;
1370 case QualType::DK_none:
1371 llvm_unreachable("no cleanup for trivially-destructible variable");
1373 case QualType::DK_cxx_destructor:
1374 // If there's an NRVO flag on the emission, we need a different
1376 if (emission.NRVOFlag) {
1377 assert(!type->isArrayType());
1378 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1379 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1380 dtor, emission.NRVOFlag);
1385 case QualType::DK_objc_strong_lifetime:
1386 // Suppress cleanups for pseudo-strong variables.
1387 if (var->isARCPseudoStrong()) return;
1389 // Otherwise, consider whether to use an EH cleanup or not.
1390 cleanupKind = getARCCleanupKind();
1392 // Use the imprecise destroyer by default.
1393 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1394 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1397 case QualType::DK_objc_weak_lifetime:
1401 // If we haven't chosen a more specific destroyer, use the default.
1402 if (!destroyer) destroyer = getDestroyer(dtorKind);
1404 // Use an EH cleanup in array destructors iff the destructor itself
1405 // is being pushed as an EH cleanup.
1406 bool useEHCleanup = (cleanupKind & EHCleanup);
1407 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1411 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1412 assert(emission.Variable && "emission was not valid!");
1414 // If this was emitted as a global constant, we're done.
1415 if (emission.wasEmittedAsGlobal()) return;
1417 // If we don't have an insertion point, we're done. Sema prevents
1418 // us from jumping into any of these scopes anyway.
1419 if (!HaveInsertPoint()) return;
1421 const VarDecl &D = *emission.Variable;
1423 // Check the type for a cleanup.
1424 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1425 emitAutoVarTypeCleanup(emission, dtorKind);
1427 // In GC mode, honor objc_precise_lifetime.
1428 if (getLangOpts().getGC() != LangOptions::NonGC &&
1429 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1430 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1433 // Handle the cleanup attribute.
1434 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1435 const FunctionDecl *FD = CA->getFunctionDecl();
1437 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1438 assert(F && "Could not find function!");
1440 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1441 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1444 // If this is a block variable, call _Block_object_destroy
1445 // (on the unforwarded address).
1446 if (emission.IsByRef)
1447 enterByrefCleanup(emission);
1450 CodeGenFunction::Destroyer *
1451 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1453 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1454 case QualType::DK_cxx_destructor:
1455 return destroyCXXObject;
1456 case QualType::DK_objc_strong_lifetime:
1457 return destroyARCStrongPrecise;
1458 case QualType::DK_objc_weak_lifetime:
1459 return destroyARCWeak;
1461 llvm_unreachable("Unknown DestructionKind");
1464 /// pushEHDestroy - Push the standard destructor for the given type as
1465 /// an EH-only cleanup.
1466 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1467 Address addr, QualType type) {
1468 assert(dtorKind && "cannot push destructor for trivial type");
1469 assert(needsEHCleanup(dtorKind));
1471 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1474 /// pushDestroy - Push the standard destructor for the given type as
1475 /// at least a normal cleanup.
1476 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1477 Address addr, QualType type) {
1478 assert(dtorKind && "cannot push destructor for trivial type");
1480 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1481 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1482 cleanupKind & EHCleanup);
1485 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1486 QualType type, Destroyer *destroyer,
1487 bool useEHCleanupForArray) {
1488 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1489 destroyer, useEHCleanupForArray);
1492 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1493 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1496 void CodeGenFunction::pushLifetimeExtendedDestroy(
1497 CleanupKind cleanupKind, Address addr, QualType type,
1498 Destroyer *destroyer, bool useEHCleanupForArray) {
1499 assert(!isInConditionalBranch() &&
1500 "performing lifetime extension from within conditional");
1502 // Push an EH-only cleanup for the object now.
1503 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1504 // around in case a temporary's destructor throws an exception.
1505 if (cleanupKind & EHCleanup)
1506 EHStack.pushCleanup<DestroyObject>(
1507 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1508 destroyer, useEHCleanupForArray);
1510 // Remember that we need to push a full cleanup for the object at the
1511 // end of the full-expression.
1512 pushCleanupAfterFullExpr<DestroyObject>(
1513 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1516 /// emitDestroy - Immediately perform the destruction of the given
1519 /// \param addr - the address of the object; a type*
1520 /// \param type - the type of the object; if an array type, all
1521 /// objects are destroyed in reverse order
1522 /// \param destroyer - the function to call to destroy individual
1524 /// \param useEHCleanupForArray - whether an EH cleanup should be
1525 /// used when destroying array elements, in case one of the
1526 /// destructions throws an exception
1527 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1528 Destroyer *destroyer,
1529 bool useEHCleanupForArray) {
1530 const ArrayType *arrayType = getContext().getAsArrayType(type);
1532 return destroyer(*this, addr, type);
1534 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1536 CharUnits elementAlign =
1538 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1540 // Normally we have to check whether the array is zero-length.
1541 bool checkZeroLength = true;
1543 // But if the array length is constant, we can suppress that.
1544 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1545 // ...and if it's constant zero, we can just skip the entire thing.
1546 if (constLength->isZero()) return;
1547 checkZeroLength = false;
1550 llvm::Value *begin = addr.getPointer();
1551 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1552 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1553 checkZeroLength, useEHCleanupForArray);
1556 /// emitArrayDestroy - Destroys all the elements of the given array,
1557 /// beginning from last to first. The array cannot be zero-length.
1559 /// \param begin - a type* denoting the first element of the array
1560 /// \param end - a type* denoting one past the end of the array
1561 /// \param elementType - the element type of the array
1562 /// \param destroyer - the function to call to destroy elements
1563 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1564 /// the remaining elements in case the destruction of a single
1566 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1568 QualType elementType,
1569 CharUnits elementAlign,
1570 Destroyer *destroyer,
1571 bool checkZeroLength,
1572 bool useEHCleanup) {
1573 assert(!elementType->isArrayType());
1575 // The basic structure here is a do-while loop, because we don't
1576 // need to check for the zero-element case.
1577 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1578 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1580 if (checkZeroLength) {
1581 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1582 "arraydestroy.isempty");
1583 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1586 // Enter the loop body, making that address the current address.
1587 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1589 llvm::PHINode *elementPast =
1590 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1591 elementPast->addIncoming(end, entryBB);
1593 // Shift the address back by one element.
1594 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1595 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1596 "arraydestroy.element");
1599 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1602 // Perform the actual destruction there.
1603 destroyer(*this, Address(element, elementAlign), elementType);
1608 // Check whether we've reached the end.
1609 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1610 Builder.CreateCondBr(done, doneBB, bodyBB);
1611 elementPast->addIncoming(element, Builder.GetInsertBlock());
1617 /// Perform partial array destruction as if in an EH cleanup. Unlike
1618 /// emitArrayDestroy, the element type here may still be an array type.
1619 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1620 llvm::Value *begin, llvm::Value *end,
1621 QualType type, CharUnits elementAlign,
1622 CodeGenFunction::Destroyer *destroyer) {
1623 // If the element type is itself an array, drill down.
1624 unsigned arrayDepth = 0;
1625 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1626 // VLAs don't require a GEP index to walk into.
1627 if (!isa<VariableArrayType>(arrayType))
1629 type = arrayType->getElementType();
1633 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1635 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1636 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1637 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1640 // Destroy the array. We don't ever need an EH cleanup because we
1641 // assume that we're in an EH cleanup ourselves, so a throwing
1642 // destructor causes an immediate terminate.
1643 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1644 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1648 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1649 /// array destroy where the end pointer is regularly determined and
1650 /// does not need to be loaded from a local.
1651 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1652 llvm::Value *ArrayBegin;
1653 llvm::Value *ArrayEnd;
1654 QualType ElementType;
1655 CodeGenFunction::Destroyer *Destroyer;
1656 CharUnits ElementAlign;
1658 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1659 QualType elementType, CharUnits elementAlign,
1660 CodeGenFunction::Destroyer *destroyer)
1661 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1662 ElementType(elementType), Destroyer(destroyer),
1663 ElementAlign(elementAlign) {}
1665 void Emit(CodeGenFunction &CGF, Flags flags) override {
1666 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1667 ElementType, ElementAlign, Destroyer);
1671 /// IrregularPartialArrayDestroy - a cleanup which performs a
1672 /// partial array destroy where the end pointer is irregularly
1673 /// determined and must be loaded from a local.
1674 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1675 llvm::Value *ArrayBegin;
1676 Address ArrayEndPointer;
1677 QualType ElementType;
1678 CodeGenFunction::Destroyer *Destroyer;
1679 CharUnits ElementAlign;
1681 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1682 Address arrayEndPointer,
1683 QualType elementType,
1684 CharUnits elementAlign,
1685 CodeGenFunction::Destroyer *destroyer)
1686 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1687 ElementType(elementType), Destroyer(destroyer),
1688 ElementAlign(elementAlign) {}
1690 void Emit(CodeGenFunction &CGF, Flags flags) override {
1691 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1692 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1693 ElementType, ElementAlign, Destroyer);
1696 } // end anonymous namespace
1698 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1699 /// already-constructed elements of the given array. The cleanup
1700 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1702 /// \param elementType - the immediate element type of the array;
1703 /// possibly still an array type
1704 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1705 Address arrayEndPointer,
1706 QualType elementType,
1707 CharUnits elementAlign,
1708 Destroyer *destroyer) {
1709 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1710 arrayBegin, arrayEndPointer,
1711 elementType, elementAlign,
1715 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1716 /// already-constructed elements of the given array. The cleanup
1717 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1719 /// \param elementType - the immediate element type of the array;
1720 /// possibly still an array type
1721 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1722 llvm::Value *arrayEnd,
1723 QualType elementType,
1724 CharUnits elementAlign,
1725 Destroyer *destroyer) {
1726 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1727 arrayBegin, arrayEnd,
1728 elementType, elementAlign,
1732 /// Lazily declare the @llvm.lifetime.start intrinsic.
1733 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1734 if (LifetimeStartFn)
1735 return LifetimeStartFn;
1736 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1737 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
1738 return LifetimeStartFn;
1741 /// Lazily declare the @llvm.lifetime.end intrinsic.
1742 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1744 return LifetimeEndFn;
1745 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1746 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
1747 return LifetimeEndFn;
1751 /// A cleanup to perform a release of an object at the end of a
1752 /// function. This is used to balance out the incoming +1 of a
1753 /// ns_consumed argument when we can't reasonably do that just by
1754 /// not doing the initial retain for a __block argument.
1755 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1756 ConsumeARCParameter(llvm::Value *param,
1757 ARCPreciseLifetime_t precise)
1758 : Param(param), Precise(precise) {}
1761 ARCPreciseLifetime_t Precise;
1763 void Emit(CodeGenFunction &CGF, Flags flags) override {
1764 CGF.EmitARCRelease(Param, Precise);
1767 } // end anonymous namespace
1769 /// Emit an alloca (or GlobalValue depending on target)
1770 /// for the specified parameter and set up LocalDeclMap.
1771 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1773 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1774 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1775 "Invalid argument to EmitParmDecl");
1777 Arg.getAnyValue()->setName(D.getName());
1779 QualType Ty = D.getType();
1781 // Use better IR generation for certain implicit parameters.
1782 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1783 // The only implicit argument a block has is its literal.
1784 // We assume this is always passed directly.
1786 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1790 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1791 // handle the case where 'this' is passed indirectly as part of an inalloca
1793 if (const CXXMethodDecl *MD =
1794 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1795 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1796 llvm::Value *This = Arg.isIndirect()
1797 ? Builder.CreateLoad(Arg.getIndirectAddress())
1798 : Arg.getDirectValue();
1799 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1800 *this, CurGD, This);
1801 if (Arg.isIndirect())
1802 Builder.CreateStore(This, Arg.getIndirectAddress());
1804 Arg = ParamValue::forDirect(This);
1809 Address DeclPtr = Address::invalid();
1810 bool DoStore = false;
1811 bool IsScalar = hasScalarEvaluationKind(Ty);
1812 // If we already have a pointer to the argument, reuse the input pointer.
1813 if (Arg.isIndirect()) {
1814 DeclPtr = Arg.getIndirectAddress();
1815 // If we have a prettier pointer type at this point, bitcast to that.
1816 unsigned AS = DeclPtr.getType()->getAddressSpace();
1817 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1818 if (DeclPtr.getType() != IRTy)
1819 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1821 // Push a destructor cleanup for this parameter if the ABI requires it.
1822 // Don't push a cleanup in a thunk for a method that will also emit a
1824 if (!IsScalar && !CurFuncIsThunk &&
1825 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1826 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1827 if (RD && RD->hasNonTrivialDestructor())
1828 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1831 // Otherwise, create a temporary to hold the value.
1832 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1833 D.getName() + ".addr");
1837 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1839 LValue lv = MakeAddrLValue(DeclPtr, Ty);
1841 Qualifiers qs = Ty.getQualifiers();
1842 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1843 // We honor __attribute__((ns_consumed)) for types with lifetime.
1844 // For __strong, it's handled by just skipping the initial retain;
1845 // otherwise we have to balance out the initial +1 with an extra
1846 // cleanup to do the release at the end of the function.
1847 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1849 // 'self' is always formally __strong, but if this is not an
1850 // init method then we don't want to retain it.
1851 if (D.isARCPseudoStrong()) {
1852 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1853 assert(&D == method->getSelfDecl());
1854 assert(lt == Qualifiers::OCL_Strong);
1855 assert(qs.hasConst());
1856 assert(method->getMethodFamily() != OMF_init);
1858 lt = Qualifiers::OCL_ExplicitNone;
1861 // Load objects passed indirectly.
1862 if (Arg.isIndirect() && !ArgVal)
1863 ArgVal = Builder.CreateLoad(DeclPtr);
1865 if (lt == Qualifiers::OCL_Strong) {
1867 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1868 // use objc_storeStrong(&dest, value) for retaining the
1869 // object. But first, store a null into 'dest' because
1870 // objc_storeStrong attempts to release its old value.
1871 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1872 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1873 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1877 // Don't use objc_retainBlock for block pointers, because we
1878 // don't want to Block_copy something just because we got it
1880 ArgVal = EmitARCRetainNonBlock(ArgVal);
1883 // Push the cleanup for a consumed parameter.
1885 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1886 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1887 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1891 if (lt == Qualifiers::OCL_Weak) {
1892 EmitARCInitWeak(DeclPtr, ArgVal);
1893 DoStore = false; // The weak init is a store, no need to do two.
1897 // Enter the cleanup scope.
1898 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1902 // Store the initial value into the alloca.
1904 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1906 setAddrOfLocalVar(&D, DeclPtr);
1908 // Emit debug info for param declaration.
1909 if (CGDebugInfo *DI = getDebugInfo()) {
1910 if (CGM.getCodeGenOpts().getDebugInfo() >=
1911 codegenoptions::LimitedDebugInfo) {
1912 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1916 if (D.hasAttr<AnnotateAttr>())
1917 EmitVarAnnotations(&D, DeclPtr.getPointer());
1919 // We can only check return value nullability if all arguments to the
1920 // function satisfy their nullability preconditions. This makes it necessary
1921 // to emit null checks for args in the function body itself.
1922 if (requiresReturnValueNullabilityCheck()) {
1923 auto Nullability = Ty->getNullability(getContext());
1924 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1925 SanitizerScope SanScope(this);
1926 RetValNullabilityPrecondition =
1927 Builder.CreateAnd(RetValNullabilityPrecondition,
1928 Builder.CreateIsNotNull(Arg.getAnyValue()));
1933 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1934 CodeGenFunction *CGF) {
1935 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1937 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);