CodeGenModule.cpp 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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 coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CodeGenFunction.h"
  21. #include "CodeGenTBAA.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/CharUnits.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclTemplate.h"
  28. #include "clang/AST/Mangle.h"
  29. #include "clang/AST/RecordLayout.h"
  30. #include "clang/AST/RecursiveASTVisitor.h"
  31. #include "clang/Basic/Builtins.h"
  32. #include "clang/Basic/ConvertUTF.h"
  33. #include "clang/Basic/Diagnostic.h"
  34. #include "clang/Basic/Module.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Basic/TargetInfo.h"
  37. #include "clang/Frontend/CodeGenOptions.h"
  38. #include "llvm/ADT/APSInt.h"
  39. #include "llvm/ADT/Triple.h"
  40. #include "llvm/IR/CallingConv.h"
  41. #include "llvm/IR/DataLayout.h"
  42. #include "llvm/IR/Intrinsics.h"
  43. #include "llvm/IR/LLVMContext.h"
  44. #include "llvm/IR/Module.h"
  45. #include "llvm/Support/CallSite.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include "llvm/Target/Mangler.h"
  48. using namespace clang;
  49. using namespace CodeGen;
  50. static const char AnnotationSection[] = "llvm.metadata";
  51. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  52. switch (CGM.getContext().getTargetInfo().getCXXABI()) {
  53. case CXXABI_ARM: return *CreateARMCXXABI(CGM);
  54. case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
  55. case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
  56. }
  57. llvm_unreachable("invalid C++ ABI kind");
  58. }
  59. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  60. llvm::Module &M, const llvm::DataLayout &TD,
  61. DiagnosticsEngine &diags)
  62. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  63. TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags),
  64. ABI(createCXXABI(*this)),
  65. Types(*this),
  66. TBAA(0),
  67. VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
  68. DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
  69. RRData(0), CFConstantStringClassRef(0),
  70. ConstantStringClassRef(0), NSConstantStringType(0),
  71. VMContext(M.getContext()),
  72. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
  73. BlockObjectAssign(0), BlockObjectDispose(0),
  74. BlockDescriptorType(0), GenericBlockLiteralType(0),
  75. SanitizerBlacklist(CGO.SanitizerBlacklistFile),
  76. SanOpts(SanitizerBlacklist.isIn(M) ?
  77. SanitizerOptions::Disabled : LangOpts.Sanitize) {
  78. // Initialize the type cache.
  79. llvm::LLVMContext &LLVMContext = M.getContext();
  80. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  81. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  82. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  83. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  84. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  85. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  86. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  87. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  88. PointerAlignInBytes =
  89. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  90. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  91. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  92. Int8PtrTy = Int8Ty->getPointerTo(0);
  93. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  94. if (LangOpts.ObjC1)
  95. createObjCRuntime();
  96. if (LangOpts.OpenCL)
  97. createOpenCLRuntime();
  98. if (LangOpts.CUDA)
  99. createCUDARuntime();
  100. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  101. if (SanOpts.Thread ||
  102. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  103. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  104. ABI.getMangleContext());
  105. // If debug info or coverage generation is enabled, create the CGDebugInfo
  106. // object.
  107. if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
  108. CodeGenOpts.EmitGcovArcs ||
  109. CodeGenOpts.EmitGcovNotes)
  110. DebugInfo = new CGDebugInfo(*this);
  111. Block.GlobalUniqueCount = 0;
  112. if (C.getLangOpts().ObjCAutoRefCount)
  113. ARCData = new ARCEntrypoints();
  114. RRData = new RREntrypoints();
  115. }
  116. CodeGenModule::~CodeGenModule() {
  117. delete ObjCRuntime;
  118. delete OpenCLRuntime;
  119. delete CUDARuntime;
  120. delete TheTargetCodeGenInfo;
  121. delete &ABI;
  122. delete TBAA;
  123. delete DebugInfo;
  124. delete ARCData;
  125. delete RRData;
  126. }
  127. void CodeGenModule::createObjCRuntime() {
  128. // This is just isGNUFamily(), but we want to force implementors of
  129. // new ABIs to decide how best to do this.
  130. switch (LangOpts.ObjCRuntime.getKind()) {
  131. case ObjCRuntime::GNUstep:
  132. case ObjCRuntime::GCC:
  133. case ObjCRuntime::ObjFW:
  134. ObjCRuntime = CreateGNUObjCRuntime(*this);
  135. return;
  136. case ObjCRuntime::FragileMacOSX:
  137. case ObjCRuntime::MacOSX:
  138. case ObjCRuntime::iOS:
  139. ObjCRuntime = CreateMacObjCRuntime(*this);
  140. return;
  141. }
  142. llvm_unreachable("bad runtime kind");
  143. }
  144. void CodeGenModule::createOpenCLRuntime() {
  145. OpenCLRuntime = new CGOpenCLRuntime(*this);
  146. }
  147. void CodeGenModule::createCUDARuntime() {
  148. CUDARuntime = CreateNVCUDARuntime(*this);
  149. }
  150. void CodeGenModule::Release() {
  151. EmitDeferred();
  152. EmitCXXGlobalInitFunc();
  153. EmitCXXGlobalDtorFunc();
  154. if (ObjCRuntime)
  155. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  156. AddGlobalCtor(ObjCInitFunction);
  157. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  158. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  159. EmitGlobalAnnotations();
  160. EmitLLVMUsed();
  161. if (CodeGenOpts.ModulesAutolink) {
  162. EmitModuleLinkOptions();
  163. }
  164. SimplifyPersonality();
  165. if (getCodeGenOpts().EmitDeclMetadata)
  166. EmitDeclMetadata();
  167. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  168. EmitCoverageFile();
  169. if (DebugInfo)
  170. DebugInfo->finalize();
  171. }
  172. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  173. // Make sure that this type is translated.
  174. Types.UpdateCompletedType(TD);
  175. }
  176. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  177. if (!TBAA)
  178. return 0;
  179. return TBAA->getTBAAInfo(QTy);
  180. }
  181. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  182. if (!TBAA)
  183. return 0;
  184. return TBAA->getTBAAInfoForVTablePtr();
  185. }
  186. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  187. if (!TBAA)
  188. return 0;
  189. return TBAA->getTBAAStructInfo(QTy);
  190. }
  191. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  192. llvm::MDNode *TBAAInfo) {
  193. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  194. }
  195. bool CodeGenModule::isTargetDarwin() const {
  196. return getContext().getTargetInfo().getTriple().isOSDarwin();
  197. }
  198. void CodeGenModule::Error(SourceLocation loc, StringRef error) {
  199. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
  200. getDiags().Report(Context.getFullLoc(loc), diagID);
  201. }
  202. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  203. /// specified stmt yet.
  204. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
  205. bool OmitOnError) {
  206. if (OmitOnError && getDiags().hasErrorOccurred())
  207. return;
  208. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  209. "cannot compile this %0 yet");
  210. std::string Msg = Type;
  211. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  212. << Msg << S->getSourceRange();
  213. }
  214. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  215. /// specified decl yet.
  216. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
  217. bool OmitOnError) {
  218. if (OmitOnError && getDiags().hasErrorOccurred())
  219. return;
  220. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  221. "cannot compile this %0 yet");
  222. std::string Msg = Type;
  223. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  224. }
  225. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  226. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  227. }
  228. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  229. const NamedDecl *D) const {
  230. // Internal definitions always have default visibility.
  231. if (GV->hasLocalLinkage()) {
  232. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  233. return;
  234. }
  235. // Set visibility for definitions.
  236. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  237. if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  238. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  239. }
  240. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  241. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  242. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  243. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  244. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  245. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  246. }
  247. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  248. CodeGenOptions::TLSModel M) {
  249. switch (M) {
  250. case CodeGenOptions::GeneralDynamicTLSModel:
  251. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  252. case CodeGenOptions::LocalDynamicTLSModel:
  253. return llvm::GlobalVariable::LocalDynamicTLSModel;
  254. case CodeGenOptions::InitialExecTLSModel:
  255. return llvm::GlobalVariable::InitialExecTLSModel;
  256. case CodeGenOptions::LocalExecTLSModel:
  257. return llvm::GlobalVariable::LocalExecTLSModel;
  258. }
  259. llvm_unreachable("Invalid TLS model!");
  260. }
  261. void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
  262. const VarDecl &D) const {
  263. assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
  264. llvm::GlobalVariable::ThreadLocalMode TLM;
  265. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  266. // Override the TLS model if it is explicitly specified.
  267. if (D.hasAttr<TLSModelAttr>()) {
  268. const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
  269. TLM = GetLLVMTLSModel(Attr->getModel());
  270. }
  271. GV->setThreadLocalMode(TLM);
  272. }
  273. /// Set the symbol visibility of type information (vtable and RTTI)
  274. /// associated with the given type.
  275. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  276. const CXXRecordDecl *RD,
  277. TypeVisibilityKind TVK) const {
  278. setGlobalVisibility(GV, RD);
  279. if (!CodeGenOpts.HiddenWeakVTables)
  280. return;
  281. // We never want to drop the visibility for RTTI names.
  282. if (TVK == TVK_ForRTTIName)
  283. return;
  284. // We want to drop the visibility to hidden for weak type symbols.
  285. // This isn't possible if there might be unresolved references
  286. // elsewhere that rely on this symbol being visible.
  287. // This should be kept roughly in sync with setThunkVisibility
  288. // in CGVTables.cpp.
  289. // Preconditions.
  290. if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
  291. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  292. return;
  293. // Don't override an explicit visibility attribute.
  294. if (RD->getExplicitVisibility())
  295. return;
  296. switch (RD->getTemplateSpecializationKind()) {
  297. // We have to disable the optimization if this is an EI definition
  298. // because there might be EI declarations in other shared objects.
  299. case TSK_ExplicitInstantiationDefinition:
  300. case TSK_ExplicitInstantiationDeclaration:
  301. return;
  302. // Every use of a non-template class's type information has to emit it.
  303. case TSK_Undeclared:
  304. break;
  305. // In theory, implicit instantiations can ignore the possibility of
  306. // an explicit instantiation declaration because there necessarily
  307. // must be an EI definition somewhere with default visibility. In
  308. // practice, it's possible to have an explicit instantiation for
  309. // an arbitrary template class, and linkers aren't necessarily able
  310. // to deal with mixed-visibility symbols.
  311. case TSK_ExplicitSpecialization:
  312. case TSK_ImplicitInstantiation:
  313. return;
  314. }
  315. // If there's a key function, there may be translation units
  316. // that don't have the key function's definition. But ignore
  317. // this if we're emitting RTTI under -fno-rtti.
  318. if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
  319. if (Context.getKeyFunction(RD))
  320. return;
  321. }
  322. // Otherwise, drop the visibility to hidden.
  323. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  324. GV->setUnnamedAddr(true);
  325. }
  326. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  327. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  328. StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  329. if (!Str.empty())
  330. return Str;
  331. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  332. IdentifierInfo *II = ND->getIdentifier();
  333. assert(II && "Attempt to mangle unnamed decl.");
  334. Str = II->getName();
  335. return Str;
  336. }
  337. SmallString<256> Buffer;
  338. llvm::raw_svector_ostream Out(Buffer);
  339. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  340. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  341. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  342. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  343. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
  344. getCXXABI().getMangleContext().mangleBlock(BD, Out,
  345. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
  346. else
  347. getCXXABI().getMangleContext().mangleName(ND, Out);
  348. // Allocate space for the mangled name.
  349. Out.flush();
  350. size_t Length = Buffer.size();
  351. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  352. std::copy(Buffer.begin(), Buffer.end(), Name);
  353. Str = StringRef(Name, Length);
  354. return Str;
  355. }
  356. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  357. const BlockDecl *BD) {
  358. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  359. const Decl *D = GD.getDecl();
  360. llvm::raw_svector_ostream Out(Buffer.getBuffer());
  361. if (D == 0)
  362. MangleCtx.mangleGlobalBlock(BD,
  363. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  364. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  365. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  366. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  367. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  368. else
  369. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  370. }
  371. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  372. return getModule().getNamedValue(Name);
  373. }
  374. /// AddGlobalCtor - Add a function to the list that will be called before
  375. /// main() runs.
  376. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  377. // FIXME: Type coercion of void()* types.
  378. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  379. }
  380. /// AddGlobalDtor - Add a function to the list that will be called
  381. /// when the module is unloaded.
  382. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  383. // FIXME: Type coercion of void()* types.
  384. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  385. }
  386. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  387. // Ctor function type is void()*.
  388. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  389. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  390. // Get the type of a ctor entry, { i32, void ()* }.
  391. llvm::StructType *CtorStructTy =
  392. llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
  393. // Construct the constructor and destructor arrays.
  394. SmallVector<llvm::Constant*, 8> Ctors;
  395. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  396. llvm::Constant *S[] = {
  397. llvm::ConstantInt::get(Int32Ty, I->second, false),
  398. llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
  399. };
  400. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  401. }
  402. if (!Ctors.empty()) {
  403. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  404. new llvm::GlobalVariable(TheModule, AT, false,
  405. llvm::GlobalValue::AppendingLinkage,
  406. llvm::ConstantArray::get(AT, Ctors),
  407. GlobalName);
  408. }
  409. }
  410. llvm::GlobalValue::LinkageTypes
  411. CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
  412. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  413. if (Linkage == GVA_Internal)
  414. return llvm::Function::InternalLinkage;
  415. if (D->hasAttr<DLLExportAttr>())
  416. return llvm::Function::DLLExportLinkage;
  417. if (D->hasAttr<WeakAttr>())
  418. return llvm::Function::WeakAnyLinkage;
  419. // In C99 mode, 'inline' functions are guaranteed to have a strong
  420. // definition somewhere else, so we can use available_externally linkage.
  421. if (Linkage == GVA_C99Inline)
  422. return llvm::Function::AvailableExternallyLinkage;
  423. // Note that Apple's kernel linker doesn't support symbol
  424. // coalescing, so we need to avoid linkonce and weak linkages there.
  425. // Normally, this means we just map to internal, but for explicit
  426. // instantiations we'll map to external.
  427. // In C++, the compiler has to emit a definition in every translation unit
  428. // that references the function. We should use linkonce_odr because
  429. // a) if all references in this translation unit are optimized away, we
  430. // don't need to codegen it. b) if the function persists, it needs to be
  431. // merged with other definitions. c) C++ has the ODR, so we know the
  432. // definition is dependable.
  433. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  434. return !Context.getLangOpts().AppleKext
  435. ? llvm::Function::LinkOnceODRLinkage
  436. : llvm::Function::InternalLinkage;
  437. // An explicit instantiation of a template has weak linkage, since
  438. // explicit instantiations can occur in multiple translation units
  439. // and must all be equivalent. However, we are not allowed to
  440. // throw away these explicit instantiations.
  441. if (Linkage == GVA_ExplicitTemplateInstantiation)
  442. return !Context.getLangOpts().AppleKext
  443. ? llvm::Function::WeakODRLinkage
  444. : llvm::Function::ExternalLinkage;
  445. // Otherwise, we have strong external linkage.
  446. assert(Linkage == GVA_StrongExternal);
  447. return llvm::Function::ExternalLinkage;
  448. }
  449. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  450. ///
  451. /// FIXME: This is currently only done for aliases and functions, but not for
  452. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  453. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  454. llvm::GlobalValue *GV) {
  455. SetCommonAttributes(D, GV);
  456. }
  457. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  458. const CGFunctionInfo &Info,
  459. llvm::Function *F) {
  460. unsigned CallingConv;
  461. AttributeListType AttributeList;
  462. ConstructAttributeList(Info, D, AttributeList, CallingConv);
  463. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  464. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  465. }
  466. /// Determines whether the language options require us to model
  467. /// unwind exceptions. We treat -fexceptions as mandating this
  468. /// except under the fragile ObjC ABI with only ObjC exceptions
  469. /// enabled. This means, for example, that C with -fexceptions
  470. /// enables this.
  471. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  472. // If exceptions are completely disabled, obviously this is false.
  473. if (!LangOpts.Exceptions) return false;
  474. // If C++ exceptions are enabled, this is true.
  475. if (LangOpts.CXXExceptions) return true;
  476. // If ObjC exceptions are enabled, this depends on the ABI.
  477. if (LangOpts.ObjCExceptions) {
  478. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  479. }
  480. return true;
  481. }
  482. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  483. llvm::Function *F) {
  484. if (CodeGenOpts.UnwindTables)
  485. F->setHasUWTable();
  486. if (!hasUnwindExceptions(LangOpts))
  487. F->addFnAttr(llvm::Attribute::NoUnwind);
  488. if (D->hasAttr<NakedAttr>()) {
  489. // Naked implies noinline: we should not be inlining such functions.
  490. F->addFnAttr(llvm::Attribute::Naked);
  491. F->addFnAttr(llvm::Attribute::NoInline);
  492. }
  493. if (D->hasAttr<NoInlineAttr>())
  494. F->addFnAttr(llvm::Attribute::NoInline);
  495. // (noinline wins over always_inline, and we can't specify both in IR)
  496. if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
  497. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  498. llvm::Attribute::NoInline))
  499. F->addFnAttr(llvm::Attribute::AlwaysInline);
  500. // FIXME: Communicate hot and cold attributes to LLVM more directly.
  501. if (D->hasAttr<ColdAttr>())
  502. F->addFnAttr(llvm::Attribute::OptimizeForSize);
  503. if (D->hasAttr<MinSizeAttr>())
  504. F->addFnAttr(llvm::Attribute::MinSize);
  505. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  506. F->setUnnamedAddr(true);
  507. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
  508. if (MD->isVirtual())
  509. F->setUnnamedAddr(true);
  510. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  511. F->addFnAttr(llvm::Attribute::StackProtect);
  512. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  513. F->addFnAttr(llvm::Attribute::StackProtectReq);
  514. if (SanOpts.Address) {
  515. // When AddressSanitizer is enabled, set AddressSafety attribute
  516. // unless __attribute__((no_address_safety_analysis)) is used.
  517. if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
  518. F->addFnAttr(llvm::Attribute::AddressSafety);
  519. }
  520. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  521. if (alignment)
  522. F->setAlignment(alignment);
  523. // C++ ABI requires 2-byte alignment for member functions.
  524. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  525. F->setAlignment(2);
  526. }
  527. void CodeGenModule::SetCommonAttributes(const Decl *D,
  528. llvm::GlobalValue *GV) {
  529. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  530. setGlobalVisibility(GV, ND);
  531. else
  532. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  533. if (D->hasAttr<UsedAttr>())
  534. AddUsedGlobal(GV);
  535. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  536. GV->setSection(SA->getName());
  537. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  538. }
  539. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  540. llvm::Function *F,
  541. const CGFunctionInfo &FI) {
  542. SetLLVMFunctionAttributes(D, FI, F);
  543. SetLLVMFunctionAttributesForDefinition(D, F);
  544. F->setLinkage(llvm::Function::InternalLinkage);
  545. SetCommonAttributes(D, F);
  546. }
  547. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  548. llvm::Function *F,
  549. bool IsIncompleteFunction) {
  550. if (unsigned IID = F->getIntrinsicID()) {
  551. // If this is an intrinsic function, set the function's attributes
  552. // to the intrinsic's attributes.
  553. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
  554. (llvm::Intrinsic::ID)IID));
  555. return;
  556. }
  557. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  558. if (!IsIncompleteFunction)
  559. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  560. // Only a few attributes are set on declarations; these may later be
  561. // overridden by a definition.
  562. if (FD->hasAttr<DLLImportAttr>()) {
  563. F->setLinkage(llvm::Function::DLLImportLinkage);
  564. } else if (FD->hasAttr<WeakAttr>() ||
  565. FD->isWeakImported()) {
  566. // "extern_weak" is overloaded in LLVM; we probably should have
  567. // separate linkage types for this.
  568. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  569. } else {
  570. F->setLinkage(llvm::Function::ExternalLinkage);
  571. NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
  572. if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
  573. F->setVisibility(GetLLVMVisibility(LV.visibility()));
  574. }
  575. }
  576. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  577. F->setSection(SA->getName());
  578. }
  579. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  580. assert(!GV->isDeclaration() &&
  581. "Only globals with definition can force usage.");
  582. LLVMUsed.push_back(GV);
  583. }
  584. void CodeGenModule::EmitLLVMUsed() {
  585. // Don't create llvm.used if there is no need.
  586. if (LLVMUsed.empty())
  587. return;
  588. // Convert LLVMUsed to what ConstantArray needs.
  589. SmallVector<llvm::Constant*, 8> UsedArray;
  590. UsedArray.resize(LLVMUsed.size());
  591. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  592. UsedArray[i] =
  593. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  594. Int8PtrTy);
  595. }
  596. if (UsedArray.empty())
  597. return;
  598. llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
  599. llvm::GlobalVariable *GV =
  600. new llvm::GlobalVariable(getModule(), ATy, false,
  601. llvm::GlobalValue::AppendingLinkage,
  602. llvm::ConstantArray::get(ATy, UsedArray),
  603. "llvm.used");
  604. GV->setSection("llvm.metadata");
  605. }
  606. /// \brief Add link options implied by the given module, including modules
  607. /// it depends on, using a postorder walk.
  608. static void addLinkOptionsPostorder(llvm::LLVMContext &Context,
  609. Module *Mod,
  610. SmallVectorImpl<llvm::Value *> &Metadata,
  611. llvm::SmallPtrSet<Module *, 16> &Visited) {
  612. // Import this module's parent.
  613. if (Mod->Parent && Visited.insert(Mod->Parent)) {
  614. addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited);
  615. }
  616. // Import this module's dependencies.
  617. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  618. if (Visited.insert(Mod->Imports[I-1]))
  619. addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited);
  620. }
  621. // Add linker options to link against the libraries/frameworks
  622. // described by this module.
  623. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  624. // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
  625. // We need to know more about the linker to know how to encode these
  626. // options propertly.
  627. // Link against a framework.
  628. if (Mod->LinkLibraries[I-1].IsFramework) {
  629. llvm::Value *Args[2] = {
  630. llvm::MDString::get(Context, "-framework"),
  631. llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
  632. };
  633. Metadata.push_back(llvm::MDNode::get(Context, Args));
  634. continue;
  635. }
  636. // Link against a library.
  637. llvm::Value *OptString
  638. = llvm::MDString::get(Context,
  639. "-l" + Mod->LinkLibraries[I-1].Library);
  640. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  641. }
  642. }
  643. void CodeGenModule::EmitModuleLinkOptions() {
  644. // Collect the set of all of the modules we want to visit to emit link
  645. // options, which is essentially the imported modules and all of their
  646. // non-explicit child modules.
  647. llvm::SetVector<clang::Module *> LinkModules;
  648. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  649. SmallVector<clang::Module *, 16> Stack;
  650. // Seed the stack with imported modules.
  651. for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
  652. MEnd = ImportedModules.end();
  653. M != MEnd; ++M) {
  654. if (Visited.insert(*M))
  655. Stack.push_back(*M);
  656. }
  657. // Find all of the modules to import, making a little effort to prune
  658. // non-leaf modules.
  659. while (!Stack.empty()) {
  660. clang::Module *Mod = Stack.back();
  661. Stack.pop_back();
  662. bool AnyChildren = false;
  663. // Visit the submodules of this module.
  664. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  665. SubEnd = Mod->submodule_end();
  666. Sub != SubEnd; ++Sub) {
  667. // Skip explicit children; they need to be explicitly imported to be
  668. // linked against.
  669. if ((*Sub)->IsExplicit)
  670. continue;
  671. if (Visited.insert(*Sub)) {
  672. Stack.push_back(*Sub);
  673. AnyChildren = true;
  674. }
  675. }
  676. // We didn't find any children, so add this module to the list of
  677. // modules to link against.
  678. if (!AnyChildren) {
  679. LinkModules.insert(Mod);
  680. }
  681. }
  682. // Add link options for all of the imported modules in reverse topological
  683. // order.
  684. SmallVector<llvm::Value *, 16> MetadataArgs;
  685. Visited.clear();
  686. for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
  687. MEnd = LinkModules.end();
  688. M != MEnd; ++M) {
  689. if (Visited.insert(*M))
  690. addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited);
  691. }
  692. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  693. // Add the linker options metadata flag.
  694. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  695. llvm::MDNode::get(getLLVMContext(), MetadataArgs));
  696. }
  697. void CodeGenModule::EmitDeferred() {
  698. // Emit code for any potentially referenced deferred decls. Since a
  699. // previously unused static decl may become used during the generation of code
  700. // for a static function, iterate until no changes are made.
  701. while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
  702. if (!DeferredVTables.empty()) {
  703. const CXXRecordDecl *RD = DeferredVTables.back();
  704. DeferredVTables.pop_back();
  705. getCXXABI().EmitVTables(RD);
  706. continue;
  707. }
  708. GlobalDecl D = DeferredDeclsToEmit.back();
  709. DeferredDeclsToEmit.pop_back();
  710. // Check to see if we've already emitted this. This is necessary
  711. // for a couple of reasons: first, decls can end up in the
  712. // deferred-decls queue multiple times, and second, decls can end
  713. // up with definitions in unusual ways (e.g. by an extern inline
  714. // function acquiring a strong function redefinition). Just
  715. // ignore these cases.
  716. //
  717. // TODO: That said, looking this up multiple times is very wasteful.
  718. StringRef Name = getMangledName(D);
  719. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  720. assert(CGRef && "Deferred decl wasn't referenced?");
  721. if (!CGRef->isDeclaration())
  722. continue;
  723. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  724. // purposes an alias counts as a definition.
  725. if (isa<llvm::GlobalAlias>(CGRef))
  726. continue;
  727. // Otherwise, emit the definition and move on to the next one.
  728. EmitGlobalDefinition(D);
  729. }
  730. }
  731. void CodeGenModule::EmitGlobalAnnotations() {
  732. if (Annotations.empty())
  733. return;
  734. // Create a new global variable for the ConstantStruct in the Module.
  735. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  736. Annotations[0]->getType(), Annotations.size()), Annotations);
  737. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
  738. Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
  739. "llvm.global.annotations");
  740. gv->setSection(AnnotationSection);
  741. }
  742. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  743. llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
  744. if (i != AnnotationStrings.end())
  745. return i->second;
  746. // Not found yet, create a new global.
  747. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  748. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
  749. true, llvm::GlobalValue::PrivateLinkage, s, ".str");
  750. gv->setSection(AnnotationSection);
  751. gv->setUnnamedAddr(true);
  752. AnnotationStrings[Str] = gv;
  753. return gv;
  754. }
  755. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  756. SourceManager &SM = getContext().getSourceManager();
  757. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  758. if (PLoc.isValid())
  759. return EmitAnnotationString(PLoc.getFilename());
  760. return EmitAnnotationString(SM.getBufferName(Loc));
  761. }
  762. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  763. SourceManager &SM = getContext().getSourceManager();
  764. PresumedLoc PLoc = SM.getPresumedLoc(L);
  765. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  766. SM.getExpansionLineNumber(L);
  767. return llvm::ConstantInt::get(Int32Ty, LineNo);
  768. }
  769. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  770. const AnnotateAttr *AA,
  771. SourceLocation L) {
  772. // Get the globals for file name, annotation, and the line number.
  773. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  774. *UnitGV = EmitAnnotationUnit(L),
  775. *LineNoCst = EmitAnnotationLineNo(L);
  776. // Create the ConstantStruct for the global annotation.
  777. llvm::Constant *Fields[4] = {
  778. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  779. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  780. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  781. LineNoCst
  782. };
  783. return llvm::ConstantStruct::getAnon(Fields);
  784. }
  785. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  786. llvm::GlobalValue *GV) {
  787. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  788. // Get the struct elements for these annotations.
  789. for (specific_attr_iterator<AnnotateAttr>
  790. ai = D->specific_attr_begin<AnnotateAttr>(),
  791. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  792. Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
  793. }
  794. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  795. // Never defer when EmitAllDecls is specified.
  796. if (LangOpts.EmitAllDecls)
  797. return false;
  798. return !getContext().DeclMustBeEmitted(Global);
  799. }
  800. llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
  801. const CXXUuidofExpr* E) {
  802. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  803. // well-formed.
  804. StringRef Uuid;
  805. if (E->isTypeOperand())
  806. Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
  807. else {
  808. // Special case: __uuidof(0) means an all-zero GUID.
  809. Expr *Op = E->getExprOperand();
  810. if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
  811. Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
  812. else
  813. Uuid = "00000000-0000-0000-0000-000000000000";
  814. }
  815. std::string Name = "__uuid_" + Uuid.str();
  816. // Look for an existing global.
  817. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  818. return GV;
  819. llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
  820. assert(Init && "failed to initialize as constant");
  821. // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
  822. // first field is declared as "long", which for many targets is 8 bytes.
  823. // Those architectures are not supported. (With the MS abi, long is always 4
  824. // bytes.)
  825. llvm::Type *GuidType = getTypes().ConvertType(E->getType());
  826. if (Init->getType() != GuidType) {
  827. DiagnosticsEngine &Diags = getDiags();
  828. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  829. "__uuidof codegen is not supported on this architecture");
  830. Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
  831. Init = llvm::UndefValue::get(GuidType);
  832. }
  833. llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
  834. /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
  835. GV->setUnnamedAddr(true);
  836. return GV;
  837. }
  838. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  839. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  840. assert(AA && "No alias?");
  841. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  842. // See if there is already something with the target's name in the module.
  843. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  844. if (Entry) {
  845. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  846. return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  847. }
  848. llvm::Constant *Aliasee;
  849. if (isa<llvm::FunctionType>(DeclTy))
  850. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  851. GlobalDecl(cast<FunctionDecl>(VD)),
  852. /*ForVTable=*/false);
  853. else
  854. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  855. llvm::PointerType::getUnqual(DeclTy), 0);
  856. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  857. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  858. WeakRefReferences.insert(F);
  859. return Aliasee;
  860. }
  861. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  862. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  863. // Weak references don't produce any output by themselves.
  864. if (Global->hasAttr<WeakRefAttr>())
  865. return;
  866. // If this is an alias definition (which otherwise looks like a declaration)
  867. // emit it now.
  868. if (Global->hasAttr<AliasAttr>())
  869. return EmitAliasDefinition(GD);
  870. // If this is CUDA, be selective about which declarations we emit.
  871. if (LangOpts.CUDA) {
  872. if (CodeGenOpts.CUDAIsDevice) {
  873. if (!Global->hasAttr<CUDADeviceAttr>() &&
  874. !Global->hasAttr<CUDAGlobalAttr>() &&
  875. !Global->hasAttr<CUDAConstantAttr>() &&
  876. !Global->hasAttr<CUDASharedAttr>())
  877. return;
  878. } else {
  879. if (!Global->hasAttr<CUDAHostAttr>() && (
  880. Global->hasAttr<CUDADeviceAttr>() ||
  881. Global->hasAttr<CUDAConstantAttr>() ||
  882. Global->hasAttr<CUDASharedAttr>()))
  883. return;
  884. }
  885. }
  886. // Ignore declarations, they will be emitted on their first use.
  887. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  888. // Forward declarations are emitted lazily on first use.
  889. if (!FD->doesThisDeclarationHaveABody()) {
  890. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  891. return;
  892. const FunctionDecl *InlineDefinition = 0;
  893. FD->getBody(InlineDefinition);
  894. StringRef MangledName = getMangledName(GD);
  895. DeferredDecls.erase(MangledName);
  896. EmitGlobalDefinition(InlineDefinition);
  897. return;
  898. }
  899. } else {
  900. const VarDecl *VD = cast<VarDecl>(Global);
  901. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  902. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  903. return;
  904. }
  905. // Defer code generation when possible if this is a static definition, inline
  906. // function etc. These we only want to emit if they are used.
  907. if (!MayDeferGeneration(Global)) {
  908. // Emit the definition if it can't be deferred.
  909. EmitGlobalDefinition(GD);
  910. return;
  911. }
  912. // If we're deferring emission of a C++ variable with an
  913. // initializer, remember the order in which it appeared in the file.
  914. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  915. cast<VarDecl>(Global)->hasInit()) {
  916. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  917. CXXGlobalInits.push_back(0);
  918. }
  919. // If the value has already been used, add it directly to the
  920. // DeferredDeclsToEmit list.
  921. StringRef MangledName = getMangledName(GD);
  922. if (GetGlobalValue(MangledName))
  923. DeferredDeclsToEmit.push_back(GD);
  924. else {
  925. // Otherwise, remember that we saw a deferred decl with this name. The
  926. // first use of the mangled name will cause it to move into
  927. // DeferredDeclsToEmit.
  928. DeferredDecls[MangledName] = GD;
  929. }
  930. }
  931. namespace {
  932. struct FunctionIsDirectlyRecursive :
  933. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  934. const StringRef Name;
  935. const Builtin::Context &BI;
  936. bool Result;
  937. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  938. Name(N), BI(C), Result(false) {
  939. }
  940. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  941. bool TraverseCallExpr(CallExpr *E) {
  942. const FunctionDecl *FD = E->getDirectCallee();
  943. if (!FD)
  944. return true;
  945. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  946. if (Attr && Name == Attr->getLabel()) {
  947. Result = true;
  948. return false;
  949. }
  950. unsigned BuiltinID = FD->getBuiltinID();
  951. if (!BuiltinID)
  952. return true;
  953. StringRef BuiltinName = BI.GetName(BuiltinID);
  954. if (BuiltinName.startswith("__builtin_") &&
  955. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  956. Result = true;
  957. return false;
  958. }
  959. return true;
  960. }
  961. };
  962. }
  963. // isTriviallyRecursive - Check if this function calls another
  964. // decl that, because of the asm attribute or the other decl being a builtin,
  965. // ends up pointing to itself.
  966. bool
  967. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  968. StringRef Name;
  969. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  970. // asm labels are a special kind of mangling we have to support.
  971. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  972. if (!Attr)
  973. return false;
  974. Name = Attr->getLabel();
  975. } else {
  976. Name = FD->getName();
  977. }
  978. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  979. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  980. return Walker.Result;
  981. }
  982. bool
  983. CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
  984. if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
  985. return true;
  986. if (CodeGenOpts.OptimizationLevel == 0 &&
  987. !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
  988. return false;
  989. // PR9614. Avoid cases where the source code is lying to us. An available
  990. // externally function should have an equivalent function somewhere else,
  991. // but a function that calls itself is clearly not equivalent to the real
  992. // implementation.
  993. // This happens in glibc's btowc and in some configure checks.
  994. return !isTriviallyRecursive(F);
  995. }
  996. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  997. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  998. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  999. Context.getSourceManager(),
  1000. "Generating code for declaration");
  1001. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  1002. // At -O0, don't generate IR for functions with available_externally
  1003. // linkage.
  1004. if (!shouldEmitFunction(Function))
  1005. return;
  1006. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  1007. // Make sure to emit the definition(s) before we emit the thunks.
  1008. // This is necessary for the generation of certain thunks.
  1009. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  1010. EmitCXXConstructor(CD, GD.getCtorType());
  1011. else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
  1012. EmitCXXDestructor(DD, GD.getDtorType());
  1013. else
  1014. EmitGlobalFunctionDefinition(GD);
  1015. if (Method->isVirtual())
  1016. getVTables().EmitThunks(GD);
  1017. return;
  1018. }
  1019. return EmitGlobalFunctionDefinition(GD);
  1020. }
  1021. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  1022. return EmitGlobalVarDefinition(VD);
  1023. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1024. }
  1025. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1026. /// module, create and return an llvm Function with the specified type. If there
  1027. /// is something in the module with the specified name, return it potentially
  1028. /// bitcasted to the right type.
  1029. ///
  1030. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1031. /// to set the attributes on the function when it is first created.
  1032. llvm::Constant *
  1033. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1034. llvm::Type *Ty,
  1035. GlobalDecl D, bool ForVTable,
  1036. llvm::Attribute ExtraAttrs) {
  1037. // Lookup the entry, lazily creating it if necessary.
  1038. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1039. if (Entry) {
  1040. if (WeakRefReferences.erase(Entry)) {
  1041. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
  1042. if (FD && !FD->hasAttr<WeakAttr>())
  1043. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1044. }
  1045. if (Entry->getType()->getElementType() == Ty)
  1046. return Entry;
  1047. // Make sure the result is of the correct type.
  1048. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1049. }
  1050. // This function doesn't have a complete type (for example, the return
  1051. // type is an incomplete struct). Use a fake type instead, and make
  1052. // sure not to try to set attributes.
  1053. bool IsIncompleteFunction = false;
  1054. llvm::FunctionType *FTy;
  1055. if (isa<llvm::FunctionType>(Ty)) {
  1056. FTy = cast<llvm::FunctionType>(Ty);
  1057. } else {
  1058. FTy = llvm::FunctionType::get(VoidTy, false);
  1059. IsIncompleteFunction = true;
  1060. }
  1061. llvm::Function *F = llvm::Function::Create(FTy,
  1062. llvm::Function::ExternalLinkage,
  1063. MangledName, &getModule());
  1064. assert(F->getName() == MangledName && "name was uniqued!");
  1065. if (D.getDecl())
  1066. SetFunctionAttributes(D, F, IsIncompleteFunction);
  1067. if (ExtraAttrs.hasAttributes())
  1068. F->addAttribute(llvm::AttributeSet::FunctionIndex, ExtraAttrs);
  1069. // This is the first use or definition of a mangled name. If there is a
  1070. // deferred decl with this name, remember that we need to emit it at the end
  1071. // of the file.
  1072. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1073. if (DDI != DeferredDecls.end()) {
  1074. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1075. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1076. DeferredDeclsToEmit.push_back(DDI->second);
  1077. DeferredDecls.erase(DDI);
  1078. // Otherwise, there are cases we have to worry about where we're
  1079. // using a declaration for which we must emit a definition but where
  1080. // we might not find a top-level definition:
  1081. // - member functions defined inline in their classes
  1082. // - friend functions defined inline in some class
  1083. // - special member functions with implicit definitions
  1084. // If we ever change our AST traversal to walk into class methods,
  1085. // this will be unnecessary.
  1086. //
  1087. // We also don't emit a definition for a function if it's going to be an entry
  1088. // in a vtable, unless it's already marked as used.
  1089. } else if (getLangOpts().CPlusPlus && D.getDecl()) {
  1090. // Look for a declaration that's lexically in a record.
  1091. const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
  1092. FD = FD->getMostRecentDecl();
  1093. do {
  1094. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1095. if (FD->isImplicit() && !ForVTable) {
  1096. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  1097. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  1098. break;
  1099. } else if (FD->doesThisDeclarationHaveABody()) {
  1100. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  1101. break;
  1102. }
  1103. }
  1104. FD = FD->getPreviousDecl();
  1105. } while (FD);
  1106. }
  1107. // Make sure the result is of the requested type.
  1108. if (!IsIncompleteFunction) {
  1109. assert(F->getType()->getElementType() == Ty);
  1110. return F;
  1111. }
  1112. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1113. return llvm::ConstantExpr::getBitCast(F, PTy);
  1114. }
  1115. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1116. /// non-null, then this function will use the specified type if it has to
  1117. /// create it (this occurs when we see a definition of the function).
  1118. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1119. llvm::Type *Ty,
  1120. bool ForVTable) {
  1121. // If there was no specific requested type, just convert it now.
  1122. if (!Ty)
  1123. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  1124. StringRef MangledName = getMangledName(GD);
  1125. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
  1126. }
  1127. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1128. /// type and name.
  1129. llvm::Constant *
  1130. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1131. StringRef Name,
  1132. llvm::Attribute ExtraAttrs) {
  1133. return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1134. ExtraAttrs);
  1135. }
  1136. /// isTypeConstant - Determine whether an object of this type can be emitted
  1137. /// as a constant.
  1138. ///
  1139. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1140. /// will not be considered. The caller will need to verify that the object is
  1141. /// not written to during its construction.
  1142. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1143. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1144. return false;
  1145. if (Context.getLangOpts().CPlusPlus) {
  1146. if (const CXXRecordDecl *Record
  1147. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1148. return ExcludeCtor && !Record->hasMutableFields() &&
  1149. Record->hasTrivialDestructor();
  1150. }
  1151. return true;
  1152. }
  1153. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1154. /// create and return an llvm GlobalVariable with the specified type. If there
  1155. /// is something in the module with the specified name, return it potentially
  1156. /// bitcasted to the right type.
  1157. ///
  1158. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1159. /// to set the attributes on the global when it is first created.
  1160. llvm::Constant *
  1161. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1162. llvm::PointerType *Ty,
  1163. const VarDecl *D,
  1164. bool UnnamedAddr) {
  1165. // Lookup the entry, lazily creating it if necessary.
  1166. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1167. if (Entry) {
  1168. if (WeakRefReferences.erase(Entry)) {
  1169. if (D && !D->hasAttr<WeakAttr>())
  1170. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1171. }
  1172. if (UnnamedAddr)
  1173. Entry->setUnnamedAddr(true);
  1174. if (Entry->getType() == Ty)
  1175. return Entry;
  1176. // Make sure the result is of the correct type.
  1177. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1178. }
  1179. // This is the first use or definition of a mangled name. If there is a
  1180. // deferred decl with this name, remember that we need to emit it at the end
  1181. // of the file.
  1182. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1183. if (DDI != DeferredDecls.end()) {
  1184. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1185. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1186. DeferredDeclsToEmit.push_back(DDI->second);
  1187. DeferredDecls.erase(DDI);
  1188. }
  1189. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1190. llvm::GlobalVariable *GV =
  1191. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  1192. llvm::GlobalValue::ExternalLinkage,
  1193. 0, MangledName, 0,
  1194. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1195. // Handle things which are present even on external declarations.
  1196. if (D) {
  1197. // FIXME: This code is overly simple and should be merged with other global
  1198. // handling.
  1199. GV->setConstant(isTypeConstant(D->getType(), false));
  1200. // Set linkage and visibility in case we never see a definition.
  1201. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  1202. if (LV.linkage() != ExternalLinkage) {
  1203. // Don't set internal linkage on declarations.
  1204. } else {
  1205. if (D->hasAttr<DLLImportAttr>())
  1206. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  1207. else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
  1208. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1209. // Set visibility on a declaration only if it's explicit.
  1210. if (LV.visibilityExplicit())
  1211. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  1212. }
  1213. if (D->isThreadSpecified())
  1214. setTLSMode(GV, *D);
  1215. }
  1216. if (AddrSpace != Ty->getAddressSpace())
  1217. return llvm::ConstantExpr::getBitCast(GV, Ty);
  1218. else
  1219. return GV;
  1220. }
  1221. llvm::GlobalVariable *
  1222. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1223. llvm::Type *Ty,
  1224. llvm::GlobalValue::LinkageTypes Linkage) {
  1225. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1226. llvm::GlobalVariable *OldGV = 0;
  1227. if (GV) {
  1228. // Check if the variable has the right type.
  1229. if (GV->getType()->getElementType() == Ty)
  1230. return GV;
  1231. // Because C++ name mangling, the only way we can end up with an already
  1232. // existing global with the same name is if it has been declared extern "C".
  1233. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1234. OldGV = GV;
  1235. }
  1236. // Create a new variable.
  1237. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1238. Linkage, 0, Name);
  1239. if (OldGV) {
  1240. // Replace occurrences of the old variable if needed.
  1241. GV->takeName(OldGV);
  1242. if (!OldGV->use_empty()) {
  1243. llvm::Constant *NewPtrForOldDecl =
  1244. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1245. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1246. }
  1247. OldGV->eraseFromParent();
  1248. }
  1249. return GV;
  1250. }
  1251. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1252. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1253. /// then it will be created with the specified type instead of whatever the
  1254. /// normal requested type would be.
  1255. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1256. llvm::Type *Ty) {
  1257. assert(D->hasGlobalStorage() && "Not a global variable");
  1258. QualType ASTTy = D->getType();
  1259. if (Ty == 0)
  1260. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1261. llvm::PointerType *PTy =
  1262. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1263. StringRef MangledName = getMangledName(D);
  1264. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1265. }
  1266. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1267. /// specified type and name.
  1268. llvm::Constant *
  1269. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1270. StringRef Name) {
  1271. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
  1272. true);
  1273. }
  1274. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1275. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1276. if (MayDeferGeneration(D)) {
  1277. // If we have not seen a reference to this variable yet, place it
  1278. // into the deferred declarations table to be emitted if needed
  1279. // later.
  1280. StringRef MangledName = getMangledName(D);
  1281. if (!GetGlobalValue(MangledName)) {
  1282. DeferredDecls[MangledName] = D;
  1283. return;
  1284. }
  1285. }
  1286. // The tentative definition is the only definition.
  1287. EmitGlobalVarDefinition(D);
  1288. }
  1289. void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
  1290. if (DefinitionRequired)
  1291. getCXXABI().EmitVTables(Class);
  1292. }
  1293. llvm::GlobalVariable::LinkageTypes
  1294. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  1295. if (RD->getLinkage() != ExternalLinkage)
  1296. return llvm::GlobalVariable::InternalLinkage;
  1297. if (const CXXMethodDecl *KeyFunction
  1298. = RD->getASTContext().getKeyFunction(RD)) {
  1299. // If this class has a key function, use that to determine the linkage of
  1300. // the vtable.
  1301. const FunctionDecl *Def = 0;
  1302. if (KeyFunction->hasBody(Def))
  1303. KeyFunction = cast<CXXMethodDecl>(Def);
  1304. switch (KeyFunction->getTemplateSpecializationKind()) {
  1305. case TSK_Undeclared:
  1306. case TSK_ExplicitSpecialization:
  1307. // When compiling with optimizations turned on, we emit all vtables,
  1308. // even if the key function is not defined in the current translation
  1309. // unit. If this is the case, use available_externally linkage.
  1310. if (!Def && CodeGenOpts.OptimizationLevel)
  1311. return llvm::GlobalVariable::AvailableExternallyLinkage;
  1312. if (KeyFunction->isInlined())
  1313. return !Context.getLangOpts().AppleKext ?
  1314. llvm::GlobalVariable::LinkOnceODRLinkage :
  1315. llvm::Function::InternalLinkage;
  1316. return llvm::GlobalVariable::ExternalLinkage;
  1317. case TSK_ImplicitInstantiation:
  1318. return !Context.getLangOpts().AppleKext ?
  1319. llvm::GlobalVariable::LinkOnceODRLinkage :
  1320. llvm::Function::InternalLinkage;
  1321. case TSK_ExplicitInstantiationDefinition:
  1322. return !Context.getLangOpts().AppleKext ?
  1323. llvm::GlobalVariable::WeakODRLinkage :
  1324. llvm::Function::InternalLinkage;
  1325. case TSK_ExplicitInstantiationDeclaration:
  1326. // FIXME: Use available_externally linkage. However, this currently
  1327. // breaks LLVM's build due to undefined symbols.
  1328. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1329. return !Context.getLangOpts().AppleKext ?
  1330. llvm::GlobalVariable::LinkOnceODRLinkage :
  1331. llvm::Function::InternalLinkage;
  1332. }
  1333. }
  1334. if (Context.getLangOpts().AppleKext)
  1335. return llvm::Function::InternalLinkage;
  1336. switch (RD->getTemplateSpecializationKind()) {
  1337. case TSK_Undeclared:
  1338. case TSK_ExplicitSpecialization:
  1339. case TSK_ImplicitInstantiation:
  1340. // FIXME: Use available_externally linkage. However, this currently
  1341. // breaks LLVM's build due to undefined symbols.
  1342. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1343. case TSK_ExplicitInstantiationDeclaration:
  1344. return llvm::GlobalVariable::LinkOnceODRLinkage;
  1345. case TSK_ExplicitInstantiationDefinition:
  1346. return llvm::GlobalVariable::WeakODRLinkage;
  1347. }
  1348. llvm_unreachable("Invalid TemplateSpecializationKind!");
  1349. }
  1350. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1351. return Context.toCharUnitsFromBits(
  1352. TheDataLayout.getTypeStoreSizeInBits(Ty));
  1353. }
  1354. llvm::Constant *
  1355. CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
  1356. const Expr *rawInit) {
  1357. ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
  1358. if (const ExprWithCleanups *withCleanups =
  1359. dyn_cast<ExprWithCleanups>(rawInit)) {
  1360. cleanups = withCleanups->getObjects();
  1361. rawInit = withCleanups->getSubExpr();
  1362. }
  1363. const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
  1364. if (!init || !init->initializesStdInitializerList() ||
  1365. init->getNumInits() == 0)
  1366. return 0;
  1367. ASTContext &ctx = getContext();
  1368. unsigned numInits = init->getNumInits();
  1369. // FIXME: This check is here because we would otherwise silently miscompile
  1370. // nested global std::initializer_lists. Better would be to have a real
  1371. // implementation.
  1372. for (unsigned i = 0; i < numInits; ++i) {
  1373. const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
  1374. if (inner && inner->initializesStdInitializerList()) {
  1375. ErrorUnsupported(inner, "nested global std::initializer_list");
  1376. return 0;
  1377. }
  1378. }
  1379. // Synthesize a fake VarDecl for the array and initialize that.
  1380. QualType elementType = init->getInit(0)->getType();
  1381. llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
  1382. QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
  1383. ArrayType::Normal, 0);
  1384. IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
  1385. TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
  1386. arrayType, D->getLocation());
  1387. VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
  1388. D->getDeclContext()),
  1389. D->getLocStart(), D->getLocation(),
  1390. name, arrayType, sourceInfo,
  1391. SC_Static, SC_Static);
  1392. // Now clone the InitListExpr to initialize the array instead.
  1393. // Incredible hack: we want to use the existing InitListExpr here, so we need
  1394. // to tell it that it no longer initializes a std::initializer_list.
  1395. ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
  1396. init->getNumInits());
  1397. Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
  1398. init->getRBraceLoc());
  1399. arrayInit->setType(arrayType);
  1400. if (!cleanups.empty())
  1401. arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
  1402. backingArray->setInit(arrayInit);
  1403. // Emit the definition of the array.
  1404. EmitGlobalVarDefinition(backingArray);
  1405. // Inspect the initializer list to validate it and determine its type.
  1406. // FIXME: doing this every time is probably inefficient; caching would be nice
  1407. RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
  1408. RecordDecl::field_iterator field = record->field_begin();
  1409. if (field == record->field_end()) {
  1410. ErrorUnsupported(D, "weird std::initializer_list");
  1411. return 0;
  1412. }
  1413. QualType elementPtr = ctx.getPointerType(elementType.withConst());
  1414. // Start pointer.
  1415. if (!ctx.hasSameType(field->getType(), elementPtr)) {
  1416. ErrorUnsupported(D, "weird std::initializer_list");
  1417. return 0;
  1418. }
  1419. ++field;
  1420. if (field == record->field_end()) {
  1421. ErrorUnsupported(D, "weird std::initializer_list");
  1422. return 0;
  1423. }
  1424. bool isStartEnd = false;
  1425. if (ctx.hasSameType(field->getType(), elementPtr)) {
  1426. // End pointer.
  1427. isStartEnd = true;
  1428. } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
  1429. ErrorUnsupported(D, "weird std::initializer_list");
  1430. return 0;
  1431. }
  1432. // Now build an APValue representing the std::initializer_list.
  1433. APValue initListValue(APValue::UninitStruct(), 0, 2);
  1434. APValue &startField = initListValue.getStructField(0);
  1435. APValue::LValuePathEntry startOffsetPathEntry;
  1436. startOffsetPathEntry.ArrayIndex = 0;
  1437. startField = APValue(APValue::LValueBase(backingArray),
  1438. CharUnits::fromQuantity(0),
  1439. llvm::makeArrayRef(startOffsetPathEntry),
  1440. /*IsOnePastTheEnd=*/false, 0);
  1441. if (isStartEnd) {
  1442. APValue &endField = initListValue.getStructField(1);
  1443. APValue::LValuePathEntry endOffsetPathEntry;
  1444. endOffsetPathEntry.ArrayIndex = numInits;
  1445. endField = APValue(APValue::LValueBase(backingArray),
  1446. ctx.getTypeSizeInChars(elementType) * numInits,
  1447. llvm::makeArrayRef(endOffsetPathEntry),
  1448. /*IsOnePastTheEnd=*/true, 0);
  1449. } else {
  1450. APValue &sizeField = initListValue.getStructField(1);
  1451. sizeField = APValue(llvm::APSInt(numElements));
  1452. }
  1453. // Emit the constant for the initializer_list.
  1454. llvm::Constant *llvmInit =
  1455. EmitConstantValueForMemory(initListValue, D->getType());
  1456. assert(llvmInit && "failed to initialize as constant");
  1457. return llvmInit;
  1458. }
  1459. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1460. unsigned AddrSpace) {
  1461. if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
  1462. if (D->hasAttr<CUDAConstantAttr>())
  1463. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1464. else if (D->hasAttr<CUDASharedAttr>())
  1465. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1466. else
  1467. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1468. }
  1469. return AddrSpace;
  1470. }
  1471. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1472. llvm::Constant *Init = 0;
  1473. QualType ASTTy = D->getType();
  1474. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1475. bool NeedsGlobalCtor = false;
  1476. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1477. const VarDecl *InitDecl;
  1478. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1479. if (!InitExpr) {
  1480. // This is a tentative definition; tentative definitions are
  1481. // implicitly initialized with { 0 }.
  1482. //
  1483. // Note that tentative definitions are only emitted at the end of
  1484. // a translation unit, so they should never have incomplete
  1485. // type. In addition, EmitTentativeDefinition makes sure that we
  1486. // never attempt to emit a tentative definition if a real one
  1487. // exists. A use may still exists, however, so we still may need
  1488. // to do a RAUW.
  1489. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1490. Init = EmitNullConstant(D->getType());
  1491. } else {
  1492. // If this is a std::initializer_list, emit the special initializer.
  1493. Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
  1494. // An empty init list will perform zero-initialization, which happens
  1495. // to be exactly what we want.
  1496. // FIXME: It does so in a global constructor, which is *not* what we
  1497. // want.
  1498. if (!Init) {
  1499. initializedGlobalDecl = GlobalDecl(D);
  1500. Init = EmitConstantInit(*InitDecl);
  1501. }
  1502. if (!Init) {
  1503. QualType T = InitExpr->getType();
  1504. if (D->getType()->isReferenceType())
  1505. T = D->getType();
  1506. if (getLangOpts().CPlusPlus) {
  1507. Init = EmitNullConstant(T);
  1508. NeedsGlobalCtor = true;
  1509. } else {
  1510. ErrorUnsupported(D, "static initializer");
  1511. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1512. }
  1513. } else {
  1514. // We don't need an initializer, so remove the entry for the delayed
  1515. // initializer position (just in case this entry was delayed) if we
  1516. // also don't need to register a destructor.
  1517. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1518. DelayedCXXInitPosition.erase(D);
  1519. }
  1520. }
  1521. llvm::Type* InitType = Init->getType();
  1522. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1523. // Strip off a bitcast if we got one back.
  1524. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1525. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1526. // all zero index gep.
  1527. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1528. Entry = CE->getOperand(0);
  1529. }
  1530. // Entry is now either a Function or GlobalVariable.
  1531. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1532. // We have a definition after a declaration with the wrong type.
  1533. // We must make a new GlobalVariable* and update everything that used OldGV
  1534. // (a declaration or tentative definition) with the new GlobalVariable*
  1535. // (which will be a definition).
  1536. //
  1537. // This happens if there is a prototype for a global (e.g.
  1538. // "extern int x[];") and then a definition of a different type (e.g.
  1539. // "int x[10];"). This also happens when an initializer has a different type
  1540. // from the type of the global (this happens with unions).
  1541. if (GV == 0 ||
  1542. GV->getType()->getElementType() != InitType ||
  1543. GV->getType()->getAddressSpace() !=
  1544. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1545. // Move the old entry aside so that we'll create a new one.
  1546. Entry->setName(StringRef());
  1547. // Make a new global with the correct type, this is now guaranteed to work.
  1548. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1549. // Replace all uses of the old global with the new global
  1550. llvm::Constant *NewPtrForOldDecl =
  1551. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1552. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1553. // Erase the old global, since it is no longer used.
  1554. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1555. }
  1556. if (D->hasAttr<AnnotateAttr>())
  1557. AddGlobalAnnotations(D, GV);
  1558. GV->setInitializer(Init);
  1559. // If it is safe to mark the global 'constant', do so now.
  1560. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1561. isTypeConstant(D->getType(), true));
  1562. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1563. // Set the llvm linkage type as appropriate.
  1564. llvm::GlobalValue::LinkageTypes Linkage =
  1565. GetLLVMLinkageVarDefinition(D, GV);
  1566. GV->setLinkage(Linkage);
  1567. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1568. // common vars aren't constant even if declared const.
  1569. GV->setConstant(false);
  1570. SetCommonAttributes(D, GV);
  1571. // Emit the initializer function if necessary.
  1572. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1573. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1574. // If we are compiling with ASan, add metadata indicating dynamically
  1575. // initialized globals.
  1576. if (SanOpts.Address && NeedsGlobalCtor) {
  1577. llvm::Module &M = getModule();
  1578. llvm::NamedMDNode *DynamicInitializers =
  1579. M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
  1580. llvm::Value *GlobalToAdd[] = { GV };
  1581. llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
  1582. DynamicInitializers->addOperand(ThisGlobal);
  1583. }
  1584. // Emit global variable debug information.
  1585. if (CGDebugInfo *DI = getModuleDebugInfo())
  1586. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1587. DI->EmitGlobalVariable(GV, D);
  1588. }
  1589. llvm::GlobalValue::LinkageTypes
  1590. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
  1591. llvm::GlobalVariable *GV) {
  1592. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1593. if (Linkage == GVA_Internal)
  1594. return llvm::Function::InternalLinkage;
  1595. else if (D->hasAttr<DLLImportAttr>())
  1596. return llvm::Function::DLLImportLinkage;
  1597. else if (D->hasAttr<DLLExportAttr>())
  1598. return llvm::Function::DLLExportLinkage;
  1599. else if (D->hasAttr<WeakAttr>()) {
  1600. if (GV->isConstant())
  1601. return llvm::GlobalVariable::WeakODRLinkage;
  1602. else
  1603. return llvm::GlobalVariable::WeakAnyLinkage;
  1604. } else if (Linkage == GVA_TemplateInstantiation ||
  1605. Linkage == GVA_ExplicitTemplateInstantiation)
  1606. return llvm::GlobalVariable::WeakODRLinkage;
  1607. else if (!getLangOpts().CPlusPlus &&
  1608. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1609. D->getAttr<CommonAttr>()) &&
  1610. !D->hasExternalStorage() && !D->getInit() &&
  1611. !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
  1612. !D->getAttr<WeakImportAttr>()) {
  1613. // Thread local vars aren't considered common linkage.
  1614. return llvm::GlobalVariable::CommonLinkage;
  1615. }
  1616. return llvm::GlobalVariable::ExternalLinkage;
  1617. }
  1618. /// Replace the uses of a function that was declared with a non-proto type.
  1619. /// We want to silently drop extra arguments from call sites
  1620. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  1621. llvm::Function *newFn) {
  1622. // Fast path.
  1623. if (old->use_empty()) return;
  1624. llvm::Type *newRetTy = newFn->getReturnType();
  1625. SmallVector<llvm::Value*, 4> newArgs;
  1626. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  1627. ui != ue; ) {
  1628. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  1629. llvm::User *user = *use;
  1630. // Recognize and replace uses of bitcasts. Most calls to
  1631. // unprototyped functions will use bitcasts.
  1632. if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  1633. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  1634. replaceUsesOfNonProtoConstant(bitcast, newFn);
  1635. continue;
  1636. }
  1637. // Recognize calls to the function.
  1638. llvm::CallSite callSite(user);
  1639. if (!callSite) continue;
  1640. if (!callSite.isCallee(use)) continue;
  1641. // If the return types don't match exactly, then we can't
  1642. // transform this call unless it's dead.
  1643. if (callSite->getType() != newRetTy && !callSite->use_empty())
  1644. continue;
  1645. // Get the call site's attribute list.
  1646. SmallVector<llvm::AttributeWithIndex, 8> newAttrs;
  1647. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  1648. // Collect any return attributes from the call.
  1649. llvm::Attribute returnAttrs = oldAttrs.getRetAttributes();
  1650. if (returnAttrs.hasAttributes())
  1651. newAttrs.push_back(llvm::AttributeWithIndex::get(
  1652. llvm::AttributeSet::ReturnIndex, returnAttrs));
  1653. // If the function was passed too few arguments, don't transform.
  1654. unsigned newNumArgs = newFn->arg_size();
  1655. if (callSite.arg_size() < newNumArgs) continue;
  1656. // If extra arguments were passed, we silently drop them.
  1657. // If any of the types mismatch, we don't transform.
  1658. unsigned argNo = 0;
  1659. bool dontTransform = false;
  1660. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  1661. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  1662. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  1663. dontTransform = true;
  1664. break;
  1665. }
  1666. // Add any parameter attributes.
  1667. llvm::Attribute pAttrs = oldAttrs.getParamAttributes(argNo + 1);
  1668. if (pAttrs.hasAttributes())
  1669. newAttrs.push_back(llvm::AttributeWithIndex::get(argNo + 1, pAttrs));
  1670. }
  1671. if (dontTransform)
  1672. continue;
  1673. llvm::Attribute fnAttrs = oldAttrs.getFnAttributes();
  1674. if (fnAttrs.hasAttributes())
  1675. newAttrs.push_back(llvm::
  1676. AttributeWithIndex::get(llvm::AttributeSet::FunctionIndex,
  1677. fnAttrs));
  1678. // Okay, we can transform this. Create the new call instruction and copy
  1679. // over the required information.
  1680. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  1681. llvm::CallSite newCall;
  1682. if (callSite.isCall()) {
  1683. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  1684. callSite.getInstruction());
  1685. } else {
  1686. llvm::InvokeInst *oldInvoke =
  1687. cast<llvm::InvokeInst>(callSite.getInstruction());
  1688. newCall = llvm::InvokeInst::Create(newFn,
  1689. oldInvoke->getNormalDest(),
  1690. oldInvoke->getUnwindDest(),
  1691. newArgs, "",
  1692. callSite.getInstruction());
  1693. }
  1694. newArgs.clear(); // for the next iteration
  1695. if (!newCall->getType()->isVoidTy())
  1696. newCall->takeName(callSite.getInstruction());
  1697. newCall.setAttributes(
  1698. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  1699. newCall.setCallingConv(callSite.getCallingConv());
  1700. // Finally, remove the old call, replacing any uses with the new one.
  1701. if (!callSite->use_empty())
  1702. callSite->replaceAllUsesWith(newCall.getInstruction());
  1703. // Copy debug location attached to CI.
  1704. if (!callSite->getDebugLoc().isUnknown())
  1705. newCall->setDebugLoc(callSite->getDebugLoc());
  1706. callSite->eraseFromParent();
  1707. }
  1708. }
  1709. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1710. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1711. /// existing call uses of the old function in the module, this adjusts them to
  1712. /// call the new function directly.
  1713. ///
  1714. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1715. /// functions to be able to inline them. If there is a bitcast in the way, it
  1716. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1717. /// run at -O0.
  1718. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1719. llvm::Function *NewFn) {
  1720. // If we're redefining a global as a function, don't transform it.
  1721. if (!isa<llvm::Function>(Old)) return;
  1722. replaceUsesOfNonProtoConstant(Old, NewFn);
  1723. }
  1724. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1725. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1726. // If we have a definition, this might be a deferred decl. If the
  1727. // instantiation is explicit, make sure we emit it at the end.
  1728. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1729. GetAddrOfGlobalVar(VD);
  1730. }
  1731. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1732. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1733. // Compute the function info and LLVM type.
  1734. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1735. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1736. // Get or create the prototype for the function.
  1737. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1738. // Strip off a bitcast if we got one back.
  1739. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1740. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1741. Entry = CE->getOperand(0);
  1742. }
  1743. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1744. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1745. // If the types mismatch then we have to rewrite the definition.
  1746. assert(OldFn->isDeclaration() &&
  1747. "Shouldn't replace non-declaration");
  1748. // F is the Function* for the one with the wrong type, we must make a new
  1749. // Function* and update everything that used F (a declaration) with the new
  1750. // Function* (which will be a definition).
  1751. //
  1752. // This happens if there is a prototype for a function
  1753. // (e.g. "int f()") and then a definition of a different type
  1754. // (e.g. "int f(int x)"). Move the old function aside so that it
  1755. // doesn't interfere with GetAddrOfFunction.
  1756. OldFn->setName(StringRef());
  1757. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1758. // This might be an implementation of a function without a
  1759. // prototype, in which case, try to do special replacement of
  1760. // calls which match the new prototype. The really key thing here
  1761. // is that we also potentially drop arguments from the call site
  1762. // so as to make a direct call, which makes the inliner happier
  1763. // and suppresses a number of optimizer warnings (!) about
  1764. // dropping arguments.
  1765. if (!OldFn->use_empty()) {
  1766. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1767. OldFn->removeDeadConstantUsers();
  1768. }
  1769. // Replace uses of F with the Function we will endow with a body.
  1770. if (!Entry->use_empty()) {
  1771. llvm::Constant *NewPtrForOldDecl =
  1772. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1773. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1774. }
  1775. // Ok, delete the old function now, which is dead.
  1776. OldFn->eraseFromParent();
  1777. Entry = NewFn;
  1778. }
  1779. // We need to set linkage and visibility on the function before
  1780. // generating code for it because various parts of IR generation
  1781. // want to propagate this information down (e.g. to local static
  1782. // declarations).
  1783. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1784. setFunctionLinkage(D, Fn);
  1785. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1786. setGlobalVisibility(Fn, D);
  1787. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1788. SetFunctionDefinitionAttributes(D, Fn);
  1789. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1790. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1791. AddGlobalCtor(Fn, CA->getPriority());
  1792. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1793. AddGlobalDtor(Fn, DA->getPriority());
  1794. if (D->hasAttr<AnnotateAttr>())
  1795. AddGlobalAnnotations(D, Fn);
  1796. }
  1797. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1798. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1799. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1800. assert(AA && "Not an alias?");
  1801. StringRef MangledName = getMangledName(GD);
  1802. // If there is a definition in the module, then it wins over the alias.
  1803. // This is dubious, but allow it to be safe. Just ignore the alias.
  1804. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1805. if (Entry && !Entry->isDeclaration())
  1806. return;
  1807. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1808. // Create a reference to the named value. This ensures that it is emitted
  1809. // if a deferred decl.
  1810. llvm::Constant *Aliasee;
  1811. if (isa<llvm::FunctionType>(DeclTy))
  1812. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  1813. /*ForVTable=*/false);
  1814. else
  1815. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1816. llvm::PointerType::getUnqual(DeclTy), 0);
  1817. // Create the new alias itself, but don't set a name yet.
  1818. llvm::GlobalValue *GA =
  1819. new llvm::GlobalAlias(Aliasee->getType(),
  1820. llvm::Function::ExternalLinkage,
  1821. "", Aliasee, &getModule());
  1822. if (Entry) {
  1823. assert(Entry->isDeclaration());
  1824. // If there is a declaration in the module, then we had an extern followed
  1825. // by the alias, as in:
  1826. // extern int test6();
  1827. // ...
  1828. // int test6() __attribute__((alias("test7")));
  1829. //
  1830. // Remove it and replace uses of it with the alias.
  1831. GA->takeName(Entry);
  1832. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1833. Entry->getType()));
  1834. Entry->eraseFromParent();
  1835. } else {
  1836. GA->setName(MangledName);
  1837. }
  1838. // Set attributes which are particular to an alias; this is a
  1839. // specialization of the attributes which may be set on a global
  1840. // variable/function.
  1841. if (D->hasAttr<DLLExportAttr>()) {
  1842. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1843. // The dllexport attribute is ignored for undefined symbols.
  1844. if (FD->hasBody())
  1845. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1846. } else {
  1847. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1848. }
  1849. } else if (D->hasAttr<WeakAttr>() ||
  1850. D->hasAttr<WeakRefAttr>() ||
  1851. D->isWeakImported()) {
  1852. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1853. }
  1854. SetCommonAttributes(D, GA);
  1855. }
  1856. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  1857. ArrayRef<llvm::Type*> Tys) {
  1858. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  1859. Tys);
  1860. }
  1861. static llvm::StringMapEntry<llvm::Constant*> &
  1862. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1863. const StringLiteral *Literal,
  1864. bool TargetIsLSB,
  1865. bool &IsUTF16,
  1866. unsigned &StringLength) {
  1867. StringRef String = Literal->getString();
  1868. unsigned NumBytes = String.size();
  1869. // Check for simple case.
  1870. if (!Literal->containsNonAsciiOrNull()) {
  1871. StringLength = NumBytes;
  1872. return Map.GetOrCreateValue(String);
  1873. }
  1874. // Otherwise, convert the UTF8 literals into a string of shorts.
  1875. IsUTF16 = true;
  1876. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  1877. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1878. UTF16 *ToPtr = &ToBuf[0];
  1879. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1880. &ToPtr, ToPtr + NumBytes,
  1881. strictConversion);
  1882. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1883. StringLength = ToPtr - &ToBuf[0];
  1884. // Add an explicit null.
  1885. *ToPtr = 0;
  1886. return Map.
  1887. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  1888. (StringLength + 1) * 2));
  1889. }
  1890. static llvm::StringMapEntry<llvm::Constant*> &
  1891. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1892. const StringLiteral *Literal,
  1893. unsigned &StringLength) {
  1894. StringRef String = Literal->getString();
  1895. StringLength = String.size();
  1896. return Map.GetOrCreateValue(String);
  1897. }
  1898. llvm::Constant *
  1899. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1900. unsigned StringLength = 0;
  1901. bool isUTF16 = false;
  1902. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1903. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1904. getDataLayout().isLittleEndian(),
  1905. isUTF16, StringLength);
  1906. if (llvm::Constant *C = Entry.getValue())
  1907. return C;
  1908. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1909. llvm::Constant *Zeros[] = { Zero, Zero };
  1910. // If we don't already have it, get __CFConstantStringClassReference.
  1911. if (!CFConstantStringClassRef) {
  1912. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1913. Ty = llvm::ArrayType::get(Ty, 0);
  1914. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1915. "__CFConstantStringClassReference");
  1916. // Decay array -> ptr
  1917. CFConstantStringClassRef =
  1918. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1919. }
  1920. QualType CFTy = getContext().getCFConstantStringType();
  1921. llvm::StructType *STy =
  1922. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1923. llvm::Constant *Fields[4];
  1924. // Class pointer.
  1925. Fields[0] = CFConstantStringClassRef;
  1926. // Flags.
  1927. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1928. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1929. llvm::ConstantInt::get(Ty, 0x07C8);
  1930. // String pointer.
  1931. llvm::Constant *C = 0;
  1932. if (isUTF16) {
  1933. ArrayRef<uint16_t> Arr =
  1934. llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
  1935. const_cast<char *>(Entry.getKey().data())),
  1936. Entry.getKey().size() / 2);
  1937. C = llvm::ConstantDataArray::get(VMContext, Arr);
  1938. } else {
  1939. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1940. }
  1941. llvm::GlobalValue::LinkageTypes Linkage;
  1942. if (isUTF16)
  1943. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1944. Linkage = llvm::GlobalValue::InternalLinkage;
  1945. else
  1946. // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
  1947. // when using private linkage. It is not clear if this is a bug in ld
  1948. // or a reasonable new restriction.
  1949. Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
  1950. // Note: -fwritable-strings doesn't make the backing store strings of
  1951. // CFStrings writable. (See <rdar://problem/10657500>)
  1952. llvm::GlobalVariable *GV =
  1953. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  1954. Linkage, C, ".str");
  1955. GV->setUnnamedAddr(true);
  1956. if (isUTF16) {
  1957. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1958. GV->setAlignment(Align.getQuantity());
  1959. } else {
  1960. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1961. GV->setAlignment(Align.getQuantity());
  1962. }
  1963. // String.
  1964. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1965. if (isUTF16)
  1966. // Cast the UTF16 string to the correct type.
  1967. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  1968. // String length.
  1969. Ty = getTypes().ConvertType(getContext().LongTy);
  1970. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1971. // The struct.
  1972. C = llvm::ConstantStruct::get(STy, Fields);
  1973. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1974. llvm::GlobalVariable::PrivateLinkage, C,
  1975. "_unnamed_cfstring_");
  1976. if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
  1977. GV->setSection(Sect);
  1978. Entry.setValue(GV);
  1979. return GV;
  1980. }
  1981. static RecordDecl *
  1982. CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
  1983. DeclContext *DC, IdentifierInfo *Id) {
  1984. SourceLocation Loc;
  1985. if (Ctx.getLangOpts().CPlusPlus)
  1986. return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1987. else
  1988. return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1989. }
  1990. llvm::Constant *
  1991. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1992. unsigned StringLength = 0;
  1993. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1994. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  1995. if (llvm::Constant *C = Entry.getValue())
  1996. return C;
  1997. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1998. llvm::Constant *Zeros[] = { Zero, Zero };
  1999. // If we don't already have it, get _NSConstantStringClassReference.
  2000. if (!ConstantStringClassRef) {
  2001. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  2002. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2003. llvm::Constant *GV;
  2004. if (LangOpts.ObjCRuntime.isNonFragile()) {
  2005. std::string str =
  2006. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  2007. : "OBJC_CLASS_$_" + StringClass;
  2008. GV = getObjCRuntime().GetClassGlobal(str);
  2009. // Make sure the result is of the correct type.
  2010. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2011. ConstantStringClassRef =
  2012. llvm::ConstantExpr::getBitCast(GV, PTy);
  2013. } else {
  2014. std::string str =
  2015. StringClass.empty() ? "_NSConstantStringClassReference"
  2016. : "_" + StringClass + "ClassReference";
  2017. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  2018. GV = CreateRuntimeVariable(PTy, str);
  2019. // Decay array -> ptr
  2020. ConstantStringClassRef =
  2021. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2022. }
  2023. }
  2024. if (!NSConstantStringType) {
  2025. // Construct the type for a constant NSString.
  2026. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  2027. Context.getTranslationUnitDecl(),
  2028. &Context.Idents.get("__builtin_NSString"));
  2029. D->startDefinition();
  2030. QualType FieldTypes[3];
  2031. // const int *isa;
  2032. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2033. // const char *str;
  2034. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2035. // unsigned int length;
  2036. FieldTypes[2] = Context.UnsignedIntTy;
  2037. // Create fields
  2038. for (unsigned i = 0; i < 3; ++i) {
  2039. FieldDecl *Field = FieldDecl::Create(Context, D,
  2040. SourceLocation(),
  2041. SourceLocation(), 0,
  2042. FieldTypes[i], /*TInfo=*/0,
  2043. /*BitWidth=*/0,
  2044. /*Mutable=*/false,
  2045. ICIS_NoInit);
  2046. Field->setAccess(AS_public);
  2047. D->addDecl(Field);
  2048. }
  2049. D->completeDefinition();
  2050. QualType NSTy = Context.getTagDeclType(D);
  2051. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2052. }
  2053. llvm::Constant *Fields[3];
  2054. // Class pointer.
  2055. Fields[0] = ConstantStringClassRef;
  2056. // String pointer.
  2057. llvm::Constant *C =
  2058. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  2059. llvm::GlobalValue::LinkageTypes Linkage;
  2060. bool isConstant;
  2061. Linkage = llvm::GlobalValue::PrivateLinkage;
  2062. isConstant = !LangOpts.WritableStrings;
  2063. llvm::GlobalVariable *GV =
  2064. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  2065. ".str");
  2066. GV->setUnnamedAddr(true);
  2067. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2068. GV->setAlignment(Align.getQuantity());
  2069. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2070. // String length.
  2071. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2072. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2073. // The struct.
  2074. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2075. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2076. llvm::GlobalVariable::PrivateLinkage, C,
  2077. "_unnamed_nsstring_");
  2078. // FIXME. Fix section.
  2079. if (const char *Sect =
  2080. LangOpts.ObjCRuntime.isNonFragile()
  2081. ? getContext().getTargetInfo().getNSStringNonFragileABISection()
  2082. : getContext().getTargetInfo().getNSStringSection())
  2083. GV->setSection(Sect);
  2084. Entry.setValue(GV);
  2085. return GV;
  2086. }
  2087. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2088. if (ObjCFastEnumerationStateType.isNull()) {
  2089. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  2090. Context.getTranslationUnitDecl(),
  2091. &Context.Idents.get("__objcFastEnumerationState"));
  2092. D->startDefinition();
  2093. QualType FieldTypes[] = {
  2094. Context.UnsignedLongTy,
  2095. Context.getPointerType(Context.getObjCIdType()),
  2096. Context.getPointerType(Context.UnsignedLongTy),
  2097. Context.getConstantArrayType(Context.UnsignedLongTy,
  2098. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2099. };
  2100. for (size_t i = 0; i < 4; ++i) {
  2101. FieldDecl *Field = FieldDecl::Create(Context,
  2102. D,
  2103. SourceLocation(),
  2104. SourceLocation(), 0,
  2105. FieldTypes[i], /*TInfo=*/0,
  2106. /*BitWidth=*/0,
  2107. /*Mutable=*/false,
  2108. ICIS_NoInit);
  2109. Field->setAccess(AS_public);
  2110. D->addDecl(Field);
  2111. }
  2112. D->completeDefinition();
  2113. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2114. }
  2115. return ObjCFastEnumerationStateType;
  2116. }
  2117. llvm::Constant *
  2118. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2119. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2120. // Don't emit it as the address of the string, emit the string data itself
  2121. // as an inline array.
  2122. if (E->getCharByteWidth() == 1) {
  2123. SmallString<64> Str(E->getString());
  2124. // Resize the string to the right size, which is indicated by its type.
  2125. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2126. Str.resize(CAT->getSize().getZExtValue());
  2127. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2128. }
  2129. llvm::ArrayType *AType =
  2130. cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2131. llvm::Type *ElemTy = AType->getElementType();
  2132. unsigned NumElements = AType->getNumElements();
  2133. // Wide strings have either 2-byte or 4-byte elements.
  2134. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2135. SmallVector<uint16_t, 32> Elements;
  2136. Elements.reserve(NumElements);
  2137. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2138. Elements.push_back(E->getCodeUnit(i));
  2139. Elements.resize(NumElements);
  2140. return llvm::ConstantDataArray::get(VMContext, Elements);
  2141. }
  2142. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2143. SmallVector<uint32_t, 32> Elements;
  2144. Elements.reserve(NumElements);
  2145. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2146. Elements.push_back(E->getCodeUnit(i));
  2147. Elements.resize(NumElements);
  2148. return llvm::ConstantDataArray::get(VMContext, Elements);
  2149. }
  2150. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2151. /// constant array for the given string literal.
  2152. llvm::Constant *
  2153. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  2154. CharUnits Align = getContext().getTypeAlignInChars(S->getType());
  2155. if (S->isAscii() || S->isUTF8()) {
  2156. SmallString<64> Str(S->getString());
  2157. // Resize the string to the right size, which is indicated by its type.
  2158. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  2159. Str.resize(CAT->getSize().getZExtValue());
  2160. return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
  2161. }
  2162. // FIXME: the following does not memoize wide strings.
  2163. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2164. llvm::GlobalVariable *GV =
  2165. new llvm::GlobalVariable(getModule(),C->getType(),
  2166. !LangOpts.WritableStrings,
  2167. llvm::GlobalValue::PrivateLinkage,
  2168. C,".str");
  2169. GV->setAlignment(Align.getQuantity());
  2170. GV->setUnnamedAddr(true);
  2171. return GV;
  2172. }
  2173. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2174. /// array for the given ObjCEncodeExpr node.
  2175. llvm::Constant *
  2176. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2177. std::string Str;
  2178. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2179. return GetAddrOfConstantCString(Str);
  2180. }
  2181. /// GenerateWritableString -- Creates storage for a string literal.
  2182. static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
  2183. bool constant,
  2184. CodeGenModule &CGM,
  2185. const char *GlobalName,
  2186. unsigned Alignment) {
  2187. // Create Constant for this string literal. Don't add a '\0'.
  2188. llvm::Constant *C =
  2189. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
  2190. // Create a global variable for this string
  2191. llvm::GlobalVariable *GV =
  2192. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  2193. llvm::GlobalValue::PrivateLinkage,
  2194. C, GlobalName);
  2195. GV->setAlignment(Alignment);
  2196. GV->setUnnamedAddr(true);
  2197. return GV;
  2198. }
  2199. /// GetAddrOfConstantString - Returns a pointer to a character array
  2200. /// containing the literal. This contents are exactly that of the
  2201. /// given string, i.e. it will not be null terminated automatically;
  2202. /// see GetAddrOfConstantCString. Note that whether the result is
  2203. /// actually a pointer to an LLVM constant depends on
  2204. /// Feature.WriteableStrings.
  2205. ///
  2206. /// The result has pointer to array type.
  2207. llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
  2208. const char *GlobalName,
  2209. unsigned Alignment) {
  2210. // Get the default prefix if a name wasn't specified.
  2211. if (!GlobalName)
  2212. GlobalName = ".str";
  2213. // Don't share any string literals if strings aren't constant.
  2214. if (LangOpts.WritableStrings)
  2215. return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
  2216. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2217. ConstantStringMap.GetOrCreateValue(Str);
  2218. if (llvm::GlobalVariable *GV = Entry.getValue()) {
  2219. if (Alignment > GV->getAlignment()) {
  2220. GV->setAlignment(Alignment);
  2221. }
  2222. return GV;
  2223. }
  2224. // Create a global variable for this.
  2225. llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
  2226. Alignment);
  2227. Entry.setValue(GV);
  2228. return GV;
  2229. }
  2230. /// GetAddrOfConstantCString - Returns a pointer to a character
  2231. /// array containing the literal and a terminating '\0'
  2232. /// character. The result has pointer to array type.
  2233. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
  2234. const char *GlobalName,
  2235. unsigned Alignment) {
  2236. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2237. return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
  2238. }
  2239. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2240. /// properties for an implementation.
  2241. void CodeGenModule::EmitObjCPropertyImplementations(const
  2242. ObjCImplementationDecl *D) {
  2243. for (ObjCImplementationDecl::propimpl_iterator
  2244. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  2245. ObjCPropertyImplDecl *PID = *i;
  2246. // Dynamic is just for type-checking.
  2247. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2248. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2249. // Determine which methods need to be implemented, some may have
  2250. // been overridden. Note that ::isPropertyAccessor is not the method
  2251. // we want, that just indicates if the decl came from a
  2252. // property. What we want to know is if the method is defined in
  2253. // this implementation.
  2254. if (!D->getInstanceMethod(PD->getGetterName()))
  2255. CodeGenFunction(*this).GenerateObjCGetter(
  2256. const_cast<ObjCImplementationDecl *>(D), PID);
  2257. if (!PD->isReadOnly() &&
  2258. !D->getInstanceMethod(PD->getSetterName()))
  2259. CodeGenFunction(*this).GenerateObjCSetter(
  2260. const_cast<ObjCImplementationDecl *>(D), PID);
  2261. }
  2262. }
  2263. }
  2264. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2265. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2266. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2267. ivar; ivar = ivar->getNextIvar())
  2268. if (ivar->getType().isDestructedType())
  2269. return true;
  2270. return false;
  2271. }
  2272. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2273. /// for an implementation.
  2274. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2275. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2276. if (needsDestructMethod(D)) {
  2277. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2278. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2279. ObjCMethodDecl *DTORMethod =
  2280. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2281. cxxSelector, getContext().VoidTy, 0, D,
  2282. /*isInstance=*/true, /*isVariadic=*/false,
  2283. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2284. /*isDefined=*/false, ObjCMethodDecl::Required);
  2285. D->addInstanceMethod(DTORMethod);
  2286. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2287. D->setHasDestructors(true);
  2288. }
  2289. // If the implementation doesn't have any ivar initializers, we don't need
  2290. // a .cxx_construct.
  2291. if (D->getNumIvarInitializers() == 0)
  2292. return;
  2293. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2294. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2295. // The constructor returns 'self'.
  2296. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2297. D->getLocation(),
  2298. D->getLocation(),
  2299. cxxSelector,
  2300. getContext().getObjCIdType(), 0,
  2301. D, /*isInstance=*/true,
  2302. /*isVariadic=*/false,
  2303. /*isPropertyAccessor=*/true,
  2304. /*isImplicitlyDeclared=*/true,
  2305. /*isDefined=*/false,
  2306. ObjCMethodDecl::Required);
  2307. D->addInstanceMethod(CTORMethod);
  2308. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2309. D->setHasNonZeroConstructors(true);
  2310. }
  2311. /// EmitNamespace - Emit all declarations in a namespace.
  2312. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2313. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  2314. I != E; ++I)
  2315. EmitTopLevelDecl(*I);
  2316. }
  2317. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2318. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2319. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2320. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2321. ErrorUnsupported(LSD, "linkage spec");
  2322. return;
  2323. }
  2324. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  2325. I != E; ++I) {
  2326. // Meta-data for ObjC class includes references to implemented methods.
  2327. // Generate class's method definitions first.
  2328. if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
  2329. for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
  2330. MEnd = OID->meth_end();
  2331. M != MEnd; ++M)
  2332. EmitTopLevelDecl(*M);
  2333. }
  2334. EmitTopLevelDecl(*I);
  2335. }
  2336. }
  2337. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2338. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2339. // If an error has occurred, stop code generation, but continue
  2340. // parsing and semantic analysis (to ensure all warnings and errors
  2341. // are emitted).
  2342. if (Diags.hasErrorOccurred())
  2343. return;
  2344. // Ignore dependent declarations.
  2345. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2346. return;
  2347. switch (D->getKind()) {
  2348. case Decl::CXXConversion:
  2349. case Decl::CXXMethod:
  2350. case Decl::Function:
  2351. // Skip function templates
  2352. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2353. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2354. return;
  2355. EmitGlobal(cast<FunctionDecl>(D));
  2356. break;
  2357. case Decl::Var:
  2358. EmitGlobal(cast<VarDecl>(D));
  2359. break;
  2360. // Indirect fields from global anonymous structs and unions can be
  2361. // ignored; only the actual variable requires IR gen support.
  2362. case Decl::IndirectField:
  2363. break;
  2364. // C++ Decls
  2365. case Decl::Namespace:
  2366. EmitNamespace(cast<NamespaceDecl>(D));
  2367. break;
  2368. // No code generation needed.
  2369. case Decl::UsingShadow:
  2370. case Decl::Using:
  2371. case Decl::UsingDirective:
  2372. case Decl::ClassTemplate:
  2373. case Decl::FunctionTemplate:
  2374. case Decl::TypeAliasTemplate:
  2375. case Decl::NamespaceAlias:
  2376. case Decl::Block:
  2377. break;
  2378. case Decl::CXXConstructor:
  2379. // Skip function templates
  2380. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2381. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2382. return;
  2383. EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2384. break;
  2385. case Decl::CXXDestructor:
  2386. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2387. return;
  2388. EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2389. break;
  2390. case Decl::StaticAssert:
  2391. // Nothing to do.
  2392. break;
  2393. // Objective-C Decls
  2394. // Forward declarations, no (immediate) code generation.
  2395. case Decl::ObjCInterface:
  2396. case Decl::ObjCCategory:
  2397. break;
  2398. case Decl::ObjCProtocol: {
  2399. ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
  2400. if (Proto->isThisDeclarationADefinition())
  2401. ObjCRuntime->GenerateProtocol(Proto);
  2402. break;
  2403. }
  2404. case Decl::ObjCCategoryImpl:
  2405. // Categories have properties but don't support synthesize so we
  2406. // can ignore them here.
  2407. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2408. break;
  2409. case Decl::ObjCImplementation: {
  2410. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  2411. EmitObjCPropertyImplementations(OMD);
  2412. EmitObjCIvarInitializations(OMD);
  2413. ObjCRuntime->GenerateClass(OMD);
  2414. // Emit global variable debug information.
  2415. if (CGDebugInfo *DI = getModuleDebugInfo())
  2416. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2417. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2418. OMD->getClassInterface()), OMD->getLocation());
  2419. break;
  2420. }
  2421. case Decl::ObjCMethod: {
  2422. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  2423. // If this is not a prototype, emit the body.
  2424. if (OMD->getBody())
  2425. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2426. break;
  2427. }
  2428. case Decl::ObjCCompatibleAlias:
  2429. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2430. break;
  2431. case Decl::LinkageSpec:
  2432. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2433. break;
  2434. case Decl::FileScopeAsm: {
  2435. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  2436. StringRef AsmString = AD->getAsmString()->getString();
  2437. const std::string &S = getModule().getModuleInlineAsm();
  2438. if (S.empty())
  2439. getModule().setModuleInlineAsm(AsmString);
  2440. else if (S.end()[-1] == '\n')
  2441. getModule().setModuleInlineAsm(S + AsmString.str());
  2442. else
  2443. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2444. break;
  2445. }
  2446. case Decl::Import: {
  2447. ImportDecl *Import = cast<ImportDecl>(D);
  2448. // Ignore import declarations that come from imported modules.
  2449. if (clang::Module *Owner = Import->getOwningModule()) {
  2450. if (getLangOpts().CurrentModule.empty() ||
  2451. Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
  2452. break;
  2453. }
  2454. ImportedModules.insert(Import->getImportedModule());
  2455. break;
  2456. }
  2457. default:
  2458. // Make sure we handled everything we should, every other kind is a
  2459. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2460. // function. Need to recode Decl::Kind to do that easily.
  2461. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2462. }
  2463. }
  2464. /// Turns the given pointer into a constant.
  2465. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2466. const void *Ptr) {
  2467. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2468. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2469. return llvm::ConstantInt::get(i64, PtrInt);
  2470. }
  2471. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2472. llvm::NamedMDNode *&GlobalMetadata,
  2473. GlobalDecl D,
  2474. llvm::GlobalValue *Addr) {
  2475. if (!GlobalMetadata)
  2476. GlobalMetadata =
  2477. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2478. // TODO: should we report variant information for ctors/dtors?
  2479. llvm::Value *Ops[] = {
  2480. Addr,
  2481. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2482. };
  2483. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2484. }
  2485. /// Emits metadata nodes associating all the global values in the
  2486. /// current module with the Decls they came from. This is useful for
  2487. /// projects using IR gen as a subroutine.
  2488. ///
  2489. /// Since there's currently no way to associate an MDNode directly
  2490. /// with an llvm::GlobalValue, we create a global named metadata
  2491. /// with the name 'clang.global.decl.ptrs'.
  2492. void CodeGenModule::EmitDeclMetadata() {
  2493. llvm::NamedMDNode *GlobalMetadata = 0;
  2494. // StaticLocalDeclMap
  2495. for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
  2496. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  2497. I != E; ++I) {
  2498. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  2499. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  2500. }
  2501. }
  2502. /// Emits metadata nodes for all the local variables in the current
  2503. /// function.
  2504. void CodeGenFunction::EmitDeclMetadata() {
  2505. if (LocalDeclMap.empty()) return;
  2506. llvm::LLVMContext &Context = getLLVMContext();
  2507. // Find the unique metadata ID for this name.
  2508. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2509. llvm::NamedMDNode *GlobalMetadata = 0;
  2510. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  2511. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  2512. const Decl *D = I->first;
  2513. llvm::Value *Addr = I->second;
  2514. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2515. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2516. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2517. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2518. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2519. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2520. }
  2521. }
  2522. }
  2523. void CodeGenModule::EmitCoverageFile() {
  2524. if (!getCodeGenOpts().CoverageFile.empty()) {
  2525. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2526. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2527. llvm::LLVMContext &Ctx = TheModule.getContext();
  2528. llvm::MDString *CoverageFile =
  2529. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2530. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2531. llvm::MDNode *CU = CUNode->getOperand(i);
  2532. llvm::Value *node[] = { CoverageFile, CU };
  2533. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2534. GCov->addOperand(N);
  2535. }
  2536. }
  2537. }
  2538. }
  2539. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
  2540. QualType GuidType) {
  2541. // Sema has checked that all uuid strings are of the form
  2542. // "12345678-1234-1234-1234-1234567890ab".
  2543. assert(Uuid.size() == 36);
  2544. const char *Uuidstr = Uuid.data();
  2545. for (int i = 0; i < 36; ++i) {
  2546. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
  2547. else assert(isxdigit(Uuidstr[i]));
  2548. }
  2549. llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
  2550. llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
  2551. llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
  2552. static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  2553. APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
  2554. InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
  2555. InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
  2556. InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
  2557. APValue& Arr = InitStruct.getStructField(3);
  2558. Arr = APValue(APValue::UninitArray(), 8, 8);
  2559. for (int t = 0; t < 8; ++t)
  2560. Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
  2561. llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
  2562. return EmitConstantValue(InitStruct, GuidType);
  2563. }