CGDecl.cpp 97 KB

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