CodeGenModule.cpp 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833
  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 "CGHLSLRuntime.h" // HLSL Change
  21. #include "CGOpenMPRuntime.h"
  22. #include "CodeGenFunction.h"
  23. #include "CodeGenPGO.h"
  24. #include "CodeGenTBAA.h"
  25. #include "CoverageMappingGen.h"
  26. #include "TargetInfo.h"
  27. #include "clang/AST/ASTContext.h"
  28. #include "clang/AST/CharUnits.h"
  29. #include "clang/AST/DeclCXX.h"
  30. #include "clang/AST/DeclObjC.h"
  31. #include "clang/AST/DeclTemplate.h"
  32. #include "clang/AST/Mangle.h"
  33. #include "clang/AST/RecordLayout.h"
  34. #include "clang/AST/RecursiveASTVisitor.h"
  35. #include "clang/Basic/Builtins.h"
  36. #include "clang/Basic/CharInfo.h"
  37. #include "clang/Basic/Diagnostic.h"
  38. #include "clang/Basic/Module.h"
  39. #include "clang/Basic/SourceManager.h"
  40. #include "clang/Basic/TargetInfo.h"
  41. #include "clang/Basic/Version.h"
  42. #include "clang/Frontend/CodeGenOptions.h"
  43. #include "clang/Sema/SemaDiagnostic.h"
  44. #include "llvm/ADT/APSInt.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include "llvm/IR/CallSite.h"
  47. #include "llvm/IR/CallingConv.h"
  48. #include "llvm/IR/DataLayout.h"
  49. #include "llvm/IR/Intrinsics.h"
  50. #include "llvm/IR/LLVMContext.h"
  51. #include "llvm/IR/Module.h"
  52. #include "llvm/ProfileData/InstrProfReader.h"
  53. #include "llvm/Support/ConvertUTF.h"
  54. #include "llvm/Support/ErrorHandling.h"
  55. #include "dxc/HLSL/DxilConstants.h" // HLSL Change
  56. using namespace clang;
  57. using namespace CodeGen;
  58. static const char AnnotationSection[] = "llvm.metadata";
  59. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  60. switch (CGM.getTarget().getCXXABI().getKind()) {
  61. case TargetCXXABI::GenericAArch64:
  62. case TargetCXXABI::GenericARM:
  63. case TargetCXXABI::iOS:
  64. case TargetCXXABI::iOS64:
  65. case TargetCXXABI::GenericMIPS:
  66. case TargetCXXABI::GenericItanium:
  67. return CreateItaniumCXXABI(CGM);
  68. case TargetCXXABI::Microsoft:
  69. return CreateMicrosoftCXXABI(CGM);
  70. }
  71. llvm_unreachable("invalid C++ ABI kind");
  72. }
  73. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  74. const PreprocessorOptions &PPO,
  75. const CodeGenOptions &CGO, llvm::Module &M,
  76. const llvm::DataLayout &TD,
  77. DiagnosticsEngine &diags,
  78. CoverageSourceInfo *CoverageInfo)
  79. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  80. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  81. TheDataLayout(TD), Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  82. VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr),
  83. Types(*this), VTables(*this), ObjCRuntime(nullptr),
  84. OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr),
  85. HLSLRuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr), // HLSL Change
  86. NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
  87. CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
  88. NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
  89. NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
  90. BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
  91. GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
  92. LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
  93. // Initialize the type cache.
  94. llvm::LLVMContext &LLVMContext = M.getContext();
  95. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  96. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  97. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  98. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  99. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  100. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  101. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  102. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  103. PointerAlignInBytes =
  104. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  105. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  106. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  107. Int8PtrTy = Int8Ty->getPointerTo(0);
  108. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  109. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  110. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  111. if (LangOpts.ObjC1)
  112. createObjCRuntime();
  113. if (LangOpts.OpenCL)
  114. createOpenCLRuntime();
  115. if (LangOpts.OpenMP)
  116. createOpenMPRuntime();
  117. if (LangOpts.CUDA)
  118. createCUDARuntime();
  119. // HLSL Change Starts
  120. std::unique_ptr<CGHLSLRuntime> RuntimePtr;
  121. std::unique_ptr<CodeGenTBAA> TBAAPtr;
  122. std::unique_ptr<CGDebugInfo> DebugInfoPtr;
  123. if (LangOpts.HLSL) {
  124. createHLSLRuntime();
  125. RuntimePtr.reset(HLSLRuntime);
  126. }
  127. // HLSL Change Ends
  128. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  129. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  130. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  131. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  132. getCXXABI().getMangleContext());
  133. TBAAPtr.reset(TBAA); // HLSL Change
  134. // If debug info or coverage generation is enabled, create the CGDebugInfo
  135. // object.
  136. if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
  137. CodeGenOpts.EmitGcovArcs ||
  138. CodeGenOpts.EmitGcovNotes)
  139. DebugInfo = new CGDebugInfo(*this);
  140. DebugInfoPtr.reset(DebugInfo); // HLSL Change
  141. Block.GlobalUniqueCount = 0;
  142. #if 0 // HLSL Change Starts - no ARC support
  143. if (C.getLangOpts().ObjCAutoRefCount)
  144. ARCData = new ARCEntrypoints();
  145. RRData = new RREntrypoints();
  146. #endif // HLSL Change Ends - no ARC support
  147. if (!CodeGenOpts.InstrProfileInput.empty()) {
  148. auto ReaderOrErr =
  149. llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
  150. if (std::error_code EC = ReaderOrErr.getError()) {
  151. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  152. "Could not read profile %0: %1");
  153. getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput
  154. << EC.message();
  155. } else
  156. PGOReader = std::move(ReaderOrErr.get());
  157. }
  158. // If coverage mapping generation is enabled, create the
  159. // CoverageMappingModuleGen object.
  160. if (CodeGenOpts.CoverageMapping)
  161. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  162. // HLSL Change Starts - release acquired pointers
  163. RuntimePtr.release();
  164. TBAAPtr.release();
  165. DebugInfoPtr.release();
  166. // HLSL Change Ends
  167. }
  168. CodeGenModule::~CodeGenModule() {
  169. #if 0 // HLSL Change - no ObjC, OpenCL, OpenMP, or CUDA support
  170. delete ObjCRuntime;
  171. delete OpenCLRuntime;
  172. delete OpenMPRuntime;
  173. delete CUDARuntime;
  174. #endif // HLSL Change
  175. delete HLSLRuntime; // HLSL Change
  176. TheTargetCodeGenInfo.reset(nullptr); // HLSL Change
  177. delete TBAA;
  178. delete DebugInfo;
  179. delete ARCData;
  180. delete RRData;
  181. }
  182. void CodeGenModule::createObjCRuntime() {
  183. #if 0 // HLSL Change - no ObjC support
  184. // This is just isGNUFamily(), but we want to force implementors of
  185. // new ABIs to decide how best to do this.
  186. switch (LangOpts.ObjCRuntime.getKind()) {
  187. case ObjCRuntime::GNUstep:
  188. case ObjCRuntime::GCC:
  189. case ObjCRuntime::ObjFW:
  190. ObjCRuntime = CreateGNUObjCRuntime(*this);
  191. return;
  192. case ObjCRuntime::FragileMacOSX:
  193. case ObjCRuntime::MacOSX:
  194. case ObjCRuntime::iOS:
  195. ObjCRuntime = CreateMacObjCRuntime(*this);
  196. return;
  197. }
  198. llvm_unreachable("bad runtime kind");
  199. #endif // HLSL Change - no ObjC support
  200. }
  201. void CodeGenModule::createOpenCLRuntime() {
  202. #if 0 // HLSL Change - no OpenCL support
  203. OpenCLRuntime = new CGOpenCLRuntime(*this);
  204. #endif // HLSL Change - no OpenCL support
  205. }
  206. void CodeGenModule::createOpenMPRuntime() {
  207. #if 0 // HLSL Change - no OpenMP support
  208. OpenMPRuntime = new CGOpenMPRuntime(*this);
  209. #endif // HLSL Change - no OpenMP support
  210. }
  211. void CodeGenModule::createCUDARuntime() {
  212. #if 0 // HLSL Change - no CUDA support
  213. CUDARuntime = CreateNVCUDARuntime(*this);
  214. #endif // HLSL Change - no CUDA support
  215. }
  216. // HLSL Change Starts
  217. void CodeGenModule::createHLSLRuntime() {
  218. HLSLRuntime = CreateMSHLSLRuntime(*this);
  219. }
  220. void CodeGenModule::FinishCodeGen() {
  221. HLSLRuntime->FinishCodeGen();
  222. }
  223. // HLSL Change Ends
  224. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  225. Replacements[Name] = C;
  226. }
  227. void CodeGenModule::applyReplacements() {
  228. for (auto &I : Replacements) {
  229. StringRef MangledName = I.first();
  230. llvm::Constant *Replacement = I.second;
  231. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  232. if (!Entry)
  233. continue;
  234. auto *OldF = cast<llvm::Function>(Entry);
  235. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  236. if (!NewF) {
  237. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  238. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  239. } else {
  240. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  241. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  242. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  243. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  244. }
  245. }
  246. // Replace old with new, but keep the old order.
  247. OldF->replaceAllUsesWith(Replacement);
  248. if (NewF) {
  249. NewF->removeFromParent();
  250. OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
  251. }
  252. OldF->eraseFromParent();
  253. }
  254. }
  255. // This is only used in aliases that we created and we know they have a
  256. // linear structure.
  257. static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
  258. llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
  259. const llvm::Constant *C = &GA;
  260. for (;;) {
  261. C = C->stripPointerCasts();
  262. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  263. return GO;
  264. // stripPointerCasts will not walk over weak aliases.
  265. auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
  266. if (!GA2)
  267. return nullptr;
  268. if (!Visited.insert(GA2).second)
  269. return nullptr;
  270. C = GA2->getAliasee();
  271. }
  272. }
  273. void CodeGenModule::checkAliases() {
  274. // Check if the constructed aliases are well formed. It is really unfortunate
  275. // that we have to do this in CodeGen, but we only construct mangled names
  276. // and aliases during codegen.
  277. bool Error = false;
  278. DiagnosticsEngine &Diags = getDiags();
  279. for (const GlobalDecl &GD : Aliases) {
  280. const auto *D = cast<ValueDecl>(GD.getDecl());
  281. const AliasAttr *AA = D->getAttr<AliasAttr>();
  282. StringRef MangledName = getMangledName(GD);
  283. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  284. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  285. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  286. if (!GV) {
  287. Error = true;
  288. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  289. } else if (GV->isDeclaration()) {
  290. Error = true;
  291. Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
  292. }
  293. llvm::Constant *Aliasee = Alias->getAliasee();
  294. llvm::GlobalValue *AliaseeGV;
  295. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  296. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  297. else
  298. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  299. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  300. StringRef AliasSection = SA->getName();
  301. if (AliasSection != AliaseeGV->getSection())
  302. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  303. << AliasSection;
  304. }
  305. // We have to handle alias to weak aliases in here. LLVM itself disallows
  306. // this since the object semantics would not match the IL one. For
  307. // compatibility with gcc we implement it by just pointing the alias
  308. // to its aliasee's aliasee. We also warn, since the user is probably
  309. // expecting the link to be weak.
  310. if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
  311. if (GA->mayBeOverridden()) {
  312. Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
  313. << GV->getName() << GA->getName();
  314. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  315. GA->getAliasee(), Alias->getType());
  316. Alias->setAliasee(Aliasee);
  317. }
  318. }
  319. }
  320. if (!Error)
  321. return;
  322. for (const GlobalDecl &GD : Aliases) {
  323. StringRef MangledName = getMangledName(GD);
  324. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  325. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  326. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  327. Alias->eraseFromParent();
  328. }
  329. }
  330. void CodeGenModule::clear() {
  331. DeferredDeclsToEmit.clear();
  332. if (OpenMPRuntime)
  333. OpenMPRuntime->clear();
  334. }
  335. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  336. StringRef MainFile) {
  337. if (!hasDiagnostics())
  338. return;
  339. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  340. if (MainFile.empty())
  341. MainFile = "<stdin>";
  342. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  343. } else
  344. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
  345. << Mismatched;
  346. }
  347. void CodeGenModule::Release() {
  348. EmitDeferred();
  349. applyReplacements();
  350. checkAliases();
  351. EmitCXXGlobalInitFunc();
  352. EmitCXXGlobalDtorFunc();
  353. EmitCXXThreadLocalInitFunc();
  354. if (ObjCRuntime)
  355. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  356. AddGlobalCtor(ObjCInitFunction);
  357. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  358. CUDARuntime) {
  359. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  360. AddGlobalCtor(CudaCtorFunction);
  361. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  362. AddGlobalDtor(CudaDtorFunction);
  363. }
  364. if (PGOReader && PGOStats.hasDiagnostics())
  365. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  366. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  367. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  368. EmitGlobalAnnotations();
  369. EmitStaticExternCAliases();
  370. EmitDeferredUnusedCoverageMappings();
  371. if (CoverageMapping)
  372. CoverageMapping->emit();
  373. emitLLVMUsed();
  374. if (CodeGenOpts.Autolink &&
  375. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  376. EmitModuleLinkOptions();
  377. }
  378. if (CodeGenOpts.DwarfVersion)
  379. // We actually want the latest version when there are conflicts.
  380. // We can change from Warning to Latest if such mode is supported.
  381. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  382. CodeGenOpts.DwarfVersion);
  383. if (DebugInfo)
  384. // We support a single version in the linked module. The LLVM
  385. // parser will drop debug info with a different version number
  386. // (and warn about it, too).
  387. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  388. llvm::DEBUG_METADATA_VERSION);
  389. // We need to record the widths of enums and wchar_t, so that we can generate
  390. // the correct build attributes in the ARM backend.
  391. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  392. if ( Arch == llvm::Triple::arm
  393. || Arch == llvm::Triple::armeb
  394. || Arch == llvm::Triple::thumb
  395. || Arch == llvm::Triple::thumbeb) {
  396. // Width of wchar_t in bytes
  397. uint64_t WCharWidth =
  398. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  399. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  400. // The minimum width of an enum in bytes
  401. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  402. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  403. }
  404. // HLSL Change Starts
  405. if (Context.getLangOpts().HLSL) {
  406. FinishCodeGen();
  407. }
  408. // HLSL Change Ends
  409. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  410. llvm::PICLevel::Level PL = llvm::PICLevel::Default;
  411. switch (PLevel) {
  412. case 0: break;
  413. case 1: PL = llvm::PICLevel::Small; break;
  414. case 2: PL = llvm::PICLevel::Large; break;
  415. default: llvm_unreachable("Invalid PIC Level");
  416. }
  417. getModule().setPICLevel(PL);
  418. }
  419. SimplifyPersonality();
  420. if (getCodeGenOpts().EmitDeclMetadata)
  421. EmitDeclMetadata();
  422. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  423. EmitCoverageFile();
  424. if (DebugInfo)
  425. DebugInfo->finalize();
  426. EmitVersionIdentMetadata();
  427. EmitTargetMetadata();
  428. }
  429. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  430. // Make sure that this type is translated.
  431. Types.UpdateCompletedType(TD);
  432. }
  433. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  434. if (!TBAA)
  435. return nullptr;
  436. return TBAA->getTBAAInfo(QTy);
  437. }
  438. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  439. if (!TBAA)
  440. return nullptr;
  441. return TBAA->getTBAAInfoForVTablePtr();
  442. }
  443. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  444. if (!TBAA)
  445. return nullptr;
  446. return TBAA->getTBAAStructInfo(QTy);
  447. }
  448. llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
  449. if (!TBAA)
  450. return nullptr;
  451. return TBAA->getTBAAStructTypeInfo(QTy);
  452. }
  453. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  454. llvm::MDNode *AccessN,
  455. uint64_t O) {
  456. if (!TBAA)
  457. return nullptr;
  458. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  459. }
  460. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  461. /// and struct-path aware TBAA, the tag has the same format:
  462. /// base type, access type and offset.
  463. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  464. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  465. llvm::MDNode *TBAAInfo,
  466. bool ConvertTypeToTag) {
  467. if (ConvertTypeToTag && TBAA)
  468. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  469. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  470. else
  471. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  472. }
  473. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  474. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  475. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  476. }
  477. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  478. /// specified stmt yet.
  479. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  480. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  481. "cannot compile this %0 yet");
  482. std::string Msg = Type;
  483. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  484. << Msg << S->getSourceRange();
  485. }
  486. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  487. /// specified decl yet.
  488. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  489. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  490. "cannot compile this %0 yet");
  491. std::string Msg = Type;
  492. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  493. }
  494. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  495. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  496. }
  497. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  498. const NamedDecl *D) const {
  499. // Internal definitions always have default visibility.
  500. if (GV->hasLocalLinkage()) {
  501. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  502. return;
  503. }
  504. // Set visibility for definitions.
  505. LinkageInfo LV = D->getLinkageAndVisibility();
  506. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  507. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  508. }
  509. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  510. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  511. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  512. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  513. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  514. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  515. }
  516. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  517. CodeGenOptions::TLSModel M) {
  518. switch (M) {
  519. case CodeGenOptions::GeneralDynamicTLSModel:
  520. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  521. case CodeGenOptions::LocalDynamicTLSModel:
  522. return llvm::GlobalVariable::LocalDynamicTLSModel;
  523. case CodeGenOptions::InitialExecTLSModel:
  524. return llvm::GlobalVariable::InitialExecTLSModel;
  525. case CodeGenOptions::LocalExecTLSModel:
  526. return llvm::GlobalVariable::LocalExecTLSModel;
  527. }
  528. llvm_unreachable("Invalid TLS model!");
  529. }
  530. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  531. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  532. llvm::GlobalValue::ThreadLocalMode TLM;
  533. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  534. // Override the TLS model if it is explicitly specified.
  535. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  536. TLM = GetLLVMTLSModel(Attr->getModel());
  537. }
  538. GV->setThreadLocalMode(TLM);
  539. }
  540. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  541. StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
  542. if (!FoundStr.empty())
  543. return FoundStr;
  544. const auto *ND = cast<NamedDecl>(GD.getDecl());
  545. // HLSL Change Starts
  546. if (ND->getKind() == Decl::Function &&
  547. ND->getNameAsString() == CodeGenOpts.HLSLEntryFunction) {
  548. return CodeGenOpts.HLSLEntryFunction;
  549. }
  550. // HLSL Change Ends
  551. SmallString<256> Buffer;
  552. StringRef Str;
  553. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  554. llvm::raw_svector_ostream Out(Buffer);
  555. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  556. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  557. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  558. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  559. else
  560. getCXXABI().getMangleContext().mangleName(ND, Out);
  561. Str = Out.str();
  562. } else {
  563. IdentifierInfo *II = ND->getIdentifier();
  564. assert(II && "Attempt to mangle unnamed decl.");
  565. Str = II->getName();
  566. }
  567. // Keep the first result in the case of a mangling collision.
  568. auto Result = Manglings.insert(std::make_pair(Str, GD));
  569. return FoundStr = Result.first->first();
  570. }
  571. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  572. const BlockDecl *BD) {
  573. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  574. const Decl *D = GD.getDecl();
  575. SmallString<256> Buffer;
  576. llvm::raw_svector_ostream Out(Buffer);
  577. if (!D)
  578. MangleCtx.mangleGlobalBlock(BD,
  579. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  580. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  581. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  582. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  583. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  584. else
  585. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  586. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  587. return Result.first->first();
  588. }
  589. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  590. return getModule().getNamedValue(Name);
  591. }
  592. /// AddGlobalCtor - Add a function to the list that will be called before
  593. /// main() runs.
  594. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  595. llvm::Constant *AssociatedData) {
  596. // FIXME: Type coercion of void()* types.
  597. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  598. }
  599. /// AddGlobalDtor - Add a function to the list that will be called
  600. /// when the module is unloaded.
  601. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  602. // FIXME: Type coercion of void()* types.
  603. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  604. }
  605. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  606. // Ctor function type is void()*.
  607. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  608. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  609. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  610. llvm::StructType *CtorStructTy = llvm::StructType::get(
  611. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
  612. // Construct the constructor and destructor arrays.
  613. SmallVector<llvm::Constant *, 8> Ctors;
  614. for (const auto &I : Fns) {
  615. llvm::Constant *S[] = {
  616. llvm::ConstantInt::get(Int32Ty, I.Priority, false),
  617. llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
  618. (I.AssociatedData
  619. ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
  620. : llvm::Constant::getNullValue(VoidPtrTy))};
  621. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  622. }
  623. if (!Ctors.empty()) {
  624. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  625. new llvm::GlobalVariable(TheModule, AT, false,
  626. llvm::GlobalValue::AppendingLinkage,
  627. llvm::ConstantArray::get(AT, Ctors),
  628. GlobalName);
  629. }
  630. }
  631. llvm::GlobalValue::LinkageTypes
  632. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  633. const auto *D = cast<FunctionDecl>(GD.getDecl());
  634. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  635. if (isa<CXXDestructorDecl>(D) &&
  636. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  637. GD.getDtorType())) {
  638. // Destructor variants in the Microsoft C++ ABI are always internal or
  639. // linkonce_odr thunks emitted on an as-needed basis.
  640. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  641. : llvm::GlobalValue::LinkOnceODRLinkage;
  642. }
  643. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  644. }
  645. void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
  646. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  647. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  648. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  649. // Don't dllexport/import destructor thunks.
  650. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  651. return;
  652. }
  653. }
  654. if (FD->hasAttr<DLLImportAttr>())
  655. F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  656. else if (FD->hasAttr<DLLExportAttr>())
  657. F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  658. else
  659. F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  660. }
  661. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  662. llvm::Function *F) {
  663. setNonAliasAttributes(D, F);
  664. }
  665. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  666. const CGFunctionInfo &Info,
  667. llvm::Function *F) {
  668. unsigned CallingConv;
  669. AttributeListType AttributeList;
  670. ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
  671. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  672. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  673. // HLSL Change Begins
  674. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  675. getHLSLRuntime().AddHLSLFunctionInfo(F, FD);
  676. // HLSL Change Ends
  677. }
  678. /// Determines whether the language options require us to model
  679. /// unwind exceptions. We treat -fexceptions as mandating this
  680. /// except under the fragile ObjC ABI with only ObjC exceptions
  681. /// enabled. This means, for example, that C with -fexceptions
  682. /// enables this.
  683. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  684. // If exceptions are completely disabled, obviously this is false.
  685. if (!LangOpts.Exceptions) return false;
  686. // If C++ exceptions are enabled, this is true.
  687. if (LangOpts.CXXExceptions) return true;
  688. // If ObjC exceptions are enabled, this depends on the ABI.
  689. if (LangOpts.ObjCExceptions) {
  690. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  691. }
  692. return true;
  693. }
  694. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  695. llvm::Function *F) {
  696. llvm::AttrBuilder B;
  697. if (CodeGenOpts.UnwindTables)
  698. B.addAttribute(llvm::Attribute::UWTable);
  699. if (!hasUnwindExceptions(LangOpts))
  700. B.addAttribute(llvm::Attribute::NoUnwind);
  701. if (D->hasAttr<NakedAttr>()) {
  702. // Naked implies noinline: we should not be inlining such functions.
  703. B.addAttribute(llvm::Attribute::Naked);
  704. B.addAttribute(llvm::Attribute::NoInline);
  705. } else if (D->hasAttr<NoDuplicateAttr>()) {
  706. B.addAttribute(llvm::Attribute::NoDuplicate);
  707. } else if (D->hasAttr<NoInlineAttr>()) {
  708. B.addAttribute(llvm::Attribute::NoInline);
  709. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  710. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  711. llvm::Attribute::NoInline)) {
  712. // (noinline wins over always_inline, and we can't specify both in IR)
  713. B.addAttribute(llvm::Attribute::AlwaysInline);
  714. }
  715. if (D->hasAttr<ColdAttr>()) {
  716. if (!D->hasAttr<OptimizeNoneAttr>())
  717. B.addAttribute(llvm::Attribute::OptimizeForSize);
  718. B.addAttribute(llvm::Attribute::Cold);
  719. }
  720. if (D->hasAttr<MinSizeAttr>())
  721. B.addAttribute(llvm::Attribute::MinSize);
  722. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  723. B.addAttribute(llvm::Attribute::StackProtect);
  724. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  725. B.addAttribute(llvm::Attribute::StackProtectStrong);
  726. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  727. B.addAttribute(llvm::Attribute::StackProtectReq);
  728. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  729. llvm::AttributeSet::get(
  730. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  731. if (D->hasAttr<OptimizeNoneAttr>()) {
  732. // OptimizeNone implies noinline; we should not be inlining such functions.
  733. F->addFnAttr(llvm::Attribute::OptimizeNone);
  734. F->addFnAttr(llvm::Attribute::NoInline);
  735. // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
  736. assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
  737. "OptimizeNone and OptimizeForSize on same function!");
  738. assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
  739. "OptimizeNone and MinSize on same function!");
  740. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  741. "OptimizeNone and AlwaysInline on same function!");
  742. // Attribute 'inlinehint' has no effect on 'optnone' functions.
  743. // Explicitly remove it from the set of function attributes.
  744. F->removeFnAttr(llvm::Attribute::InlineHint);
  745. }
  746. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  747. F->setUnnamedAddr(true);
  748. else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
  749. if (MD->isVirtual())
  750. F->setUnnamedAddr(true);
  751. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  752. if (alignment)
  753. F->setAlignment(alignment);
  754. // C++ ABI requires 2-byte alignment for member functions.
  755. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  756. F->setAlignment(2);
  757. }
  758. void CodeGenModule::SetCommonAttributes(const Decl *D,
  759. llvm::GlobalValue *GV) {
  760. if (const auto *ND = dyn_cast<NamedDecl>(D))
  761. setGlobalVisibility(GV, ND);
  762. else
  763. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  764. if (D->hasAttr<UsedAttr>())
  765. addUsedGlobal(GV);
  766. }
  767. void CodeGenModule::setAliasAttributes(const Decl *D,
  768. llvm::GlobalValue *GV) {
  769. SetCommonAttributes(D, GV);
  770. // Process the dllexport attribute based on whether the original definition
  771. // (not necessarily the aliasee) was exported.
  772. if (D->hasAttr<DLLExportAttr>())
  773. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  774. }
  775. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  776. llvm::GlobalObject *GO) {
  777. SetCommonAttributes(D, GO);
  778. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  779. GO->setSection(SA->getName());
  780. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  781. }
  782. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  783. llvm::Function *F,
  784. const CGFunctionInfo &FI) {
  785. SetLLVMFunctionAttributes(D, FI, F);
  786. SetLLVMFunctionAttributesForDefinition(D, F);
  787. F->setLinkage(llvm::Function::InternalLinkage);
  788. setNonAliasAttributes(D, F);
  789. }
  790. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  791. const NamedDecl *ND) {
  792. // Set linkage and visibility in case we never see a definition.
  793. LinkageInfo LV = ND->getLinkageAndVisibility();
  794. if (LV.getLinkage() != ExternalLinkage) {
  795. // Don't set internal linkage on declarations.
  796. } else {
  797. if (ND->hasAttr<DLLImportAttr>()) {
  798. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  799. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  800. } else if (ND->hasAttr<DLLExportAttr>()) {
  801. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  802. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  803. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  804. // "extern_weak" is overloaded in LLVM; we probably should have
  805. // separate linkage types for this.
  806. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  807. }
  808. // Set visibility on a declaration only if it's explicit.
  809. if (LV.isVisibilityExplicit())
  810. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  811. }
  812. }
  813. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  814. bool IsIncompleteFunction,
  815. bool IsThunk) {
  816. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  817. // If this is an intrinsic function, set the function's attributes
  818. // to the intrinsic's attributes.
  819. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  820. return;
  821. }
  822. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  823. if (!IsIncompleteFunction)
  824. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  825. // Add the Returned attribute for "this", except for iOS 5 and earlier
  826. // where substantial code, including the libstdc++ dylib, was compiled with
  827. // GCC and does not actually return "this".
  828. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  829. !(getTarget().getTriple().isiOS() &&
  830. getTarget().getTriple().isOSVersionLT(6))) {
  831. assert(!F->arg_empty() &&
  832. F->arg_begin()->getType()
  833. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  834. "unexpected this return");
  835. F->addAttribute(1, llvm::Attribute::Returned);
  836. }
  837. // Only a few attributes are set on declarations; these may later be
  838. // overridden by a definition.
  839. setLinkageAndVisibilityForGV(F, FD);
  840. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  841. F->setSection(SA->getName());
  842. // A replaceable global allocation function does not act like a builtin by
  843. // default, only if it is invoked by a new-expression or delete-expression.
  844. if (FD->isReplaceableGlobalAllocationFunction())
  845. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  846. llvm::Attribute::NoBuiltin);
  847. }
  848. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  849. assert(!GV->isDeclaration() &&
  850. "Only globals with definition can force usage.");
  851. LLVMUsed.emplace_back(GV);
  852. }
  853. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  854. assert(!GV->isDeclaration() &&
  855. "Only globals with definition can force usage.");
  856. LLVMCompilerUsed.emplace_back(GV);
  857. }
  858. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  859. std::vector<llvm::WeakVH> &List) {
  860. // Don't create llvm.used if there is no need.
  861. if (List.empty())
  862. return;
  863. // Convert List to what ConstantArray needs.
  864. SmallVector<llvm::Constant*, 8> UsedArray;
  865. UsedArray.resize(List.size());
  866. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  867. UsedArray[i] =
  868. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  869. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  870. }
  871. if (UsedArray.empty())
  872. return;
  873. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  874. auto *GV = new llvm::GlobalVariable(
  875. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  876. llvm::ConstantArray::get(ATy, UsedArray), Name);
  877. GV->setSection("llvm.metadata");
  878. }
  879. void CodeGenModule::emitLLVMUsed() {
  880. emitUsed(*this, "llvm.used", LLVMUsed);
  881. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  882. }
  883. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  884. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  885. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  886. }
  887. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  888. llvm::SmallString<32> Opt;
  889. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  890. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  891. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  892. }
  893. void CodeGenModule::AddDependentLib(StringRef Lib) {
  894. llvm::SmallString<24> Opt;
  895. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  896. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  897. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  898. }
  899. /// \brief Add link options implied by the given module, including modules
  900. /// it depends on, using a postorder walk.
  901. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  902. SmallVectorImpl<llvm::Metadata *> &Metadata,
  903. llvm::SmallPtrSet<Module *, 16> &Visited) {
  904. // Import this module's parent.
  905. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  906. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  907. }
  908. // Import this module's dependencies.
  909. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  910. if (Visited.insert(Mod->Imports[I - 1]).second)
  911. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  912. }
  913. // Add linker options to link against the libraries/frameworks
  914. // described by this module.
  915. llvm::LLVMContext &Context = CGM.getLLVMContext();
  916. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  917. // Link against a framework. Frameworks are currently Darwin only, so we
  918. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  919. if (Mod->LinkLibraries[I-1].IsFramework) {
  920. llvm::Metadata *Args[2] = {
  921. llvm::MDString::get(Context, "-framework"),
  922. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  923. Metadata.push_back(llvm::MDNode::get(Context, Args));
  924. continue;
  925. }
  926. // Link against a library.
  927. llvm::SmallString<24> Opt;
  928. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  929. Mod->LinkLibraries[I-1].Library, Opt);
  930. auto *OptString = llvm::MDString::get(Context, Opt);
  931. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  932. }
  933. }
  934. void CodeGenModule::EmitModuleLinkOptions() {
  935. // Collect the set of all of the modules we want to visit to emit link
  936. // options, which is essentially the imported modules and all of their
  937. // non-explicit child modules.
  938. llvm::SetVector<clang::Module *> LinkModules;
  939. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  940. SmallVector<clang::Module *, 16> Stack;
  941. // Seed the stack with imported modules.
  942. for (Module *M : ImportedModules)
  943. if (Visited.insert(M).second)
  944. Stack.push_back(M);
  945. // Find all of the modules to import, making a little effort to prune
  946. // non-leaf modules.
  947. while (!Stack.empty()) {
  948. clang::Module *Mod = Stack.pop_back_val();
  949. bool AnyChildren = false;
  950. // Visit the submodules of this module.
  951. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  952. SubEnd = Mod->submodule_end();
  953. Sub != SubEnd; ++Sub) {
  954. // Skip explicit children; they need to be explicitly imported to be
  955. // linked against.
  956. if ((*Sub)->IsExplicit)
  957. continue;
  958. if (Visited.insert(*Sub).second) {
  959. Stack.push_back(*Sub);
  960. AnyChildren = true;
  961. }
  962. }
  963. // We didn't find any children, so add this module to the list of
  964. // modules to link against.
  965. if (!AnyChildren) {
  966. LinkModules.insert(Mod);
  967. }
  968. }
  969. // Add link options for all of the imported modules in reverse topological
  970. // order. We don't do anything to try to order import link flags with respect
  971. // to linker options inserted by things like #pragma comment().
  972. SmallVector<llvm::Metadata *, 16> MetadataArgs;
  973. Visited.clear();
  974. for (Module *M : LinkModules)
  975. if (Visited.insert(M).second)
  976. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  977. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  978. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  979. // Add the linker options metadata flag.
  980. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  981. llvm::MDNode::get(getLLVMContext(),
  982. LinkerOptionsMetadata));
  983. }
  984. void CodeGenModule::EmitDeferred() {
  985. // Emit code for any potentially referenced deferred decls. Since a
  986. // previously unused static decl may become used during the generation of code
  987. // for a static function, iterate until no changes are made.
  988. if (!DeferredVTables.empty()) {
  989. EmitDeferredVTables();
  990. // Emitting a v-table doesn't directly cause more v-tables to
  991. // become deferred, although it can cause functions to be
  992. // emitted that then need those v-tables.
  993. assert(DeferredVTables.empty());
  994. }
  995. // Stop if we're out of both deferred v-tables and deferred declarations.
  996. if (DeferredDeclsToEmit.empty())
  997. return;
  998. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  999. // work, it will not interfere with this.
  1000. std::vector<DeferredGlobal> CurDeclsToEmit;
  1001. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1002. for (DeferredGlobal &G : CurDeclsToEmit) {
  1003. GlobalDecl D = G.GD;
  1004. llvm::GlobalValue *GV = G.GV;
  1005. G.GV = nullptr;
  1006. assert(!GV || GV == GetGlobalValue(getMangledName(D)));
  1007. if (!GV)
  1008. GV = GetGlobalValue(getMangledName(D));
  1009. // Check to see if we've already emitted this. This is necessary
  1010. // for a couple of reasons: first, decls can end up in the
  1011. // deferred-decls queue multiple times, and second, decls can end
  1012. // up with definitions in unusual ways (e.g. by an extern inline
  1013. // function acquiring a strong function redefinition). Just
  1014. // ignore these cases.
  1015. if (GV && !GV->isDeclaration())
  1016. continue;
  1017. // Otherwise, emit the definition and move on to the next one.
  1018. EmitGlobalDefinition(D, GV);
  1019. // If we found out that we need to emit more decls, do that recursively.
  1020. // This has the advantage that the decls are emitted in a DFS and related
  1021. // ones are close together, which is convenient for testing.
  1022. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1023. EmitDeferred();
  1024. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1025. }
  1026. }
  1027. }
  1028. void CodeGenModule::EmitGlobalAnnotations() {
  1029. if (Annotations.empty())
  1030. return;
  1031. // Create a new global variable for the ConstantStruct in the Module.
  1032. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1033. Annotations[0]->getType(), Annotations.size()), Annotations);
  1034. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1035. llvm::GlobalValue::AppendingLinkage,
  1036. Array, "llvm.global.annotations");
  1037. gv->setSection(AnnotationSection);
  1038. }
  1039. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1040. llvm::Constant *&AStr = AnnotationStrings[Str];
  1041. if (AStr)
  1042. return AStr;
  1043. // Not found yet, create a new global.
  1044. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1045. auto *gv =
  1046. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1047. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1048. gv->setSection(AnnotationSection);
  1049. gv->setUnnamedAddr(true);
  1050. AStr = gv;
  1051. return gv;
  1052. }
  1053. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1054. SourceManager &SM = getContext().getSourceManager();
  1055. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1056. if (PLoc.isValid())
  1057. return EmitAnnotationString(PLoc.getFilename());
  1058. return EmitAnnotationString(SM.getBufferName(Loc));
  1059. }
  1060. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1061. SourceManager &SM = getContext().getSourceManager();
  1062. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1063. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1064. SM.getExpansionLineNumber(L);
  1065. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1066. }
  1067. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1068. const AnnotateAttr *AA,
  1069. SourceLocation L) {
  1070. // Get the globals for file name, annotation, and the line number.
  1071. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1072. *UnitGV = EmitAnnotationUnit(L),
  1073. *LineNoCst = EmitAnnotationLineNo(L);
  1074. // Create the ConstantStruct for the global annotation.
  1075. llvm::Constant *Fields[4] = {
  1076. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1077. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1078. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1079. LineNoCst
  1080. };
  1081. return llvm::ConstantStruct::getAnon(Fields);
  1082. }
  1083. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1084. llvm::GlobalValue *GV) {
  1085. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1086. // Get the struct elements for these annotations.
  1087. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1088. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1089. }
  1090. bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
  1091. SourceLocation Loc) const {
  1092. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1093. // Blacklist by function name.
  1094. if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
  1095. return true;
  1096. // Blacklist by location.
  1097. if (!Loc.isInvalid())
  1098. return SanitizerBL.isBlacklistedLocation(Loc);
  1099. // If location is unknown, this may be a compiler-generated function. Assume
  1100. // it's located in the main file.
  1101. auto &SM = Context.getSourceManager();
  1102. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1103. return SanitizerBL.isBlacklistedFile(MainFile->getName());
  1104. }
  1105. return false;
  1106. }
  1107. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1108. SourceLocation Loc, QualType Ty,
  1109. StringRef Category) const {
  1110. // For now globals can be blacklisted only in ASan and KASan.
  1111. if (!LangOpts.Sanitize.hasOneOf(
  1112. SanitizerKind::Address | SanitizerKind::KernelAddress))
  1113. return false;
  1114. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1115. if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
  1116. return true;
  1117. if (SanitizerBL.isBlacklistedLocation(Loc, Category))
  1118. return true;
  1119. // Check global type.
  1120. if (!Ty.isNull()) {
  1121. // Drill down the array types: if global variable of a fixed type is
  1122. // blacklisted, we also don't instrument arrays of them.
  1123. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1124. Ty = AT->getElementType();
  1125. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1126. // We allow to blacklist only record types (classes, structs etc.)
  1127. if (Ty->isRecordType()) {
  1128. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1129. if (SanitizerBL.isBlacklistedType(TypeStr, Category))
  1130. return true;
  1131. }
  1132. }
  1133. return false;
  1134. }
  1135. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1136. // Never defer when EmitAllDecls is specified.
  1137. if (LangOpts.EmitAllDecls)
  1138. return true;
  1139. return getContext().DeclMustBeEmitted(Global);
  1140. }
  1141. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1142. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1143. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1144. // Implicit template instantiations may change linkage if they are later
  1145. // explicitly instantiated, so they should not be emitted eagerly.
  1146. return false;
  1147. // OACR error 6287
  1148. #pragma prefast(disable: __WARNING_ZEROLOGICALANDLOSINGSIDEEFFECTS, "language options are constants, by design")
  1149. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1150. // codegen for global variables, because they may be marked as threadprivate.
  1151. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1152. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1153. return false;
  1154. return true;
  1155. }
  1156. llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
  1157. const CXXUuidofExpr* E) {
  1158. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1159. // well-formed.
  1160. StringRef Uuid = E->getUuidAsStringRef(Context);
  1161. std::string Name = "_GUID_" + Uuid.lower();
  1162. std::replace(Name.begin(), Name.end(), '-', '_');
  1163. // Look for an existing global.
  1164. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1165. return GV;
  1166. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1167. assert(Init && "failed to initialize as constant");
  1168. auto *GV = new llvm::GlobalVariable(
  1169. getModule(), Init->getType(),
  1170. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1171. if (supportsCOMDAT())
  1172. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1173. return GV;
  1174. }
  1175. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1176. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1177. assert(AA && "No alias?");
  1178. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1179. // See if there is already something with the target's name in the module.
  1180. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1181. if (Entry) {
  1182. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1183. return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1184. }
  1185. llvm::Constant *Aliasee;
  1186. if (isa<llvm::FunctionType>(DeclTy))
  1187. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1188. GlobalDecl(cast<FunctionDecl>(VD)),
  1189. /*ForVTable=*/false);
  1190. else
  1191. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1192. llvm::PointerType::getUnqual(DeclTy),
  1193. nullptr);
  1194. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1195. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1196. WeakRefReferences.insert(F);
  1197. return Aliasee;
  1198. }
  1199. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1200. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1201. // Weak references don't produce any output by themselves.
  1202. if (Global->hasAttr<WeakRefAttr>())
  1203. return;
  1204. // If this is an alias definition (which otherwise looks like a declaration)
  1205. // emit it now.
  1206. if (Global->hasAttr<AliasAttr>())
  1207. return EmitAliasDefinition(GD);
  1208. // If this is CUDA, be selective about which declarations we emit.
  1209. if (LangOpts.CUDA) {
  1210. if (LangOpts.CUDAIsDevice) {
  1211. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1212. !Global->hasAttr<CUDAGlobalAttr>() &&
  1213. !Global->hasAttr<CUDAConstantAttr>() &&
  1214. !Global->hasAttr<CUDASharedAttr>())
  1215. return;
  1216. } else {
  1217. if (!Global->hasAttr<CUDAHostAttr>() && (
  1218. Global->hasAttr<CUDADeviceAttr>() ||
  1219. Global->hasAttr<CUDAConstantAttr>() ||
  1220. Global->hasAttr<CUDASharedAttr>()))
  1221. return;
  1222. }
  1223. }
  1224. // Ignore declarations, they will be emitted on their first use.
  1225. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1226. // Forward declarations are emitted lazily on first use.
  1227. if (!FD->doesThisDeclarationHaveABody()) {
  1228. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1229. return;
  1230. StringRef MangledName = getMangledName(GD);
  1231. // Compute the function info and LLVM type.
  1232. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1233. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1234. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1235. /*DontDefer=*/false);
  1236. return;
  1237. }
  1238. } else {
  1239. const auto *VD = cast<VarDecl>(Global);
  1240. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1241. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1242. !Context.isMSStaticDataMemberInlineDefinition(VD))
  1243. return;
  1244. }
  1245. // Defer code generation to first use when possible, e.g. if this is an inline
  1246. // function. If the global must always be emitted, do it eagerly if possible
  1247. // to benefit from cache locality.
  1248. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1249. // Emit the definition if it can't be deferred.
  1250. EmitGlobalDefinition(GD);
  1251. return;
  1252. }
  1253. // If we're deferring emission of a C++ variable with an
  1254. // initializer, remember the order in which it appeared in the file.
  1255. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1256. cast<VarDecl>(Global)->hasInit()) {
  1257. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1258. CXXGlobalInits.push_back(nullptr);
  1259. }
  1260. StringRef MangledName = getMangledName(GD);
  1261. if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
  1262. // The value has already been used and should therefore be emitted.
  1263. addDeferredDeclToEmit(GV, GD);
  1264. } else if (MustBeEmitted(Global)) {
  1265. // The value must be emitted, but cannot be emitted eagerly.
  1266. assert(!MayBeEmittedEagerly(Global));
  1267. addDeferredDeclToEmit(/*GV=*/nullptr, GD);
  1268. } else {
  1269. // Otherwise, remember that we saw a deferred decl with this name. The
  1270. // first use of the mangled name will cause it to move into
  1271. // DeferredDeclsToEmit.
  1272. DeferredDecls[MangledName] = GD;
  1273. }
  1274. }
  1275. namespace {
  1276. struct FunctionIsDirectlyRecursive :
  1277. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1278. const StringRef Name;
  1279. const Builtin::Context &BI;
  1280. bool Result;
  1281. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1282. Name(N), BI(C), Result(false) {
  1283. }
  1284. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1285. bool TraverseCallExpr(CallExpr *E) {
  1286. const FunctionDecl *FD = E->getDirectCallee();
  1287. if (!FD)
  1288. return true;
  1289. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1290. if (Attr && Name == Attr->getLabel()) {
  1291. Result = true;
  1292. return false;
  1293. }
  1294. unsigned BuiltinID = FD->getBuiltinID();
  1295. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1296. return true;
  1297. StringRef BuiltinName = BI.GetName(BuiltinID);
  1298. if (BuiltinName.startswith("__builtin_") &&
  1299. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1300. Result = true;
  1301. return false;
  1302. }
  1303. return true;
  1304. }
  1305. };
  1306. }
  1307. // isTriviallyRecursive - Check if this function calls another
  1308. // decl that, because of the asm attribute or the other decl being a builtin,
  1309. // ends up pointing to itself.
  1310. bool
  1311. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1312. StringRef Name;
  1313. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1314. // asm labels are a special kind of mangling we have to support.
  1315. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1316. if (!Attr)
  1317. return false;
  1318. Name = Attr->getLabel();
  1319. } else {
  1320. Name = FD->getName();
  1321. }
  1322. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1323. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1324. return Walker.Result;
  1325. }
  1326. bool
  1327. CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1328. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1329. return true;
  1330. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1331. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1332. return false;
  1333. // PR9614. Avoid cases where the source code is lying to us. An available
  1334. // externally function should have an equivalent function somewhere else,
  1335. // but a function that calls itself is clearly not equivalent to the real
  1336. // implementation.
  1337. // This happens in glibc's btowc and in some configure checks.
  1338. return !isTriviallyRecursive(F);
  1339. }
  1340. /// If the type for the method's class was generated by
  1341. /// CGDebugInfo::createContextChain(), the cache contains only a
  1342. /// limited DIType without any declarations. Since EmitFunctionStart()
  1343. /// needs to find the canonical declaration for each method, we need
  1344. /// to construct the complete type prior to emitting the method.
  1345. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1346. if (!D->isInstance())
  1347. return;
  1348. if (CGDebugInfo *DI = getModuleDebugInfo())
  1349. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  1350. const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
  1351. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1352. }
  1353. }
  1354. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1355. const auto *D = cast<ValueDecl>(GD.getDecl());
  1356. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1357. Context.getSourceManager(),
  1358. "Generating code for declaration");
  1359. if (isa<FunctionDecl>(D)) {
  1360. // At -O0, don't generate IR for functions with available_externally
  1361. // linkage.
  1362. if (!shouldEmitFunction(GD))
  1363. return;
  1364. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1365. CompleteDIClassType(Method);
  1366. // Make sure to emit the definition(s) before we emit the thunks.
  1367. // This is necessary for the generation of certain thunks.
  1368. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1369. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1370. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1371. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1372. else
  1373. EmitGlobalFunctionDefinition(GD, GV);
  1374. if (Method->isVirtual())
  1375. getVTables().EmitThunks(GD);
  1376. return;
  1377. }
  1378. return EmitGlobalFunctionDefinition(GD, GV);
  1379. }
  1380. if (const auto *VD = dyn_cast<VarDecl>(D))
  1381. return EmitGlobalVarDefinition(VD);
  1382. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1383. }
  1384. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1385. /// module, create and return an llvm Function with the specified type. If there
  1386. /// is something in the module with the specified name, return it potentially
  1387. /// bitcasted to the right type.
  1388. ///
  1389. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1390. /// to set the attributes on the function when it is first created.
  1391. llvm::Constant *
  1392. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1393. llvm::Type *Ty,
  1394. GlobalDecl GD, bool ForVTable,
  1395. bool DontDefer, bool IsThunk,
  1396. llvm::AttributeSet ExtraAttrs) {
  1397. const Decl *D = GD.getDecl();
  1398. // Lookup the entry, lazily creating it if necessary.
  1399. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1400. if (Entry) {
  1401. if (WeakRefReferences.erase(Entry)) {
  1402. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1403. if (FD && !FD->hasAttr<WeakAttr>())
  1404. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1405. }
  1406. // Handle dropped DLL attributes.
  1407. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1408. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1409. if (Entry->getType()->getElementType() == Ty)
  1410. return Entry;
  1411. // Make sure the result is of the correct type.
  1412. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1413. }
  1414. // This function doesn't have a complete type (for example, the return
  1415. // type is an incomplete struct). Use a fake type instead, and make
  1416. // sure not to try to set attributes.
  1417. bool IsIncompleteFunction = false;
  1418. llvm::FunctionType *FTy;
  1419. if (isa<llvm::FunctionType>(Ty)) {
  1420. FTy = cast<llvm::FunctionType>(Ty);
  1421. } else {
  1422. FTy = llvm::FunctionType::get(VoidTy, false);
  1423. IsIncompleteFunction = true;
  1424. }
  1425. // HLSL Change: unique_ptr for F
  1426. llvm::Function *F = llvm::Function::Create(FTy,
  1427. llvm::Function::ExternalLinkage,
  1428. MangledName, &getModule());
  1429. assert(F->getName() == MangledName && "name was uniqued!");
  1430. if (D)
  1431. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  1432. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1433. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1434. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1435. llvm::AttributeSet::get(VMContext,
  1436. llvm::AttributeSet::FunctionIndex,
  1437. B));
  1438. }
  1439. if (!DontDefer) {
  1440. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1441. // each other bottoming out with the base dtor. Therefore we emit non-base
  1442. // dtors on usage, even if there is no dtor definition in the TU.
  1443. if (D && isa<CXXDestructorDecl>(D) &&
  1444. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1445. GD.getDtorType()))
  1446. addDeferredDeclToEmit(F, GD);
  1447. // This is the first use or definition of a mangled name. If there is a
  1448. // deferred decl with this name, remember that we need to emit it at the end
  1449. // of the file.
  1450. auto DDI = DeferredDecls.find(MangledName);
  1451. if (DDI != DeferredDecls.end()) {
  1452. // Move the potentially referenced deferred decl to the
  1453. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1454. // don't need it anymore).
  1455. addDeferredDeclToEmit(F, DDI->second);
  1456. DeferredDecls.erase(DDI);
  1457. // Otherwise, there are cases we have to worry about where we're
  1458. // using a declaration for which we must emit a definition but where
  1459. // we might not find a top-level definition:
  1460. // - member functions defined inline in their classes
  1461. // - friend functions defined inline in some class
  1462. // - special member functions with implicit definitions
  1463. // If we ever change our AST traversal to walk into class methods,
  1464. // this will be unnecessary.
  1465. //
  1466. // We also don't emit a definition for a function if it's going to be an
  1467. // entry in a vtable, unless it's already marked as used.
  1468. } else if (getLangOpts().CPlusPlus && D) {
  1469. // Look for a declaration that's lexically in a record.
  1470. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1471. FD = FD->getPreviousDecl()) {
  1472. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1473. if (FD->doesThisDeclarationHaveABody()) {
  1474. addDeferredDeclToEmit(F, GD.getWithDecl(FD));
  1475. break;
  1476. }
  1477. }
  1478. }
  1479. }
  1480. }
  1481. // Make sure the result is of the requested type.
  1482. if (!IsIncompleteFunction) {
  1483. assert(F->getType()->getElementType() == Ty);
  1484. return F;
  1485. }
  1486. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1487. return llvm::ConstantExpr::getBitCast(F, PTy);
  1488. }
  1489. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1490. /// non-null, then this function will use the specified type if it has to
  1491. /// create it (this occurs when we see a definition of the function).
  1492. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1493. llvm::Type *Ty,
  1494. bool ForVTable,
  1495. bool DontDefer) {
  1496. // If there was no specific requested type, just convert it now.
  1497. if (!Ty)
  1498. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  1499. StringRef MangledName = getMangledName(GD);
  1500. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
  1501. }
  1502. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1503. /// type and name.
  1504. llvm::Constant *
  1505. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1506. StringRef Name,
  1507. llvm::AttributeSet ExtraAttrs) {
  1508. llvm::Constant *C =
  1509. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1510. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1511. if (auto *F = dyn_cast<llvm::Function>(C))
  1512. if (F->empty())
  1513. F->setCallingConv(getRuntimeCC());
  1514. return C;
  1515. }
  1516. /// CreateBuiltinFunction - Create a new builtin function with the specified
  1517. /// type and name.
  1518. llvm::Constant *
  1519. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
  1520. StringRef Name,
  1521. llvm::AttributeSet ExtraAttrs) {
  1522. llvm::Constant *C =
  1523. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1524. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1525. if (auto *F = dyn_cast<llvm::Function>(C))
  1526. if (F->empty())
  1527. F->setCallingConv(getBuiltinCC());
  1528. return C;
  1529. }
  1530. /// isTypeConstant - Determine whether an object of this type can be emitted
  1531. /// as a constant.
  1532. ///
  1533. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1534. /// will not be considered. The caller will need to verify that the object is
  1535. /// not written to during its construction.
  1536. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1537. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1538. return false;
  1539. if (Context.getLangOpts().CPlusPlus) {
  1540. if (const CXXRecordDecl *Record
  1541. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1542. return ExcludeCtor && !Record->hasMutableFields() &&
  1543. Record->hasTrivialDestructor();
  1544. }
  1545. return true;
  1546. }
  1547. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1548. /// create and return an llvm GlobalVariable with the specified type. If there
  1549. /// is something in the module with the specified name, return it potentially
  1550. /// bitcasted to the right type.
  1551. ///
  1552. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1553. /// to set the attributes on the global when it is first created.
  1554. llvm::Constant *
  1555. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1556. llvm::PointerType *Ty,
  1557. const VarDecl *D) {
  1558. // Lookup the entry, lazily creating it if necessary.
  1559. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1560. if (Entry) {
  1561. if (WeakRefReferences.erase(Entry)) {
  1562. if (D && !D->hasAttr<WeakAttr>())
  1563. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1564. }
  1565. // Handle dropped DLL attributes.
  1566. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1567. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1568. if (Entry->getType() == Ty)
  1569. return Entry;
  1570. // Make sure the result is of the correct type.
  1571. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) {
  1572. // HLSL Change Begins
  1573. // TODO: do we put address space in type?
  1574. if (LangOpts.HLSL) return Entry;
  1575. else
  1576. // HLSL Change Ends
  1577. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  1578. }
  1579. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1580. }
  1581. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1582. auto *GV = new llvm::GlobalVariable(
  1583. getModule(), Ty->getElementType(), false,
  1584. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  1585. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1586. // This is the first use or definition of a mangled name. If there is a
  1587. // deferred decl with this name, remember that we need to emit it at the end
  1588. // of the file.
  1589. auto DDI = DeferredDecls.find(MangledName);
  1590. if (DDI != DeferredDecls.end()) {
  1591. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1592. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1593. addDeferredDeclToEmit(GV, DDI->second);
  1594. DeferredDecls.erase(DDI);
  1595. }
  1596. // Handle things which are present even on external declarations.
  1597. if (D) {
  1598. // FIXME: This code is overly simple and should be merged with other global
  1599. // handling.
  1600. GV->setConstant(isTypeConstant(D->getType(), false));
  1601. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1602. setLinkageAndVisibilityForGV(GV, D);
  1603. if (D->getTLSKind()) {
  1604. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1605. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1606. setTLSMode(GV, *D);
  1607. }
  1608. // If required by the ABI, treat declarations of static data members with
  1609. // inline initializers as definitions.
  1610. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  1611. EmitGlobalVarDefinition(D);
  1612. }
  1613. // Handle XCore specific ABI requirements.
  1614. if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
  1615. D->getLanguageLinkage() == CLanguageLinkage &&
  1616. D->getType().isConstant(Context) &&
  1617. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  1618. GV->setSection(".cp.rodata");
  1619. }
  1620. if (AddrSpace != Ty->getAddressSpace() && !LangOpts.HLSL) // HLSL Change -TODO: do we put address space in type?
  1621. return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
  1622. return GV;
  1623. }
  1624. llvm::GlobalVariable *
  1625. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1626. llvm::Type *Ty,
  1627. llvm::GlobalValue::LinkageTypes Linkage) {
  1628. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1629. llvm::GlobalVariable *OldGV = nullptr;
  1630. if (GV) {
  1631. // Check if the variable has the right type.
  1632. if (GV->getType()->getElementType() == Ty)
  1633. return GV;
  1634. // Because C++ name mangling, the only way we can end up with an already
  1635. // existing global with the same name is if it has been declared extern "C".
  1636. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1637. OldGV = GV;
  1638. }
  1639. // Create a new variable.
  1640. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1641. Linkage, nullptr, Name);
  1642. if (OldGV) {
  1643. // Replace occurrences of the old variable if needed.
  1644. GV->takeName(OldGV);
  1645. if (!OldGV->use_empty()) {
  1646. llvm::Constant *NewPtrForOldDecl =
  1647. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1648. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1649. }
  1650. OldGV->eraseFromParent();
  1651. }
  1652. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  1653. !GV->hasAvailableExternallyLinkage())
  1654. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1655. return GV;
  1656. }
  1657. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1658. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1659. /// then it will be created with the specified type instead of whatever the
  1660. /// normal requested type would be.
  1661. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1662. llvm::Type *Ty) {
  1663. assert(D->hasGlobalStorage() && "Not a global variable");
  1664. QualType ASTTy = D->getType();
  1665. if (!Ty)
  1666. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1667. llvm::PointerType *PTy =
  1668. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1669. StringRef MangledName = getMangledName(D);
  1670. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1671. }
  1672. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1673. /// specified type and name.
  1674. llvm::Constant *
  1675. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1676. StringRef Name) {
  1677. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  1678. }
  1679. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1680. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1681. if (!MustBeEmitted(D)) {
  1682. // If we have not seen a reference to this variable yet, place it
  1683. // into the deferred declarations table to be emitted if needed
  1684. // later.
  1685. StringRef MangledName = getMangledName(D);
  1686. if (!GetGlobalValue(MangledName)) {
  1687. DeferredDecls[MangledName] = D;
  1688. return;
  1689. }
  1690. }
  1691. // The tentative definition is the only definition.
  1692. EmitGlobalVarDefinition(D);
  1693. }
  1694. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1695. return Context.toCharUnitsFromBits(
  1696. TheDataLayout.getTypeStoreSizeInBits(Ty));
  1697. }
  1698. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1699. unsigned AddrSpace) {
  1700. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  1701. if (D->hasAttr<CUDAConstantAttr>())
  1702. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1703. else if (D->hasAttr<CUDASharedAttr>())
  1704. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1705. else
  1706. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1707. }
  1708. // HLSL Change Begins
  1709. if (LangOpts.HLSL) {
  1710. if (D->hasAttr<HLSLGroupSharedAttr>())
  1711. AddrSpace = getContext().getTargetAddressSpace(hlsl::DXIL::kTGSMAddrSpace);
  1712. }
  1713. // HLSL Change Ends
  1714. return AddrSpace;
  1715. }
  1716. template<typename SomeDecl>
  1717. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  1718. llvm::GlobalValue *GV) {
  1719. if (!getLangOpts().CPlusPlus)
  1720. return;
  1721. // Must have 'used' attribute, or else inline assembly can't rely on
  1722. // the name existing.
  1723. if (!D->template hasAttr<UsedAttr>())
  1724. return;
  1725. // Must have internal linkage and an ordinary name.
  1726. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  1727. return;
  1728. // Must be in an extern "C" context. Entities declared directly within
  1729. // a record are not extern "C" even if the record is in such a context.
  1730. const SomeDecl *First = D->getFirstDecl();
  1731. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  1732. return;
  1733. // OK, this is an internal linkage entity inside an extern "C" linkage
  1734. // specification. Make a note of that so we can give it the "expected"
  1735. // mangled name if nothing else is using that name.
  1736. std::pair<StaticExternCMap::iterator, bool> R =
  1737. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  1738. // If we have multiple internal linkage entities with the same name
  1739. // in extern "C" regions, none of them gets that name.
  1740. if (!R.second)
  1741. R.first->second = nullptr;
  1742. }
  1743. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  1744. if (!CGM.supportsCOMDAT())
  1745. return false;
  1746. if (D.hasAttr<SelectAnyAttr>())
  1747. return true;
  1748. GVALinkage Linkage;
  1749. if (auto *VD = dyn_cast<VarDecl>(&D))
  1750. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  1751. else
  1752. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  1753. switch (Linkage) {
  1754. case GVA_Internal:
  1755. case GVA_AvailableExternally:
  1756. case GVA_StrongExternal:
  1757. return false;
  1758. case GVA_DiscardableODR:
  1759. case GVA_StrongODR:
  1760. return true;
  1761. }
  1762. llvm_unreachable("No such linkage");
  1763. }
  1764. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  1765. llvm::GlobalObject &GO) {
  1766. if (!shouldBeInCOMDAT(*this, D))
  1767. return;
  1768. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  1769. }
  1770. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1771. llvm::Constant *Init = nullptr;
  1772. QualType ASTTy = D->getType();
  1773. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1774. bool NeedsGlobalCtor = false;
  1775. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1776. const VarDecl *InitDecl;
  1777. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1778. if (!InitExpr) {
  1779. // This is a tentative definition; tentative definitions are
  1780. // implicitly initialized with { 0 }.
  1781. //
  1782. // Note that tentative definitions are only emitted at the end of
  1783. // a translation unit, so they should never have incomplete
  1784. // type. In addition, EmitTentativeDefinition makes sure that we
  1785. // never attempt to emit a tentative definition if a real one
  1786. // exists. A use may still exists, however, so we still may need
  1787. // to do a RAUW.
  1788. // HLSL Change Starts
  1789. // Allow incomplete type.
  1790. if (getLangOpts().HLSL && ASTTy->isIncompleteType()) {
  1791. if (hlsl::IsIncompleteHLSLResourceArrayType(getContext(), ASTTy)) {
  1792. llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
  1793. llvm::Constant *Entry = GetAddrOfGlobalVar(D, Ty);
  1794. // Entry is now either a Function or GlobalVariable.
  1795. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1796. // Emit global variable debug information.
  1797. if (CGDebugInfo *DI = getModuleDebugInfo())
  1798. if (getCodeGenOpts().getDebugInfo() >=
  1799. CodeGenOptions::LimitedDebugInfo)
  1800. DI->EmitGlobalVariable(GV, D);
  1801. return;
  1802. }
  1803. }
  1804. // HLSL Change Ends
  1805. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1806. Init = EmitNullConstant(D->getType());
  1807. } else {
  1808. initializedGlobalDecl = GlobalDecl(D);
  1809. Init = EmitConstantInit(*InitDecl);
  1810. if (!Init) {
  1811. QualType T = InitExpr->getType();
  1812. if (D->getType()->isReferenceType())
  1813. T = D->getType();
  1814. if (getLangOpts().CPlusPlus) {
  1815. Init = EmitNullConstant(T);
  1816. NeedsGlobalCtor = true;
  1817. // HLSL Change Begins.
  1818. if (getLangOpts().HLSL && D->isExternallyVisible()) {
  1819. // For global constant with init, the init will be ignored.
  1820. // Warning here.
  1821. unsigned DiagID = Diags.getCustomDiagID(
  1822. DiagnosticsEngine::Warning,
  1823. "Initializer of external global will be ignored");
  1824. Diags.Report(D->getLocation(), DiagID);
  1825. // Don't create global ctor for it.
  1826. NeedsGlobalCtor = false;
  1827. }
  1828. // HLSL Change Ends.
  1829. } else {
  1830. ErrorUnsupported(D, "static initializer");
  1831. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1832. }
  1833. } else {
  1834. // We don't need an initializer, so remove the entry for the delayed
  1835. // initializer position (just in case this entry was delayed) if we
  1836. // also don't need to register a destructor.
  1837. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1838. DelayedCXXInitPosition.erase(D);
  1839. // HLSL Change Begins.
  1840. if (getLangOpts().HLSL && D->isExternallyVisible() && !D->isStaticDataMember()) {
  1841. // For global constant with init, the init will be ignored.
  1842. Init = EmitNullConstant(D->getType());
  1843. unsigned DiagID = Diags.getCustomDiagID(
  1844. DiagnosticsEngine::Warning,
  1845. "Initializer of external global will be ignored");
  1846. Diags.Report(D->getLocation(), DiagID);
  1847. }
  1848. // HLSL Change Ends.
  1849. }
  1850. }
  1851. llvm::Type* InitType = Init->getType();
  1852. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1853. // Strip off a bitcast if we got one back.
  1854. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1855. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1856. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  1857. // All zero index gep.
  1858. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1859. Entry = CE->getOperand(0);
  1860. }
  1861. // Entry is now either a Function or GlobalVariable.
  1862. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1863. // We have a definition after a declaration with the wrong type.
  1864. // We must make a new GlobalVariable* and update everything that used OldGV
  1865. // (a declaration or tentative definition) with the new GlobalVariable*
  1866. // (which will be a definition).
  1867. //
  1868. // This happens if there is a prototype for a global (e.g.
  1869. // "extern int x[];") and then a definition of a different type (e.g.
  1870. // "int x[10];"). This also happens when an initializer has a different type
  1871. // from the type of the global (this happens with unions).
  1872. if (!GV ||
  1873. GV->getType()->getElementType() != InitType ||
  1874. GV->getType()->getAddressSpace() !=
  1875. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1876. // Move the old entry aside so that we'll create a new one.
  1877. Entry->setName(StringRef());
  1878. // Make a new global with the correct type, this is now guaranteed to work.
  1879. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1880. // Replace all uses of the old global with the new global
  1881. llvm::Constant *NewPtrForOldDecl =
  1882. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1883. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1884. // Erase the old global, since it is no longer used.
  1885. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1886. }
  1887. MaybeHandleStaticInExternC(D, GV);
  1888. if (D->hasAttr<AnnotateAttr>())
  1889. AddGlobalAnnotations(D, GV);
  1890. GV->setInitializer(Init);
  1891. // If it is safe to mark the global 'constant', do so now.
  1892. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1893. isTypeConstant(D->getType(), true));
  1894. // If it is in a read-only section, mark it 'constant'.
  1895. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  1896. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  1897. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  1898. GV->setConstant(true);
  1899. }
  1900. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1901. // Set the llvm linkage type as appropriate.
  1902. llvm::GlobalValue::LinkageTypes Linkage =
  1903. getLLVMLinkageVarDefinition(D, GV->isConstant());
  1904. // On Darwin, the backing variable for a C++11 thread_local variable always
  1905. // has internal linkage; all accesses should just be calls to the
  1906. // Itanium-specified entry point, which has the normal linkage of the
  1907. // variable.
  1908. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  1909. Context.getTargetInfo().getTriple().isMacOSX())
  1910. Linkage = llvm::GlobalValue::InternalLinkage;
  1911. GV->setLinkage(Linkage);
  1912. if (D->hasAttr<DLLImportAttr>())
  1913. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  1914. else if (D->hasAttr<DLLExportAttr>())
  1915. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  1916. else
  1917. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  1918. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1919. // common vars aren't constant even if declared const.
  1920. GV->setConstant(false);
  1921. setNonAliasAttributes(D, GV);
  1922. if (D->getTLSKind() && !GV->isThreadLocal()) {
  1923. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1924. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1925. setTLSMode(GV, *D);
  1926. }
  1927. maybeSetTrivialComdat(*D, *GV);
  1928. // Emit the initializer function if necessary.
  1929. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1930. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1931. // HLSL Change Begin.
  1932. if (NeedsGlobalCtor)
  1933. GV->setInitializer(llvm::UndefValue::get(InitType));
  1934. // HLSL Change End.
  1935. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  1936. // Emit global variable debug information.
  1937. if (CGDebugInfo *DI = getModuleDebugInfo())
  1938. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1939. DI->EmitGlobalVariable(GV, D);
  1940. }
  1941. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  1942. CodeGenModule &CGM, const VarDecl *D,
  1943. bool NoCommon) {
  1944. // Don't give variables common linkage if -fno-common was specified unless it
  1945. // was overridden by a NoCommon attribute.
  1946. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  1947. return true;
  1948. // C11 6.9.2/2:
  1949. // A declaration of an identifier for an object that has file scope without
  1950. // an initializer, and without a storage-class specifier or with the
  1951. // storage-class specifier static, constitutes a tentative definition.
  1952. if (D->getInit() || D->hasExternalStorage())
  1953. return true;
  1954. // A variable cannot be both common and exist in a section.
  1955. if (D->hasAttr<SectionAttr>())
  1956. return true;
  1957. // Thread local vars aren't considered common linkage.
  1958. if (D->getTLSKind())
  1959. return true;
  1960. // Tentative definitions marked with WeakImportAttr are true definitions.
  1961. if (D->hasAttr<WeakImportAttr>())
  1962. return true;
  1963. // A variable cannot be both common and exist in a comdat.
  1964. if (shouldBeInCOMDAT(CGM, *D))
  1965. return true;
  1966. // Declarations with a required alignment do not have common linakge in MSVC
  1967. // mode.
  1968. if (Context.getLangOpts().MSVCCompat) {
  1969. if (D->hasAttr<AlignedAttr>())
  1970. return true;
  1971. QualType VarType = D->getType();
  1972. if (Context.isAlignmentRequired(VarType))
  1973. return true;
  1974. if (const auto *RT = VarType->getAs<RecordType>()) {
  1975. const RecordDecl *RD = RT->getDecl();
  1976. for (const FieldDecl *FD : RD->fields()) {
  1977. if (FD->isBitField())
  1978. continue;
  1979. if (FD->hasAttr<AlignedAttr>())
  1980. return true;
  1981. if (Context.isAlignmentRequired(FD->getType()))
  1982. return true;
  1983. }
  1984. }
  1985. }
  1986. return false;
  1987. }
  1988. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  1989. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  1990. if (Linkage == GVA_Internal)
  1991. return llvm::Function::InternalLinkage;
  1992. if (D->hasAttr<WeakAttr>()) {
  1993. if (IsConstantVariable)
  1994. return llvm::GlobalVariable::WeakODRLinkage;
  1995. else
  1996. return llvm::GlobalVariable::WeakAnyLinkage;
  1997. }
  1998. // We are guaranteed to have a strong definition somewhere else,
  1999. // so we can use available_externally linkage.
  2000. if (Linkage == GVA_AvailableExternally)
  2001. return llvm::Function::AvailableExternallyLinkage;
  2002. // Note that Apple's kernel linker doesn't support symbol
  2003. // coalescing, so we need to avoid linkonce and weak linkages there.
  2004. // Normally, this means we just map to internal, but for explicit
  2005. // instantiations we'll map to external.
  2006. // In C++, the compiler has to emit a definition in every translation unit
  2007. // that references the function. We should use linkonce_odr because
  2008. // a) if all references in this translation unit are optimized away, we
  2009. // don't need to codegen it. b) if the function persists, it needs to be
  2010. // merged with other definitions. c) C++ has the ODR, so we know the
  2011. // definition is dependable.
  2012. if (Linkage == GVA_DiscardableODR)
  2013. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2014. : llvm::Function::InternalLinkage;
  2015. // An explicit instantiation of a template has weak linkage, since
  2016. // explicit instantiations can occur in multiple translation units
  2017. // and must all be equivalent. However, we are not allowed to
  2018. // throw away these explicit instantiations.
  2019. if (Linkage == GVA_StrongODR)
  2020. return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
  2021. : llvm::Function::ExternalLinkage;
  2022. // C++ doesn't have tentative definitions and thus cannot have common
  2023. // linkage.
  2024. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2025. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2026. CodeGenOpts.NoCommon))
  2027. return llvm::GlobalVariable::CommonLinkage;
  2028. // selectany symbols are externally visible, so use weak instead of
  2029. // linkonce. MSVC optimizes away references to const selectany globals, so
  2030. // all definitions should be the same and ODR linkage should be used.
  2031. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2032. if (D->hasAttr<SelectAnyAttr>())
  2033. return llvm::GlobalVariable::WeakODRLinkage;
  2034. // Otherwise, we have strong external linkage.
  2035. assert(Linkage == GVA_StrongExternal);
  2036. return llvm::GlobalVariable::ExternalLinkage;
  2037. }
  2038. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2039. const VarDecl *VD, bool IsConstant) {
  2040. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2041. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2042. }
  2043. /// Replace the uses of a function that was declared with a non-proto type.
  2044. /// We want to silently drop extra arguments from call sites
  2045. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2046. llvm::Function *newFn) {
  2047. // Fast path.
  2048. if (old->use_empty()) return;
  2049. llvm::Type *newRetTy = newFn->getReturnType();
  2050. SmallVector<llvm::Value*, 4> newArgs;
  2051. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2052. ui != ue; ) {
  2053. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2054. llvm::User *user = use->getUser();
  2055. // Recognize and replace uses of bitcasts. Most calls to
  2056. // unprototyped functions will use bitcasts.
  2057. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2058. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2059. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2060. continue;
  2061. }
  2062. // Recognize calls to the function.
  2063. llvm::CallSite callSite(user);
  2064. if (!callSite) continue;
  2065. if (!callSite.isCallee(&*use)) continue;
  2066. // If the return types don't match exactly, then we can't
  2067. // transform this call unless it's dead.
  2068. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2069. continue;
  2070. // Get the call site's attribute list.
  2071. SmallVector<llvm::AttributeSet, 8> newAttrs;
  2072. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  2073. // Collect any return attributes from the call.
  2074. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  2075. newAttrs.push_back(
  2076. llvm::AttributeSet::get(newFn->getContext(),
  2077. oldAttrs.getRetAttributes()));
  2078. // If the function was passed too few arguments, don't transform.
  2079. unsigned newNumArgs = newFn->arg_size();
  2080. if (callSite.arg_size() < newNumArgs) continue;
  2081. // If extra arguments were passed, we silently drop them.
  2082. // If any of the types mismatch, we don't transform.
  2083. unsigned argNo = 0;
  2084. bool dontTransform = false;
  2085. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  2086. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  2087. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  2088. dontTransform = true;
  2089. break;
  2090. }
  2091. // Add any parameter attributes.
  2092. if (oldAttrs.hasAttributes(argNo + 1))
  2093. newAttrs.
  2094. push_back(llvm::
  2095. AttributeSet::get(newFn->getContext(),
  2096. oldAttrs.getParamAttributes(argNo + 1)));
  2097. }
  2098. if (dontTransform)
  2099. continue;
  2100. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  2101. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  2102. oldAttrs.getFnAttributes()));
  2103. // Okay, we can transform this. Create the new call instruction and copy
  2104. // over the required information.
  2105. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  2106. llvm::CallSite newCall;
  2107. if (callSite.isCall()) {
  2108. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  2109. callSite.getInstruction());
  2110. } else {
  2111. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2112. newCall = llvm::InvokeInst::Create(newFn,
  2113. oldInvoke->getNormalDest(),
  2114. oldInvoke->getUnwindDest(),
  2115. newArgs, "",
  2116. callSite.getInstruction());
  2117. }
  2118. newArgs.clear(); // for the next iteration
  2119. if (!newCall->getType()->isVoidTy())
  2120. newCall->takeName(callSite.getInstruction());
  2121. newCall.setAttributes(
  2122. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  2123. newCall.setCallingConv(callSite.getCallingConv());
  2124. // Finally, remove the old call, replacing any uses with the new one.
  2125. if (!callSite->use_empty())
  2126. callSite->replaceAllUsesWith(newCall.getInstruction());
  2127. // Copy debug location attached to CI.
  2128. if (callSite->getDebugLoc())
  2129. newCall->setDebugLoc(callSite->getDebugLoc());
  2130. callSite->eraseFromParent();
  2131. }
  2132. }
  2133. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2134. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2135. /// existing call uses of the old function in the module, this adjusts them to
  2136. /// call the new function directly.
  2137. ///
  2138. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2139. /// functions to be able to inline them. If there is a bitcast in the way, it
  2140. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2141. /// run at -O0.
  2142. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2143. llvm::Function *NewFn) {
  2144. // If we're redefining a global as a function, don't transform it.
  2145. if (!isa<llvm::Function>(Old)) return;
  2146. replaceUsesOfNonProtoConstant(Old, NewFn);
  2147. }
  2148. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  2149. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  2150. // If we have a definition, this might be a deferred decl. If the
  2151. // instantiation is explicit, make sure we emit it at the end.
  2152. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  2153. GetAddrOfGlobalVar(VD);
  2154. EmitTopLevelDecl(VD);
  2155. }
  2156. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  2157. llvm::GlobalValue *GV) {
  2158. const auto *D = cast<FunctionDecl>(GD.getDecl());
  2159. // Compute the function info and LLVM type.
  2160. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2161. // HLSL Change Begins.
  2162. // Out parameter is not ByVal.
  2163. auto I = const_cast<CGFunctionInfo&>(FI).arg_begin();
  2164. for (const ParmVarDecl *Param : D->params()) {
  2165. if (Param->isModifierOut() && I->info.isIndirect()) {
  2166. I->info.setIndirectByVal(false);
  2167. }
  2168. I++;
  2169. }
  2170. // HLSL Change Ends.
  2171. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2172. // Get or create the prototype for the function.
  2173. if (!GV) {
  2174. llvm::Constant *C =
  2175. GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
  2176. // Strip off a bitcast if we got one back.
  2177. if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
  2178. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  2179. GV = cast<llvm::GlobalValue>(CE->getOperand(0));
  2180. } else {
  2181. GV = cast<llvm::GlobalValue>(C);
  2182. }
  2183. }
  2184. if (!GV->isDeclaration()) {
  2185. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
  2186. GlobalDecl OldGD = Manglings.lookup(GV->getName());
  2187. if (auto *Prev = OldGD.getDecl())
  2188. getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
  2189. return;
  2190. }
  2191. if (GV->getType()->getElementType() != Ty) {
  2192. // If the types mismatch then we have to rewrite the definition.
  2193. assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
  2194. // F is the Function* for the one with the wrong type, we must make a new
  2195. // Function* and update everything that used F (a declaration) with the new
  2196. // Function* (which will be a definition).
  2197. //
  2198. // This happens if there is a prototype for a function
  2199. // (e.g. "int f()") and then a definition of a different type
  2200. // (e.g. "int f(int x)"). Move the old function aside so that it
  2201. // doesn't interfere with GetAddrOfFunction.
  2202. GV->setName(StringRef());
  2203. auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  2204. // This might be an implementation of a function without a
  2205. // prototype, in which case, try to do special replacement of
  2206. // calls which match the new prototype. The really key thing here
  2207. // is that we also potentially drop arguments from the call site
  2208. // so as to make a direct call, which makes the inliner happier
  2209. // and suppresses a number of optimizer warnings (!) about
  2210. // dropping arguments.
  2211. if (!GV->use_empty()) {
  2212. ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
  2213. GV->removeDeadConstantUsers();
  2214. }
  2215. // Replace uses of F with the Function we will endow with a body.
  2216. if (!GV->use_empty()) {
  2217. llvm::Constant *NewPtrForOldDecl =
  2218. llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
  2219. GV->replaceAllUsesWith(NewPtrForOldDecl);
  2220. }
  2221. // Ok, delete the old function now, which is dead.
  2222. GV->eraseFromParent();
  2223. GV = NewFn;
  2224. }
  2225. // We need to set linkage and visibility on the function before
  2226. // generating code for it because various parts of IR generation
  2227. // want to propagate this information down (e.g. to local static
  2228. // declarations).
  2229. auto *Fn = cast<llvm::Function>(GV);
  2230. setFunctionLinkage(GD, Fn);
  2231. setFunctionDLLStorageClass(GD, Fn);
  2232. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  2233. setGlobalVisibility(Fn, D);
  2234. MaybeHandleStaticInExternC(D, Fn);
  2235. maybeSetTrivialComdat(*D, *Fn);
  2236. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  2237. setFunctionDefinitionAttributes(D, Fn);
  2238. SetLLVMFunctionAttributesForDefinition(D, Fn);
  2239. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  2240. AddGlobalCtor(Fn, CA->getPriority());
  2241. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  2242. AddGlobalDtor(Fn, DA->getPriority());
  2243. if (D->hasAttr<AnnotateAttr>())
  2244. AddGlobalAnnotations(D, Fn);
  2245. }
  2246. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  2247. const auto *D = cast<ValueDecl>(GD.getDecl());
  2248. const AliasAttr *AA = D->getAttr<AliasAttr>();
  2249. assert(AA && "Not an alias?");
  2250. StringRef MangledName = getMangledName(GD);
  2251. // If there is a definition in the module, then it wins over the alias.
  2252. // This is dubious, but allow it to be safe. Just ignore the alias.
  2253. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2254. if (Entry && !Entry->isDeclaration())
  2255. return;
  2256. Aliases.push_back(GD);
  2257. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2258. // Create a reference to the named value. This ensures that it is emitted
  2259. // if a deferred decl.
  2260. llvm::Constant *Aliasee;
  2261. if (isa<llvm::FunctionType>(DeclTy))
  2262. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  2263. /*ForVTable=*/false);
  2264. else
  2265. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2266. llvm::PointerType::getUnqual(DeclTy),
  2267. /*D=*/nullptr);
  2268. // Create the new alias itself, but don't set a name yet.
  2269. auto *GA = llvm::GlobalAlias::create(
  2270. cast<llvm::PointerType>(Aliasee->getType()),
  2271. llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  2272. if (Entry) {
  2273. if (GA->getAliasee() == Entry) {
  2274. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  2275. return;
  2276. }
  2277. assert(Entry->isDeclaration());
  2278. // If there is a declaration in the module, then we had an extern followed
  2279. // by the alias, as in:
  2280. // extern int test6();
  2281. // ...
  2282. // int test6() __attribute__((alias("test7")));
  2283. //
  2284. // Remove it and replace uses of it with the alias.
  2285. GA->takeName(Entry);
  2286. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  2287. Entry->getType()));
  2288. Entry->eraseFromParent();
  2289. } else {
  2290. GA->setName(MangledName);
  2291. }
  2292. // Set attributes which are particular to an alias; this is a
  2293. // specialization of the attributes which may be set on a global
  2294. // variable/function.
  2295. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  2296. D->isWeakImported()) {
  2297. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2298. }
  2299. if (const auto *VD = dyn_cast<VarDecl>(D))
  2300. if (VD->getTLSKind())
  2301. setTLSMode(GA, *VD);
  2302. setAliasAttributes(D, GA);
  2303. }
  2304. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2305. ArrayRef<llvm::Type*> Tys) {
  2306. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2307. Tys);
  2308. }
  2309. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2310. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2311. const StringLiteral *Literal, bool TargetIsLSB,
  2312. bool &IsUTF16, unsigned &StringLength) {
  2313. StringRef String = Literal->getString();
  2314. unsigned NumBytes = String.size();
  2315. // Check for simple case.
  2316. if (!Literal->containsNonAsciiOrNull()) {
  2317. StringLength = NumBytes;
  2318. return *Map.insert(std::make_pair(String, nullptr)).first;
  2319. }
  2320. // Otherwise, convert the UTF8 literals into a string of shorts.
  2321. IsUTF16 = true;
  2322. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2323. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2324. UTF16 *ToPtr = &ToBuf[0];
  2325. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2326. &ToPtr, ToPtr + NumBytes,
  2327. strictConversion);
  2328. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2329. StringLength = ToPtr - &ToBuf[0];
  2330. // Add an explicit null.
  2331. *ToPtr = 0;
  2332. return *Map.insert(std::make_pair(
  2333. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2334. (StringLength + 1) * 2),
  2335. nullptr)).first;
  2336. }
  2337. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2338. GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2339. const StringLiteral *Literal, unsigned &StringLength) {
  2340. StringRef String = Literal->getString();
  2341. StringLength = String.size();
  2342. return *Map.insert(std::make_pair(String, nullptr)).first;
  2343. }
  2344. llvm::Constant *
  2345. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2346. unsigned StringLength = 0;
  2347. bool isUTF16 = false;
  2348. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2349. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2350. getDataLayout().isLittleEndian(), isUTF16,
  2351. StringLength);
  2352. if (auto *C = Entry.second)
  2353. return C;
  2354. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2355. llvm::Constant *Zeros[] = { Zero, Zero };
  2356. llvm::Value *V;
  2357. // If we don't already have it, get __CFConstantStringClassReference.
  2358. if (!CFConstantStringClassRef) {
  2359. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2360. Ty = llvm::ArrayType::get(Ty, 0);
  2361. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  2362. "__CFConstantStringClassReference");
  2363. // Decay array -> ptr
  2364. V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  2365. CFConstantStringClassRef = V;
  2366. }
  2367. else
  2368. V = CFConstantStringClassRef;
  2369. QualType CFTy = getContext().getCFConstantStringType();
  2370. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2371. llvm::Constant *Fields[4];
  2372. // Class pointer.
  2373. Fields[0] = cast<llvm::ConstantExpr>(V);
  2374. // Flags.
  2375. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2376. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  2377. llvm::ConstantInt::get(Ty, 0x07C8);
  2378. // String pointer.
  2379. llvm::Constant *C = nullptr;
  2380. if (isUTF16) {
  2381. ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
  2382. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  2383. Entry.first().size() / 2);
  2384. C = llvm::ConstantDataArray::get(VMContext, Arr);
  2385. } else {
  2386. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2387. }
  2388. // Note: -fwritable-strings doesn't make the backing store strings of
  2389. // CFStrings writable. (See <rdar://problem/10657500>)
  2390. auto *GV =
  2391. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  2392. llvm::GlobalValue::PrivateLinkage, C, ".str");
  2393. GV->setUnnamedAddr(true);
  2394. // Don't enforce the target's minimum global alignment, since the only use
  2395. // of the string is via this class initializer.
  2396. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
  2397. // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
  2398. // that changes the section it ends in, which surprises ld64.
  2399. if (isUTF16) {
  2400. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  2401. GV->setAlignment(Align.getQuantity());
  2402. GV->setSection("__TEXT,__ustring");
  2403. } else {
  2404. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2405. GV->setAlignment(Align.getQuantity());
  2406. GV->setSection("__TEXT,__cstring,cstring_literals");
  2407. }
  2408. // String.
  2409. Fields[2] =
  2410. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2411. if (isUTF16)
  2412. // Cast the UTF16 string to the correct type.
  2413. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  2414. // String length.
  2415. Ty = getTypes().ConvertType(getContext().LongTy);
  2416. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  2417. // The struct.
  2418. C = llvm::ConstantStruct::get(STy, Fields);
  2419. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2420. llvm::GlobalVariable::PrivateLinkage, C,
  2421. "_unnamed_cfstring_");
  2422. GV->setSection("__DATA,__cfstring");
  2423. Entry.second = GV;
  2424. return GV;
  2425. }
  2426. llvm::GlobalVariable *
  2427. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  2428. unsigned StringLength = 0;
  2429. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2430. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  2431. if (auto *C = Entry.second)
  2432. return C;
  2433. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2434. llvm::Constant *Zeros[] = { Zero, Zero };
  2435. llvm::Value *V;
  2436. // If we don't already have it, get _NSConstantStringClassReference.
  2437. if (!ConstantStringClassRef) {
  2438. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  2439. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2440. llvm::Constant *GV;
  2441. if (LangOpts.ObjCRuntime.isNonFragile()) {
  2442. std::string str =
  2443. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  2444. : "OBJC_CLASS_$_" + StringClass;
  2445. GV = getObjCRuntime().GetClassGlobal(str);
  2446. // Make sure the result is of the correct type.
  2447. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2448. V = llvm::ConstantExpr::getBitCast(GV, PTy);
  2449. ConstantStringClassRef = V;
  2450. } else {
  2451. std::string str =
  2452. StringClass.empty() ? "_NSConstantStringClassReference"
  2453. : "_" + StringClass + "ClassReference";
  2454. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  2455. GV = CreateRuntimeVariable(PTy, str);
  2456. // Decay array -> ptr
  2457. V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
  2458. ConstantStringClassRef = V;
  2459. }
  2460. } else
  2461. V = ConstantStringClassRef;
  2462. if (!NSConstantStringType) {
  2463. // Construct the type for a constant NSString.
  2464. RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
  2465. D->startDefinition();
  2466. QualType FieldTypes[3];
  2467. // const int *isa;
  2468. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2469. // const char *str;
  2470. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2471. // unsigned int length;
  2472. FieldTypes[2] = Context.UnsignedIntTy;
  2473. // Create fields
  2474. for (unsigned i = 0; i < 3; ++i) {
  2475. FieldDecl *Field = FieldDecl::Create(Context, D,
  2476. SourceLocation(),
  2477. SourceLocation(), nullptr,
  2478. FieldTypes[i], /*TInfo=*/nullptr,
  2479. /*BitWidth=*/nullptr,
  2480. /*Mutable=*/false,
  2481. ICIS_NoInit);
  2482. Field->setAccess(AS_public);
  2483. D->addDecl(Field);
  2484. }
  2485. D->completeDefinition();
  2486. QualType NSTy = Context.getTagDeclType(D);
  2487. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2488. }
  2489. llvm::Constant *Fields[3];
  2490. // Class pointer.
  2491. Fields[0] = cast<llvm::ConstantExpr>(V);
  2492. // String pointer.
  2493. llvm::Constant *C =
  2494. llvm::ConstantDataArray::getString(VMContext, Entry.first());
  2495. llvm::GlobalValue::LinkageTypes Linkage;
  2496. bool isConstant;
  2497. Linkage = llvm::GlobalValue::PrivateLinkage;
  2498. isConstant = !LangOpts.WritableStrings;
  2499. auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
  2500. Linkage, C, ".str");
  2501. GV->setUnnamedAddr(true);
  2502. // Don't enforce the target's minimum global alignment, since the only use
  2503. // of the string is via this class initializer.
  2504. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2505. GV->setAlignment(Align.getQuantity());
  2506. Fields[1] =
  2507. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  2508. // String length.
  2509. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2510. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2511. // The struct.
  2512. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2513. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2514. llvm::GlobalVariable::PrivateLinkage, C,
  2515. "_unnamed_nsstring_");
  2516. const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
  2517. const char *NSStringNonFragileABISection =
  2518. "__DATA,__objc_stringobj,regular,no_dead_strip";
  2519. // FIXME. Fix section.
  2520. GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
  2521. ? NSStringNonFragileABISection
  2522. : NSStringSection);
  2523. Entry.second = GV;
  2524. return GV;
  2525. }
  2526. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2527. if (ObjCFastEnumerationStateType.isNull()) {
  2528. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  2529. D->startDefinition();
  2530. QualType FieldTypes[] = {
  2531. Context.UnsignedLongTy,
  2532. Context.getPointerType(Context.getObjCIdType()),
  2533. Context.getPointerType(Context.UnsignedLongTy),
  2534. Context.getConstantArrayType(Context.UnsignedLongTy,
  2535. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2536. };
  2537. for (size_t i = 0; i < 4; ++i) {
  2538. FieldDecl *Field = FieldDecl::Create(Context,
  2539. D,
  2540. SourceLocation(),
  2541. SourceLocation(), nullptr,
  2542. FieldTypes[i], /*TInfo=*/nullptr,
  2543. /*BitWidth=*/nullptr,
  2544. /*Mutable=*/false,
  2545. ICIS_NoInit);
  2546. Field->setAccess(AS_public);
  2547. D->addDecl(Field);
  2548. }
  2549. D->completeDefinition();
  2550. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2551. }
  2552. return ObjCFastEnumerationStateType;
  2553. }
  2554. llvm::Constant *
  2555. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2556. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2557. // Don't emit it as the address of the string, emit the string data itself
  2558. // as an inline array.
  2559. if (E->getCharByteWidth() == 1) {
  2560. SmallString<64> Str(E->getString());
  2561. // Resize the string to the right size, which is indicated by its type.
  2562. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2563. Str.resize(CAT->getSize().getZExtValue());
  2564. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2565. }
  2566. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2567. llvm::Type *ElemTy = AType->getElementType();
  2568. unsigned NumElements = AType->getNumElements();
  2569. // Wide strings have either 2-byte or 4-byte elements.
  2570. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2571. SmallVector<uint16_t, 32> Elements;
  2572. Elements.reserve(NumElements);
  2573. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2574. Elements.push_back(E->getCodeUnit(i));
  2575. Elements.resize(NumElements);
  2576. return llvm::ConstantDataArray::get(VMContext, Elements);
  2577. }
  2578. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2579. SmallVector<uint32_t, 32> Elements;
  2580. Elements.reserve(NumElements);
  2581. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2582. Elements.push_back(E->getCodeUnit(i));
  2583. Elements.resize(NumElements);
  2584. return llvm::ConstantDataArray::get(VMContext, Elements);
  2585. }
  2586. static llvm::GlobalVariable *
  2587. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  2588. CodeGenModule &CGM, StringRef GlobalName,
  2589. unsigned Alignment) {
  2590. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2591. unsigned AddrSpace = 0;
  2592. if (CGM.getLangOpts().OpenCL)
  2593. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  2594. llvm::Module &M = CGM.getModule();
  2595. // Create a global variable for this string
  2596. auto *GV = new llvm::GlobalVariable(
  2597. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  2598. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  2599. GV->setAlignment(Alignment);
  2600. GV->setUnnamedAddr(true);
  2601. if (GV->isWeakForLinker()) {
  2602. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  2603. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  2604. }
  2605. return GV;
  2606. }
  2607. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2608. /// constant array for the given string literal.
  2609. llvm::GlobalVariable *
  2610. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  2611. StringRef Name) {
  2612. auto Alignment =
  2613. getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
  2614. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2615. llvm::GlobalVariable **Entry = nullptr;
  2616. if (!LangOpts.WritableStrings) {
  2617. Entry = &ConstantStringMap[C];
  2618. if (auto GV = *Entry) {
  2619. if (Alignment > GV->getAlignment())
  2620. GV->setAlignment(Alignment);
  2621. return GV;
  2622. }
  2623. }
  2624. SmallString<256> MangledNameBuffer;
  2625. StringRef GlobalVariableName;
  2626. llvm::GlobalValue::LinkageTypes LT;
  2627. // Mangle the string literal if the ABI allows for it. However, we cannot
  2628. // do this if we are compiling with ASan or -fwritable-strings because they
  2629. // rely on strings having normal linkage.
  2630. if (!LangOpts.WritableStrings &&
  2631. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  2632. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  2633. llvm::raw_svector_ostream Out(MangledNameBuffer);
  2634. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  2635. Out.flush();
  2636. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  2637. GlobalVariableName = MangledNameBuffer;
  2638. } else {
  2639. LT = llvm::GlobalValue::PrivateLinkage;
  2640. GlobalVariableName = Name;
  2641. }
  2642. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  2643. if (Entry)
  2644. *Entry = GV;
  2645. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  2646. QualType());
  2647. return GV;
  2648. }
  2649. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2650. /// array for the given ObjCEncodeExpr node.
  2651. llvm::GlobalVariable *
  2652. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2653. std::string Str;
  2654. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2655. return GetAddrOfConstantCString(Str);
  2656. }
  2657. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  2658. /// the literal and a terminating '\0' character.
  2659. /// The result has pointer to array type.
  2660. llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
  2661. const std::string &Str, const char *GlobalName, unsigned Alignment) {
  2662. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2663. if (Alignment == 0) {
  2664. Alignment = getContext()
  2665. .getAlignOfGlobalVarInChars(getContext().CharTy)
  2666. .getQuantity();
  2667. }
  2668. llvm::Constant *C =
  2669. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  2670. // Don't share any string literals if strings aren't constant.
  2671. llvm::GlobalVariable **Entry = nullptr;
  2672. if (!LangOpts.WritableStrings) {
  2673. Entry = &ConstantStringMap[C];
  2674. if (auto GV = *Entry) {
  2675. if (Alignment > GV->getAlignment())
  2676. GV->setAlignment(Alignment);
  2677. return GV;
  2678. }
  2679. }
  2680. // Get the default prefix if a name wasn't specified.
  2681. if (!GlobalName)
  2682. GlobalName = ".str";
  2683. // Create a global variable for this.
  2684. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  2685. GlobalName, Alignment);
  2686. if (Entry)
  2687. *Entry = GV;
  2688. return GV;
  2689. }
  2690. llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
  2691. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2692. assert((E->getStorageDuration() == SD_Static ||
  2693. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2694. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  2695. // If we're not materializing a subobject of the temporary, keep the
  2696. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2697. QualType MaterializedType = Init->getType();
  2698. if (Init == E->GetTemporaryExpr())
  2699. MaterializedType = E->getType();
  2700. llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
  2701. if (Slot)
  2702. return Slot;
  2703. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2704. // we need to give each temporary the same name in every translation unit (and
  2705. // we also need to make the temporaries externally-visible).
  2706. SmallString<256> Name;
  2707. llvm::raw_svector_ostream Out(Name);
  2708. getCXXABI().getMangleContext().mangleReferenceTemporary(
  2709. VD, E->getManglingNumber(), Out);
  2710. Out.flush();
  2711. APValue *Value = nullptr;
  2712. if (E->getStorageDuration() == SD_Static) {
  2713. // We might have a cached constant initializer for this temporary. Note
  2714. // that this might have a different value from the value computed by
  2715. // evaluating the initializer if the surrounding constant expression
  2716. // modifies the temporary.
  2717. Value = getContext().getMaterializedTemporaryValue(E, false);
  2718. if (Value && Value->isUninit())
  2719. Value = nullptr;
  2720. }
  2721. // Try evaluating it now, it might have a constant initializer.
  2722. Expr::EvalResult EvalResult;
  2723. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  2724. !EvalResult.hasSideEffects())
  2725. Value = &EvalResult.Val;
  2726. llvm::Constant *InitialValue = nullptr;
  2727. bool Constant = false;
  2728. llvm::Type *Type;
  2729. if (Value) {
  2730. // The temporary has a constant initializer, use it.
  2731. InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
  2732. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  2733. Type = InitialValue->getType();
  2734. } else {
  2735. // No initializer, the initialization will be provided when we
  2736. // initialize the declaration which performed lifetime extension.
  2737. Type = getTypes().ConvertTypeForMem(MaterializedType);
  2738. }
  2739. // Create a global variable for this lifetime-extended temporary.
  2740. llvm::GlobalValue::LinkageTypes Linkage =
  2741. getLLVMLinkageVarDefinition(VD, Constant);
  2742. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  2743. const VarDecl *InitVD;
  2744. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  2745. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  2746. // Temporaries defined inside a class get linkonce_odr linkage because the
  2747. // class can be defined in multipe translation units.
  2748. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  2749. } else {
  2750. // There is no need for this temporary to have external linkage if the
  2751. // VarDecl has external linkage.
  2752. Linkage = llvm::GlobalVariable::InternalLinkage;
  2753. }
  2754. }
  2755. unsigned AddrSpace = GetGlobalVarAddressSpace(
  2756. VD, getContext().getTargetAddressSpace(MaterializedType));
  2757. auto *GV = new llvm::GlobalVariable(
  2758. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  2759. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  2760. AddrSpace);
  2761. setGlobalVisibility(GV, VD);
  2762. GV->setAlignment(
  2763. getContext().getTypeAlignInChars(MaterializedType).getQuantity());
  2764. if (supportsCOMDAT() && GV->isWeakForLinker())
  2765. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2766. if (VD->getTLSKind())
  2767. setTLSMode(GV, *VD);
  2768. Slot = GV;
  2769. return GV;
  2770. }
  2771. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2772. /// properties for an implementation.
  2773. void CodeGenModule::EmitObjCPropertyImplementations(const
  2774. ObjCImplementationDecl *D) {
  2775. #if 0 // HLSL Change - no ObjC support
  2776. for (const auto *PID : D->property_impls()) {
  2777. // Dynamic is just for type-checking.
  2778. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2779. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2780. // Determine which methods need to be implemented, some may have
  2781. // been overridden. Note that ::isPropertyAccessor is not the method
  2782. // we want, that just indicates if the decl came from a
  2783. // property. What we want to know is if the method is defined in
  2784. // this implementation.
  2785. if (!D->getInstanceMethod(PD->getGetterName()))
  2786. CodeGenFunction(*this).GenerateObjCGetter(
  2787. const_cast<ObjCImplementationDecl *>(D), PID);
  2788. if (!PD->isReadOnly() &&
  2789. !D->getInstanceMethod(PD->getSetterName()))
  2790. CodeGenFunction(*this).GenerateObjCSetter(
  2791. const_cast<ObjCImplementationDecl *>(D), PID);
  2792. }
  2793. }
  2794. #endif // HLSL Change - no ObjC support
  2795. }
  2796. #if 0 // HLSL Change - no ObjC support
  2797. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2798. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2799. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2800. ivar; ivar = ivar->getNextIvar())
  2801. if (ivar->getType().isDestructedType())
  2802. return true;
  2803. return false;
  2804. }
  2805. static bool AllTrivialInitializers(CodeGenModule &CGM,
  2806. ObjCImplementationDecl *D) {
  2807. CodeGenFunction CGF(CGM);
  2808. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  2809. E = D->init_end(); B != E; ++B) {
  2810. CXXCtorInitializer *CtorInitExp = *B;
  2811. Expr *Init = CtorInitExp->getInit();
  2812. if (!CGF.isTrivialInitializer(Init))
  2813. return false;
  2814. }
  2815. return true;
  2816. }
  2817. #endif
  2818. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2819. /// for an implementation.
  2820. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2821. #if 0 // HLSL Change - no ObjC support
  2822. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2823. if (needsDestructMethod(D)) {
  2824. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2825. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2826. ObjCMethodDecl *DTORMethod =
  2827. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2828. cxxSelector, getContext().VoidTy, nullptr, D,
  2829. /*isInstance=*/true, /*isVariadic=*/false,
  2830. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2831. /*isDefined=*/false, ObjCMethodDecl::Required);
  2832. D->addInstanceMethod(DTORMethod);
  2833. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2834. D->setHasDestructors(true);
  2835. }
  2836. // If the implementation doesn't have any ivar initializers, we don't need
  2837. // a .cxx_construct.
  2838. if (D->getNumIvarInitializers() == 0 ||
  2839. AllTrivialInitializers(*this, D))
  2840. return;
  2841. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2842. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2843. // The constructor returns 'self'.
  2844. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2845. D->getLocation(),
  2846. D->getLocation(),
  2847. cxxSelector,
  2848. getContext().getObjCIdType(),
  2849. nullptr, D, /*isInstance=*/true,
  2850. /*isVariadic=*/false,
  2851. /*isPropertyAccessor=*/true,
  2852. /*isImplicitlyDeclared=*/true,
  2853. /*isDefined=*/false,
  2854. ObjCMethodDecl::Required);
  2855. D->addInstanceMethod(CTORMethod);
  2856. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2857. D->setHasNonZeroConstructors(true);
  2858. #endif // HLSL Change - no ObjC support
  2859. }
  2860. /// EmitNamespace - Emit all declarations in a namespace.
  2861. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2862. for (auto *I : ND->decls()) {
  2863. if (const auto *VD = dyn_cast<VarDecl>(I))
  2864. if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  2865. VD->getTemplateSpecializationKind() != TSK_Undeclared)
  2866. continue;
  2867. EmitTopLevelDecl(I);
  2868. }
  2869. }
  2870. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2871. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2872. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2873. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2874. ErrorUnsupported(LSD, "linkage spec");
  2875. return;
  2876. }
  2877. for (auto *I : LSD->decls()) {
  2878. // Meta-data for ObjC class includes references to implemented methods.
  2879. // Generate class's method definitions first.
  2880. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  2881. for (auto *M : OID->methods())
  2882. EmitTopLevelDecl(M);
  2883. }
  2884. EmitTopLevelDecl(I);
  2885. }
  2886. }
  2887. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2888. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2889. // Ignore dependent declarations.
  2890. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2891. return;
  2892. switch (D->getKind()) {
  2893. case Decl::CXXConversion:
  2894. case Decl::CXXMethod:
  2895. case Decl::Function:
  2896. // Skip function templates
  2897. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2898. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2899. return;
  2900. EmitGlobal(cast<FunctionDecl>(D));
  2901. // Always provide some coverage mapping
  2902. // even for the functions that aren't emitted.
  2903. AddDeferredUnusedCoverageMapping(D);
  2904. break;
  2905. case Decl::Var:
  2906. // Skip variable templates
  2907. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  2908. return;
  2909. case Decl::VarTemplateSpecialization:
  2910. EmitGlobal(cast<VarDecl>(D));
  2911. getHLSLRuntime().addResource(D); // HLSL Change - add resource for global variables
  2912. break;
  2913. // Indirect fields from global anonymous structs and unions can be
  2914. // ignored; only the actual variable requires IR gen support.
  2915. case Decl::IndirectField:
  2916. break;
  2917. // C++ Decls
  2918. case Decl::Namespace:
  2919. EmitNamespace(cast<NamespaceDecl>(D));
  2920. break;
  2921. // No code generation needed.
  2922. case Decl::UsingShadow:
  2923. case Decl::ClassTemplate:
  2924. case Decl::VarTemplate:
  2925. case Decl::VarTemplatePartialSpecialization:
  2926. case Decl::FunctionTemplate:
  2927. case Decl::TypeAliasTemplate:
  2928. case Decl::Block:
  2929. case Decl::Empty:
  2930. break;
  2931. case Decl::Using: // using X; [C++]
  2932. if (CGDebugInfo *DI = getModuleDebugInfo())
  2933. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  2934. return;
  2935. case Decl::NamespaceAlias:
  2936. if (CGDebugInfo *DI = getModuleDebugInfo())
  2937. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  2938. return;
  2939. case Decl::UsingDirective: // using namespace X; [C++]
  2940. if (CGDebugInfo *DI = getModuleDebugInfo())
  2941. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  2942. return;
  2943. case Decl::CXXConstructor:
  2944. // Skip function templates
  2945. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2946. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2947. return;
  2948. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2949. break;
  2950. case Decl::CXXDestructor:
  2951. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2952. return;
  2953. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2954. break;
  2955. case Decl::StaticAssert:
  2956. // Nothing to do.
  2957. break;
  2958. // Objective-C Decls
  2959. #if 0 // HLSL Change Starts - no ObjC support
  2960. // Forward declarations, no (immediate) code generation.
  2961. case Decl::ObjCInterface:
  2962. case Decl::ObjCCategory:
  2963. break;
  2964. case Decl::ObjCProtocol: {
  2965. auto *Proto = cast<ObjCProtocolDecl>(D);
  2966. if (Proto->isThisDeclarationADefinition())
  2967. ObjCRuntime->GenerateProtocol(Proto);
  2968. break;
  2969. }
  2970. case Decl::ObjCCategoryImpl:
  2971. // Categories have properties but don't support synthesize so we
  2972. // can ignore them here.
  2973. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2974. break;
  2975. case Decl::ObjCImplementation: {
  2976. auto *OMD = cast<ObjCImplementationDecl>(D);
  2977. EmitObjCPropertyImplementations(OMD);
  2978. EmitObjCIvarInitializations(OMD);
  2979. ObjCRuntime->GenerateClass(OMD);
  2980. // Emit global variable debug information.
  2981. if (CGDebugInfo *DI = getModuleDebugInfo())
  2982. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2983. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2984. OMD->getClassInterface()), OMD->getLocation());
  2985. break;
  2986. }
  2987. case Decl::ObjCMethod: {
  2988. auto *OMD = cast<ObjCMethodDecl>(D);
  2989. // If this is not a prototype, emit the body.
  2990. if (OMD->getBody())
  2991. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2992. break;
  2993. }
  2994. case Decl::ObjCCompatibleAlias:
  2995. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2996. break;
  2997. #endif // HLSL Change Ends - no ObjC support
  2998. case Decl::LinkageSpec:
  2999. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3000. break;
  3001. #if 0 // HLSL Change Starts - no asm, import or openmp support
  3002. case Decl::FileScopeAsm: {
  3003. // File-scope asm is ignored during device-side CUDA compilation.
  3004. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3005. break;
  3006. auto *AD = cast<FileScopeAsmDecl>(D);
  3007. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3008. break;
  3009. }
  3010. case Decl::Import: {
  3011. auto *Import = cast<ImportDecl>(D);
  3012. // Ignore import declarations that come from imported modules.
  3013. if (clang::Module *Owner = Import->getImportedOwningModule()) {
  3014. if (getLangOpts().CurrentModule.empty() ||
  3015. Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
  3016. break;
  3017. }
  3018. if (CGDebugInfo *DI = getModuleDebugInfo())
  3019. DI->EmitImportDecl(*Import);
  3020. ImportedModules.insert(Import->getImportedModule());
  3021. break;
  3022. }
  3023. case Decl::OMPThreadPrivate:
  3024. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3025. break;
  3026. #endif // HLSL Change Ends - no asm, import or openmp support
  3027. case Decl::ClassTemplateSpecialization: {
  3028. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3029. if (DebugInfo &&
  3030. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3031. Spec->hasDefinition())
  3032. DebugInfo->completeTemplateDefinition(*Spec);
  3033. break;
  3034. }
  3035. // HLSL Change Starts
  3036. case Decl::HLSLBuffer: {
  3037. // TODO: add resource to HLSLRuntime
  3038. HLSLBufferDecl *BD = cast<HLSLBufferDecl>(D);
  3039. getHLSLRuntime().addResource(BD);
  3040. break;
  3041. }
  3042. // HLSL Change Ends
  3043. default:
  3044. // Make sure we handled everything we should, every other kind is a
  3045. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3046. // function. Need to recode Decl::Kind to do that easily.
  3047. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3048. break;
  3049. }
  3050. }
  3051. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3052. // Do we need to generate coverage mapping?
  3053. if (!CodeGenOpts.CoverageMapping)
  3054. return;
  3055. switch (D->getKind()) {
  3056. case Decl::CXXConversion:
  3057. case Decl::CXXMethod:
  3058. case Decl::Function:
  3059. case Decl::ObjCMethod:
  3060. case Decl::CXXConstructor:
  3061. case Decl::CXXDestructor: {
  3062. if (!cast<FunctionDecl>(D)->hasBody())
  3063. return;
  3064. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3065. if (I == DeferredEmptyCoverageMappingDecls.end())
  3066. DeferredEmptyCoverageMappingDecls[D] = true;
  3067. break;
  3068. }
  3069. default:
  3070. break;
  3071. };
  3072. }
  3073. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3074. // Do we need to generate coverage mapping?
  3075. if (!CodeGenOpts.CoverageMapping)
  3076. return;
  3077. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3078. if (Fn->isTemplateInstantiation())
  3079. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3080. }
  3081. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3082. if (I == DeferredEmptyCoverageMappingDecls.end())
  3083. DeferredEmptyCoverageMappingDecls[D] = false;
  3084. else
  3085. I->second = false;
  3086. }
  3087. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3088. std::vector<const Decl *> DeferredDecls;
  3089. for (const auto &I : DeferredEmptyCoverageMappingDecls) {
  3090. if (!I.second)
  3091. continue;
  3092. DeferredDecls.push_back(I.first);
  3093. }
  3094. // Sort the declarations by their location to make sure that the tests get a
  3095. // predictable order for the coverage mapping for the unused declarations.
  3096. if (CodeGenOpts.DumpCoverageMapping)
  3097. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  3098. [] (const Decl *LHS, const Decl *RHS) {
  3099. return LHS->getLocStart() < RHS->getLocStart();
  3100. });
  3101. for (const auto *D : DeferredDecls) {
  3102. switch (D->getKind()) {
  3103. case Decl::CXXConversion:
  3104. case Decl::CXXMethod:
  3105. case Decl::Function:
  3106. case Decl::ObjCMethod: {
  3107. CodeGenPGO PGO(*this);
  3108. GlobalDecl GD(cast<FunctionDecl>(D));
  3109. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3110. getFunctionLinkage(GD));
  3111. break;
  3112. }
  3113. case Decl::CXXConstructor: {
  3114. CodeGenPGO PGO(*this);
  3115. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3116. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3117. getFunctionLinkage(GD));
  3118. break;
  3119. }
  3120. case Decl::CXXDestructor: {
  3121. CodeGenPGO PGO(*this);
  3122. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3123. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3124. getFunctionLinkage(GD));
  3125. break;
  3126. }
  3127. default:
  3128. break;
  3129. };
  3130. }
  3131. }
  3132. /// Turns the given pointer into a constant.
  3133. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  3134. const void *Ptr) {
  3135. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3136. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3137. return llvm::ConstantInt::get(i64, PtrInt);
  3138. }
  3139. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3140. llvm::NamedMDNode *&GlobalMetadata,
  3141. GlobalDecl D,
  3142. llvm::GlobalValue *Addr) {
  3143. if (!GlobalMetadata)
  3144. GlobalMetadata =
  3145. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3146. // TODO: should we report variant information for ctors/dtors?
  3147. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3148. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3149. CGM.getLLVMContext(), D.getDecl()))};
  3150. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3151. }
  3152. /// For each function which is declared within an extern "C" region and marked
  3153. /// as 'used', but has internal linkage, create an alias from the unmangled
  3154. /// name to the mangled name if possible. People expect to be able to refer
  3155. /// to such functions with an unmangled name from inline assembly within the
  3156. /// same translation unit.
  3157. void CodeGenModule::EmitStaticExternCAliases() {
  3158. for (auto &I : StaticExternCValues) {
  3159. IdentifierInfo *Name = I.first;
  3160. llvm::GlobalValue *Val = I.second;
  3161. if (Val && !getModule().getNamedValue(Name->getName()))
  3162. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3163. }
  3164. }
  3165. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3166. GlobalDecl &Result) const {
  3167. auto Res = Manglings.find(MangledName);
  3168. if (Res == Manglings.end())
  3169. return false;
  3170. Result = Res->getValue();
  3171. return true;
  3172. }
  3173. /// Emits metadata nodes associating all the global values in the
  3174. /// current module with the Decls they came from. This is useful for
  3175. /// projects using IR gen as a subroutine.
  3176. ///
  3177. /// Since there's currently no way to associate an MDNode directly
  3178. /// with an llvm::GlobalValue, we create a global named metadata
  3179. /// with the name 'clang.global.decl.ptrs'.
  3180. void CodeGenModule::EmitDeclMetadata() {
  3181. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3182. // StaticLocalDeclMap
  3183. for (auto &I : MangledDeclNames) {
  3184. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  3185. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  3186. }
  3187. }
  3188. /// Emits metadata nodes for all the local variables in the current
  3189. /// function.
  3190. void CodeGenFunction::EmitDeclMetadata() {
  3191. if (LocalDeclMap.empty()) return;
  3192. llvm::LLVMContext &Context = getLLVMContext();
  3193. // Find the unique metadata ID for this name.
  3194. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  3195. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3196. for (auto &I : LocalDeclMap) {
  3197. const Decl *D = I.first;
  3198. llvm::Value *Addr = I.second;
  3199. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  3200. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  3201. Alloca->setMetadata(
  3202. DeclPtrKind, llvm::MDNode::get(
  3203. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  3204. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  3205. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  3206. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  3207. }
  3208. }
  3209. }
  3210. void CodeGenModule::EmitVersionIdentMetadata() {
  3211. llvm::NamedMDNode *IdentMetadata =
  3212. TheModule.getOrInsertNamedMetadata("llvm.ident");
  3213. std::string Version = getClangFullVersion();
  3214. llvm::LLVMContext &Ctx = TheModule.getContext();
  3215. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  3216. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  3217. }
  3218. void CodeGenModule::EmitTargetMetadata() {
  3219. // Warning, new MangledDeclNames may be appended within this loop.
  3220. // We rely on MapVector insertions adding new elements to the end
  3221. // of the container.
  3222. // FIXME: Move this loop into the one target that needs it, and only
  3223. // loop over those declarations for which we couldn't emit the target
  3224. // metadata when we emitted the declaration.
  3225. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  3226. auto Val = *(MangledDeclNames.begin() + I);
  3227. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  3228. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  3229. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  3230. }
  3231. }
  3232. void CodeGenModule::EmitCoverageFile() {
  3233. if (!getCodeGenOpts().CoverageFile.empty()) {
  3234. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  3235. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  3236. llvm::LLVMContext &Ctx = TheModule.getContext();
  3237. llvm::MDString *CoverageFile =
  3238. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  3239. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  3240. llvm::MDNode *CU = CUNode->getOperand(i);
  3241. llvm::Metadata *Elts[] = {CoverageFile, CU};
  3242. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  3243. }
  3244. }
  3245. }
  3246. }
  3247. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  3248. // Sema has checked that all uuid strings are of the form
  3249. // "12345678-1234-1234-1234-1234567890ab".
  3250. assert(Uuid.size() == 36);
  3251. for (unsigned i = 0; i < 36; ++i) {
  3252. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  3253. else assert(isHexDigit(Uuid[i]));
  3254. }
  3255. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  3256. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  3257. llvm::Constant *Field3[8];
  3258. for (unsigned Idx = 0; Idx < 8; ++Idx)
  3259. Field3[Idx] = llvm::ConstantInt::get(
  3260. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  3261. llvm::Constant *Fields[4] = {
  3262. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  3263. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  3264. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  3265. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  3266. };
  3267. return llvm::ConstantStruct::getAnon(Fields);
  3268. }
  3269. llvm::Constant *
  3270. CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
  3271. QualType CatchHandlerType) {
  3272. return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
  3273. }
  3274. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  3275. bool ForEH) {
  3276. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  3277. // FIXME: should we even be calling this method if RTTI is disabled
  3278. // and it's not for EH?
  3279. if (!ForEH && !getLangOpts().RTTI)
  3280. return llvm::Constant::getNullValue(Int8PtrTy);
  3281. if (ForEH && Ty->isObjCObjectPointerType() &&
  3282. LangOpts.ObjCRuntime.isGNUFamily())
  3283. return ObjCRuntime->GetEHType(Ty);
  3284. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  3285. }
  3286. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  3287. #if 0 // HLSL Change - no OpenMP support
  3288. for (auto RefExpr : D->varlists()) {
  3289. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  3290. bool PerformInit =
  3291. VD->getAnyInitializer() &&
  3292. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  3293. /*ForRef=*/false);
  3294. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  3295. VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
  3296. CXXGlobalInits.push_back(InitFunction);
  3297. }
  3298. #endif
  3299. }
  3300. llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
  3301. llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
  3302. std::string OutName;
  3303. llvm::raw_string_ostream Out(OutName);
  3304. getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
  3305. llvm::Metadata *BitsetOps[] = {
  3306. llvm::MDString::get(getLLVMContext(), Out.str()),
  3307. llvm::ConstantAsMetadata::get(VTable),
  3308. llvm::ConstantAsMetadata::get(
  3309. llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
  3310. return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
  3311. }