CodeGenFunction.cpp 86 KB

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