CodeGenFunction.cpp 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  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-function state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGBlocks.h"
  15. #include "CGCleanup.h"
  16. #include "CGCUDARuntime.h"
  17. #include "CGCXXABI.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGOpenMPRuntime.h"
  20. #include "CodeGenModule.h"
  21. #include "CodeGenPGO.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/ASTLambda.h"
  25. #include "clang/AST/Decl.h"
  26. #include "clang/AST/DeclCXX.h"
  27. #include "clang/AST/StmtCXX.h"
  28. #include "clang/AST/StmtObjC.h"
  29. #include "clang/Basic/Builtins.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/CodeGen/CGFunctionInfo.h"
  32. #include "clang/Frontend/CodeGenOptions.h"
  33. #include "clang/Sema/SemaDiagnostic.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/Dominators.h"
  36. #include "llvm/IR/Intrinsics.h"
  37. #include "llvm/IR/MDBuilder.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  40. using namespace clang;
  41. using namespace CodeGen;
  42. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  43. /// markers.
  44. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  45. const LangOptions &LangOpts) {
  46. if (CGOpts.DisableLifetimeMarkers)
  47. return false;
  48. // Disable lifetime markers in msan builds.
  49. // FIXME: Remove this when msan works with lifetime markers.
  50. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  51. return false;
  52. // Asan uses markers for use-after-scope checks.
  53. if (CGOpts.SanitizeAddressUseAfterScope)
  54. return true;
  55. // For now, only in optimized builds.
  56. return CGOpts.OptimizationLevel != 0;
  57. }
  58. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  59. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  60. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  61. CGBuilderInserterTy(this)),
  62. CurFn(nullptr), ReturnValue(Address::invalid()),
  63. CapturedStmtInfo(nullptr), SanOpts(CGM.getLangOpts().Sanitize),
  64. IsSanitizerScope(false), CurFuncIsThunk(false), AutoreleaseResult(false),
  65. SawAsmBlock(false), IsOutlinedSEHHelper(false), BlockInfo(nullptr),
  66. BlockPointer(nullptr), LambdaThisCaptureField(nullptr),
  67. NormalCleanupDest(Address::invalid()), NextCleanupDestIndex(1),
  68. FirstBlockInfo(nullptr), EHResumeBlock(nullptr), ExceptionSlot(nullptr),
  69. EHSelectorSlot(nullptr), DebugInfo(CGM.getModuleDebugInfo()),
  70. DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr),
  71. PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr),
  72. CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0),
  73. NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr),
  74. CXXABIThisValue(nullptr), CXXThisValue(nullptr),
  75. CXXStructorImplicitParamDecl(nullptr),
  76. CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr),
  77. CurLexicalScope(nullptr), TerminateLandingPad(nullptr),
  78. TerminateHandler(nullptr), TrapBB(nullptr),
  79. ShouldEmitLifetimeMarkers(
  80. shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  81. if (!suppressNewContext)
  82. CGM.getCXXABI().getMangleContext().startNewFunction();
  83. llvm::FastMathFlags FMF;
  84. if (CGM.getLangOpts().FastMath)
  85. FMF.setFast();
  86. if (CGM.getLangOpts().FiniteMathOnly) {
  87. FMF.setNoNaNs();
  88. FMF.setNoInfs();
  89. }
  90. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  91. FMF.setNoNaNs();
  92. }
  93. if (CGM.getCodeGenOpts().NoSignedZeros) {
  94. FMF.setNoSignedZeros();
  95. }
  96. if (CGM.getCodeGenOpts().ReciprocalMath) {
  97. FMF.setAllowReciprocal();
  98. }
  99. if (CGM.getCodeGenOpts().Reassociate) {
  100. FMF.setAllowReassoc();
  101. }
  102. Builder.setFastMathFlags(FMF);
  103. }
  104. CodeGenFunction::~CodeGenFunction() {
  105. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  106. // If there are any unclaimed block infos, go ahead and destroy them
  107. // now. This can happen if IR-gen gets clever and skips evaluating
  108. // something.
  109. if (FirstBlockInfo)
  110. destroyBlockInfos(FirstBlockInfo);
  111. if (getLangOpts().OpenMP && CurFn)
  112. CGM.getOpenMPRuntime().functionFinished(*this);
  113. }
  114. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  115. LValueBaseInfo *BaseInfo,
  116. TBAAAccessInfo *TBAAInfo) {
  117. return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
  118. /* forPointeeType= */ true);
  119. }
  120. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  121. LValueBaseInfo *BaseInfo,
  122. TBAAAccessInfo *TBAAInfo,
  123. bool forPointeeType) {
  124. if (TBAAInfo)
  125. *TBAAInfo = CGM.getTBAAAccessInfo(T);
  126. // Honor alignment typedef attributes even on incomplete types.
  127. // We also honor them straight for C++ class types, even as pointees;
  128. // there's an expressivity gap here.
  129. if (auto TT = T->getAs<TypedefType>()) {
  130. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  131. if (BaseInfo)
  132. *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
  133. return getContext().toCharUnitsFromBits(Align);
  134. }
  135. }
  136. if (BaseInfo)
  137. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  138. CharUnits Alignment;
  139. if (T->isIncompleteType()) {
  140. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  141. } else {
  142. // For C++ class pointees, we don't know whether we're pointing at a
  143. // base or a complete object, so we generally need to use the
  144. // non-virtual alignment.
  145. const CXXRecordDecl *RD;
  146. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  147. Alignment = CGM.getClassPointerAlignment(RD);
  148. } else {
  149. Alignment = getContext().getTypeAlignInChars(T);
  150. if (T.getQualifiers().hasUnaligned())
  151. Alignment = CharUnits::One();
  152. }
  153. // Cap to the global maximum type alignment unless the alignment
  154. // was somehow explicit on the type.
  155. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  156. if (Alignment.getQuantity() > MaxAlign &&
  157. !getContext().isAlignmentRequired(T))
  158. Alignment = CharUnits::fromQuantity(MaxAlign);
  159. }
  160. }
  161. return Alignment;
  162. }
  163. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  164. LValueBaseInfo BaseInfo;
  165. TBAAAccessInfo TBAAInfo;
  166. CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
  167. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
  168. TBAAInfo);
  169. }
  170. /// Given a value of type T* that may not be to a complete object,
  171. /// construct an l-value with the natural pointee alignment of T.
  172. LValue
  173. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  174. LValueBaseInfo BaseInfo;
  175. TBAAAccessInfo TBAAInfo;
  176. CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
  177. /* forPointeeType= */ true);
  178. return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
  179. }
  180. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  181. return CGM.getTypes().ConvertTypeForMem(T);
  182. }
  183. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  184. return CGM.getTypes().ConvertType(T);
  185. }
  186. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  187. type = type.getCanonicalType();
  188. while (true) {
  189. switch (type->getTypeClass()) {
  190. #define TYPE(name, parent)
  191. #define ABSTRACT_TYPE(name, parent)
  192. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  193. #define DEPENDENT_TYPE(name, parent) case Type::name:
  194. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  195. #include "clang/AST/TypeNodes.def"
  196. llvm_unreachable("non-canonical or dependent type in IR-generation");
  197. case Type::Auto:
  198. case Type::DeducedTemplateSpecialization:
  199. llvm_unreachable("undeduced type in IR-generation");
  200. // Various scalar types.
  201. case Type::Builtin:
  202. case Type::Pointer:
  203. case Type::BlockPointer:
  204. case Type::LValueReference:
  205. case Type::RValueReference:
  206. case Type::MemberPointer:
  207. case Type::Vector:
  208. case Type::ExtVector:
  209. case Type::FunctionProto:
  210. case Type::FunctionNoProto:
  211. case Type::Enum:
  212. case Type::ObjCObjectPointer:
  213. case Type::Pipe:
  214. return TEK_Scalar;
  215. // Complexes.
  216. case Type::Complex:
  217. return TEK_Complex;
  218. // Arrays, records, and Objective-C objects.
  219. case Type::ConstantArray:
  220. case Type::IncompleteArray:
  221. case Type::VariableArray:
  222. case Type::Record:
  223. case Type::ObjCObject:
  224. case Type::ObjCInterface:
  225. return TEK_Aggregate;
  226. // We operate on atomic values according to their underlying type.
  227. case Type::Atomic:
  228. type = cast<AtomicType>(type)->getValueType();
  229. continue;
  230. }
  231. llvm_unreachable("unknown type kind!");
  232. }
  233. }
  234. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  235. // For cleanliness, we try to avoid emitting the return block for
  236. // simple cases.
  237. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  238. if (CurBB) {
  239. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  240. // We have a valid insert point, reuse it if it is empty or there are no
  241. // explicit jumps to the return block.
  242. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  243. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  244. delete ReturnBlock.getBlock();
  245. } else
  246. EmitBlock(ReturnBlock.getBlock());
  247. return llvm::DebugLoc();
  248. }
  249. // Otherwise, if the return block is the target of a single direct
  250. // branch then we can just put the code in that block instead. This
  251. // cleans up functions which started with a unified return block.
  252. if (ReturnBlock.getBlock()->hasOneUse()) {
  253. llvm::BranchInst *BI =
  254. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  255. if (BI && BI->isUnconditional() &&
  256. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  257. // Record/return the DebugLoc of the simple 'return' expression to be used
  258. // later by the actual 'ret' instruction.
  259. llvm::DebugLoc Loc = BI->getDebugLoc();
  260. Builder.SetInsertPoint(BI->getParent());
  261. BI->eraseFromParent();
  262. delete ReturnBlock.getBlock();
  263. return Loc;
  264. }
  265. }
  266. // FIXME: We are at an unreachable point, there is no reason to emit the block
  267. // unless it has uses. However, we still need a place to put the debug
  268. // region.end for now.
  269. EmitBlock(ReturnBlock.getBlock());
  270. return llvm::DebugLoc();
  271. }
  272. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  273. if (!BB) return;
  274. if (!BB->use_empty())
  275. return CGF.CurFn->getBasicBlockList().push_back(BB);
  276. delete BB;
  277. }
  278. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  279. assert(BreakContinueStack.empty() &&
  280. "mismatched push/pop in break/continue stack!");
  281. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  282. && NumSimpleReturnExprs == NumReturnExprs
  283. && ReturnBlock.getBlock()->use_empty();
  284. // Usually the return expression is evaluated before the cleanup
  285. // code. If the function contains only a simple return statement,
  286. // such as a constant, the location before the cleanup code becomes
  287. // the last useful breakpoint in the function, because the simple
  288. // return expression will be evaluated after the cleanup code. To be
  289. // safe, set the debug location for cleanup code to the location of
  290. // the return statement. Otherwise the cleanup code should be at the
  291. // end of the function's lexical scope.
  292. //
  293. // If there are multiple branches to the return block, the branch
  294. // instructions will get the location of the return statements and
  295. // all will be fine.
  296. if (CGDebugInfo *DI = getDebugInfo()) {
  297. if (OnlySimpleReturnStmts)
  298. DI->EmitLocation(Builder, LastStopPoint);
  299. else
  300. DI->EmitLocation(Builder, EndLoc);
  301. }
  302. // Pop any cleanups that might have been associated with the
  303. // parameters. Do this in whatever block we're currently in; it's
  304. // important to do this before we enter the return block or return
  305. // edges will be *really* confused.
  306. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  307. bool HasOnlyLifetimeMarkers =
  308. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  309. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  310. if (HasCleanups) {
  311. // Make sure the line table doesn't jump back into the body for
  312. // the ret after it's been at EndLoc.
  313. if (CGDebugInfo *DI = getDebugInfo())
  314. if (OnlySimpleReturnStmts)
  315. DI->EmitLocation(Builder, EndLoc);
  316. PopCleanupBlocks(PrologueCleanupDepth);
  317. }
  318. // Emit function epilog (to return).
  319. llvm::DebugLoc Loc = EmitReturnBlock();
  320. if (ShouldInstrumentFunction()) {
  321. if (CGM.getCodeGenOpts().InstrumentFunctions)
  322. CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
  323. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  324. CurFn->addFnAttr("instrument-function-exit-inlined",
  325. "__cyg_profile_func_exit");
  326. }
  327. // Emit debug descriptor for function end.
  328. if (CGDebugInfo *DI = getDebugInfo())
  329. DI->EmitFunctionEnd(Builder, CurFn);
  330. // Reset the debug location to that of the simple 'return' expression, if any
  331. // rather than that of the end of the function's scope '}'.
  332. ApplyDebugLocation AL(*this, Loc);
  333. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  334. EmitEndEHSpec(CurCodeDecl);
  335. assert(EHStack.empty() &&
  336. "did not remove all scopes from cleanup stack!");
  337. // If someone did an indirect goto, emit the indirect goto block at the end of
  338. // the function.
  339. if (IndirectBranch) {
  340. EmitBlock(IndirectBranch->getParent());
  341. Builder.ClearInsertionPoint();
  342. }
  343. // If some of our locals escaped, insert a call to llvm.localescape in the
  344. // entry block.
  345. if (!EscapedLocals.empty()) {
  346. // Invert the map from local to index into a simple vector. There should be
  347. // no holes.
  348. SmallVector<llvm::Value *, 4> EscapeArgs;
  349. EscapeArgs.resize(EscapedLocals.size());
  350. for (auto &Pair : EscapedLocals)
  351. EscapeArgs[Pair.second] = Pair.first;
  352. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  353. &CGM.getModule(), llvm::Intrinsic::localescape);
  354. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  355. }
  356. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  357. llvm::Instruction *Ptr = AllocaInsertPt;
  358. AllocaInsertPt = nullptr;
  359. Ptr->eraseFromParent();
  360. // If someone took the address of a label but never did an indirect goto, we
  361. // made a zero entry PHI node, which is illegal, zap it now.
  362. if (IndirectBranch) {
  363. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  364. if (PN->getNumIncomingValues() == 0) {
  365. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  366. PN->eraseFromParent();
  367. }
  368. }
  369. EmitIfUsed(*this, EHResumeBlock);
  370. EmitIfUsed(*this, TerminateLandingPad);
  371. EmitIfUsed(*this, TerminateHandler);
  372. EmitIfUsed(*this, UnreachableBlock);
  373. for (const auto &FuncletAndParent : TerminateFunclets)
  374. EmitIfUsed(*this, FuncletAndParent.second);
  375. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  376. EmitDeclMetadata();
  377. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  378. I = DeferredReplacements.begin(),
  379. E = DeferredReplacements.end();
  380. I != E; ++I) {
  381. I->first->replaceAllUsesWith(I->second);
  382. I->first->eraseFromParent();
  383. }
  384. // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
  385. // PHIs if the current function is a coroutine. We don't do it for all
  386. // functions as it may result in slight increase in numbers of instructions
  387. // if compiled with no optimizations. We do it for coroutine as the lifetime
  388. // of CleanupDestSlot alloca make correct coroutine frame building very
  389. // difficult.
  390. if (NormalCleanupDest.isValid() && isCoroutine()) {
  391. llvm::DominatorTree DT(*CurFn);
  392. llvm::PromoteMemToReg(
  393. cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
  394. NormalCleanupDest = Address::invalid();
  395. }
  396. }
  397. /// ShouldInstrumentFunction - Return true if the current function should be
  398. /// instrumented with __cyg_profile_func_* calls
  399. bool CodeGenFunction::ShouldInstrumentFunction() {
  400. if (!CGM.getCodeGenOpts().InstrumentFunctions &&
  401. !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
  402. !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  403. return false;
  404. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  405. return false;
  406. return true;
  407. }
  408. /// ShouldXRayInstrument - Return true if the current function should be
  409. /// instrumented with XRay nop sleds.
  410. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  411. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  412. }
  413. /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
  414. /// the __xray_customevent(...) builin calls, when doing XRay instrumentation.
  415. bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
  416. return CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents;
  417. }
  418. llvm::Constant *
  419. CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
  420. llvm::Constant *Addr) {
  421. // Addresses stored in prologue data can't require run-time fixups and must
  422. // be PC-relative. Run-time fixups are undesirable because they necessitate
  423. // writable text segments, which are unsafe. And absolute addresses are
  424. // undesirable because they break PIE mode.
  425. // Add a layer of indirection through a private global. Taking its address
  426. // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
  427. auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
  428. /*isConstant=*/true,
  429. llvm::GlobalValue::PrivateLinkage, Addr);
  430. // Create a PC-relative address.
  431. auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
  432. auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
  433. auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
  434. return (IntPtrTy == Int32Ty)
  435. ? PCRelAsInt
  436. : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
  437. }
  438. llvm::Value *
  439. CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
  440. llvm::Value *EncodedAddr) {
  441. // Reconstruct the address of the global.
  442. auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
  443. auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
  444. auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
  445. auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
  446. // Load the original pointer through the global.
  447. return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
  448. "decoded_addr");
  449. }
  450. static void removeImageAccessQualifier(std::string& TyName) {
  451. std::string ReadOnlyQual("__read_only");
  452. std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
  453. if (ReadOnlyPos != std::string::npos)
  454. // "+ 1" for the space after access qualifier.
  455. TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
  456. else {
  457. std::string WriteOnlyQual("__write_only");
  458. std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
  459. if (WriteOnlyPos != std::string::npos)
  460. TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
  461. else {
  462. std::string ReadWriteQual("__read_write");
  463. std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
  464. if (ReadWritePos != std::string::npos)
  465. TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
  466. }
  467. }
  468. }
  469. // Returns the address space id that should be produced to the
  470. // kernel_arg_addr_space metadata. This is always fixed to the ids
  471. // as specified in the SPIR 2.0 specification in order to differentiate
  472. // for example in clGetKernelArgInfo() implementation between the address
  473. // spaces with targets without unique mapping to the OpenCL address spaces
  474. // (basically all single AS CPUs).
  475. static unsigned ArgInfoAddressSpace(LangAS AS) {
  476. switch (AS) {
  477. case LangAS::opencl_global: return 1;
  478. case LangAS::opencl_constant: return 2;
  479. case LangAS::opencl_local: return 3;
  480. case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
  481. default:
  482. return 0; // Assume private.
  483. }
  484. }
  485. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  486. // information in the program executable. The argument information stored
  487. // includes the argument name, its type, the address and access qualifiers used.
  488. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  489. CodeGenModule &CGM, llvm::LLVMContext &Context,
  490. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  491. // Create MDNodes that represent the kernel arg metadata.
  492. // Each MDNode is a list in the form of "key", N number of values which is
  493. // the same number of values as their are kernel arguments.
  494. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  495. // MDNode for the kernel argument address space qualifiers.
  496. SmallVector<llvm::Metadata *, 8> addressQuals;
  497. // MDNode for the kernel argument access qualifiers (images only).
  498. SmallVector<llvm::Metadata *, 8> accessQuals;
  499. // MDNode for the kernel argument type names.
  500. SmallVector<llvm::Metadata *, 8> argTypeNames;
  501. // MDNode for the kernel argument base type names.
  502. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  503. // MDNode for the kernel argument type qualifiers.
  504. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  505. // MDNode for the kernel argument names.
  506. SmallVector<llvm::Metadata *, 8> argNames;
  507. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  508. const ParmVarDecl *parm = FD->getParamDecl(i);
  509. QualType ty = parm->getType();
  510. std::string typeQuals;
  511. if (ty->isPointerType()) {
  512. QualType pointeeTy = ty->getPointeeType();
  513. // Get address qualifier.
  514. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  515. ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
  516. // Get argument type name.
  517. std::string typeName =
  518. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  519. // Turn "unsigned type" to "utype"
  520. std::string::size_type pos = typeName.find("unsigned");
  521. if (pointeeTy.isCanonical() && pos != std::string::npos)
  522. typeName.erase(pos+1, 8);
  523. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  524. std::string baseTypeName =
  525. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  526. Policy) +
  527. "*";
  528. // Turn "unsigned type" to "utype"
  529. pos = baseTypeName.find("unsigned");
  530. if (pos != std::string::npos)
  531. baseTypeName.erase(pos+1, 8);
  532. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  533. // Get argument type qualifiers:
  534. if (ty.isRestrictQualified())
  535. typeQuals = "restrict";
  536. if (pointeeTy.isConstQualified() ||
  537. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  538. typeQuals += typeQuals.empty() ? "const" : " const";
  539. if (pointeeTy.isVolatileQualified())
  540. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  541. } else {
  542. uint32_t AddrSpc = 0;
  543. bool isPipe = ty->isPipeType();
  544. if (ty->isImageType() || isPipe)
  545. AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
  546. addressQuals.push_back(
  547. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  548. // Get argument type name.
  549. std::string typeName;
  550. if (isPipe)
  551. typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
  552. .getAsString(Policy);
  553. else
  554. typeName = ty.getUnqualifiedType().getAsString(Policy);
  555. // Turn "unsigned type" to "utype"
  556. std::string::size_type pos = typeName.find("unsigned");
  557. if (ty.isCanonical() && pos != std::string::npos)
  558. typeName.erase(pos+1, 8);
  559. std::string baseTypeName;
  560. if (isPipe)
  561. baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
  562. ->getElementType().getCanonicalType()
  563. .getAsString(Policy);
  564. else
  565. baseTypeName =
  566. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  567. // Remove access qualifiers on images
  568. // (as they are inseparable from type in clang implementation,
  569. // but OpenCL spec provides a special query to get access qualifier
  570. // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
  571. if (ty->isImageType()) {
  572. removeImageAccessQualifier(typeName);
  573. removeImageAccessQualifier(baseTypeName);
  574. }
  575. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  576. // Turn "unsigned type" to "utype"
  577. pos = baseTypeName.find("unsigned");
  578. if (pos != std::string::npos)
  579. baseTypeName.erase(pos+1, 8);
  580. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  581. if (isPipe)
  582. typeQuals = "pipe";
  583. }
  584. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  585. // Get image and pipe access qualifier:
  586. if (ty->isImageType()|| ty->isPipeType()) {
  587. const Decl *PDecl = parm;
  588. if (auto *TD = dyn_cast<TypedefType>(ty))
  589. PDecl = TD->getDecl();
  590. const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
  591. if (A && A->isWriteOnly())
  592. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  593. else if (A && A->isReadWrite())
  594. accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
  595. else
  596. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  597. } else
  598. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  599. // Get argument name.
  600. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  601. }
  602. Fn->setMetadata("kernel_arg_addr_space",
  603. llvm::MDNode::get(Context, addressQuals));
  604. Fn->setMetadata("kernel_arg_access_qual",
  605. llvm::MDNode::get(Context, accessQuals));
  606. Fn->setMetadata("kernel_arg_type",
  607. llvm::MDNode::get(Context, argTypeNames));
  608. Fn->setMetadata("kernel_arg_base_type",
  609. llvm::MDNode::get(Context, argBaseTypeNames));
  610. Fn->setMetadata("kernel_arg_type_qual",
  611. llvm::MDNode::get(Context, argTypeQuals));
  612. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  613. Fn->setMetadata("kernel_arg_name",
  614. llvm::MDNode::get(Context, argNames));
  615. }
  616. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  617. llvm::Function *Fn)
  618. {
  619. if (!FD->hasAttr<OpenCLKernelAttr>())
  620. return;
  621. llvm::LLVMContext &Context = getLLVMContext();
  622. GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
  623. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  624. QualType HintQTy = A->getTypeHint();
  625. const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
  626. bool IsSignedInteger =
  627. HintQTy->isSignedIntegerType() ||
  628. (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
  629. llvm::Metadata *AttrMDArgs[] = {
  630. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  631. CGM.getTypes().ConvertType(A->getTypeHint()))),
  632. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  633. llvm::IntegerType::get(Context, 32),
  634. llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
  635. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
  636. }
  637. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  638. llvm::Metadata *AttrMDArgs[] = {
  639. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  640. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  641. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  642. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
  643. }
  644. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  645. llvm::Metadata *AttrMDArgs[] = {
  646. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  647. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  648. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  649. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
  650. }
  651. if (const OpenCLIntelReqdSubGroupSizeAttr *A =
  652. FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  653. llvm::Metadata *AttrMDArgs[] = {
  654. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
  655. Fn->setMetadata("intel_reqd_sub_group_size",
  656. llvm::MDNode::get(Context, AttrMDArgs));
  657. }
  658. }
  659. /// Determine whether the function F ends with a return stmt.
  660. static bool endsWithReturn(const Decl* F) {
  661. const Stmt *Body = nullptr;
  662. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  663. Body = FD->getBody();
  664. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  665. Body = OMD->getBody();
  666. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  667. auto LastStmt = CS->body_rbegin();
  668. if (LastStmt != CS->body_rend())
  669. return isa<ReturnStmt>(*LastStmt);
  670. }
  671. return false;
  672. }
  673. static void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  674. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  675. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  676. }
  677. static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
  678. auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  679. if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
  680. !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
  681. (MD->getNumParams() != 1 && MD->getNumParams() != 2))
  682. return false;
  683. if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
  684. return false;
  685. if (MD->getNumParams() == 2) {
  686. auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
  687. if (!PT || !PT->isVoidPointerType() ||
  688. !PT->getPointeeType().isConstQualified())
  689. return false;
  690. }
  691. return true;
  692. }
  693. /// Return the UBSan prologue signature for \p FD if one is available.
  694. static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
  695. const FunctionDecl *FD) {
  696. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  697. if (!MD->isStatic())
  698. return nullptr;
  699. return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
  700. }
  701. void CodeGenFunction::StartFunction(GlobalDecl GD,
  702. QualType RetTy,
  703. llvm::Function *Fn,
  704. const CGFunctionInfo &FnInfo,
  705. const FunctionArgList &Args,
  706. SourceLocation Loc,
  707. SourceLocation StartLoc) {
  708. assert(!CurFn &&
  709. "Do not use a CodeGenFunction object for more than one function");
  710. const Decl *D = GD.getDecl();
  711. DidCallStackSave = false;
  712. CurCodeDecl = D;
  713. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  714. if (FD->usesSEHTry())
  715. CurSEHParent = FD;
  716. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  717. FnRetTy = RetTy;
  718. CurFn = Fn;
  719. CurFnInfo = &FnInfo;
  720. assert(CurFn->isDeclaration() && "Function already has body?");
  721. // If this function has been blacklisted for any of the enabled sanitizers,
  722. // disable the sanitizer for the function.
  723. do {
  724. #define SANITIZER(NAME, ID) \
  725. if (SanOpts.empty()) \
  726. break; \
  727. if (SanOpts.has(SanitizerKind::ID)) \
  728. if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \
  729. SanOpts.set(SanitizerKind::ID, false);
  730. #include "clang/Basic/Sanitizers.def"
  731. #undef SANITIZER
  732. } while (0);
  733. if (D) {
  734. // Apply the no_sanitize* attributes to SanOpts.
  735. for (auto Attr : D->specific_attrs<NoSanitizeAttr>())
  736. SanOpts.Mask &= ~Attr->getMask();
  737. }
  738. // Apply sanitizer attributes to the function.
  739. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  740. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  741. if (SanOpts.hasOneOf(SanitizerKind::HWAddress))
  742. Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
  743. if (SanOpts.has(SanitizerKind::Thread))
  744. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  745. if (SanOpts.has(SanitizerKind::Memory))
  746. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  747. if (SanOpts.has(SanitizerKind::SafeStack))
  748. Fn->addFnAttr(llvm::Attribute::SafeStack);
  749. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  750. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  751. if (SanOpts.has(SanitizerKind::Thread)) {
  752. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  753. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  754. if (OMD->getMethodFamily() == OMF_dealloc ||
  755. OMD->getMethodFamily() == OMF_initialize ||
  756. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  757. markAsIgnoreThreadCheckingAtRuntime(Fn);
  758. }
  759. } else if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  760. IdentifierInfo *II = FD->getIdentifier();
  761. if (II && II->isStr("__destroy_helper_block_"))
  762. markAsIgnoreThreadCheckingAtRuntime(Fn);
  763. }
  764. }
  765. // Ignore unrelated casts in STL allocate() since the allocator must cast
  766. // from void* to T* before object initialization completes. Don't match on the
  767. // namespace because not all allocators are in std::
  768. if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  769. if (matchesStlAllocatorFn(D, getContext()))
  770. SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
  771. }
  772. // Apply xray attributes to the function (as a string, for now)
  773. bool InstrumentXray = ShouldXRayInstrumentFunction();
  774. if (D && InstrumentXray) {
  775. if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
  776. if (XRayAttr->alwaysXRayInstrument())
  777. Fn->addFnAttr("function-instrument", "xray-always");
  778. if (XRayAttr->neverXRayInstrument())
  779. Fn->addFnAttr("function-instrument", "xray-never");
  780. if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) {
  781. Fn->addFnAttr("xray-log-args",
  782. llvm::utostr(LogArgs->getArgumentCount()));
  783. }
  784. } else {
  785. if (!CGM.imbueXRayAttrs(Fn, Loc))
  786. Fn->addFnAttr(
  787. "xray-instruction-threshold",
  788. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  789. }
  790. }
  791. // Add no-jump-tables value.
  792. Fn->addFnAttr("no-jump-tables",
  793. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  794. // Add profile-sample-accurate value.
  795. if (CGM.getCodeGenOpts().ProfileSampleAccurate)
  796. Fn->addFnAttr("profile-sample-accurate");
  797. if (getLangOpts().OpenCL) {
  798. // Add metadata for a kernel function.
  799. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  800. EmitOpenCLKernelMetadata(FD, Fn);
  801. }
  802. // If we are checking function types, emit a function type signature as
  803. // prologue data.
  804. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  805. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  806. if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
  807. // Remove any (C++17) exception specifications, to allow calling e.g. a
  808. // noexcept function through a non-noexcept pointer.
  809. auto ProtoTy =
  810. getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
  811. EST_None);
  812. llvm::Constant *FTRTTIConst =
  813. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  814. llvm::Constant *FTRTTIConstEncoded =
  815. EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
  816. llvm::Constant *PrologueStructElems[] = {PrologueSig,
  817. FTRTTIConstEncoded};
  818. llvm::Constant *PrologueStructConst =
  819. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  820. Fn->setPrologueData(PrologueStructConst);
  821. }
  822. }
  823. }
  824. // If we're checking nullability, we need to know whether we can check the
  825. // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
  826. if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
  827. auto Nullability = FnRetTy->getNullability(getContext());
  828. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  829. if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  830. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
  831. RetValNullabilityPrecondition =
  832. llvm::ConstantInt::getTrue(getLLVMContext());
  833. }
  834. }
  835. // If we're in C++ mode and the function name is "main", it is guaranteed
  836. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  837. // used within a program").
  838. if (getLangOpts().CPlusPlus)
  839. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  840. if (FD->isMain())
  841. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  842. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  843. // Create a marker to make it easy to insert allocas into the entryblock
  844. // later. Don't create this with the builder, because we don't want it
  845. // folded.
  846. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  847. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  848. ReturnBlock = getJumpDestInCurrentScope("return");
  849. Builder.SetInsertPoint(EntryBB);
  850. // If we're checking the return value, allocate space for a pointer to a
  851. // precise source location of the checked return statement.
  852. if (requiresReturnValueCheck()) {
  853. ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
  854. InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
  855. }
  856. // Emit subprogram debug descriptor.
  857. if (CGDebugInfo *DI = getDebugInfo()) {
  858. // Reconstruct the type from the argument list so that implicit parameters,
  859. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  860. // convention.
  861. CallingConv CC = CallingConv::CC_C;
  862. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  863. if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
  864. CC = SrcFnTy->getCallConv();
  865. SmallVector<QualType, 16> ArgTypes;
  866. for (const VarDecl *VD : Args)
  867. ArgTypes.push_back(VD->getType());
  868. QualType FnType = getContext().getFunctionType(
  869. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  870. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder);
  871. }
  872. if (ShouldInstrumentFunction()) {
  873. if (CGM.getCodeGenOpts().InstrumentFunctions)
  874. CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
  875. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  876. CurFn->addFnAttr("instrument-function-entry-inlined",
  877. "__cyg_profile_func_enter");
  878. if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  879. CurFn->addFnAttr("instrument-function-entry-inlined",
  880. "__cyg_profile_func_enter_bare");
  881. }
  882. // Since emitting the mcount call here impacts optimizations such as function
  883. // inlining, we just add an attribute to insert a mcount call in backend.
  884. // The attribute "counting-function" is set to mcount function name which is
  885. // architecture dependent.
  886. if (CGM.getCodeGenOpts().InstrumentForProfiling) {
  887. if (CGM.getCodeGenOpts().CallFEntry)
  888. Fn->addFnAttr("fentry-call", "true");
  889. else {
  890. if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
  891. Fn->addFnAttr("instrument-function-entry-inlined",
  892. getTarget().getMCountName());
  893. }
  894. }
  895. }
  896. if (RetTy->isVoidType()) {
  897. // Void type; nothing to return.
  898. ReturnValue = Address::invalid();
  899. // Count the implicit return.
  900. if (!endsWithReturn(D))
  901. ++NumReturnExprs;
  902. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  903. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  904. // Indirect aggregate return; emit returned value directly into sret slot.
  905. // This reduces code size, and affects correctness in C++.
  906. auto AI = CurFn->arg_begin();
  907. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  908. ++AI;
  909. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  910. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  911. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  912. // Load the sret pointer from the argument struct and return into that.
  913. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  914. llvm::Function::arg_iterator EI = CurFn->arg_end();
  915. --EI;
  916. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  917. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  918. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  919. } else {
  920. ReturnValue = CreateIRTemp(RetTy, "retval");
  921. // Tell the epilog emitter to autorelease the result. We do this
  922. // now so that various specialized functions can suppress it
  923. // during their IR-generation.
  924. if (getLangOpts().ObjCAutoRefCount &&
  925. !CurFnInfo->isReturnsRetained() &&
  926. RetTy->isObjCRetainableType())
  927. AutoreleaseResult = true;
  928. }
  929. EmitStartEHSpec(CurCodeDecl);
  930. PrologueCleanupDepth = EHStack.stable_begin();
  931. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  932. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  933. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  934. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  935. if (MD->getParent()->isLambda() &&
  936. MD->getOverloadedOperator() == OO_Call) {
  937. // We're in a lambda; figure out the captures.
  938. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  939. LambdaThisCaptureField);
  940. if (LambdaThisCaptureField) {
  941. // If the lambda captures the object referred to by '*this' - either by
  942. // value or by reference, make sure CXXThisValue points to the correct
  943. // object.
  944. // Get the lvalue for the field (which is a copy of the enclosing object
  945. // or contains the address of the enclosing object).
  946. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  947. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  948. // If the enclosing object was captured by value, just use its address.
  949. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  950. } else {
  951. // Load the lvalue pointed to by the field, since '*this' was captured
  952. // by reference.
  953. CXXThisValue =
  954. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  955. }
  956. }
  957. for (auto *FD : MD->getParent()->fields()) {
  958. if (FD->hasCapturedVLAType()) {
  959. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  960. SourceLocation()).getScalarVal();
  961. auto VAT = FD->getCapturedVLAType();
  962. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  963. }
  964. }
  965. } else {
  966. // Not in a lambda; just use 'this' from the method.
  967. // FIXME: Should we generate a new load for each use of 'this'? The
  968. // fast register allocator would be happier...
  969. CXXThisValue = CXXABIThisValue;
  970. }
  971. // Check the 'this' pointer once per function, if it's available.
  972. if (CXXABIThisValue) {
  973. SanitizerSet SkippedChecks;
  974. SkippedChecks.set(SanitizerKind::ObjectSize, true);
  975. QualType ThisTy = MD->getThisType(getContext());
  976. // If this is the call operator of a lambda with no capture-default, it
  977. // may have a static invoker function, which may call this operator with
  978. // a null 'this' pointer.
  979. if (isLambdaCallOperator(MD) &&
  980. MD->getParent()->getLambdaCaptureDefault() == LCD_None)
  981. SkippedChecks.set(SanitizerKind::Null, true);
  982. EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
  983. : TCK_MemberCall,
  984. Loc, CXXABIThisValue, ThisTy,
  985. getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
  986. SkippedChecks);
  987. }
  988. }
  989. // If any of the arguments have a variably modified type, make sure to
  990. // emit the type size.
  991. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  992. i != e; ++i) {
  993. const VarDecl *VD = *i;
  994. // Dig out the type as written from ParmVarDecls; it's unclear whether
  995. // the standard (C99 6.9.1p10) requires this, but we're following the
  996. // precedent set by gcc.
  997. QualType Ty;
  998. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  999. Ty = PVD->getOriginalType();
  1000. else
  1001. Ty = VD->getType();
  1002. if (Ty->isVariablyModifiedType())
  1003. EmitVariablyModifiedType(Ty);
  1004. }
  1005. // Emit a location at the end of the prologue.
  1006. if (CGDebugInfo *DI = getDebugInfo())
  1007. DI->EmitLocation(Builder, StartLoc);
  1008. }
  1009. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  1010. const Stmt *Body) {
  1011. incrementProfileCounter(Body);
  1012. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  1013. EmitCompoundStmtWithoutScope(*S);
  1014. else
  1015. EmitStmt(Body);
  1016. }
  1017. /// When instrumenting to collect profile data, the counts for some blocks
  1018. /// such as switch cases need to not include the fall-through counts, so
  1019. /// emit a branch around the instrumentation code. When not instrumenting,
  1020. /// this just calls EmitBlock().
  1021. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  1022. const Stmt *S) {
  1023. llvm::BasicBlock *SkipCountBB = nullptr;
  1024. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  1025. // When instrumenting for profiling, the fallthrough to certain
  1026. // statements needs to skip over the instrumentation code so that we
  1027. // get an accurate count.
  1028. SkipCountBB = createBasicBlock("skipcount");
  1029. EmitBranch(SkipCountBB);
  1030. }
  1031. EmitBlock(BB);
  1032. uint64_t CurrentCount = getCurrentProfileCount();
  1033. incrementProfileCounter(S);
  1034. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  1035. if (SkipCountBB)
  1036. EmitBlock(SkipCountBB);
  1037. }
  1038. /// Tries to mark the given function nounwind based on the
  1039. /// non-existence of any throwing calls within it. We believe this is
  1040. /// lightweight enough to do at -O0.
  1041. static void TryMarkNoThrow(llvm::Function *F) {
  1042. // LLVM treats 'nounwind' on a function as part of the type, so we
  1043. // can't do this on functions that can be overwritten.
  1044. if (F->isInterposable()) return;
  1045. for (llvm::BasicBlock &BB : *F)
  1046. for (llvm::Instruction &I : BB)
  1047. if (I.mayThrow())
  1048. return;
  1049. F->setDoesNotThrow();
  1050. }
  1051. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  1052. FunctionArgList &Args) {
  1053. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1054. QualType ResTy = FD->getReturnType();
  1055. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  1056. if (MD && MD->isInstance()) {
  1057. if (CGM.getCXXABI().HasThisReturn(GD))
  1058. ResTy = MD->getThisType(getContext());
  1059. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  1060. ResTy = CGM.getContext().VoidPtrTy;
  1061. CGM.getCXXABI().buildThisParam(*this, Args);
  1062. }
  1063. // The base version of an inheriting constructor whose constructed base is a
  1064. // virtual base is not passed any arguments (because it doesn't actually call
  1065. // the inherited constructor).
  1066. bool PassedParams = true;
  1067. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  1068. if (auto Inherited = CD->getInheritedConstructor())
  1069. PassedParams =
  1070. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  1071. if (PassedParams) {
  1072. for (auto *Param : FD->parameters()) {
  1073. Args.push_back(Param);
  1074. if (!Param->hasAttr<PassObjectSizeAttr>())
  1075. continue;
  1076. auto *Implicit = ImplicitParamDecl::Create(
  1077. getContext(), Param->getDeclContext(), Param->getLocation(),
  1078. /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
  1079. SizeArguments[Param] = Implicit;
  1080. Args.push_back(Implicit);
  1081. }
  1082. }
  1083. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  1084. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  1085. return ResTy;
  1086. }
  1087. static bool
  1088. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  1089. const ASTContext &Context) {
  1090. QualType T = FD->getReturnType();
  1091. // Avoid the optimization for functions that return a record type with a
  1092. // trivial destructor or another trivially copyable type.
  1093. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  1094. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1095. return !ClassDecl->hasTrivialDestructor();
  1096. }
  1097. return !T.isTriviallyCopyableType(Context);
  1098. }
  1099. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1100. const CGFunctionInfo &FnInfo) {
  1101. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1102. CurGD = GD;
  1103. FunctionArgList Args;
  1104. QualType ResTy = BuildFunctionArgList(GD, Args);
  1105. // Check if we should generate debug info for this function.
  1106. if (FD->hasAttr<NoDebugAttr>())
  1107. DebugInfo = nullptr; // disable debug info indefinitely for this function
  1108. // The function might not have a body if we're generating thunks for a
  1109. // function declaration.
  1110. SourceRange BodyRange;
  1111. if (Stmt *Body = FD->getBody())
  1112. BodyRange = Body->getSourceRange();
  1113. else
  1114. BodyRange = FD->getLocation();
  1115. CurEHLocation = BodyRange.getEnd();
  1116. // Use the location of the start of the function to determine where
  1117. // the function definition is located. By default use the location
  1118. // of the declaration as the location for the subprogram. A function
  1119. // may lack a declaration in the source code if it is created by code
  1120. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  1121. SourceLocation Loc = FD->getLocation();
  1122. // If this is a function specialization then use the pattern body
  1123. // as the location for the function.
  1124. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  1125. if (SpecDecl->hasBody(SpecDecl))
  1126. Loc = SpecDecl->getLocation();
  1127. Stmt *Body = FD->getBody();
  1128. // Initialize helper which will detect jumps which can cause invalid lifetime
  1129. // markers.
  1130. if (Body && ShouldEmitLifetimeMarkers)
  1131. Bypasses.Init(Body);
  1132. // Emit the standard function prologue.
  1133. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  1134. // Generate the body of the function.
  1135. PGO.assignRegionCounters(GD, CurFn);
  1136. if (isa<CXXDestructorDecl>(FD))
  1137. EmitDestructorBody(Args);
  1138. else if (isa<CXXConstructorDecl>(FD))
  1139. EmitConstructorBody(Args);
  1140. else if (getLangOpts().CUDA &&
  1141. !getLangOpts().CUDAIsDevice &&
  1142. FD->hasAttr<CUDAGlobalAttr>())
  1143. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  1144. else if (isa<CXXMethodDecl>(FD) &&
  1145. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  1146. // The lambda static invoker function is special, because it forwards or
  1147. // clones the body of the function call operator (but is actually static).
  1148. EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
  1149. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  1150. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  1151. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  1152. // Implicit copy-assignment gets the same special treatment as implicit
  1153. // copy-constructors.
  1154. emitImplicitAssignmentOperatorBody(Args);
  1155. } else if (Body) {
  1156. EmitFunctionBody(Args, Body);
  1157. } else
  1158. llvm_unreachable("no definition for emitted function");
  1159. // C++11 [stmt.return]p2:
  1160. // Flowing off the end of a function [...] results in undefined behavior in
  1161. // a value-returning function.
  1162. // C11 6.9.1p12:
  1163. // If the '}' that terminates a function is reached, and the value of the
  1164. // function call is used by the caller, the behavior is undefined.
  1165. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1166. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1167. bool ShouldEmitUnreachable =
  1168. CGM.getCodeGenOpts().StrictReturn ||
  1169. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1170. if (SanOpts.has(SanitizerKind::Return)) {
  1171. SanitizerScope SanScope(this);
  1172. llvm::Value *IsFalse = Builder.getFalse();
  1173. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1174. SanitizerHandler::MissingReturn,
  1175. EmitCheckSourceLocation(FD->getLocation()), None);
  1176. } else if (ShouldEmitUnreachable) {
  1177. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1178. EmitTrapCall(llvm::Intrinsic::trap);
  1179. }
  1180. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1181. Builder.CreateUnreachable();
  1182. Builder.ClearInsertionPoint();
  1183. }
  1184. }
  1185. // Emit the standard function epilogue.
  1186. FinishFunction(BodyRange.getEnd());
  1187. // If we haven't marked the function nothrow through other means, do
  1188. // a quick pass now to see if we can.
  1189. if (!CurFn->doesNotThrow())
  1190. TryMarkNoThrow(CurFn);
  1191. }
  1192. /// ContainsLabel - Return true if the statement contains a label in it. If
  1193. /// this statement is not executed normally, it not containing a label means
  1194. /// that we can just remove the code.
  1195. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1196. // Null statement, not a label!
  1197. if (!S) return false;
  1198. // If this is a label, we have to emit the code, consider something like:
  1199. // if (0) { ... foo: bar(); } goto foo;
  1200. //
  1201. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1202. // can't jump to one from outside their declared region.
  1203. if (isa<LabelStmt>(S))
  1204. return true;
  1205. // If this is a case/default statement, and we haven't seen a switch, we have
  1206. // to emit the code.
  1207. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1208. return true;
  1209. // If this is a switch statement, we want to ignore cases below it.
  1210. if (isa<SwitchStmt>(S))
  1211. IgnoreCaseStmts = true;
  1212. // Scan subexpressions for verboten labels.
  1213. for (const Stmt *SubStmt : S->children())
  1214. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1215. return true;
  1216. return false;
  1217. }
  1218. /// containsBreak - Return true if the statement contains a break out of it.
  1219. /// If the statement (recursively) contains a switch or loop with a break
  1220. /// inside of it, this is fine.
  1221. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1222. // Null statement, not a label!
  1223. if (!S) return false;
  1224. // If this is a switch or loop that defines its own break scope, then we can
  1225. // include it and anything inside of it.
  1226. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1227. isa<ForStmt>(S))
  1228. return false;
  1229. if (isa<BreakStmt>(S))
  1230. return true;
  1231. // Scan subexpressions for verboten breaks.
  1232. for (const Stmt *SubStmt : S->children())
  1233. if (containsBreak(SubStmt))
  1234. return true;
  1235. return false;
  1236. }
  1237. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1238. if (!S) return false;
  1239. // Some statement kinds add a scope and thus never add a decl to the current
  1240. // scope. Note, this list is longer than the list of statements that might
  1241. // have an unscoped decl nested within them, but this way is conservatively
  1242. // correct even if more statement kinds are added.
  1243. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1244. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1245. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1246. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1247. return false;
  1248. if (isa<DeclStmt>(S))
  1249. return true;
  1250. for (const Stmt *SubStmt : S->children())
  1251. if (mightAddDeclToScope(SubStmt))
  1252. return true;
  1253. return false;
  1254. }
  1255. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1256. /// to a constant, or if it does but contains a label, return false. If it
  1257. /// constant folds return true and set the boolean result in Result.
  1258. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1259. bool &ResultBool,
  1260. bool AllowLabels) {
  1261. llvm::APSInt ResultInt;
  1262. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1263. return false;
  1264. ResultBool = ResultInt.getBoolValue();
  1265. return true;
  1266. }
  1267. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1268. /// to a constant, or if it does but contains a label, return false. If it
  1269. /// constant folds return true and set the folded value.
  1270. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1271. llvm::APSInt &ResultInt,
  1272. bool AllowLabels) {
  1273. // FIXME: Rename and handle conversion of other evaluatable things
  1274. // to bool.
  1275. llvm::APSInt Int;
  1276. if (!Cond->EvaluateAsInt(Int, getContext()))
  1277. return false; // Not foldable, not integer or not fully evaluatable.
  1278. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1279. return false; // Contains a label.
  1280. ResultInt = Int;
  1281. return true;
  1282. }
  1283. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1284. /// statement) to the specified blocks. Based on the condition, this might try
  1285. /// to simplify the codegen of the conditional based on the branch.
  1286. ///
  1287. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1288. llvm::BasicBlock *TrueBlock,
  1289. llvm::BasicBlock *FalseBlock,
  1290. uint64_t TrueCount) {
  1291. Cond = Cond->IgnoreParens();
  1292. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1293. // Handle X && Y in a condition.
  1294. if (CondBOp->getOpcode() == BO_LAnd) {
  1295. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1296. // folded if the case was simple enough.
  1297. bool ConstantBool = false;
  1298. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1299. ConstantBool) {
  1300. // br(1 && X) -> br(X).
  1301. incrementProfileCounter(CondBOp);
  1302. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1303. TrueCount);
  1304. }
  1305. // If we have "X && 1", simplify the code to use an uncond branch.
  1306. // "X && 0" would have been constant folded to 0.
  1307. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1308. ConstantBool) {
  1309. // br(X && 1) -> br(X).
  1310. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1311. TrueCount);
  1312. }
  1313. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1314. // want to jump to the FalseBlock.
  1315. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1316. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1317. // can be propagated to that branch.
  1318. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1319. ConditionalEvaluation eval(*this);
  1320. {
  1321. ApplyDebugLocation DL(*this, Cond);
  1322. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1323. EmitBlock(LHSTrue);
  1324. }
  1325. incrementProfileCounter(CondBOp);
  1326. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1327. // Any temporaries created here are conditional.
  1328. eval.begin(*this);
  1329. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1330. eval.end(*this);
  1331. return;
  1332. }
  1333. if (CondBOp->getOpcode() == BO_LOr) {
  1334. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1335. // folded if the case was simple enough.
  1336. bool ConstantBool = false;
  1337. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1338. !ConstantBool) {
  1339. // br(0 || X) -> br(X).
  1340. incrementProfileCounter(CondBOp);
  1341. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1342. TrueCount);
  1343. }
  1344. // If we have "X || 0", simplify the code to use an uncond branch.
  1345. // "X || 1" would have been constant folded to 1.
  1346. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1347. !ConstantBool) {
  1348. // br(X || 0) -> br(X).
  1349. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1350. TrueCount);
  1351. }
  1352. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1353. // want to jump to the TrueBlock.
  1354. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1355. // We have the count for entry to the RHS and for the whole expression
  1356. // being true, so we can divy up True count between the short circuit and
  1357. // the RHS.
  1358. uint64_t LHSCount =
  1359. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1360. uint64_t RHSCount = TrueCount - LHSCount;
  1361. ConditionalEvaluation eval(*this);
  1362. {
  1363. ApplyDebugLocation DL(*this, Cond);
  1364. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1365. EmitBlock(LHSFalse);
  1366. }
  1367. incrementProfileCounter(CondBOp);
  1368. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1369. // Any temporaries created here are conditional.
  1370. eval.begin(*this);
  1371. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1372. eval.end(*this);
  1373. return;
  1374. }
  1375. }
  1376. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1377. // br(!x, t, f) -> br(x, f, t)
  1378. if (CondUOp->getOpcode() == UO_LNot) {
  1379. // Negate the count.
  1380. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1381. // Negate the condition and swap the destination blocks.
  1382. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1383. FalseCount);
  1384. }
  1385. }
  1386. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1387. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1388. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1389. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1390. ConditionalEvaluation cond(*this);
  1391. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1392. getProfileCount(CondOp));
  1393. // When computing PGO branch weights, we only know the overall count for
  1394. // the true block. This code is essentially doing tail duplication of the
  1395. // naive code-gen, introducing new edges for which counts are not
  1396. // available. Divide the counts proportionally between the LHS and RHS of
  1397. // the conditional operator.
  1398. uint64_t LHSScaledTrueCount = 0;
  1399. if (TrueCount) {
  1400. double LHSRatio =
  1401. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1402. LHSScaledTrueCount = TrueCount * LHSRatio;
  1403. }
  1404. cond.begin(*this);
  1405. EmitBlock(LHSBlock);
  1406. incrementProfileCounter(CondOp);
  1407. {
  1408. ApplyDebugLocation DL(*this, Cond);
  1409. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1410. LHSScaledTrueCount);
  1411. }
  1412. cond.end(*this);
  1413. cond.begin(*this);
  1414. EmitBlock(RHSBlock);
  1415. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1416. TrueCount - LHSScaledTrueCount);
  1417. cond.end(*this);
  1418. return;
  1419. }
  1420. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1421. // Conditional operator handling can give us a throw expression as a
  1422. // condition for a case like:
  1423. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1424. // Fold this to:
  1425. // br(c, throw x, br(y, t, f))
  1426. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1427. return;
  1428. }
  1429. // If the branch has a condition wrapped by __builtin_unpredictable,
  1430. // create metadata that specifies that the branch is unpredictable.
  1431. // Don't bother if not optimizing because that metadata would not be used.
  1432. llvm::MDNode *Unpredictable = nullptr;
  1433. auto *Call = dyn_cast<CallExpr>(Cond);
  1434. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1435. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1436. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1437. llvm::MDBuilder MDHelper(getLLVMContext());
  1438. Unpredictable = MDHelper.createUnpredictable();
  1439. }
  1440. }
  1441. // Create branch weights based on the number of times we get here and the
  1442. // number of times the condition should be true.
  1443. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1444. llvm::MDNode *Weights =
  1445. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1446. // Emit the code with the fully general case.
  1447. llvm::Value *CondV;
  1448. {
  1449. ApplyDebugLocation DL(*this, Cond);
  1450. CondV = EvaluateExprAsBool(Cond);
  1451. }
  1452. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1453. }
  1454. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1455. /// specified stmt yet.
  1456. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1457. CGM.ErrorUnsupported(S, Type);
  1458. }
  1459. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1460. /// variable-length array whose elements have a non-zero bit-pattern.
  1461. ///
  1462. /// \param baseType the inner-most element type of the array
  1463. /// \param src - a char* pointing to the bit-pattern for a single
  1464. /// base element of the array
  1465. /// \param sizeInChars - the total size of the VLA, in chars
  1466. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1467. Address dest, Address src,
  1468. llvm::Value *sizeInChars) {
  1469. CGBuilderTy &Builder = CGF.Builder;
  1470. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1471. llvm::Value *baseSizeInChars
  1472. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1473. Address begin =
  1474. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1475. llvm::Value *end =
  1476. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1477. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1478. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1479. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1480. // Make a loop over the VLA. C99 guarantees that the VLA element
  1481. // count must be nonzero.
  1482. CGF.EmitBlock(loopBB);
  1483. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1484. cur->addIncoming(begin.getPointer(), originBB);
  1485. CharUnits curAlign =
  1486. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1487. // memcpy the individual element bit-pattern.
  1488. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1489. /*volatile*/ false);
  1490. // Go to the next element.
  1491. llvm::Value *next =
  1492. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1493. // Leave if that's the end of the VLA.
  1494. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1495. Builder.CreateCondBr(done, contBB, loopBB);
  1496. cur->addIncoming(next, loopBB);
  1497. CGF.EmitBlock(contBB);
  1498. }
  1499. void
  1500. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1501. // Ignore empty classes in C++.
  1502. if (getLangOpts().CPlusPlus) {
  1503. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1504. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1505. return;
  1506. }
  1507. }
  1508. // Cast the dest ptr to the appropriate i8 pointer type.
  1509. if (DestPtr.getElementType() != Int8Ty)
  1510. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1511. // Get size and alignment info for this aggregate.
  1512. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1513. llvm::Value *SizeVal;
  1514. const VariableArrayType *vla;
  1515. // Don't bother emitting a zero-byte memset.
  1516. if (size.isZero()) {
  1517. // But note that getTypeInfo returns 0 for a VLA.
  1518. if (const VariableArrayType *vlaType =
  1519. dyn_cast_or_null<VariableArrayType>(
  1520. getContext().getAsArrayType(Ty))) {
  1521. auto VlaSize = getVLASize(vlaType);
  1522. SizeVal = VlaSize.NumElts;
  1523. CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1524. if (!eltSize.isOne())
  1525. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1526. vla = vlaType;
  1527. } else {
  1528. return;
  1529. }
  1530. } else {
  1531. SizeVal = CGM.getSize(size);
  1532. vla = nullptr;
  1533. }
  1534. // If the type contains a pointer to data member we can't memset it to zero.
  1535. // Instead, create a null constant and copy it to the destination.
  1536. // TODO: there are other patterns besides zero that we can usefully memset,
  1537. // like -1, which happens to be the pattern used by member-pointers.
  1538. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1539. // For a VLA, emit a single element, then splat that over the VLA.
  1540. if (vla) Ty = getContext().getBaseElementType(vla);
  1541. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1542. llvm::GlobalVariable *NullVariable =
  1543. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1544. /*isConstant=*/true,
  1545. llvm::GlobalVariable::PrivateLinkage,
  1546. NullConstant, Twine());
  1547. CharUnits NullAlign = DestPtr.getAlignment();
  1548. NullVariable->setAlignment(NullAlign.getQuantity());
  1549. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1550. NullAlign);
  1551. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1552. // Get and call the appropriate llvm.memcpy overload.
  1553. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1554. return;
  1555. }
  1556. // Otherwise, just memset the whole thing to zero. This is legal
  1557. // because in LLVM, all default initializers (other than the ones we just
  1558. // handled above) are guaranteed to have a bit pattern of all zeros.
  1559. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1560. }
  1561. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1562. // Make sure that there is a block for the indirect goto.
  1563. if (!IndirectBranch)
  1564. GetIndirectGotoBlock();
  1565. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1566. // Make sure the indirect branch includes all of the address-taken blocks.
  1567. IndirectBranch->addDestination(BB);
  1568. return llvm::BlockAddress::get(CurFn, BB);
  1569. }
  1570. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1571. // If we already made the indirect branch for indirect goto, return its block.
  1572. if (IndirectBranch) return IndirectBranch->getParent();
  1573. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1574. // Create the PHI node that indirect gotos will add entries to.
  1575. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1576. "indirect.goto.dest");
  1577. // Create the indirect branch instruction.
  1578. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1579. return IndirectBranch->getParent();
  1580. }
  1581. /// Computes the length of an array in elements, as well as the base
  1582. /// element type and a properly-typed first element pointer.
  1583. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1584. QualType &baseType,
  1585. Address &addr) {
  1586. const ArrayType *arrayType = origArrayType;
  1587. // If it's a VLA, we have to load the stored size. Note that
  1588. // this is the size of the VLA in bytes, not its size in elements.
  1589. llvm::Value *numVLAElements = nullptr;
  1590. if (isa<VariableArrayType>(arrayType)) {
  1591. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
  1592. // Walk into all VLAs. This doesn't require changes to addr,
  1593. // which has type T* where T is the first non-VLA element type.
  1594. do {
  1595. QualType elementType = arrayType->getElementType();
  1596. arrayType = getContext().getAsArrayType(elementType);
  1597. // If we only have VLA components, 'addr' requires no adjustment.
  1598. if (!arrayType) {
  1599. baseType = elementType;
  1600. return numVLAElements;
  1601. }
  1602. } while (isa<VariableArrayType>(arrayType));
  1603. // We get out here only if we find a constant array type
  1604. // inside the VLA.
  1605. }
  1606. // We have some number of constant-length arrays, so addr should
  1607. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1608. // down to the first element of addr.
  1609. SmallVector<llvm::Value*, 8> gepIndices;
  1610. // GEP down to the array type.
  1611. llvm::ConstantInt *zero = Builder.getInt32(0);
  1612. gepIndices.push_back(zero);
  1613. uint64_t countFromCLAs = 1;
  1614. QualType eltType;
  1615. llvm::ArrayType *llvmArrayType =
  1616. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1617. while (llvmArrayType) {
  1618. assert(isa<ConstantArrayType>(arrayType));
  1619. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1620. == llvmArrayType->getNumElements());
  1621. gepIndices.push_back(zero);
  1622. countFromCLAs *= llvmArrayType->getNumElements();
  1623. eltType = arrayType->getElementType();
  1624. llvmArrayType =
  1625. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1626. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1627. assert((!llvmArrayType || arrayType) &&
  1628. "LLVM and Clang types are out-of-synch");
  1629. }
  1630. if (arrayType) {
  1631. // From this point onwards, the Clang array type has been emitted
  1632. // as some other type (probably a packed struct). Compute the array
  1633. // size, and just emit the 'begin' expression as a bitcast.
  1634. while (arrayType) {
  1635. countFromCLAs *=
  1636. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1637. eltType = arrayType->getElementType();
  1638. arrayType = getContext().getAsArrayType(eltType);
  1639. }
  1640. llvm::Type *baseType = ConvertType(eltType);
  1641. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1642. } else {
  1643. // Create the actual GEP.
  1644. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1645. gepIndices, "array.begin"),
  1646. addr.getAlignment());
  1647. }
  1648. baseType = eltType;
  1649. llvm::Value *numElements
  1650. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1651. // If we had any VLA dimensions, factor them in.
  1652. if (numVLAElements)
  1653. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1654. return numElements;
  1655. }
  1656. CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
  1657. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1658. assert(vla && "type was not a variable array type!");
  1659. return getVLASize(vla);
  1660. }
  1661. CodeGenFunction::VlaSizePair
  1662. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1663. // The number of elements so far; always size_t.
  1664. llvm::Value *numElements = nullptr;
  1665. QualType elementType;
  1666. do {
  1667. elementType = type->getElementType();
  1668. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1669. assert(vlaSize && "no size for VLA!");
  1670. assert(vlaSize->getType() == SizeTy);
  1671. if (!numElements) {
  1672. numElements = vlaSize;
  1673. } else {
  1674. // It's undefined behavior if this wraps around, so mark it that way.
  1675. // FIXME: Teach -fsanitize=undefined to trap this.
  1676. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1677. }
  1678. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1679. return { numElements, elementType };
  1680. }
  1681. CodeGenFunction::VlaSizePair
  1682. CodeGenFunction::getVLAElements1D(QualType type) {
  1683. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1684. assert(vla && "type was not a variable array type!");
  1685. return getVLAElements1D(vla);
  1686. }
  1687. CodeGenFunction::VlaSizePair
  1688. CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
  1689. llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
  1690. assert(VlaSize && "no size for VLA!");
  1691. assert(VlaSize->getType() == SizeTy);
  1692. return { VlaSize, Vla->getElementType() };
  1693. }
  1694. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1695. assert(type->isVariablyModifiedType() &&
  1696. "Must pass variably modified type to EmitVLASizes!");
  1697. EnsureInsertPoint();
  1698. // We're going to walk down into the type and look for VLA
  1699. // expressions.
  1700. do {
  1701. assert(type->isVariablyModifiedType());
  1702. const Type *ty = type.getTypePtr();
  1703. switch (ty->getTypeClass()) {
  1704. #define TYPE(Class, Base)
  1705. #define ABSTRACT_TYPE(Class, Base)
  1706. #define NON_CANONICAL_TYPE(Class, Base)
  1707. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1708. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1709. #include "clang/AST/TypeNodes.def"
  1710. llvm_unreachable("unexpected dependent type!");
  1711. // These types are never variably-modified.
  1712. case Type::Builtin:
  1713. case Type::Complex:
  1714. case Type::Vector:
  1715. case Type::ExtVector:
  1716. case Type::Record:
  1717. case Type::Enum:
  1718. case Type::Elaborated:
  1719. case Type::TemplateSpecialization:
  1720. case Type::ObjCTypeParam:
  1721. case Type::ObjCObject:
  1722. case Type::ObjCInterface:
  1723. case Type::ObjCObjectPointer:
  1724. llvm_unreachable("type class is never variably-modified!");
  1725. case Type::Adjusted:
  1726. type = cast<AdjustedType>(ty)->getAdjustedType();
  1727. break;
  1728. case Type::Decayed:
  1729. type = cast<DecayedType>(ty)->getPointeeType();
  1730. break;
  1731. case Type::Pointer:
  1732. type = cast<PointerType>(ty)->getPointeeType();
  1733. break;
  1734. case Type::BlockPointer:
  1735. type = cast<BlockPointerType>(ty)->getPointeeType();
  1736. break;
  1737. case Type::LValueReference:
  1738. case Type::RValueReference:
  1739. type = cast<ReferenceType>(ty)->getPointeeType();
  1740. break;
  1741. case Type::MemberPointer:
  1742. type = cast<MemberPointerType>(ty)->getPointeeType();
  1743. break;
  1744. case Type::ConstantArray:
  1745. case Type::IncompleteArray:
  1746. // Losing element qualification here is fine.
  1747. type = cast<ArrayType>(ty)->getElementType();
  1748. break;
  1749. case Type::VariableArray: {
  1750. // Losing element qualification here is fine.
  1751. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1752. // Unknown size indication requires no size computation.
  1753. // Otherwise, evaluate and record it.
  1754. if (const Expr *size = vat->getSizeExpr()) {
  1755. // It's possible that we might have emitted this already,
  1756. // e.g. with a typedef and a pointer to it.
  1757. llvm::Value *&entry = VLASizeMap[size];
  1758. if (!entry) {
  1759. llvm::Value *Size = EmitScalarExpr(size);
  1760. // C11 6.7.6.2p5:
  1761. // If the size is an expression that is not an integer constant
  1762. // expression [...] each time it is evaluated it shall have a value
  1763. // greater than zero.
  1764. if (SanOpts.has(SanitizerKind::VLABound) &&
  1765. size->getType()->isSignedIntegerType()) {
  1766. SanitizerScope SanScope(this);
  1767. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1768. llvm::Constant *StaticArgs[] = {
  1769. EmitCheckSourceLocation(size->getLocStart()),
  1770. EmitCheckTypeDescriptor(size->getType())
  1771. };
  1772. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1773. SanitizerKind::VLABound),
  1774. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1775. }
  1776. // Always zexting here would be wrong if it weren't
  1777. // undefined behavior to have a negative bound.
  1778. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1779. }
  1780. }
  1781. type = vat->getElementType();
  1782. break;
  1783. }
  1784. case Type::FunctionProto:
  1785. case Type::FunctionNoProto:
  1786. type = cast<FunctionType>(ty)->getReturnType();
  1787. break;
  1788. case Type::Paren:
  1789. case Type::TypeOf:
  1790. case Type::UnaryTransform:
  1791. case Type::Attributed:
  1792. case Type::SubstTemplateTypeParm:
  1793. case Type::PackExpansion:
  1794. // Keep walking after single level desugaring.
  1795. type = type.getSingleStepDesugaredType(getContext());
  1796. break;
  1797. case Type::Typedef:
  1798. case Type::Decltype:
  1799. case Type::Auto:
  1800. case Type::DeducedTemplateSpecialization:
  1801. // Stop walking: nothing to do.
  1802. return;
  1803. case Type::TypeOfExpr:
  1804. // Stop walking: emit typeof expression.
  1805. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1806. return;
  1807. case Type::Atomic:
  1808. type = cast<AtomicType>(ty)->getValueType();
  1809. break;
  1810. case Type::Pipe:
  1811. type = cast<PipeType>(ty)->getElementType();
  1812. break;
  1813. }
  1814. } while (type->isVariablyModifiedType());
  1815. }
  1816. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1817. if (getContext().getBuiltinVaListType()->isArrayType())
  1818. return EmitPointerWithAlignment(E);
  1819. return EmitLValue(E).getAddress();
  1820. }
  1821. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1822. return EmitLValue(E).getAddress();
  1823. }
  1824. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1825. const APValue &Init) {
  1826. assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
  1827. if (CGDebugInfo *Dbg = getDebugInfo())
  1828. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1829. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1830. }
  1831. CodeGenFunction::PeepholeProtection
  1832. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1833. // At the moment, the only aggressive peephole we do in IR gen
  1834. // is trunc(zext) folding, but if we add more, we can easily
  1835. // extend this protection.
  1836. if (!rvalue.isScalar()) return PeepholeProtection();
  1837. llvm::Value *value = rvalue.getScalarVal();
  1838. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1839. // Just make an extra bitcast.
  1840. assert(HaveInsertPoint());
  1841. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1842. Builder.GetInsertBlock());
  1843. PeepholeProtection protection;
  1844. protection.Inst = inst;
  1845. return protection;
  1846. }
  1847. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1848. if (!protection.Inst) return;
  1849. // In theory, we could try to duplicate the peepholes now, but whatever.
  1850. protection.Inst->eraseFromParent();
  1851. }
  1852. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1853. llvm::Value *AnnotatedVal,
  1854. StringRef AnnotationStr,
  1855. SourceLocation Location) {
  1856. llvm::Value *Args[4] = {
  1857. AnnotatedVal,
  1858. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1859. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1860. CGM.EmitAnnotationLineNo(Location)
  1861. };
  1862. return Builder.CreateCall(AnnotationFn, Args);
  1863. }
  1864. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1865. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1866. // FIXME We create a new bitcast for every annotation because that's what
  1867. // llvm-gcc was doing.
  1868. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1869. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1870. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1871. I->getAnnotation(), D->getLocation());
  1872. }
  1873. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1874. Address Addr) {
  1875. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1876. llvm::Value *V = Addr.getPointer();
  1877. llvm::Type *VTy = V->getType();
  1878. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1879. CGM.Int8PtrTy);
  1880. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1881. // FIXME Always emit the cast inst so we can differentiate between
  1882. // annotation on the first field of a struct and annotation on the struct
  1883. // itself.
  1884. if (VTy != CGM.Int8PtrTy)
  1885. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1886. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1887. V = Builder.CreateBitCast(V, VTy);
  1888. }
  1889. return Address(V, Addr.getAlignment());
  1890. }
  1891. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1892. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1893. : CGF(CGF) {
  1894. assert(!CGF->IsSanitizerScope);
  1895. CGF->IsSanitizerScope = true;
  1896. }
  1897. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1898. CGF->IsSanitizerScope = false;
  1899. }
  1900. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1901. const llvm::Twine &Name,
  1902. llvm::BasicBlock *BB,
  1903. llvm::BasicBlock::iterator InsertPt) const {
  1904. LoopStack.InsertHelper(I);
  1905. if (IsSanitizerScope)
  1906. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1907. }
  1908. void CGBuilderInserter::InsertHelper(
  1909. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1910. llvm::BasicBlock::iterator InsertPt) const {
  1911. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1912. if (CGF)
  1913. CGF->InsertHelper(I, Name, BB, InsertPt);
  1914. }
  1915. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1916. CodeGenModule &CGM, const FunctionDecl *FD,
  1917. std::string &FirstMissing) {
  1918. // If there aren't any required features listed then go ahead and return.
  1919. if (ReqFeatures.empty())
  1920. return false;
  1921. // Now build up the set of caller features and verify that all the required
  1922. // features are there.
  1923. llvm::StringMap<bool> CallerFeatureMap;
  1924. CGM.getFunctionFeatureMap(CallerFeatureMap, FD);
  1925. // If we have at least one of the features in the feature list return
  1926. // true, otherwise return false.
  1927. return std::all_of(
  1928. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  1929. SmallVector<StringRef, 1> OrFeatures;
  1930. Feature.split(OrFeatures, "|");
  1931. return std::any_of(OrFeatures.begin(), OrFeatures.end(),
  1932. [&](StringRef Feature) {
  1933. if (!CallerFeatureMap.lookup(Feature)) {
  1934. FirstMissing = Feature.str();
  1935. return false;
  1936. }
  1937. return true;
  1938. });
  1939. });
  1940. }
  1941. // Emits an error if we don't have a valid set of target features for the
  1942. // called function.
  1943. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  1944. const FunctionDecl *TargetDecl) {
  1945. // Early exit if this is an indirect call.
  1946. if (!TargetDecl)
  1947. return;
  1948. // Get the current enclosing function if it exists. If it doesn't
  1949. // we can't check the target features anyhow.
  1950. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  1951. if (!FD)
  1952. return;
  1953. // Grab the required features for the call. For a builtin this is listed in
  1954. // the td file with the default cpu, for an always_inline function this is any
  1955. // listed cpu and any listed features.
  1956. unsigned BuiltinID = TargetDecl->getBuiltinID();
  1957. std::string MissingFeature;
  1958. if (BuiltinID) {
  1959. SmallVector<StringRef, 1> ReqFeatures;
  1960. const char *FeatureList =
  1961. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1962. // Return if the builtin doesn't have any required features.
  1963. if (!FeatureList || StringRef(FeatureList) == "")
  1964. return;
  1965. StringRef(FeatureList).split(ReqFeatures, ",");
  1966. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1967. CGM.getDiags().Report(E->getLocStart(), diag::err_builtin_needs_feature)
  1968. << TargetDecl->getDeclName()
  1969. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  1970. } else if (TargetDecl->hasAttr<TargetAttr>()) {
  1971. // Get the required features for the callee.
  1972. SmallVector<StringRef, 1> ReqFeatures;
  1973. llvm::StringMap<bool> CalleeFeatureMap;
  1974. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  1975. for (const auto &F : CalleeFeatureMap) {
  1976. // Only positive features are "required".
  1977. if (F.getValue())
  1978. ReqFeatures.push_back(F.getKey());
  1979. }
  1980. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  1981. CGM.getDiags().Report(E->getLocStart(), diag::err_function_needs_feature)
  1982. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  1983. }
  1984. }
  1985. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  1986. if (!CGM.getCodeGenOpts().SanitizeStats)
  1987. return;
  1988. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  1989. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  1990. CGM.getSanStats().create(IRB, SSK);
  1991. }
  1992. llvm::Value *
  1993. CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
  1994. llvm::Value *TrueCondition = nullptr;
  1995. if (!RO.ParsedAttribute.Architecture.empty())
  1996. TrueCondition = EmitX86CpuIs(RO.ParsedAttribute.Architecture);
  1997. if (!RO.ParsedAttribute.Features.empty()) {
  1998. SmallVector<StringRef, 8> FeatureList;
  1999. llvm::for_each(RO.ParsedAttribute.Features,
  2000. [&FeatureList](const std::string &Feature) {
  2001. FeatureList.push_back(StringRef{Feature}.substr(1));
  2002. });
  2003. llvm::Value *FeatureCmp = EmitX86CpuSupports(FeatureList);
  2004. TrueCondition = TrueCondition ? Builder.CreateAnd(TrueCondition, FeatureCmp)
  2005. : FeatureCmp;
  2006. }
  2007. return TrueCondition;
  2008. }
  2009. void CodeGenFunction::EmitMultiVersionResolver(
  2010. llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
  2011. assert((getContext().getTargetInfo().getTriple().getArch() ==
  2012. llvm::Triple::x86 ||
  2013. getContext().getTargetInfo().getTriple().getArch() ==
  2014. llvm::Triple::x86_64) &&
  2015. "Only implemented for x86 targets");
  2016. // Main function's basic block.
  2017. llvm::BasicBlock *CurBlock = createBasicBlock("entry", Resolver);
  2018. Builder.SetInsertPoint(CurBlock);
  2019. EmitX86CpuInit();
  2020. llvm::Function *DefaultFunc = nullptr;
  2021. for (const MultiVersionResolverOption &RO : Options) {
  2022. Builder.SetInsertPoint(CurBlock);
  2023. llvm::Value *TrueCondition = FormResolverCondition(RO);
  2024. if (!TrueCondition) {
  2025. DefaultFunc = RO.Function;
  2026. } else {
  2027. llvm::BasicBlock *RetBlock = createBasicBlock("ro_ret", Resolver);
  2028. llvm::IRBuilder<> RetBuilder(RetBlock);
  2029. RetBuilder.CreateRet(RO.Function);
  2030. CurBlock = createBasicBlock("ro_else", Resolver);
  2031. Builder.CreateCondBr(TrueCondition, RetBlock, CurBlock);
  2032. }
  2033. }
  2034. assert(DefaultFunc && "No default version?");
  2035. // Emit return from the 'else-ist' block.
  2036. Builder.SetInsertPoint(CurBlock);
  2037. Builder.CreateRet(DefaultFunc);
  2038. }
  2039. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  2040. if (CGDebugInfo *DI = getDebugInfo())
  2041. return DI->SourceLocToDebugLoc(Location);
  2042. return llvm::DebugLoc();
  2043. }