CGDecl.cpp 96 KB

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