CodeGenModule.cpp 117 KB

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