CGDecl.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Decl nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGBlocks.h"
  14. #include "CGCXXABI.h"
  15. #include "CGCleanup.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGOpenCLRuntime.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenFunction.h"
  20. #include "CodeGenModule.h"
  21. #include "ConstantEmitter.h"
  22. #include "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/Analysis/ValueTracking.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/GlobalVariable.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/Type.h"
  37. using namespace clang;
  38. 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:
  44. case Decl::Namespace:
  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:
  54. case Decl::CXXMethod:
  55. case Decl::CXXConstructor:
  56. case Decl::CXXDestructor:
  57. case Decl::CXXConversion:
  58. case Decl::Field:
  59. case Decl::MSProperty:
  60. case Decl::IndirectField:
  61. case Decl::ObjCIvar:
  62. case Decl::ObjCAtDefsField:
  63. case Decl::ParmVar:
  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:
  82. case Decl::Export:
  83. case Decl::ObjCPropertyImpl:
  84. case Decl::FileScopeAsm:
  85. case Decl::Friend:
  86. case Decl::FriendTemplate:
  87. case Decl::Block:
  88. case Decl::Captured:
  89. case Decl::ClassScopeFunctionSpecialization:
  90. case Decl::UsingShadow:
  91. case Decl::ConstructorUsingShadow:
  92. case Decl::ObjCTypeParam:
  93. case Decl::Binding:
  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;
  102. case Decl::Import:
  103. case Decl::OMPThreadPrivate:
  104. case Decl::OMPCapturedExpr:
  105. case Decl::OMPRequires:
  106. case Decl::Empty:
  107. // None of these decls require codegen support.
  108. return;
  109. case Decl::NamespaceAlias:
  110. if (CGDebugInfo *DI = getDebugInfo())
  111. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  112. return;
  113. case Decl::Using: // using X; [C++]
  114. if (CGDebugInfo *DI = getDebugInfo())
  115. DI->EmitUsingDecl(cast<UsingDecl>(D));
  116. return;
  117. case Decl::UsingPack:
  118. for (auto *Using : cast<UsingPackDecl>(D).expansions())
  119. EmitDecl(*Using);
  120. return;
  121. case Decl::UsingDirective: // using namespace X; [C++]
  122. if (CGDebugInfo *DI = getDebugInfo())
  123. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  124. return;
  125. case Decl::Var:
  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!");
  130. EmitVarDecl(VD);
  131. if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
  132. for (auto *B : DD->bindings())
  133. if (auto *HD = B->getHoldingVar())
  134. EmitVarDecl(*HD);
  135. return;
  136. }
  137. case Decl::OMPDeclareReduction:
  138. return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
  139. case Decl::Typedef: // typedef int X;
  140. case Decl::TypeAlias: { // using X = int; [C++0x]
  141. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  142. QualType Ty = TD.getUnderlyingType();
  143. if (Ty->isVariablyModifiedType())
  144. EmitVariablyModifiedType(Ty);
  145. }
  146. }
  147. }
  148. /// EmitVarDecl - This method handles emission of any variable declaration
  149. /// inside a function, including static vars etc.
  150. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  151. if (D.hasExternalStorage())
  152. // Don't emit it now, allow it to be emitted lazily on its first use.
  153. return;
  154. // Some function-scope variable does not have static storage but still
  155. // needs to be emitted like a static variable, e.g. a function-scope
  156. // variable in constant address space in OpenCL.
  157. if (D.getStorageDuration() != SD_Automatic) {
  158. // Static sampler variables translated to function calls.
  159. if (D.getType()->isSamplerT())
  160. return;
  161. llvm::GlobalValue::LinkageTypes Linkage =
  162. CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
  163. // FIXME: We need to force the emission/use of a guard variable for
  164. // some variables even if we can constant-evaluate them because
  165. // we can't guarantee every translation unit will constant-evaluate them.
  166. return EmitStaticVarDecl(D, Linkage);
  167. }
  168. if (D.getType().getAddressSpace() == LangAS::opencl_local)
  169. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  170. assert(D.hasLocalStorage());
  171. return EmitAutoVarDecl(D);
  172. }
  173. static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
  174. if (CGM.getLangOpts().CPlusPlus)
  175. return CGM.getMangledName(&D).str();
  176. // If this isn't C++, we don't need a mangled name, just a pretty one.
  177. assert(!D.isExternallyVisible() && "name shouldn't matter");
  178. std::string ContextName;
  179. const DeclContext *DC = D.getDeclContext();
  180. if (auto *CD = dyn_cast<CapturedDecl>(DC))
  181. DC = cast<DeclContext>(CD->getNonClosureContext());
  182. if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  183. ContextName = CGM.getMangledName(FD);
  184. else if (const auto *BD = dyn_cast<BlockDecl>(DC))
  185. ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
  186. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
  187. ContextName = OMD->getSelector().getAsString();
  188. else
  189. llvm_unreachable("Unknown context for static var decl");
  190. ContextName += "." + D.getNameAsString();
  191. return ContextName;
  192. }
  193. llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
  194. const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
  195. // In general, we don't always emit static var decls once before we reference
  196. // them. It is possible to reference them before emitting the function that
  197. // contains them, and it is possible to emit the containing function multiple
  198. // times.
  199. if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
  200. return ExistingGV;
  201. QualType Ty = D.getType();
  202. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  203. // Use the label if the variable is renamed with the asm-label extension.
  204. std::string Name;
  205. if (D.hasAttr<AsmLabelAttr>())
  206. Name = getMangledName(&D);
  207. else
  208. Name = getStaticDeclName(*this, D);
  209. llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
  210. LangAS AS = GetGlobalVarAddressSpace(&D);
  211. unsigned TargetAS = getContext().getTargetAddressSpace(AS);
  212. // OpenCL variables in local address space and CUDA shared
  213. // variables cannot have an initializer.
  214. llvm::Constant *Init = nullptr;
  215. if (Ty.getAddressSpace() == LangAS::opencl_local ||
  216. D.hasAttr<CUDASharedAttr>())
  217. Init = llvm::UndefValue::get(LTy);
  218. else
  219. Init = EmitNullConstant(Ty);
  220. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  221. getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
  222. nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  223. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  224. if (supportsCOMDAT() && GV->isWeakForLinker())
  225. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  226. if (D.getTLSKind())
  227. setTLSMode(GV, D);
  228. setGVProperties(GV, &D);
  229. // Make sure the result is of the correct type.
  230. LangAS ExpectedAS = Ty.getAddressSpace();
  231. llvm::Constant *Addr = GV;
  232. if (AS != ExpectedAS) {
  233. Addr = getTargetCodeGenInfo().performAddrSpaceCast(
  234. *this, GV, AS, ExpectedAS,
  235. LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
  236. }
  237. setStaticLocalDeclAddress(&D, Addr);
  238. // Ensure that the static local gets initialized by making sure the parent
  239. // function gets emitted eventually.
  240. const Decl *DC = cast<Decl>(D.getDeclContext());
  241. // We can't name blocks or captured statements directly, so try to emit their
  242. // parents.
  243. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
  244. DC = DC->getNonClosureContext();
  245. // FIXME: Ensure that global blocks get emitted.
  246. if (!DC)
  247. return Addr;
  248. }
  249. GlobalDecl GD;
  250. if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  251. GD = GlobalDecl(CD, Ctor_Base);
  252. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  253. GD = GlobalDecl(DD, Dtor_Base);
  254. else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  255. GD = GlobalDecl(FD);
  256. else {
  257. // Don't do anything for Obj-C method decls or global closures. We should
  258. // never defer them.
  259. assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
  260. }
  261. if (GD.getDecl()) {
  262. // Disable emission of the parent function for the OpenMP device codegen.
  263. CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
  264. (void)GetAddrOfGlobal(GD);
  265. }
  266. return Addr;
  267. }
  268. /// hasNontrivialDestruction - Determine whether a type's destruction is
  269. /// non-trivial. If so, and the variable uses static initialization, we must
  270. /// register its destructor to run on exit.
  271. static bool hasNontrivialDestruction(QualType T) {
  272. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  273. return RD && !RD->hasTrivialDestructor();
  274. }
  275. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  276. /// global variable that has already been created for it. If the initializer
  277. /// has a different type than GV does, this may free GV and return a different
  278. /// one. Otherwise it just returns GV.
  279. llvm::GlobalVariable *
  280. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  281. llvm::GlobalVariable *GV) {
  282. ConstantEmitter emitter(*this);
  283. llvm::Constant *Init = emitter.tryEmitForInitializer(D);
  284. // If constant emission failed, then this should be a C++ static
  285. // initializer.
  286. if (!Init) {
  287. if (!getLangOpts().CPlusPlus)
  288. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  289. else if (HaveInsertPoint()) {
  290. // Since we have a static initializer, this global variable can't
  291. // be constant.
  292. GV->setConstant(false);
  293. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  294. }
  295. return GV;
  296. }
  297. // The initializer may differ in type from the global. Rewrite
  298. // the global to match the initializer. (We have to do this
  299. // because some types, like unions, can't be completely represented
  300. // in the LLVM type system.)
  301. if (GV->getType()->getElementType() != Init->getType()) {
  302. llvm::GlobalVariable *OldGV = GV;
  303. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  304. OldGV->isConstant(),
  305. OldGV->getLinkage(), Init, "",
  306. /*InsertBefore*/ OldGV,
  307. OldGV->getThreadLocalMode(),
  308. CGM.getContext().getTargetAddressSpace(D.getType()));
  309. GV->setVisibility(OldGV->getVisibility());
  310. GV->setDSOLocal(OldGV->isDSOLocal());
  311. GV->setComdat(OldGV->getComdat());
  312. // Steal the name of the old global
  313. GV->takeName(OldGV);
  314. // Replace all uses of the old global with the new global
  315. llvm::Constant *NewPtrForOldDecl =
  316. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  317. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  318. // Erase the old global, since it is no longer used.
  319. OldGV->eraseFromParent();
  320. }
  321. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  322. GV->setInitializer(Init);
  323. emitter.finalize(GV);
  324. if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
  325. // We have a constant initializer, but a nontrivial destructor. We still
  326. // need to perform a guarded "initialization" in order to register the
  327. // destructor.
  328. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  329. }
  330. return GV;
  331. }
  332. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  333. llvm::GlobalValue::LinkageTypes Linkage) {
  334. // Check to see if we already have a global variable for this
  335. // declaration. This can happen when double-emitting function
  336. // bodies, e.g. with complete and base constructors.
  337. llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
  338. CharUnits alignment = getContext().getDeclAlign(&D);
  339. // Store into LocalDeclMap before generating initializer to handle
  340. // circular references.
  341. setAddrOfLocalVar(&D, Address(addr, alignment));
  342. // We can't have a VLA here, but we can have a pointer to a VLA,
  343. // even though that doesn't really make any sense.
  344. // Make sure to evaluate VLA bounds now so that we have them for later.
  345. if (D.getType()->isVariablyModifiedType())
  346. EmitVariablyModifiedType(D.getType());
  347. // Save the type in case adding the initializer forces a type change.
  348. llvm::Type *expectedType = addr->getType();
  349. llvm::GlobalVariable *var =
  350. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  351. // CUDA's local and local static __shared__ variables should not
  352. // have any non-empty initializers. This is ensured by Sema.
  353. // Whatever initializer such variable may have when it gets here is
  354. // a no-op and should not be emitted.
  355. bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  356. D.hasAttr<CUDASharedAttr>();
  357. // If this value has an initializer, emit it.
  358. if (D.getInit() && !isCudaSharedVar)
  359. var = AddInitializerToStaticVarDecl(D, var);
  360. var->setAlignment(alignment.getQuantity());
  361. if (D.hasAttr<AnnotateAttr>())
  362. CGM.AddGlobalAnnotations(&D, var);
  363. if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
  364. var->addAttribute("bss-section", SA->getName());
  365. if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
  366. var->addAttribute("data-section", SA->getName());
  367. if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
  368. var->addAttribute("rodata-section", SA->getName());
  369. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  370. var->setSection(SA->getName());
  371. if (D.hasAttr<UsedAttr>())
  372. CGM.addUsedGlobal(var);
  373. // We may have to cast the constant because of the initializer
  374. // mismatch above.
  375. //
  376. // FIXME: It is really dangerous to store this in the map; if anyone
  377. // RAUW's the GV uses of this constant will be invalid.
  378. llvm::Constant *castedAddr =
  379. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  380. if (var != castedAddr)
  381. LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
  382. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  383. CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
  384. // Emit global variable debug descriptor for static vars.
  385. CGDebugInfo *DI = getDebugInfo();
  386. if (DI &&
  387. CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
  388. DI->setLocation(D.getLocation());
  389. DI->EmitGlobalVariable(var, &D);
  390. }
  391. }
  392. namespace {
  393. struct DestroyObject final : EHScopeStack::Cleanup {
  394. DestroyObject(Address addr, QualType type,
  395. CodeGenFunction::Destroyer *destroyer,
  396. bool useEHCleanupForArray)
  397. : addr(addr), type(type), destroyer(destroyer),
  398. useEHCleanupForArray(useEHCleanupForArray) {}
  399. Address addr;
  400. QualType type;
  401. CodeGenFunction::Destroyer *destroyer;
  402. bool useEHCleanupForArray;
  403. void Emit(CodeGenFunction &CGF, Flags flags) override {
  404. // Don't use an EH cleanup recursively from an EH cleanup.
  405. bool useEHCleanupForArray =
  406. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  407. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  408. }
  409. };
  410. template <class Derived>
  411. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  412. DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
  413. : NRVOFlag(NRVOFlag), Loc(addr) {}
  414. llvm::Value *NRVOFlag;
  415. Address Loc;
  416. void Emit(CodeGenFunction &CGF, Flags flags) override {
  417. // Along the exceptions path we always execute the dtor.
  418. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  419. llvm::BasicBlock *SkipDtorBB = nullptr;
  420. if (NRVO) {
  421. // If we exited via NRVO, we skip the destructor call.
  422. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  423. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  424. llvm::Value *DidNRVO =
  425. CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
  426. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  427. CGF.EmitBlock(RunDtorBB);
  428. }
  429. static_cast<Derived *>(this)->emitDestructorCall(CGF);
  430. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  431. }
  432. virtual ~DestroyNRVOVariable() = default;
  433. };
  434. struct DestroyNRVOVariableCXX final
  435. : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
  436. DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
  437. llvm::Value *NRVOFlag)
  438. : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
  439. Dtor(Dtor) {}
  440. const CXXDestructorDecl *Dtor;
  441. void emitDestructorCall(CodeGenFunction &CGF) {
  442. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  443. /*ForVirtualBase=*/false,
  444. /*Delegating=*/false, Loc);
  445. }
  446. };
  447. struct DestroyNRVOVariableC final
  448. : DestroyNRVOVariable<DestroyNRVOVariableC> {
  449. DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
  450. : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
  451. QualType Ty;
  452. void emitDestructorCall(CodeGenFunction &CGF) {
  453. CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
  454. }
  455. };
  456. struct CallStackRestore final : EHScopeStack::Cleanup {
  457. Address Stack;
  458. CallStackRestore(Address Stack) : Stack(Stack) {}
  459. void Emit(CodeGenFunction &CGF, Flags flags) override {
  460. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  461. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  462. CGF.Builder.CreateCall(F, V);
  463. }
  464. };
  465. struct ExtendGCLifetime final : EHScopeStack::Cleanup {
  466. const VarDecl &Var;
  467. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  468. void Emit(CodeGenFunction &CGF, Flags flags) override {
  469. // Compute the address of the local variable, in case it's a
  470. // byref or something.
  471. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  472. Var.getType(), VK_LValue, SourceLocation());
  473. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  474. SourceLocation());
  475. CGF.EmitExtendGCLifetime(value);
  476. }
  477. };
  478. struct CallCleanupFunction final : EHScopeStack::Cleanup {
  479. llvm::Constant *CleanupFn;
  480. const CGFunctionInfo &FnInfo;
  481. const VarDecl &Var;
  482. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  483. const VarDecl *Var)
  484. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  485. void Emit(CodeGenFunction &CGF, Flags flags) override {
  486. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  487. Var.getType(), VK_LValue, SourceLocation());
  488. // Compute the address of the local variable, in case it's a byref
  489. // or something.
  490. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
  491. // In some cases, the type of the function argument will be different from
  492. // the type of the pointer. An example of this is
  493. // void f(void* arg);
  494. // __attribute__((cleanup(f))) void *g;
  495. //
  496. // To fix this we insert a bitcast here.
  497. QualType ArgTy = FnInfo.arg_begin()->type;
  498. llvm::Value *Arg =
  499. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  500. CallArgList Args;
  501. Args.add(RValue::get(Arg),
  502. CGF.getContext().getPointerType(Var.getType()));
  503. auto Callee = CGCallee::forDirect(CleanupFn);
  504. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  505. }
  506. };
  507. } // end anonymous namespace
  508. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  509. /// variable with lifetime.
  510. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  511. Address addr,
  512. Qualifiers::ObjCLifetime lifetime) {
  513. switch (lifetime) {
  514. case Qualifiers::OCL_None:
  515. llvm_unreachable("present but none");
  516. case Qualifiers::OCL_ExplicitNone:
  517. // nothing to do
  518. break;
  519. case Qualifiers::OCL_Strong: {
  520. CodeGenFunction::Destroyer *destroyer =
  521. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  522. ? CodeGenFunction::destroyARCStrongPrecise
  523. : CodeGenFunction::destroyARCStrongImprecise);
  524. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  525. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  526. cleanupKind & EHCleanup);
  527. break;
  528. }
  529. case Qualifiers::OCL_Autoreleasing:
  530. // nothing to do
  531. break;
  532. case Qualifiers::OCL_Weak:
  533. // __weak objects always get EH cleanups; otherwise, exceptions
  534. // could cause really nasty crashes instead of mere leaks.
  535. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  536. CodeGenFunction::destroyARCWeak,
  537. /*useEHCleanup*/ true);
  538. break;
  539. }
  540. }
  541. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  542. if (const Expr *e = dyn_cast<Expr>(s)) {
  543. // Skip the most common kinds of expressions that make
  544. // hierarchy-walking expensive.
  545. s = e = e->IgnoreParenCasts();
  546. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  547. return (ref->getDecl() == &var);
  548. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  549. const BlockDecl *block = be->getBlockDecl();
  550. for (const auto &I : block->captures()) {
  551. if (I.getVariable() == &var)
  552. return true;
  553. }
  554. }
  555. }
  556. for (const Stmt *SubStmt : s->children())
  557. // SubStmt might be null; as in missing decl or conditional of an if-stmt.
  558. if (SubStmt && isAccessedBy(var, SubStmt))
  559. return true;
  560. return false;
  561. }
  562. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  563. if (!decl) return false;
  564. if (!isa<VarDecl>(decl)) return false;
  565. const VarDecl *var = cast<VarDecl>(decl);
  566. return isAccessedBy(*var, e);
  567. }
  568. static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
  569. const LValue &destLV, const Expr *init) {
  570. bool needsCast = false;
  571. while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
  572. switch (castExpr->getCastKind()) {
  573. // Look through casts that don't require representation changes.
  574. case CK_NoOp:
  575. case CK_BitCast:
  576. case CK_BlockPointerToObjCPointerCast:
  577. needsCast = true;
  578. break;
  579. // If we find an l-value to r-value cast from a __weak variable,
  580. // emit this operation as a copy or move.
  581. case CK_LValueToRValue: {
  582. const Expr *srcExpr = castExpr->getSubExpr();
  583. if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
  584. return false;
  585. // Emit the source l-value.
  586. LValue srcLV = CGF.EmitLValue(srcExpr);
  587. // Handle a formal type change to avoid asserting.
  588. auto srcAddr = srcLV.getAddress();
  589. if (needsCast) {
  590. srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
  591. destLV.getAddress().getElementType());
  592. }
  593. // If it was an l-value, use objc_copyWeak.
  594. if (srcExpr->getValueKind() == VK_LValue) {
  595. CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
  596. } else {
  597. assert(srcExpr->getValueKind() == VK_XValue);
  598. CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
  599. }
  600. return true;
  601. }
  602. // Stop at anything else.
  603. default:
  604. return false;
  605. }
  606. init = castExpr->getSubExpr();
  607. }
  608. return false;
  609. }
  610. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  611. LValue &lvalue,
  612. const VarDecl *var) {
  613. lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
  614. }
  615. void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
  616. SourceLocation Loc) {
  617. if (!SanOpts.has(SanitizerKind::NullabilityAssign))
  618. return;
  619. auto Nullability = LHS.getType()->getNullability(getContext());
  620. if (!Nullability || *Nullability != NullabilityKind::NonNull)
  621. return;
  622. // Check if the right hand side of the assignment is nonnull, if the left
  623. // hand side must be nonnull.
  624. SanitizerScope SanScope(this);
  625. llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
  626. llvm::Constant *StaticData[] = {
  627. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
  628. llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
  629. llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
  630. EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
  631. SanitizerHandler::TypeMismatch, StaticData, RHS);
  632. }
  633. void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
  634. LValue lvalue, bool capturedByInit) {
  635. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  636. if (!lifetime) {
  637. llvm::Value *value = EmitScalarExpr(init);
  638. if (capturedByInit)
  639. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  640. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  641. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  642. return;
  643. }
  644. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  645. init = DIE->getExpr();
  646. // If we're emitting a value with lifetime, we have to do the
  647. // initialization *before* we leave the cleanup scopes.
  648. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  649. enterFullExpression(ewc);
  650. init = ewc->getSubExpr();
  651. }
  652. CodeGenFunction::RunCleanupsScope Scope(*this);
  653. // We have to maintain the illusion that the variable is
  654. // zero-initialized. If the variable might be accessed in its
  655. // initializer, zero-initialize before running the initializer, then
  656. // actually perform the initialization with an assign.
  657. bool accessedByInit = false;
  658. if (lifetime != Qualifiers::OCL_ExplicitNone)
  659. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  660. if (accessedByInit) {
  661. LValue tempLV = lvalue;
  662. // Drill down to the __block object if necessary.
  663. if (capturedByInit) {
  664. // We can use a simple GEP for this because it can't have been
  665. // moved yet.
  666. tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
  667. cast<VarDecl>(D),
  668. /*follow*/ false));
  669. }
  670. auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
  671. llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
  672. // If __weak, we want to use a barrier under certain conditions.
  673. if (lifetime == Qualifiers::OCL_Weak)
  674. EmitARCInitWeak(tempLV.getAddress(), zero);
  675. // Otherwise just do a simple store.
  676. else
  677. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  678. }
  679. // Emit the initializer.
  680. llvm::Value *value = nullptr;
  681. switch (lifetime) {
  682. case Qualifiers::OCL_None:
  683. llvm_unreachable("present but none");
  684. case Qualifiers::OCL_ExplicitNone:
  685. value = EmitARCUnsafeUnretainedScalarExpr(init);
  686. break;
  687. case Qualifiers::OCL_Strong: {
  688. value = EmitARCRetainScalarExpr(init);
  689. break;
  690. }
  691. case Qualifiers::OCL_Weak: {
  692. // If it's not accessed by the initializer, try to emit the
  693. // initialization with a copy or move.
  694. if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
  695. return;
  696. }
  697. // No way to optimize a producing initializer into this. It's not
  698. // worth optimizing for, because the value will immediately
  699. // disappear in the common case.
  700. value = EmitScalarExpr(init);
  701. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  702. if (accessedByInit)
  703. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  704. else
  705. EmitARCInitWeak(lvalue.getAddress(), value);
  706. return;
  707. }
  708. case Qualifiers::OCL_Autoreleasing:
  709. value = EmitARCRetainAutoreleaseScalarExpr(init);
  710. break;
  711. }
  712. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  713. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  714. // If the variable might have been accessed by its initializer, we
  715. // might have to initialize with a barrier. We have to do this for
  716. // both __weak and __strong, but __weak got filtered out above.
  717. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  718. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  719. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  720. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  721. return;
  722. }
  723. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  724. }
  725. /// Decide whether we can emit the non-zero parts of the specified initializer
  726. /// with equal or fewer than NumStores scalar stores.
  727. static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
  728. unsigned &NumStores) {
  729. // Zero and Undef never requires any extra stores.
  730. if (isa<llvm::ConstantAggregateZero>(Init) ||
  731. isa<llvm::ConstantPointerNull>(Init) ||
  732. isa<llvm::UndefValue>(Init))
  733. return true;
  734. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  735. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  736. isa<llvm::ConstantExpr>(Init))
  737. return Init->isNullValue() || NumStores--;
  738. // See if we can emit each element.
  739. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  740. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  741. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  742. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  743. return false;
  744. }
  745. return true;
  746. }
  747. if (llvm::ConstantDataSequential *CDS =
  748. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  749. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  750. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  751. if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
  752. return false;
  753. }
  754. return true;
  755. }
  756. // Anything else is hard and scary.
  757. return false;
  758. }
  759. /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
  760. /// the scalar stores that would be required.
  761. static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
  762. llvm::Constant *Init, Address Loc,
  763. bool isVolatile, CGBuilderTy &Builder) {
  764. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  765. "called emitStoresForInitAfterBZero for zero or undef value.");
  766. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  767. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  768. isa<llvm::ConstantExpr>(Init)) {
  769. Builder.CreateStore(Init, Loc, isVolatile);
  770. return;
  771. }
  772. if (llvm::ConstantDataSequential *CDS =
  773. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  774. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  775. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  776. // If necessary, get a pointer to the element and emit it.
  777. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  778. emitStoresForInitAfterBZero(
  779. CGM, Elt,
  780. Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
  781. isVolatile, Builder);
  782. }
  783. return;
  784. }
  785. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  786. "Unknown value type!");
  787. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  788. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  789. // If necessary, get a pointer to the element and emit it.
  790. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  791. emitStoresForInitAfterBZero(
  792. CGM, Elt,
  793. Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
  794. isVolatile, Builder);
  795. }
  796. }
  797. /// Decide whether we should use bzero plus some stores to initialize a local
  798. /// variable instead of using a memcpy from a constant global. It is beneficial
  799. /// to use bzero if the global is all zeros, or mostly zeros and large.
  800. static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
  801. uint64_t GlobalSize) {
  802. // If a global is all zeros, always use a bzero.
  803. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  804. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  805. // do it if it will require 6 or fewer scalar stores.
  806. // TODO: Should budget depends on the size? Avoiding a large global warrants
  807. // plopping in more stores.
  808. unsigned StoreBudget = 6;
  809. uint64_t SizeLimit = 32;
  810. return GlobalSize > SizeLimit &&
  811. canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
  812. }
  813. /// Decide whether we should use memset to initialize a local variable instead
  814. /// of using a memcpy from a constant global. Assumes we've already decided to
  815. /// not user bzero.
  816. /// FIXME We could be more clever, as we are for bzero above, and generate
  817. /// memset followed by stores. It's unclear that's worth the effort.
  818. static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
  819. uint64_t GlobalSize) {
  820. uint64_t SizeLimit = 32;
  821. if (GlobalSize <= SizeLimit)
  822. return nullptr;
  823. return llvm::isBytewiseValue(Init);
  824. }
  825. static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
  826. Address Loc, bool isVolatile,
  827. CGBuilderTy &Builder,
  828. llvm::Constant *constant) {
  829. auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
  830. auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
  831. // If the initializer is all or mostly the same, codegen with bzero / memset
  832. // then do a few stores afterward.
  833. uint64_t ConstantSize =
  834. CGM.getDataLayout().getTypeAllocSize(constant->getType());
  835. auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
  836. if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
  837. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  838. isVolatile);
  839. bool valueAlreadyCorrect =
  840. constant->isNullValue() || isa<llvm::UndefValue>(constant);
  841. if (!valueAlreadyCorrect) {
  842. Loc = Builder.CreateBitCast(
  843. Loc, constant->getType()->getPointerTo(Loc.getAddressSpace()));
  844. emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
  845. }
  846. return;
  847. }
  848. llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
  849. if (Pattern) {
  850. uint64_t Value = 0x00;
  851. if (!isa<llvm::UndefValue>(Pattern)) {
  852. const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
  853. assert(AP.getBitWidth() <= 8);
  854. Value = AP.getLimitedValue();
  855. }
  856. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
  857. isVolatile);
  858. return;
  859. }
  860. // Otherwise, create a temporary global with the initializer then memcpy from
  861. // the global to the alloca.
  862. std::string Name = getStaticDeclName(CGM, D);
  863. unsigned AS = CGM.getContext().getTargetAddressSpace(
  864. CGM.getStringLiteralAddressSpace());
  865. llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
  866. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  867. CGM.getModule(), constant->getType(), true,
  868. llvm::GlobalValue::PrivateLinkage, constant, Name, nullptr,
  869. llvm::GlobalValue::NotThreadLocal, AS);
  870. GV->setAlignment(Loc.getAlignment().getQuantity());
  871. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  872. Address SrcPtr = Address(GV, Loc.getAlignment());
  873. if (SrcPtr.getType() != BP)
  874. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  875. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
  876. }
  877. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  878. /// variable declaration with auto, register, or no storage class specifier.
  879. /// These turn into simple stack objects, or GlobalValues depending on target.
  880. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  881. AutoVarEmission emission = EmitAutoVarAlloca(D);
  882. EmitAutoVarInit(emission);
  883. EmitAutoVarCleanups(emission);
  884. }
  885. /// Emit a lifetime.begin marker if some criteria are satisfied.
  886. /// \return a pointer to the temporary size Value if a marker was emitted, null
  887. /// otherwise
  888. llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
  889. llvm::Value *Addr) {
  890. if (!ShouldEmitLifetimeMarkers)
  891. return nullptr;
  892. assert(Addr->getType()->getPointerAddressSpace() ==
  893. CGM.getDataLayout().getAllocaAddrSpace() &&
  894. "Pointer should be in alloca address space");
  895. llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
  896. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  897. llvm::CallInst *C =
  898. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  899. C->setDoesNotThrow();
  900. return SizeV;
  901. }
  902. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  903. assert(Addr->getType()->getPointerAddressSpace() ==
  904. CGM.getDataLayout().getAllocaAddrSpace() &&
  905. "Pointer should be in alloca address space");
  906. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  907. llvm::CallInst *C =
  908. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  909. C->setDoesNotThrow();
  910. }
  911. void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
  912. CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
  913. // For each dimension stores its QualType and corresponding
  914. // size-expression Value.
  915. SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
  916. // Break down the array into individual dimensions.
  917. QualType Type1D = D.getType();
  918. while (getContext().getAsVariableArrayType(Type1D)) {
  919. auto VlaSize = getVLAElements1D(Type1D);
  920. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  921. Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
  922. else {
  923. auto SizeExprAddr = CreateDefaultAlignTempAlloca(
  924. VlaSize.NumElts->getType(), "__vla_expr");
  925. Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
  926. Dimensions.emplace_back(SizeExprAddr.getPointer(),
  927. Type1D.getUnqualifiedType());
  928. }
  929. Type1D = VlaSize.Type;
  930. }
  931. if (!EmitDebugInfo)
  932. return;
  933. // Register each dimension's size-expression with a DILocalVariable,
  934. // so that it can be used by CGDebugInfo when instantiating a DISubrange
  935. // to describe this array.
  936. for (auto &VlaSize : Dimensions) {
  937. llvm::Metadata *MD;
  938. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  939. MD = llvm::ConstantAsMetadata::get(C);
  940. else {
  941. // Create an artificial VarDecl to generate debug info for.
  942. IdentifierInfo &NameIdent = getContext().Idents.getOwn(
  943. cast<llvm::AllocaInst>(VlaSize.NumElts)->getName());
  944. auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
  945. auto QT = getContext().getIntTypeForBitwidth(
  946. VlaExprTy->getScalarSizeInBits(), false);
  947. auto *ArtificialDecl = VarDecl::Create(
  948. getContext(), const_cast<DeclContext *>(D.getDeclContext()),
  949. D.getLocation(), D.getLocation(), &NameIdent, QT,
  950. getContext().CreateTypeSourceInfo(QT), SC_Auto);
  951. ArtificialDecl->setImplicit();
  952. MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
  953. Builder);
  954. }
  955. assert(MD && "No Size expression debug node created");
  956. DI->registerVLASizeExpression(VlaSize.Type, MD);
  957. }
  958. }
  959. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  960. /// local variable. Does not emit initialization or destruction.
  961. CodeGenFunction::AutoVarEmission
  962. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  963. QualType Ty = D.getType();
  964. assert(
  965. Ty.getAddressSpace() == LangAS::Default ||
  966. (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
  967. AutoVarEmission emission(D);
  968. bool isByRef = D.hasAttr<BlocksAttr>();
  969. emission.IsByRef = isByRef;
  970. CharUnits alignment = getContext().getDeclAlign(&D);
  971. // If the type is variably-modified, emit all the VLA sizes for it.
  972. if (Ty->isVariablyModifiedType())
  973. EmitVariablyModifiedType(Ty);
  974. auto *DI = getDebugInfo();
  975. bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
  976. codegenoptions::LimitedDebugInfo;
  977. Address address = Address::invalid();
  978. Address AllocaAddr = Address::invalid();
  979. if (Ty->isConstantSizeType()) {
  980. bool NRVO = getLangOpts().ElideConstructors &&
  981. D.isNRVOVariable();
  982. // If this value is an array or struct with a statically determinable
  983. // constant initializer, there are optimizations we can do.
  984. //
  985. // TODO: We should constant-evaluate the initializer of any variable,
  986. // as long as it is initialized by a constant expression. Currently,
  987. // isConstantInitializer produces wrong answers for structs with
  988. // reference or bitfield members, and a few other cases, and checking
  989. // for POD-ness protects us from some of these.
  990. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  991. (D.isConstexpr() ||
  992. ((Ty.isPODType(getContext()) ||
  993. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  994. D.getInit()->isConstantInitializer(getContext(), false)))) {
  995. // If the variable's a const type, and it's neither an NRVO
  996. // candidate nor a __block variable and has no mutable members,
  997. // emit it as a global instead.
  998. // Exception is if a variable is located in non-constant address space
  999. // in OpenCL.
  1000. if ((!getLangOpts().OpenCL ||
  1001. Ty.getAddressSpace() == LangAS::opencl_constant) &&
  1002. (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  1003. CGM.isTypeConstant(Ty, true))) {
  1004. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  1005. // Signal this condition to later callbacks.
  1006. emission.Addr = Address::invalid();
  1007. assert(emission.wasEmittedAsGlobal());
  1008. return emission;
  1009. }
  1010. // Otherwise, tell the initialization code that we're in this case.
  1011. emission.IsConstantAggregate = true;
  1012. }
  1013. // A normal fixed sized variable becomes an alloca in the entry block,
  1014. // unless:
  1015. // - it's an NRVO variable.
  1016. // - we are compiling OpenMP and it's an OpenMP local variable.
  1017. Address OpenMPLocalAddr =
  1018. getLangOpts().OpenMP
  1019. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  1020. : Address::invalid();
  1021. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  1022. address = OpenMPLocalAddr;
  1023. } else if (NRVO) {
  1024. // The named return value optimization: allocate this variable in the
  1025. // return slot, so that we can elide the copy when returning this
  1026. // variable (C++0x [class.copy]p34).
  1027. address = ReturnValue;
  1028. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  1029. const auto *RD = RecordTy->getDecl();
  1030. const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  1031. if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
  1032. RD->isNonTrivialToPrimitiveDestroy()) {
  1033. // Create a flag that is used to indicate when the NRVO was applied
  1034. // to this variable. Set it to zero to indicate that NRVO was not
  1035. // applied.
  1036. llvm::Value *Zero = Builder.getFalse();
  1037. Address NRVOFlag =
  1038. CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
  1039. EnsureInsertPoint();
  1040. Builder.CreateStore(Zero, NRVOFlag);
  1041. // Record the NRVO flag for this variable.
  1042. NRVOFlags[&D] = NRVOFlag.getPointer();
  1043. emission.NRVOFlag = NRVOFlag.getPointer();
  1044. }
  1045. }
  1046. } else {
  1047. CharUnits allocaAlignment;
  1048. llvm::Type *allocaTy;
  1049. if (isByRef) {
  1050. auto &byrefInfo = getBlockByrefInfo(&D);
  1051. allocaTy = byrefInfo.Type;
  1052. allocaAlignment = byrefInfo.ByrefAlignment;
  1053. } else {
  1054. allocaTy = ConvertTypeForMem(Ty);
  1055. allocaAlignment = alignment;
  1056. }
  1057. // Create the alloca. Note that we set the name separately from
  1058. // building the instruction so that it's there even in no-asserts
  1059. // builds.
  1060. address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
  1061. /*ArraySize=*/nullptr, &AllocaAddr);
  1062. // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
  1063. // the catch parameter starts in the catchpad instruction, and we can't
  1064. // insert code in those basic blocks.
  1065. bool IsMSCatchParam =
  1066. D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
  1067. // Emit a lifetime intrinsic if meaningful. There's no point in doing this
  1068. // if we don't have a valid insertion point (?).
  1069. if (HaveInsertPoint() && !IsMSCatchParam) {
  1070. // If there's a jump into the lifetime of this variable, its lifetime
  1071. // gets broken up into several regions in IR, which requires more work
  1072. // to handle correctly. For now, just omit the intrinsics; this is a
  1073. // rare case, and it's better to just be conservatively correct.
  1074. // PR28267.
  1075. //
  1076. // We have to do this in all language modes if there's a jump past the
  1077. // declaration. We also have to do it in C if there's a jump to an
  1078. // earlier point in the current block because non-VLA lifetimes begin as
  1079. // soon as the containing block is entered, not when its variables
  1080. // actually come into scope; suppressing the lifetime annotations
  1081. // completely in this case is unnecessarily pessimistic, but again, this
  1082. // is rare.
  1083. if (!Bypasses.IsBypassed(&D) &&
  1084. !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
  1085. uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
  1086. emission.SizeForLifetimeMarkers =
  1087. EmitLifetimeStart(size, AllocaAddr.getPointer());
  1088. }
  1089. } else {
  1090. assert(!emission.useLifetimeMarkers());
  1091. }
  1092. }
  1093. } else {
  1094. EnsureInsertPoint();
  1095. if (!DidCallStackSave) {
  1096. // Save the stack.
  1097. Address Stack =
  1098. CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
  1099. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  1100. llvm::Value *V = Builder.CreateCall(F);
  1101. Builder.CreateStore(V, Stack);
  1102. DidCallStackSave = true;
  1103. // Push a cleanup block and restore the stack there.
  1104. // FIXME: in general circumstances, this should be an EH cleanup.
  1105. pushStackRestore(NormalCleanup, Stack);
  1106. }
  1107. auto VlaSize = getVLASize(Ty);
  1108. llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
  1109. // Allocate memory for the array.
  1110. address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
  1111. &AllocaAddr);
  1112. // If we have debug info enabled, properly describe the VLA dimensions for
  1113. // this type by registering the vla size expression for each of the
  1114. // dimensions.
  1115. EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
  1116. }
  1117. setAddrOfLocalVar(&D, address);
  1118. emission.Addr = address;
  1119. emission.AllocaAddr = AllocaAddr;
  1120. // Emit debug info for local var declaration.
  1121. if (EmitDebugInfo && HaveInsertPoint()) {
  1122. DI->setLocation(D.getLocation());
  1123. (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
  1124. }
  1125. if (D.hasAttr<AnnotateAttr>())
  1126. EmitVarAnnotations(&D, address.getPointer());
  1127. // Make sure we call @llvm.lifetime.end.
  1128. if (emission.useLifetimeMarkers())
  1129. EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
  1130. emission.getOriginalAllocatedAddress(),
  1131. emission.getSizeForLifetimeMarkers());
  1132. return emission;
  1133. }
  1134. static bool isCapturedBy(const VarDecl &, const Expr *);
  1135. /// Determines whether the given __block variable is potentially
  1136. /// captured by the given statement.
  1137. static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
  1138. if (const Expr *E = dyn_cast<Expr>(S))
  1139. return isCapturedBy(Var, E);
  1140. for (const Stmt *SubStmt : S->children())
  1141. if (isCapturedBy(Var, SubStmt))
  1142. return true;
  1143. return false;
  1144. }
  1145. /// Determines whether the given __block variable is potentially
  1146. /// captured by the given expression.
  1147. static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
  1148. // Skip the most common kinds of expressions that make
  1149. // hierarchy-walking expensive.
  1150. E = E->IgnoreParenCasts();
  1151. if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
  1152. const BlockDecl *Block = BE->getBlockDecl();
  1153. for (const auto &I : Block->captures()) {
  1154. if (I.getVariable() == &Var)
  1155. return true;
  1156. }
  1157. // No need to walk into the subexpressions.
  1158. return false;
  1159. }
  1160. if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
  1161. const CompoundStmt *CS = SE->getSubStmt();
  1162. for (const auto *BI : CS->body())
  1163. if (const auto *BIE = dyn_cast<Expr>(BI)) {
  1164. if (isCapturedBy(Var, BIE))
  1165. return true;
  1166. }
  1167. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  1168. // special case declarations
  1169. for (const auto *I : DS->decls()) {
  1170. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  1171. const Expr *Init = VD->getInit();
  1172. if (Init && isCapturedBy(Var, Init))
  1173. return true;
  1174. }
  1175. }
  1176. }
  1177. else
  1178. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  1179. // Later, provide code to poke into statements for capture analysis.
  1180. return true;
  1181. return false;
  1182. }
  1183. for (const Stmt *SubStmt : E->children())
  1184. if (isCapturedBy(Var, SubStmt))
  1185. return true;
  1186. return false;
  1187. }
  1188. /// Determine whether the given initializer is trivial in the sense
  1189. /// that it requires no code to be generated.
  1190. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  1191. if (!Init)
  1192. return true;
  1193. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  1194. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  1195. if (Constructor->isTrivial() &&
  1196. Constructor->isDefaultConstructor() &&
  1197. !Construct->requiresZeroInitialization())
  1198. return true;
  1199. return false;
  1200. }
  1201. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  1202. assert(emission.Variable && "emission was not valid!");
  1203. // If this was emitted as a global constant, we're done.
  1204. if (emission.wasEmittedAsGlobal()) return;
  1205. const VarDecl &D = *emission.Variable;
  1206. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1207. QualType type = D.getType();
  1208. // If this local has an initializer, emit it now.
  1209. const Expr *Init = D.getInit();
  1210. // If we are at an unreachable point, we don't need to emit the initializer
  1211. // unless it contains a label.
  1212. if (!HaveInsertPoint()) {
  1213. if (!Init || !ContainsLabel(Init)) return;
  1214. EnsureInsertPoint();
  1215. }
  1216. // Initialize the structure of a __block variable.
  1217. if (emission.IsByRef)
  1218. emitByrefStructureInit(emission);
  1219. // Initialize the variable here if it doesn't have a initializer and it is a
  1220. // C struct that is non-trivial to initialize or an array containing such a
  1221. // struct.
  1222. if (!Init &&
  1223. type.isNonTrivialToPrimitiveDefaultInitialize() ==
  1224. QualType::PDIK_Struct) {
  1225. LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
  1226. if (emission.IsByRef)
  1227. drillIntoBlockVariable(*this, Dst, &D);
  1228. defaultInitNonTrivialCStructVar(Dst);
  1229. return;
  1230. }
  1231. if (isTrivialInitializer(Init))
  1232. return;
  1233. // Check whether this is a byref variable that's potentially
  1234. // captured and moved by its own initializer. If so, we'll need to
  1235. // emit the initializer first, then copy into the variable.
  1236. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  1237. Address Loc =
  1238. capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
  1239. llvm::Constant *constant = nullptr;
  1240. if (emission.IsConstantAggregate || D.isConstexpr()) {
  1241. assert(!capturedByInit && "constant init contains a capturing block?");
  1242. constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
  1243. }
  1244. if (!constant) {
  1245. LValue lv = MakeAddrLValue(Loc, type);
  1246. lv.setNonGC(true);
  1247. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1248. }
  1249. if (!emission.IsConstantAggregate) {
  1250. // For simple scalar/complex initialization, store the value directly.
  1251. LValue lv = MakeAddrLValue(Loc, type);
  1252. lv.setNonGC(true);
  1253. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1254. }
  1255. // If this is a simple aggregate initialization, we can optimize it
  1256. // in various ways.
  1257. bool isVolatile = type.isVolatileQualified();
  1258. llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
  1259. if (Loc.getType() != BP)
  1260. Loc = Builder.CreateBitCast(Loc, BP);
  1261. emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
  1262. }
  1263. /// Emit an expression as an initializer for an object (variable, field, etc.)
  1264. /// at the given location. The expression is not necessarily the normal
  1265. /// initializer for the object, and the address is not necessarily
  1266. /// its normal location.
  1267. ///
  1268. /// \param init the initializing expression
  1269. /// \param D the object to act as if we're initializing
  1270. /// \param loc the address to initialize; its type is a pointer
  1271. /// to the LLVM mapping of the object's type
  1272. /// \param alignment the alignment of the address
  1273. /// \param capturedByInit true if \p D is a __block variable
  1274. /// whose address is potentially changed by the initializer
  1275. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1276. LValue lvalue, bool capturedByInit) {
  1277. QualType type = D->getType();
  1278. if (type->isReferenceType()) {
  1279. RValue rvalue = EmitReferenceBindingToExpr(init);
  1280. if (capturedByInit)
  1281. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1282. EmitStoreThroughLValue(rvalue, lvalue, true);
  1283. return;
  1284. }
  1285. switch (getEvaluationKind(type)) {
  1286. case TEK_Scalar:
  1287. EmitScalarInit(init, D, lvalue, capturedByInit);
  1288. return;
  1289. case TEK_Complex: {
  1290. ComplexPairTy complex = EmitComplexExpr(init);
  1291. if (capturedByInit)
  1292. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1293. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1294. return;
  1295. }
  1296. case TEK_Aggregate:
  1297. if (type->isAtomicType()) {
  1298. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1299. } else {
  1300. AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
  1301. if (isa<VarDecl>(D))
  1302. Overlap = AggValueSlot::DoesNotOverlap;
  1303. else if (auto *FD = dyn_cast<FieldDecl>(D))
  1304. Overlap = overlapForFieldInit(FD);
  1305. // TODO: how can we delay here if D is captured by its initializer?
  1306. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  1307. AggValueSlot::IsDestructed,
  1308. AggValueSlot::DoesNotNeedGCBarriers,
  1309. AggValueSlot::IsNotAliased,
  1310. Overlap));
  1311. }
  1312. return;
  1313. }
  1314. llvm_unreachable("bad evaluation kind");
  1315. }
  1316. /// Enter a destroy cleanup for the given local variable.
  1317. void CodeGenFunction::emitAutoVarTypeCleanup(
  1318. const CodeGenFunction::AutoVarEmission &emission,
  1319. QualType::DestructionKind dtorKind) {
  1320. assert(dtorKind != QualType::DK_none);
  1321. // Note that for __block variables, we want to destroy the
  1322. // original stack object, not the possibly forwarded object.
  1323. Address addr = emission.getObjectAddress(*this);
  1324. const VarDecl *var = emission.Variable;
  1325. QualType type = var->getType();
  1326. CleanupKind cleanupKind = NormalAndEHCleanup;
  1327. CodeGenFunction::Destroyer *destroyer = nullptr;
  1328. switch (dtorKind) {
  1329. case QualType::DK_none:
  1330. llvm_unreachable("no cleanup for trivially-destructible variable");
  1331. case QualType::DK_cxx_destructor:
  1332. // If there's an NRVO flag on the emission, we need a different
  1333. // cleanup.
  1334. if (emission.NRVOFlag) {
  1335. assert(!type->isArrayType());
  1336. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1337. EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
  1338. emission.NRVOFlag);
  1339. return;
  1340. }
  1341. break;
  1342. case QualType::DK_objc_strong_lifetime:
  1343. // Suppress cleanups for pseudo-strong variables.
  1344. if (var->isARCPseudoStrong()) return;
  1345. // Otherwise, consider whether to use an EH cleanup or not.
  1346. cleanupKind = getARCCleanupKind();
  1347. // Use the imprecise destroyer by default.
  1348. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1349. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1350. break;
  1351. case QualType::DK_objc_weak_lifetime:
  1352. break;
  1353. case QualType::DK_nontrivial_c_struct:
  1354. destroyer = CodeGenFunction::destroyNonTrivialCStruct;
  1355. if (emission.NRVOFlag) {
  1356. assert(!type->isArrayType());
  1357. EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
  1358. emission.NRVOFlag, type);
  1359. return;
  1360. }
  1361. break;
  1362. }
  1363. // If we haven't chosen a more specific destroyer, use the default.
  1364. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1365. // Use an EH cleanup in array destructors iff the destructor itself
  1366. // is being pushed as an EH cleanup.
  1367. bool useEHCleanup = (cleanupKind & EHCleanup);
  1368. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1369. useEHCleanup);
  1370. }
  1371. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1372. assert(emission.Variable && "emission was not valid!");
  1373. // If this was emitted as a global constant, we're done.
  1374. if (emission.wasEmittedAsGlobal()) return;
  1375. // If we don't have an insertion point, we're done. Sema prevents
  1376. // us from jumping into any of these scopes anyway.
  1377. if (!HaveInsertPoint()) return;
  1378. const VarDecl &D = *emission.Variable;
  1379. // Check the type for a cleanup.
  1380. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  1381. emitAutoVarTypeCleanup(emission, dtorKind);
  1382. // In GC mode, honor objc_precise_lifetime.
  1383. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1384. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1385. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1386. }
  1387. // Handle the cleanup attribute.
  1388. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1389. const FunctionDecl *FD = CA->getFunctionDecl();
  1390. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1391. assert(F && "Could not find function!");
  1392. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1393. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1394. }
  1395. // If this is a block variable, call _Block_object_destroy
  1396. // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
  1397. // mode.
  1398. if (emission.IsByRef && CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
  1399. BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
  1400. if (emission.Variable->getType().isObjCGCWeak())
  1401. Flags |= BLOCK_FIELD_IS_WEAK;
  1402. enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
  1403. /*LoadBlockVarAddr*/ false,
  1404. cxxDestructorCanThrow(emission.Variable->getType()));
  1405. }
  1406. }
  1407. CodeGenFunction::Destroyer *
  1408. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1409. switch (kind) {
  1410. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1411. case QualType::DK_cxx_destructor:
  1412. return destroyCXXObject;
  1413. case QualType::DK_objc_strong_lifetime:
  1414. return destroyARCStrongPrecise;
  1415. case QualType::DK_objc_weak_lifetime:
  1416. return destroyARCWeak;
  1417. case QualType::DK_nontrivial_c_struct:
  1418. return destroyNonTrivialCStruct;
  1419. }
  1420. llvm_unreachable("Unknown DestructionKind");
  1421. }
  1422. /// pushEHDestroy - Push the standard destructor for the given type as
  1423. /// an EH-only cleanup.
  1424. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1425. Address addr, QualType type) {
  1426. assert(dtorKind && "cannot push destructor for trivial type");
  1427. assert(needsEHCleanup(dtorKind));
  1428. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1429. }
  1430. /// pushDestroy - Push the standard destructor for the given type as
  1431. /// at least a normal cleanup.
  1432. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1433. Address addr, QualType type) {
  1434. assert(dtorKind && "cannot push destructor for trivial type");
  1435. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1436. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1437. cleanupKind & EHCleanup);
  1438. }
  1439. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
  1440. QualType type, Destroyer *destroyer,
  1441. bool useEHCleanupForArray) {
  1442. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1443. destroyer, useEHCleanupForArray);
  1444. }
  1445. void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
  1446. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1447. }
  1448. void CodeGenFunction::pushLifetimeExtendedDestroy(
  1449. CleanupKind cleanupKind, Address addr, QualType type,
  1450. Destroyer *destroyer, bool useEHCleanupForArray) {
  1451. // Push an EH-only cleanup for the object now.
  1452. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1453. // around in case a temporary's destructor throws an exception.
  1454. if (cleanupKind & EHCleanup)
  1455. EHStack.pushCleanup<DestroyObject>(
  1456. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1457. destroyer, useEHCleanupForArray);
  1458. // Remember that we need to push a full cleanup for the object at the
  1459. // end of the full-expression.
  1460. pushCleanupAfterFullExpr<DestroyObject>(
  1461. cleanupKind, addr, type, destroyer, useEHCleanupForArray);
  1462. }
  1463. /// emitDestroy - Immediately perform the destruction of the given
  1464. /// object.
  1465. ///
  1466. /// \param addr - the address of the object; a type*
  1467. /// \param type - the type of the object; if an array type, all
  1468. /// objects are destroyed in reverse order
  1469. /// \param destroyer - the function to call to destroy individual
  1470. /// elements
  1471. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1472. /// used when destroying array elements, in case one of the
  1473. /// destructions throws an exception
  1474. void CodeGenFunction::emitDestroy(Address addr, QualType type,
  1475. Destroyer *destroyer,
  1476. bool useEHCleanupForArray) {
  1477. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1478. if (!arrayType)
  1479. return destroyer(*this, addr, type);
  1480. llvm::Value *length = emitArrayLength(arrayType, type, addr);
  1481. CharUnits elementAlign =
  1482. addr.getAlignment()
  1483. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1484. // Normally we have to check whether the array is zero-length.
  1485. bool checkZeroLength = true;
  1486. // But if the array length is constant, we can suppress that.
  1487. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1488. // ...and if it's constant zero, we can just skip the entire thing.
  1489. if (constLength->isZero()) return;
  1490. checkZeroLength = false;
  1491. }
  1492. llvm::Value *begin = addr.getPointer();
  1493. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1494. emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1495. checkZeroLength, useEHCleanupForArray);
  1496. }
  1497. /// emitArrayDestroy - Destroys all the elements of the given array,
  1498. /// beginning from last to first. The array cannot be zero-length.
  1499. ///
  1500. /// \param begin - a type* denoting the first element of the array
  1501. /// \param end - a type* denoting one past the end of the array
  1502. /// \param elementType - the element type of the array
  1503. /// \param destroyer - the function to call to destroy elements
  1504. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1505. /// the remaining elements in case the destruction of a single
  1506. /// element throws
  1507. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1508. llvm::Value *end,
  1509. QualType elementType,
  1510. CharUnits elementAlign,
  1511. Destroyer *destroyer,
  1512. bool checkZeroLength,
  1513. bool useEHCleanup) {
  1514. assert(!elementType->isArrayType());
  1515. // The basic structure here is a do-while loop, because we don't
  1516. // need to check for the zero-element case.
  1517. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1518. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1519. if (checkZeroLength) {
  1520. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1521. "arraydestroy.isempty");
  1522. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1523. }
  1524. // Enter the loop body, making that address the current address.
  1525. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1526. EmitBlock(bodyBB);
  1527. llvm::PHINode *elementPast =
  1528. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1529. elementPast->addIncoming(end, entryBB);
  1530. // Shift the address back by one element.
  1531. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1532. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1533. "arraydestroy.element");
  1534. if (useEHCleanup)
  1535. pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
  1536. destroyer);
  1537. // Perform the actual destruction there.
  1538. destroyer(*this, Address(element, elementAlign), elementType);
  1539. if (useEHCleanup)
  1540. PopCleanupBlock();
  1541. // Check whether we've reached the end.
  1542. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1543. Builder.CreateCondBr(done, doneBB, bodyBB);
  1544. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1545. // Done.
  1546. EmitBlock(doneBB);
  1547. }
  1548. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1549. /// emitArrayDestroy, the element type here may still be an array type.
  1550. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1551. llvm::Value *begin, llvm::Value *end,
  1552. QualType type, CharUnits elementAlign,
  1553. CodeGenFunction::Destroyer *destroyer) {
  1554. // If the element type is itself an array, drill down.
  1555. unsigned arrayDepth = 0;
  1556. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1557. // VLAs don't require a GEP index to walk into.
  1558. if (!isa<VariableArrayType>(arrayType))
  1559. arrayDepth++;
  1560. type = arrayType->getElementType();
  1561. }
  1562. if (arrayDepth) {
  1563. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1564. SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
  1565. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1566. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1567. }
  1568. // Destroy the array. We don't ever need an EH cleanup because we
  1569. // assume that we're in an EH cleanup ourselves, so a throwing
  1570. // destructor causes an immediate terminate.
  1571. CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1572. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1573. }
  1574. namespace {
  1575. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1576. /// array destroy where the end pointer is regularly determined and
  1577. /// does not need to be loaded from a local.
  1578. class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1579. llvm::Value *ArrayBegin;
  1580. llvm::Value *ArrayEnd;
  1581. QualType ElementType;
  1582. CodeGenFunction::Destroyer *Destroyer;
  1583. CharUnits ElementAlign;
  1584. public:
  1585. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1586. QualType elementType, CharUnits elementAlign,
  1587. CodeGenFunction::Destroyer *destroyer)
  1588. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1589. ElementType(elementType), Destroyer(destroyer),
  1590. ElementAlign(elementAlign) {}
  1591. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1592. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1593. ElementType, ElementAlign, Destroyer);
  1594. }
  1595. };
  1596. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1597. /// partial array destroy where the end pointer is irregularly
  1598. /// determined and must be loaded from a local.
  1599. class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1600. llvm::Value *ArrayBegin;
  1601. Address ArrayEndPointer;
  1602. QualType ElementType;
  1603. CodeGenFunction::Destroyer *Destroyer;
  1604. CharUnits ElementAlign;
  1605. public:
  1606. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1607. Address arrayEndPointer,
  1608. QualType elementType,
  1609. CharUnits elementAlign,
  1610. CodeGenFunction::Destroyer *destroyer)
  1611. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1612. ElementType(elementType), Destroyer(destroyer),
  1613. ElementAlign(elementAlign) {}
  1614. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1615. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1616. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1617. ElementType, ElementAlign, Destroyer);
  1618. }
  1619. };
  1620. } // end anonymous namespace
  1621. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1622. /// already-constructed elements of the given array. The cleanup
  1623. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1624. ///
  1625. /// \param elementType - the immediate element type of the array;
  1626. /// possibly still an array type
  1627. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1628. Address arrayEndPointer,
  1629. QualType elementType,
  1630. CharUnits elementAlign,
  1631. Destroyer *destroyer) {
  1632. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1633. arrayBegin, arrayEndPointer,
  1634. elementType, elementAlign,
  1635. destroyer);
  1636. }
  1637. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1638. /// already-constructed elements of the given array. The cleanup
  1639. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1640. ///
  1641. /// \param elementType - the immediate element type of the array;
  1642. /// possibly still an array type
  1643. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1644. llvm::Value *arrayEnd,
  1645. QualType elementType,
  1646. CharUnits elementAlign,
  1647. Destroyer *destroyer) {
  1648. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1649. arrayBegin, arrayEnd,
  1650. elementType, elementAlign,
  1651. destroyer);
  1652. }
  1653. /// Lazily declare the @llvm.lifetime.start intrinsic.
  1654. llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
  1655. if (LifetimeStartFn)
  1656. return LifetimeStartFn;
  1657. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1658. llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
  1659. return LifetimeStartFn;
  1660. }
  1661. /// Lazily declare the @llvm.lifetime.end intrinsic.
  1662. llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
  1663. if (LifetimeEndFn)
  1664. return LifetimeEndFn;
  1665. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1666. llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
  1667. return LifetimeEndFn;
  1668. }
  1669. namespace {
  1670. /// A cleanup to perform a release of an object at the end of a
  1671. /// function. This is used to balance out the incoming +1 of a
  1672. /// ns_consumed argument when we can't reasonably do that just by
  1673. /// not doing the initial retain for a __block argument.
  1674. struct ConsumeARCParameter final : EHScopeStack::Cleanup {
  1675. ConsumeARCParameter(llvm::Value *param,
  1676. ARCPreciseLifetime_t precise)
  1677. : Param(param), Precise(precise) {}
  1678. llvm::Value *Param;
  1679. ARCPreciseLifetime_t Precise;
  1680. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1681. CGF.EmitARCRelease(Param, Precise);
  1682. }
  1683. };
  1684. } // end anonymous namespace
  1685. /// Emit an alloca (or GlobalValue depending on target)
  1686. /// for the specified parameter and set up LocalDeclMap.
  1687. void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
  1688. unsigned ArgNo) {
  1689. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1690. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1691. "Invalid argument to EmitParmDecl");
  1692. Arg.getAnyValue()->setName(D.getName());
  1693. QualType Ty = D.getType();
  1694. // Use better IR generation for certain implicit parameters.
  1695. if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
  1696. // The only implicit argument a block has is its literal.
  1697. // This may be passed as an inalloca'ed value on Windows x86.
  1698. if (BlockInfo) {
  1699. llvm::Value *V = Arg.isIndirect()
  1700. ? Builder.CreateLoad(Arg.getIndirectAddress())
  1701. : Arg.getDirectValue();
  1702. setBlockContextParameter(IPD, ArgNo, V);
  1703. return;
  1704. }
  1705. }
  1706. Address DeclPtr = Address::invalid();
  1707. bool DoStore = false;
  1708. bool IsScalar = hasScalarEvaluationKind(Ty);
  1709. // If we already have a pointer to the argument, reuse the input pointer.
  1710. if (Arg.isIndirect()) {
  1711. DeclPtr = Arg.getIndirectAddress();
  1712. // If we have a prettier pointer type at this point, bitcast to that.
  1713. unsigned AS = DeclPtr.getType()->getAddressSpace();
  1714. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  1715. if (DeclPtr.getType() != IRTy)
  1716. DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
  1717. // Indirect argument is in alloca address space, which may be different
  1718. // from the default address space.
  1719. auto AllocaAS = CGM.getASTAllocaAddressSpace();
  1720. auto *V = DeclPtr.getPointer();
  1721. auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
  1722. auto DestLangAS =
  1723. getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
  1724. if (SrcLangAS != DestLangAS) {
  1725. assert(getContext().getTargetAddressSpace(SrcLangAS) ==
  1726. CGM.getDataLayout().getAllocaAddrSpace());
  1727. auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
  1728. auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
  1729. DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
  1730. *this, V, SrcLangAS, DestLangAS, T, true),
  1731. DeclPtr.getAlignment());
  1732. }
  1733. // Push a destructor cleanup for this parameter if the ABI requires it.
  1734. // Don't push a cleanup in a thunk for a method that will also emit a
  1735. // cleanup.
  1736. if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
  1737. Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  1738. if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
  1739. assert((DtorKind == QualType::DK_cxx_destructor ||
  1740. DtorKind == QualType::DK_nontrivial_c_struct) &&
  1741. "unexpected destructor type");
  1742. pushDestroy(DtorKind, DeclPtr, Ty);
  1743. CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
  1744. EHStack.stable_begin();
  1745. }
  1746. }
  1747. } else {
  1748. // Check if the parameter address is controlled by OpenMP runtime.
  1749. Address OpenMPLocalAddr =
  1750. getLangOpts().OpenMP
  1751. ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
  1752. : Address::invalid();
  1753. if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
  1754. DeclPtr = OpenMPLocalAddr;
  1755. } else {
  1756. // Otherwise, create a temporary to hold the value.
  1757. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  1758. D.getName() + ".addr");
  1759. }
  1760. DoStore = true;
  1761. }
  1762. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  1763. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  1764. if (IsScalar) {
  1765. Qualifiers qs = Ty.getQualifiers();
  1766. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1767. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1768. // For __strong, it's handled by just skipping the initial retain;
  1769. // otherwise we have to balance out the initial +1 with an extra
  1770. // cleanup to do the release at the end of the function.
  1771. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1772. // 'self' is always formally __strong, but if this is not an
  1773. // init method then we don't want to retain it.
  1774. if (D.isARCPseudoStrong()) {
  1775. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1776. assert(&D == method->getSelfDecl());
  1777. assert(lt == Qualifiers::OCL_Strong);
  1778. assert(qs.hasConst());
  1779. assert(method->getMethodFamily() != OMF_init);
  1780. (void) method;
  1781. lt = Qualifiers::OCL_ExplicitNone;
  1782. }
  1783. // Load objects passed indirectly.
  1784. if (Arg.isIndirect() && !ArgVal)
  1785. ArgVal = Builder.CreateLoad(DeclPtr);
  1786. if (lt == Qualifiers::OCL_Strong) {
  1787. if (!isConsumed) {
  1788. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1789. // use objc_storeStrong(&dest, value) for retaining the
  1790. // object. But first, store a null into 'dest' because
  1791. // objc_storeStrong attempts to release its old value.
  1792. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  1793. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  1794. EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
  1795. DoStore = false;
  1796. }
  1797. else
  1798. // Don't use objc_retainBlock for block pointers, because we
  1799. // don't want to Block_copy something just because we got it
  1800. // as a parameter.
  1801. ArgVal = EmitARCRetainNonBlock(ArgVal);
  1802. }
  1803. } else {
  1804. // Push the cleanup for a consumed parameter.
  1805. if (isConsumed) {
  1806. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  1807. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  1808. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  1809. precise);
  1810. }
  1811. if (lt == Qualifiers::OCL_Weak) {
  1812. EmitARCInitWeak(DeclPtr, ArgVal);
  1813. DoStore = false; // The weak init is a store, no need to do two.
  1814. }
  1815. }
  1816. // Enter the cleanup scope.
  1817. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1818. }
  1819. }
  1820. // Store the initial value into the alloca.
  1821. if (DoStore)
  1822. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  1823. setAddrOfLocalVar(&D, DeclPtr);
  1824. // Emit debug info for param declaration.
  1825. if (CGDebugInfo *DI = getDebugInfo()) {
  1826. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1827. codegenoptions::LimitedDebugInfo) {
  1828. DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
  1829. }
  1830. }
  1831. if (D.hasAttr<AnnotateAttr>())
  1832. EmitVarAnnotations(&D, DeclPtr.getPointer());
  1833. // We can only check return value nullability if all arguments to the
  1834. // function satisfy their nullability preconditions. This makes it necessary
  1835. // to emit null checks for args in the function body itself.
  1836. if (requiresReturnValueNullabilityCheck()) {
  1837. auto Nullability = Ty->getNullability(getContext());
  1838. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  1839. SanitizerScope SanScope(this);
  1840. RetValNullabilityPrecondition =
  1841. Builder.CreateAnd(RetValNullabilityPrecondition,
  1842. Builder.CreateIsNotNull(Arg.getAnyValue()));
  1843. }
  1844. }
  1845. }
  1846. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  1847. CodeGenFunction *CGF) {
  1848. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  1849. return;
  1850. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  1851. }
  1852. void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
  1853. //Do nothing - here to avoid build errors
  1854. }