CGDecl.cpp 81 KB

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