CGDecl.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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 "CGDebugInfo.h"
  14. #include "CodeGenFunction.h"
  15. #include "CodeGenModule.h"
  16. #include "CGOpenCLRuntime.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/Frontend/CodeGenOptions.h"
  24. #include "llvm/GlobalVariable.h"
  25. #include "llvm/Intrinsics.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/Type.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. void CodeGenFunction::EmitDecl(const Decl &D) {
  31. switch (D.getKind()) {
  32. case Decl::TranslationUnit:
  33. case Decl::Namespace:
  34. case Decl::UnresolvedUsingTypename:
  35. case Decl::ClassTemplateSpecialization:
  36. case Decl::ClassTemplatePartialSpecialization:
  37. case Decl::TemplateTypeParm:
  38. case Decl::UnresolvedUsingValue:
  39. case Decl::NonTypeTemplateParm:
  40. case Decl::CXXMethod:
  41. case Decl::CXXConstructor:
  42. case Decl::CXXDestructor:
  43. case Decl::CXXConversion:
  44. case Decl::Field:
  45. case Decl::IndirectField:
  46. case Decl::ObjCIvar:
  47. case Decl::ObjCAtDefsField:
  48. case Decl::ParmVar:
  49. case Decl::ImplicitParam:
  50. case Decl::ClassTemplate:
  51. case Decl::FunctionTemplate:
  52. case Decl::TypeAliasTemplate:
  53. case Decl::TemplateTemplateParm:
  54. case Decl::ObjCMethod:
  55. case Decl::ObjCCategory:
  56. case Decl::ObjCProtocol:
  57. case Decl::ObjCInterface:
  58. case Decl::ObjCCategoryImpl:
  59. case Decl::ObjCImplementation:
  60. case Decl::ObjCProperty:
  61. case Decl::ObjCCompatibleAlias:
  62. case Decl::AccessSpec:
  63. case Decl::LinkageSpec:
  64. case Decl::ObjCPropertyImpl:
  65. case Decl::FileScopeAsm:
  66. case Decl::Friend:
  67. case Decl::FriendTemplate:
  68. case Decl::Block:
  69. case Decl::ClassScopeFunctionSpecialization:
  70. llvm_unreachable("Declaration should not be in declstmts!");
  71. case Decl::Function: // void X();
  72. case Decl::Record: // struct/union/class X;
  73. case Decl::Enum: // enum X;
  74. case Decl::EnumConstant: // enum ? { X = ? }
  75. case Decl::CXXRecord: // struct/union/class X; [C++]
  76. case Decl::Using: // using X; [C++]
  77. case Decl::UsingShadow:
  78. case Decl::UsingDirective: // using namespace X; [C++]
  79. case Decl::NamespaceAlias:
  80. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  81. case Decl::Label: // __label__ x;
  82. case Decl::Import:
  83. // None of these decls require codegen support.
  84. return;
  85. case Decl::Var: {
  86. const VarDecl &VD = cast<VarDecl>(D);
  87. assert(VD.isLocalVarDecl() &&
  88. "Should not see file-scope variables inside a function!");
  89. return EmitVarDecl(VD);
  90. }
  91. case Decl::Typedef: // typedef int X;
  92. case Decl::TypeAlias: { // using X = int; [C++0x]
  93. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  94. QualType Ty = TD.getUnderlyingType();
  95. if (Ty->isVariablyModifiedType())
  96. EmitVariablyModifiedType(Ty);
  97. }
  98. }
  99. }
  100. /// EmitVarDecl - This method handles emission of any variable declaration
  101. /// inside a function, including static vars etc.
  102. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  103. switch (D.getStorageClass()) {
  104. case SC_None:
  105. case SC_Auto:
  106. case SC_Register:
  107. return EmitAutoVarDecl(D);
  108. case SC_Static: {
  109. llvm::GlobalValue::LinkageTypes Linkage =
  110. llvm::GlobalValue::InternalLinkage;
  111. // If the function definition has some sort of weak linkage, its
  112. // static variables should also be weak so that they get properly
  113. // uniqued. We can't do this in C, though, because there's no
  114. // standard way to agree on which variables are the same (i.e.
  115. // there's no mangling).
  116. if (getContext().getLangOptions().CPlusPlus)
  117. if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
  118. Linkage = CurFn->getLinkage();
  119. return EmitStaticVarDecl(D, Linkage);
  120. }
  121. case SC_Extern:
  122. case SC_PrivateExtern:
  123. // Don't emit it now, allow it to be emitted lazily on its first use.
  124. return;
  125. case SC_OpenCLWorkGroupLocal:
  126. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  127. }
  128. llvm_unreachable("Unknown storage class");
  129. }
  130. static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
  131. const char *Separator) {
  132. CodeGenModule &CGM = CGF.CGM;
  133. if (CGF.getContext().getLangOptions().CPlusPlus) {
  134. StringRef Name = CGM.getMangledName(&D);
  135. return Name.str();
  136. }
  137. std::string ContextName;
  138. if (!CGF.CurFuncDecl) {
  139. // Better be in a block declared in global scope.
  140. const NamedDecl *ND = cast<NamedDecl>(&D);
  141. const DeclContext *DC = ND->getDeclContext();
  142. if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
  143. MangleBuffer Name;
  144. CGM.getBlockMangledName(GlobalDecl(), Name, BD);
  145. ContextName = Name.getString();
  146. }
  147. else
  148. llvm_unreachable("Unknown context for block static var decl");
  149. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
  150. StringRef Name = CGM.getMangledName(FD);
  151. ContextName = Name.str();
  152. } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
  153. ContextName = CGF.CurFn->getName();
  154. else
  155. llvm_unreachable("Unknown context for static var decl");
  156. return ContextName + Separator + D.getNameAsString();
  157. }
  158. llvm::GlobalVariable *
  159. CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
  160. const char *Separator,
  161. llvm::GlobalValue::LinkageTypes Linkage) {
  162. QualType Ty = D.getType();
  163. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  164. // Use the label if the variable is renamed with the asm-label extension.
  165. std::string Name;
  166. if (D.hasAttr<AsmLabelAttr>())
  167. Name = CGM.getMangledName(&D);
  168. else
  169. Name = GetStaticDeclName(*this, D, Separator);
  170. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
  171. llvm::GlobalVariable *GV =
  172. new llvm::GlobalVariable(CGM.getModule(), LTy,
  173. Ty.isConstant(getContext()), Linkage,
  174. CGM.EmitNullConstant(D.getType()), Name, 0,
  175. D.isThreadSpecified(),
  176. CGM.getContext().getTargetAddressSpace(Ty));
  177. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  178. if (Linkage != llvm::GlobalValue::InternalLinkage)
  179. GV->setVisibility(CurFn->getVisibility());
  180. return GV;
  181. }
  182. /// hasNontrivialDestruction - Determine whether a type's destruction is
  183. /// non-trivial. If so, and the variable uses static initialization, we must
  184. /// register its destructor to run on exit.
  185. static bool hasNontrivialDestruction(QualType T) {
  186. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  187. return RD && !RD->hasTrivialDestructor();
  188. }
  189. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  190. /// global variable that has already been created for it. If the initializer
  191. /// has a different type than GV does, this may free GV and return a different
  192. /// one. Otherwise it just returns GV.
  193. llvm::GlobalVariable *
  194. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  195. llvm::GlobalVariable *GV) {
  196. llvm::Constant *Init = CGM.EmitConstantInit(D, this);
  197. // If constant emission failed, then this should be a C++ static
  198. // initializer.
  199. if (!Init) {
  200. if (!getContext().getLangOptions().CPlusPlus)
  201. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  202. else if (Builder.GetInsertBlock()) {
  203. // Since we have a static initializer, this global variable can't
  204. // be constant.
  205. GV->setConstant(false);
  206. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  207. }
  208. return GV;
  209. }
  210. // The initializer may differ in type from the global. Rewrite
  211. // the global to match the initializer. (We have to do this
  212. // because some types, like unions, can't be completely represented
  213. // in the LLVM type system.)
  214. if (GV->getType()->getElementType() != Init->getType()) {
  215. llvm::GlobalVariable *OldGV = GV;
  216. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  217. OldGV->isConstant(),
  218. OldGV->getLinkage(), Init, "",
  219. /*InsertBefore*/ OldGV,
  220. D.isThreadSpecified(),
  221. CGM.getContext().getTargetAddressSpace(D.getType()));
  222. GV->setVisibility(OldGV->getVisibility());
  223. // Steal the name of the old global
  224. GV->takeName(OldGV);
  225. // Replace all uses of the old global with the new global
  226. llvm::Constant *NewPtrForOldDecl =
  227. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  228. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  229. // Erase the old global, since it is no longer used.
  230. OldGV->eraseFromParent();
  231. }
  232. GV->setInitializer(Init);
  233. if (hasNontrivialDestruction(D.getType())) {
  234. // We have a constant initializer, but a nontrivial destructor. We still
  235. // need to perform a guarded "initialization" in order to register the
  236. // destructor. Since we're running a destructor on this variable, it can't
  237. // be a constant even if it's const.
  238. GV->setConstant(false);
  239. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  240. }
  241. return GV;
  242. }
  243. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  244. llvm::GlobalValue::LinkageTypes Linkage) {
  245. llvm::Value *&DMEntry = LocalDeclMap[&D];
  246. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  247. llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
  248. // Store into LocalDeclMap before generating initializer to handle
  249. // circular references.
  250. DMEntry = GV;
  251. // We can't have a VLA here, but we can have a pointer to a VLA,
  252. // even though that doesn't really make any sense.
  253. // Make sure to evaluate VLA bounds now so that we have them for later.
  254. if (D.getType()->isVariablyModifiedType())
  255. EmitVariablyModifiedType(D.getType());
  256. // Local static block variables must be treated as globals as they may be
  257. // referenced in their RHS initializer block-literal expresion.
  258. CGM.setStaticLocalDeclAddress(&D, GV);
  259. // If this value has an initializer, emit it.
  260. if (D.getInit())
  261. GV = AddInitializerToStaticVarDecl(D, GV);
  262. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  263. if (D.hasAttr<AnnotateAttr>())
  264. CGM.AddGlobalAnnotations(&D, GV);
  265. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  266. GV->setSection(SA->getName());
  267. if (D.hasAttr<UsedAttr>())
  268. CGM.AddUsedGlobal(GV);
  269. // We may have to cast the constant because of the initializer
  270. // mismatch above.
  271. //
  272. // FIXME: It is really dangerous to store this in the map; if anyone
  273. // RAUW's the GV uses of this constant will be invalid.
  274. llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
  275. llvm::Type *LPtrTy =
  276. LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
  277. DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
  278. // Emit global variable debug descriptor for static vars.
  279. CGDebugInfo *DI = getDebugInfo();
  280. if (DI) {
  281. DI->setLocation(D.getLocation());
  282. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
  283. }
  284. }
  285. namespace {
  286. struct DestroyObject : EHScopeStack::Cleanup {
  287. DestroyObject(llvm::Value *addr, QualType type,
  288. CodeGenFunction::Destroyer *destroyer,
  289. bool useEHCleanupForArray)
  290. : addr(addr), type(type), destroyer(destroyer),
  291. useEHCleanupForArray(useEHCleanupForArray) {}
  292. llvm::Value *addr;
  293. QualType type;
  294. CodeGenFunction::Destroyer *destroyer;
  295. bool useEHCleanupForArray;
  296. void Emit(CodeGenFunction &CGF, Flags flags) {
  297. // Don't use an EH cleanup recursively from an EH cleanup.
  298. bool useEHCleanupForArray =
  299. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  300. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  301. }
  302. };
  303. struct DestroyNRVOVariable : EHScopeStack::Cleanup {
  304. DestroyNRVOVariable(llvm::Value *addr,
  305. const CXXDestructorDecl *Dtor,
  306. llvm::Value *NRVOFlag)
  307. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  308. const CXXDestructorDecl *Dtor;
  309. llvm::Value *NRVOFlag;
  310. llvm::Value *Loc;
  311. void Emit(CodeGenFunction &CGF, Flags flags) {
  312. // Along the exceptions path we always execute the dtor.
  313. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  314. llvm::BasicBlock *SkipDtorBB = 0;
  315. if (NRVO) {
  316. // If we exited via NRVO, we skip the destructor call.
  317. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  318. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  319. llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
  320. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  321. CGF.EmitBlock(RunDtorBB);
  322. }
  323. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  324. /*ForVirtualBase=*/false, Loc);
  325. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  326. }
  327. };
  328. struct CallStackRestore : EHScopeStack::Cleanup {
  329. llvm::Value *Stack;
  330. CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
  331. void Emit(CodeGenFunction &CGF, Flags flags) {
  332. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  333. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  334. CGF.Builder.CreateCall(F, V);
  335. }
  336. };
  337. struct ExtendGCLifetime : EHScopeStack::Cleanup {
  338. const VarDecl &Var;
  339. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  340. void Emit(CodeGenFunction &CGF, Flags flags) {
  341. // Compute the address of the local variable, in case it's a
  342. // byref or something.
  343. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
  344. SourceLocation());
  345. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
  346. CGF.EmitExtendGCLifetime(value);
  347. }
  348. };
  349. struct CallCleanupFunction : EHScopeStack::Cleanup {
  350. llvm::Constant *CleanupFn;
  351. const CGFunctionInfo &FnInfo;
  352. const VarDecl &Var;
  353. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  354. const VarDecl *Var)
  355. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  356. void Emit(CodeGenFunction &CGF, Flags flags) {
  357. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
  358. SourceLocation());
  359. // Compute the address of the local variable, in case it's a byref
  360. // or something.
  361. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
  362. // In some cases, the type of the function argument will be different from
  363. // the type of the pointer. An example of this is
  364. // void f(void* arg);
  365. // __attribute__((cleanup(f))) void *g;
  366. //
  367. // To fix this we insert a bitcast here.
  368. QualType ArgTy = FnInfo.arg_begin()->type;
  369. llvm::Value *Arg =
  370. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  371. CallArgList Args;
  372. Args.add(RValue::get(Arg),
  373. CGF.getContext().getPointerType(Var.getType()));
  374. CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
  375. }
  376. };
  377. }
  378. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  379. /// variable with lifetime.
  380. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  381. llvm::Value *addr,
  382. Qualifiers::ObjCLifetime lifetime) {
  383. switch (lifetime) {
  384. case Qualifiers::OCL_None:
  385. llvm_unreachable("present but none");
  386. case Qualifiers::OCL_ExplicitNone:
  387. // nothing to do
  388. break;
  389. case Qualifiers::OCL_Strong: {
  390. CodeGenFunction::Destroyer *destroyer =
  391. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  392. ? CodeGenFunction::destroyARCStrongPrecise
  393. : CodeGenFunction::destroyARCStrongImprecise);
  394. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  395. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  396. cleanupKind & EHCleanup);
  397. break;
  398. }
  399. case Qualifiers::OCL_Autoreleasing:
  400. // nothing to do
  401. break;
  402. case Qualifiers::OCL_Weak:
  403. // __weak objects always get EH cleanups; otherwise, exceptions
  404. // could cause really nasty crashes instead of mere leaks.
  405. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  406. CodeGenFunction::destroyARCWeak,
  407. /*useEHCleanup*/ true);
  408. break;
  409. }
  410. }
  411. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  412. if (const Expr *e = dyn_cast<Expr>(s)) {
  413. // Skip the most common kinds of expressions that make
  414. // hierarchy-walking expensive.
  415. s = e = e->IgnoreParenCasts();
  416. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  417. return (ref->getDecl() == &var);
  418. }
  419. for (Stmt::const_child_range children = s->children(); children; ++children)
  420. // children might be null; as in missing decl or conditional of an if-stmt.
  421. if ((*children) && isAccessedBy(var, *children))
  422. return true;
  423. return false;
  424. }
  425. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  426. if (!decl) return false;
  427. if (!isa<VarDecl>(decl)) return false;
  428. const VarDecl *var = cast<VarDecl>(decl);
  429. return isAccessedBy(*var, e);
  430. }
  431. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  432. LValue &lvalue,
  433. const VarDecl *var) {
  434. lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
  435. }
  436. void CodeGenFunction::EmitScalarInit(const Expr *init,
  437. const ValueDecl *D,
  438. LValue lvalue,
  439. bool capturedByInit) {
  440. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  441. if (!lifetime) {
  442. llvm::Value *value = EmitScalarExpr(init);
  443. if (capturedByInit)
  444. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  445. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  446. return;
  447. }
  448. // If we're emitting a value with lifetime, we have to do the
  449. // initialization *before* we leave the cleanup scopes.
  450. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  451. enterFullExpression(ewc);
  452. init = ewc->getSubExpr();
  453. }
  454. CodeGenFunction::RunCleanupsScope Scope(*this);
  455. // We have to maintain the illusion that the variable is
  456. // zero-initialized. If the variable might be accessed in its
  457. // initializer, zero-initialize before running the initializer, then
  458. // actually perform the initialization with an assign.
  459. bool accessedByInit = false;
  460. if (lifetime != Qualifiers::OCL_ExplicitNone)
  461. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  462. if (accessedByInit) {
  463. LValue tempLV = lvalue;
  464. // Drill down to the __block object if necessary.
  465. if (capturedByInit) {
  466. // We can use a simple GEP for this because it can't have been
  467. // moved yet.
  468. tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
  469. getByRefValueLLVMField(cast<VarDecl>(D))));
  470. }
  471. llvm::PointerType *ty
  472. = cast<llvm::PointerType>(tempLV.getAddress()->getType());
  473. ty = cast<llvm::PointerType>(ty->getElementType());
  474. llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
  475. // If __weak, we want to use a barrier under certain conditions.
  476. if (lifetime == Qualifiers::OCL_Weak)
  477. EmitARCInitWeak(tempLV.getAddress(), zero);
  478. // Otherwise just do a simple store.
  479. else
  480. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  481. }
  482. // Emit the initializer.
  483. llvm::Value *value = 0;
  484. switch (lifetime) {
  485. case Qualifiers::OCL_None:
  486. llvm_unreachable("present but none");
  487. case Qualifiers::OCL_ExplicitNone:
  488. // nothing to do
  489. value = EmitScalarExpr(init);
  490. break;
  491. case Qualifiers::OCL_Strong: {
  492. value = EmitARCRetainScalarExpr(init);
  493. break;
  494. }
  495. case Qualifiers::OCL_Weak: {
  496. // No way to optimize a producing initializer into this. It's not
  497. // worth optimizing for, because the value will immediately
  498. // disappear in the common case.
  499. value = EmitScalarExpr(init);
  500. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  501. if (accessedByInit)
  502. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  503. else
  504. EmitARCInitWeak(lvalue.getAddress(), value);
  505. return;
  506. }
  507. case Qualifiers::OCL_Autoreleasing:
  508. value = EmitARCRetainAutoreleaseScalarExpr(init);
  509. break;
  510. }
  511. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  512. // If the variable might have been accessed by its initializer, we
  513. // might have to initialize with a barrier. We have to do this for
  514. // both __weak and __strong, but __weak got filtered out above.
  515. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  516. llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
  517. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  518. EmitARCRelease(oldValue, /*precise*/ false);
  519. return;
  520. }
  521. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  522. }
  523. /// EmitScalarInit - Initialize the given lvalue with the given object.
  524. void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
  525. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  526. if (!lifetime)
  527. return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
  528. switch (lifetime) {
  529. case Qualifiers::OCL_None:
  530. llvm_unreachable("present but none");
  531. case Qualifiers::OCL_ExplicitNone:
  532. // nothing to do
  533. break;
  534. case Qualifiers::OCL_Strong:
  535. init = EmitARCRetain(lvalue.getType(), init);
  536. break;
  537. case Qualifiers::OCL_Weak:
  538. // Initialize and then skip the primitive store.
  539. EmitARCInitWeak(lvalue.getAddress(), init);
  540. return;
  541. case Qualifiers::OCL_Autoreleasing:
  542. init = EmitARCRetainAutorelease(lvalue.getType(), init);
  543. break;
  544. }
  545. EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
  546. }
  547. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  548. /// non-zero parts of the specified initializer with equal or fewer than
  549. /// NumStores scalar stores.
  550. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  551. unsigned &NumStores) {
  552. // Zero and Undef never requires any extra stores.
  553. if (isa<llvm::ConstantAggregateZero>(Init) ||
  554. isa<llvm::ConstantPointerNull>(Init) ||
  555. isa<llvm::UndefValue>(Init))
  556. return true;
  557. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  558. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  559. isa<llvm::ConstantExpr>(Init))
  560. return Init->isNullValue() || NumStores--;
  561. // See if we can emit each element.
  562. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  563. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  564. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  565. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  566. return false;
  567. }
  568. return true;
  569. }
  570. if (llvm::ConstantDataSequential *CDS =
  571. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  572. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  573. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  574. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  575. return false;
  576. }
  577. return true;
  578. }
  579. // Anything else is hard and scary.
  580. return false;
  581. }
  582. /// emitStoresForInitAfterMemset - For inits that
  583. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  584. /// stores that would be required.
  585. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  586. bool isVolatile, CGBuilderTy &Builder) {
  587. // Zero doesn't require a store.
  588. if (Init->isNullValue() || isa<llvm::UndefValue>(Init))
  589. return;
  590. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  591. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  592. isa<llvm::ConstantExpr>(Init)) {
  593. Builder.CreateStore(Init, Loc, isVolatile);
  594. return;
  595. }
  596. if (llvm::ConstantDataSequential *CDS =
  597. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  598. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  599. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  600. // Get a pointer to the element and emit it.
  601. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  602. isVolatile, Builder);
  603. }
  604. return;
  605. }
  606. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  607. "Unknown value type!");
  608. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  609. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  610. // Get a pointer to the element and emit it.
  611. emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
  612. isVolatile, Builder);
  613. }
  614. }
  615. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  616. /// plus some stores to initialize a local variable instead of using a memcpy
  617. /// from a constant global. It is beneficial to use memset if the global is all
  618. /// zeros, or mostly zeros and large.
  619. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  620. uint64_t GlobalSize) {
  621. // If a global is all zeros, always use a memset.
  622. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  623. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  624. // do it if it will require 6 or fewer scalar stores.
  625. // TODO: Should budget depends on the size? Avoiding a large global warrants
  626. // plopping in more stores.
  627. unsigned StoreBudget = 6;
  628. uint64_t SizeLimit = 32;
  629. return GlobalSize > SizeLimit &&
  630. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  631. }
  632. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  633. /// variable declaration with auto, register, or no storage class specifier.
  634. /// These turn into simple stack objects, or GlobalValues depending on target.
  635. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  636. AutoVarEmission emission = EmitAutoVarAlloca(D);
  637. EmitAutoVarInit(emission);
  638. EmitAutoVarCleanups(emission);
  639. }
  640. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  641. /// local variable. Does not emit initalization or destruction.
  642. CodeGenFunction::AutoVarEmission
  643. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  644. QualType Ty = D.getType();
  645. AutoVarEmission emission(D);
  646. bool isByRef = D.hasAttr<BlocksAttr>();
  647. emission.IsByRef = isByRef;
  648. CharUnits alignment = getContext().getDeclAlign(&D);
  649. emission.Alignment = alignment;
  650. // If the type is variably-modified, emit all the VLA sizes for it.
  651. if (Ty->isVariablyModifiedType())
  652. EmitVariablyModifiedType(Ty);
  653. llvm::Value *DeclPtr;
  654. if (Ty->isConstantSizeType()) {
  655. if (!Target.useGlobalsForAutomaticVariables()) {
  656. bool NRVO = getContext().getLangOptions().ElideConstructors &&
  657. D.isNRVOVariable();
  658. // If this value is a POD array or struct with a statically
  659. // determinable constant initializer, there are optimizations we can do.
  660. //
  661. // TODO: we should constant-evaluate any variable of literal type
  662. // as long as it is initialized by a constant expression. Currently,
  663. // isConstantInitializer produces wrong answers for structs with
  664. // reference or bitfield members, and a few other cases, and checking
  665. // for POD-ness protects us from some of these.
  666. if (D.getInit() &&
  667. (Ty->isArrayType() || Ty->isRecordType()) &&
  668. (Ty.isPODType(getContext()) ||
  669. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  670. D.getInit()->isConstantInitializer(getContext(), false)) {
  671. // If the variable's a const type, and it's neither an NRVO
  672. // candidate nor a __block variable and has no mutable members,
  673. // emit it as a global instead.
  674. if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() &&
  675. !NRVO && !isByRef && Ty->isLiteralType()) {
  676. CXXRecordDecl *RD =
  677. Ty->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  678. if (!RD || !RD->hasMutableFields()) {
  679. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  680. emission.Address = 0; // signal this condition to later callbacks
  681. assert(emission.wasEmittedAsGlobal());
  682. return emission;
  683. }
  684. }
  685. // Otherwise, tell the initialization code that we're in this case.
  686. emission.IsConstantAggregate = true;
  687. }
  688. // A normal fixed sized variable becomes an alloca in the entry block,
  689. // unless it's an NRVO variable.
  690. llvm::Type *LTy = ConvertTypeForMem(Ty);
  691. if (NRVO) {
  692. // The named return value optimization: allocate this variable in the
  693. // return slot, so that we can elide the copy when returning this
  694. // variable (C++0x [class.copy]p34).
  695. DeclPtr = ReturnValue;
  696. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  697. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  698. // Create a flag that is used to indicate when the NRVO was applied
  699. // to this variable. Set it to zero to indicate that NRVO was not
  700. // applied.
  701. llvm::Value *Zero = Builder.getFalse();
  702. llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
  703. EnsureInsertPoint();
  704. Builder.CreateStore(Zero, NRVOFlag);
  705. // Record the NRVO flag for this variable.
  706. NRVOFlags[&D] = NRVOFlag;
  707. emission.NRVOFlag = NRVOFlag;
  708. }
  709. }
  710. } else {
  711. if (isByRef)
  712. LTy = BuildByRefType(&D);
  713. llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
  714. Alloc->setName(D.getName());
  715. CharUnits allocaAlignment = alignment;
  716. if (isByRef)
  717. allocaAlignment = std::max(allocaAlignment,
  718. getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
  719. Alloc->setAlignment(allocaAlignment.getQuantity());
  720. DeclPtr = Alloc;
  721. }
  722. } else {
  723. // Targets that don't support recursion emit locals as globals.
  724. const char *Class =
  725. D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
  726. DeclPtr = CreateStaticVarDecl(D, Class,
  727. llvm::GlobalValue::InternalLinkage);
  728. }
  729. } else {
  730. EnsureInsertPoint();
  731. if (!DidCallStackSave) {
  732. // Save the stack.
  733. llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
  734. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  735. llvm::Value *V = Builder.CreateCall(F);
  736. Builder.CreateStore(V, Stack);
  737. DidCallStackSave = true;
  738. // Push a cleanup block and restore the stack there.
  739. // FIXME: in general circumstances, this should be an EH cleanup.
  740. EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
  741. }
  742. llvm::Value *elementCount;
  743. QualType elementType;
  744. llvm::tie(elementCount, elementType) = getVLASize(Ty);
  745. llvm::Type *llvmTy = ConvertTypeForMem(elementType);
  746. // Allocate memory for the array.
  747. llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
  748. vla->setAlignment(alignment.getQuantity());
  749. DeclPtr = vla;
  750. }
  751. llvm::Value *&DMEntry = LocalDeclMap[&D];
  752. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  753. DMEntry = DeclPtr;
  754. emission.Address = DeclPtr;
  755. // Emit debug info for local var declaration.
  756. if (HaveInsertPoint())
  757. if (CGDebugInfo *DI = getDebugInfo()) {
  758. DI->setLocation(D.getLocation());
  759. if (Target.useGlobalsForAutomaticVariables()) {
  760. DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
  761. } else
  762. DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
  763. }
  764. if (D.hasAttr<AnnotateAttr>())
  765. EmitVarAnnotations(&D, emission.Address);
  766. return emission;
  767. }
  768. /// Determines whether the given __block variable is potentially
  769. /// captured by the given expression.
  770. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  771. // Skip the most common kinds of expressions that make
  772. // hierarchy-walking expensive.
  773. e = e->IgnoreParenCasts();
  774. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  775. const BlockDecl *block = be->getBlockDecl();
  776. for (BlockDecl::capture_const_iterator i = block->capture_begin(),
  777. e = block->capture_end(); i != e; ++i) {
  778. if (i->getVariable() == &var)
  779. return true;
  780. }
  781. // No need to walk into the subexpressions.
  782. return false;
  783. }
  784. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  785. const CompoundStmt *CS = SE->getSubStmt();
  786. for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
  787. BE = CS->body_end(); BI != BE; ++BI)
  788. if (Expr *E = dyn_cast<Expr>((*BI))) {
  789. if (isCapturedBy(var, E))
  790. return true;
  791. }
  792. else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
  793. // special case declarations
  794. for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
  795. I != E; ++I) {
  796. if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
  797. Expr *Init = VD->getInit();
  798. if (Init && isCapturedBy(var, Init))
  799. return true;
  800. }
  801. }
  802. }
  803. else
  804. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  805. // Later, provide code to poke into statements for capture analysis.
  806. return true;
  807. return false;
  808. }
  809. for (Stmt::const_child_range children = e->children(); children; ++children)
  810. if (isCapturedBy(var, cast<Expr>(*children)))
  811. return true;
  812. return false;
  813. }
  814. /// \brief Determine whether the given initializer is trivial in the sense
  815. /// that it requires no code to be generated.
  816. static bool isTrivialInitializer(const Expr *Init) {
  817. if (!Init)
  818. return true;
  819. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  820. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  821. if (Constructor->isTrivial() &&
  822. Constructor->isDefaultConstructor() &&
  823. !Construct->requiresZeroInitialization())
  824. return true;
  825. return false;
  826. }
  827. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  828. assert(emission.Variable && "emission was not valid!");
  829. // If this was emitted as a global constant, we're done.
  830. if (emission.wasEmittedAsGlobal()) return;
  831. const VarDecl &D = *emission.Variable;
  832. QualType type = D.getType();
  833. // If this local has an initializer, emit it now.
  834. const Expr *Init = D.getInit();
  835. // If we are at an unreachable point, we don't need to emit the initializer
  836. // unless it contains a label.
  837. if (!HaveInsertPoint()) {
  838. if (!Init || !ContainsLabel(Init)) return;
  839. EnsureInsertPoint();
  840. }
  841. // Initialize the structure of a __block variable.
  842. if (emission.IsByRef)
  843. emitByrefStructureInit(emission);
  844. if (isTrivialInitializer(Init))
  845. return;
  846. CharUnits alignment = emission.Alignment;
  847. // Check whether this is a byref variable that's potentially
  848. // captured and moved by its own initializer. If so, we'll need to
  849. // emit the initializer first, then copy into the variable.
  850. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  851. llvm::Value *Loc =
  852. capturedByInit ? emission.Address : emission.getObjectAddress(*this);
  853. llvm::Constant *constant = 0;
  854. if (emission.IsConstantAggregate) {
  855. assert(!capturedByInit && "constant init contains a capturing block?");
  856. constant = CGM.EmitConstantInit(D, this);
  857. }
  858. if (!constant) {
  859. LValue lv = MakeAddrLValue(Loc, type, alignment);
  860. lv.setNonGC(true);
  861. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  862. }
  863. // If this is a simple aggregate initialization, we can optimize it
  864. // in various ways.
  865. bool isVolatile = type.isVolatileQualified();
  866. llvm::Value *SizeVal =
  867. llvm::ConstantInt::get(IntPtrTy,
  868. getContext().getTypeSizeInChars(type).getQuantity());
  869. llvm::Type *BP = Int8PtrTy;
  870. if (Loc->getType() != BP)
  871. Loc = Builder.CreateBitCast(Loc, BP);
  872. // If the initializer is all or mostly zeros, codegen with memset then do
  873. // a few stores afterward.
  874. if (shouldUseMemSetPlusStoresToInitialize(constant,
  875. CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
  876. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  877. alignment.getQuantity(), isVolatile);
  878. if (!constant->isNullValue()) {
  879. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  880. emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
  881. }
  882. } else {
  883. // Otherwise, create a temporary global with the initializer then
  884. // memcpy from the global to the alloca.
  885. std::string Name = GetStaticDeclName(*this, D, ".");
  886. llvm::GlobalVariable *GV =
  887. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  888. llvm::GlobalValue::PrivateLinkage,
  889. constant, Name, 0, false, 0);
  890. GV->setAlignment(alignment.getQuantity());
  891. GV->setUnnamedAddr(true);
  892. llvm::Value *SrcPtr = GV;
  893. if (SrcPtr->getType() != BP)
  894. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  895. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
  896. isVolatile);
  897. }
  898. }
  899. /// Emit an expression as an initializer for a variable at the given
  900. /// location. The expression is not necessarily the normal
  901. /// initializer for the variable, and the address is not necessarily
  902. /// its normal location.
  903. ///
  904. /// \param init the initializing expression
  905. /// \param var the variable to act as if we're initializing
  906. /// \param loc the address to initialize; its type is a pointer
  907. /// to the LLVM mapping of the variable's type
  908. /// \param alignment the alignment of the address
  909. /// \param capturedByInit true if the variable is a __block variable
  910. /// whose address is potentially changed by the initializer
  911. void CodeGenFunction::EmitExprAsInit(const Expr *init,
  912. const ValueDecl *D,
  913. LValue lvalue,
  914. bool capturedByInit) {
  915. QualType type = D->getType();
  916. if (type->isReferenceType()) {
  917. RValue rvalue = EmitReferenceBindingToExpr(init, D);
  918. if (capturedByInit)
  919. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  920. EmitStoreThroughLValue(rvalue, lvalue, true);
  921. } else if (!hasAggregateLLVMType(type)) {
  922. EmitScalarInit(init, D, lvalue, capturedByInit);
  923. } else if (type->isAnyComplexType()) {
  924. ComplexPairTy complex = EmitComplexExpr(init);
  925. if (capturedByInit)
  926. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  927. StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
  928. } else {
  929. // TODO: how can we delay here if D is captured by its initializer?
  930. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  931. AggValueSlot::IsDestructed,
  932. AggValueSlot::DoesNotNeedGCBarriers,
  933. AggValueSlot::IsNotAliased));
  934. }
  935. }
  936. /// Enter a destroy cleanup for the given local variable.
  937. void CodeGenFunction::emitAutoVarTypeCleanup(
  938. const CodeGenFunction::AutoVarEmission &emission,
  939. QualType::DestructionKind dtorKind) {
  940. assert(dtorKind != QualType::DK_none);
  941. // Note that for __block variables, we want to destroy the
  942. // original stack object, not the possibly forwarded object.
  943. llvm::Value *addr = emission.getObjectAddress(*this);
  944. const VarDecl *var = emission.Variable;
  945. QualType type = var->getType();
  946. CleanupKind cleanupKind = NormalAndEHCleanup;
  947. CodeGenFunction::Destroyer *destroyer = 0;
  948. switch (dtorKind) {
  949. case QualType::DK_none:
  950. llvm_unreachable("no cleanup for trivially-destructible variable");
  951. case QualType::DK_cxx_destructor:
  952. // If there's an NRVO flag on the emission, we need a different
  953. // cleanup.
  954. if (emission.NRVOFlag) {
  955. assert(!type->isArrayType());
  956. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  957. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
  958. emission.NRVOFlag);
  959. return;
  960. }
  961. break;
  962. case QualType::DK_objc_strong_lifetime:
  963. // Suppress cleanups for pseudo-strong variables.
  964. if (var->isARCPseudoStrong()) return;
  965. // Otherwise, consider whether to use an EH cleanup or not.
  966. cleanupKind = getARCCleanupKind();
  967. // Use the imprecise destroyer by default.
  968. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  969. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  970. break;
  971. case QualType::DK_objc_weak_lifetime:
  972. break;
  973. }
  974. // If we haven't chosen a more specific destroyer, use the default.
  975. if (!destroyer) destroyer = getDestroyer(dtorKind);
  976. // Use an EH cleanup in array destructors iff the destructor itself
  977. // is being pushed as an EH cleanup.
  978. bool useEHCleanup = (cleanupKind & EHCleanup);
  979. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  980. useEHCleanup);
  981. }
  982. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  983. assert(emission.Variable && "emission was not valid!");
  984. // If this was emitted as a global constant, we're done.
  985. if (emission.wasEmittedAsGlobal()) return;
  986. const VarDecl &D = *emission.Variable;
  987. // Check the type for a cleanup.
  988. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  989. emitAutoVarTypeCleanup(emission, dtorKind);
  990. // In GC mode, honor objc_precise_lifetime.
  991. if (getLangOptions().getGC() != LangOptions::NonGC &&
  992. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  993. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  994. }
  995. // Handle the cleanup attribute.
  996. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  997. const FunctionDecl *FD = CA->getFunctionDecl();
  998. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  999. assert(F && "Could not find function!");
  1000. const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
  1001. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1002. }
  1003. // If this is a block variable, call _Block_object_destroy
  1004. // (on the unforwarded address).
  1005. if (emission.IsByRef)
  1006. enterByrefCleanup(emission);
  1007. }
  1008. CodeGenFunction::Destroyer *
  1009. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1010. switch (kind) {
  1011. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1012. case QualType::DK_cxx_destructor:
  1013. return destroyCXXObject;
  1014. case QualType::DK_objc_strong_lifetime:
  1015. return destroyARCStrongPrecise;
  1016. case QualType::DK_objc_weak_lifetime:
  1017. return destroyARCWeak;
  1018. }
  1019. llvm_unreachable("Unknown DestructionKind");
  1020. }
  1021. /// pushDestroy - Push the standard destructor for the given type.
  1022. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1023. llvm::Value *addr, QualType type) {
  1024. assert(dtorKind && "cannot push destructor for trivial type");
  1025. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1026. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1027. cleanupKind & EHCleanup);
  1028. }
  1029. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
  1030. QualType type, Destroyer *destroyer,
  1031. bool useEHCleanupForArray) {
  1032. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1033. destroyer, useEHCleanupForArray);
  1034. }
  1035. /// emitDestroy - Immediately perform the destruction of the given
  1036. /// object.
  1037. ///
  1038. /// \param addr - the address of the object; a type*
  1039. /// \param type - the type of the object; if an array type, all
  1040. /// objects are destroyed in reverse order
  1041. /// \param destroyer - the function to call to destroy individual
  1042. /// elements
  1043. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1044. /// used when destroying array elements, in case one of the
  1045. /// destructions throws an exception
  1046. void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
  1047. Destroyer *destroyer,
  1048. bool useEHCleanupForArray) {
  1049. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1050. if (!arrayType)
  1051. return destroyer(*this, addr, type);
  1052. llvm::Value *begin = addr;
  1053. llvm::Value *length = emitArrayLength(arrayType, type, begin);
  1054. // Normally we have to check whether the array is zero-length.
  1055. bool checkZeroLength = true;
  1056. // But if the array length is constant, we can suppress that.
  1057. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1058. // ...and if it's constant zero, we can just skip the entire thing.
  1059. if (constLength->isZero()) return;
  1060. checkZeroLength = false;
  1061. }
  1062. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1063. emitArrayDestroy(begin, end, type, destroyer,
  1064. checkZeroLength, useEHCleanupForArray);
  1065. }
  1066. /// emitArrayDestroy - Destroys all the elements of the given array,
  1067. /// beginning from last to first. The array cannot be zero-length.
  1068. ///
  1069. /// \param begin - a type* denoting the first element of the array
  1070. /// \param end - a type* denoting one past the end of the array
  1071. /// \param type - the element type of the array
  1072. /// \param destroyer - the function to call to destroy elements
  1073. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1074. /// the remaining elements in case the destruction of a single
  1075. /// element throws
  1076. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1077. llvm::Value *end,
  1078. QualType type,
  1079. Destroyer *destroyer,
  1080. bool checkZeroLength,
  1081. bool useEHCleanup) {
  1082. assert(!type->isArrayType());
  1083. // The basic structure here is a do-while loop, because we don't
  1084. // need to check for the zero-element case.
  1085. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1086. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1087. if (checkZeroLength) {
  1088. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1089. "arraydestroy.isempty");
  1090. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1091. }
  1092. // Enter the loop body, making that address the current address.
  1093. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1094. EmitBlock(bodyBB);
  1095. llvm::PHINode *elementPast =
  1096. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1097. elementPast->addIncoming(end, entryBB);
  1098. // Shift the address back by one element.
  1099. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1100. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1101. "arraydestroy.element");
  1102. if (useEHCleanup)
  1103. pushRegularPartialArrayCleanup(begin, element, type, destroyer);
  1104. // Perform the actual destruction there.
  1105. destroyer(*this, element, type);
  1106. if (useEHCleanup)
  1107. PopCleanupBlock();
  1108. // Check whether we've reached the end.
  1109. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1110. Builder.CreateCondBr(done, doneBB, bodyBB);
  1111. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1112. // Done.
  1113. EmitBlock(doneBB);
  1114. }
  1115. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1116. /// emitArrayDestroy, the element type here may still be an array type.
  1117. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1118. llvm::Value *begin, llvm::Value *end,
  1119. QualType type,
  1120. CodeGenFunction::Destroyer *destroyer) {
  1121. // If the element type is itself an array, drill down.
  1122. unsigned arrayDepth = 0;
  1123. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1124. // VLAs don't require a GEP index to walk into.
  1125. if (!isa<VariableArrayType>(arrayType))
  1126. arrayDepth++;
  1127. type = arrayType->getElementType();
  1128. }
  1129. if (arrayDepth) {
  1130. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
  1131. SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
  1132. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1133. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1134. }
  1135. // Destroy the array. We don't ever need an EH cleanup because we
  1136. // assume that we're in an EH cleanup ourselves, so a throwing
  1137. // destructor causes an immediate terminate.
  1138. CGF.emitArrayDestroy(begin, end, type, destroyer,
  1139. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1140. }
  1141. namespace {
  1142. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1143. /// array destroy where the end pointer is regularly determined and
  1144. /// does not need to be loaded from a local.
  1145. class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1146. llvm::Value *ArrayBegin;
  1147. llvm::Value *ArrayEnd;
  1148. QualType ElementType;
  1149. CodeGenFunction::Destroyer *Destroyer;
  1150. public:
  1151. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1152. QualType elementType,
  1153. CodeGenFunction::Destroyer *destroyer)
  1154. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1155. ElementType(elementType), Destroyer(destroyer) {}
  1156. void Emit(CodeGenFunction &CGF, Flags flags) {
  1157. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1158. ElementType, Destroyer);
  1159. }
  1160. };
  1161. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1162. /// partial array destroy where the end pointer is irregularly
  1163. /// determined and must be loaded from a local.
  1164. class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
  1165. llvm::Value *ArrayBegin;
  1166. llvm::Value *ArrayEndPointer;
  1167. QualType ElementType;
  1168. CodeGenFunction::Destroyer *Destroyer;
  1169. public:
  1170. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1171. llvm::Value *arrayEndPointer,
  1172. QualType elementType,
  1173. CodeGenFunction::Destroyer *destroyer)
  1174. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1175. ElementType(elementType), Destroyer(destroyer) {}
  1176. void Emit(CodeGenFunction &CGF, Flags flags) {
  1177. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1178. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1179. ElementType, Destroyer);
  1180. }
  1181. };
  1182. }
  1183. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1184. /// already-constructed elements of the given array. The cleanup
  1185. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1186. ///
  1187. /// \param elementType - the immediate element type of the array;
  1188. /// possibly still an array type
  1189. /// \param array - a value of type elementType*
  1190. /// \param destructionKind - the kind of destruction required
  1191. /// \param initializedElementCount - a value of type size_t* holding
  1192. /// the number of successfully-constructed elements
  1193. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1194. llvm::Value *arrayEndPointer,
  1195. QualType elementType,
  1196. Destroyer *destroyer) {
  1197. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1198. arrayBegin, arrayEndPointer,
  1199. elementType, destroyer);
  1200. }
  1201. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1202. /// already-constructed elements of the given array. The cleanup
  1203. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1204. ///
  1205. /// \param elementType - the immediate element type of the array;
  1206. /// possibly still an array type
  1207. /// \param array - a value of type elementType*
  1208. /// \param destructionKind - the kind of destruction required
  1209. /// \param initializedElementCount - a value of type size_t* holding
  1210. /// the number of successfully-constructed elements
  1211. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1212. llvm::Value *arrayEnd,
  1213. QualType elementType,
  1214. Destroyer *destroyer) {
  1215. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1216. arrayBegin, arrayEnd,
  1217. elementType, destroyer);
  1218. }
  1219. namespace {
  1220. /// A cleanup to perform a release of an object at the end of a
  1221. /// function. This is used to balance out the incoming +1 of a
  1222. /// ns_consumed argument when we can't reasonably do that just by
  1223. /// not doing the initial retain for a __block argument.
  1224. struct ConsumeARCParameter : EHScopeStack::Cleanup {
  1225. ConsumeARCParameter(llvm::Value *param) : Param(param) {}
  1226. llvm::Value *Param;
  1227. void Emit(CodeGenFunction &CGF, Flags flags) {
  1228. CGF.EmitARCRelease(Param, /*precise*/ false);
  1229. }
  1230. };
  1231. }
  1232. /// Emit an alloca (or GlobalValue depending on target)
  1233. /// for the specified parameter and set up LocalDeclMap.
  1234. void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
  1235. unsigned ArgNo) {
  1236. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1237. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1238. "Invalid argument to EmitParmDecl");
  1239. Arg->setName(D.getName());
  1240. // Use better IR generation for certain implicit parameters.
  1241. if (isa<ImplicitParamDecl>(D)) {
  1242. // The only implicit argument a block has is its literal.
  1243. if (BlockInfo) {
  1244. LocalDeclMap[&D] = Arg;
  1245. if (CGDebugInfo *DI = getDebugInfo()) {
  1246. DI->setLocation(D.getLocation());
  1247. DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
  1248. }
  1249. return;
  1250. }
  1251. }
  1252. QualType Ty = D.getType();
  1253. llvm::Value *DeclPtr;
  1254. // If this is an aggregate or variable sized value, reuse the input pointer.
  1255. if (!Ty->isConstantSizeType() ||
  1256. CodeGenFunction::hasAggregateLLVMType(Ty)) {
  1257. DeclPtr = Arg;
  1258. } else {
  1259. // Otherwise, create a temporary to hold the value.
  1260. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
  1261. D.getName() + ".addr");
  1262. Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  1263. DeclPtr = Alloc;
  1264. bool doStore = true;
  1265. Qualifiers qs = Ty.getQualifiers();
  1266. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1267. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1268. // For __strong, it's handled by just skipping the initial retain;
  1269. // otherwise we have to balance out the initial +1 with an extra
  1270. // cleanup to do the release at the end of the function.
  1271. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1272. // 'self' is always formally __strong, but if this is not an
  1273. // init method then we don't want to retain it.
  1274. if (D.isARCPseudoStrong()) {
  1275. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1276. assert(&D == method->getSelfDecl());
  1277. assert(lt == Qualifiers::OCL_Strong);
  1278. assert(qs.hasConst());
  1279. assert(method->getMethodFamily() != OMF_init);
  1280. (void) method;
  1281. lt = Qualifiers::OCL_ExplicitNone;
  1282. }
  1283. if (lt == Qualifiers::OCL_Strong) {
  1284. if (!isConsumed)
  1285. // Don't use objc_retainBlock for block pointers, because we
  1286. // don't want to Block_copy something just because we got it
  1287. // as a parameter.
  1288. Arg = EmitARCRetainNonBlock(Arg);
  1289. } else {
  1290. // Push the cleanup for a consumed parameter.
  1291. if (isConsumed)
  1292. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
  1293. if (lt == Qualifiers::OCL_Weak) {
  1294. EmitARCInitWeak(DeclPtr, Arg);
  1295. doStore = false; // The weak init is a store, no need to do two
  1296. }
  1297. }
  1298. // Enter the cleanup scope.
  1299. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1300. }
  1301. // Store the initial value into the alloca.
  1302. if (doStore) {
  1303. LValue lv = MakeAddrLValue(DeclPtr, Ty,
  1304. getContext().getDeclAlign(&D));
  1305. EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
  1306. }
  1307. }
  1308. llvm::Value *&DMEntry = LocalDeclMap[&D];
  1309. assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
  1310. DMEntry = DeclPtr;
  1311. // Emit debug info for param declaration.
  1312. if (CGDebugInfo *DI = getDebugInfo())
  1313. DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
  1314. if (D.hasAttr<AnnotateAttr>())
  1315. EmitVarAnnotations(&D, DeclPtr);
  1316. }